vomebook commited on
Commit ·
0bb3eae
1
Parent(s): f5a2f9a
Optimize search startup and uncached wildcards
Browse files- SEARCH_PERFORMANCE_REPORT.md +71 -0
- app.py +9 -4
- search_indexes.py +30 -4
- tests/test_benchmark.py +3 -1
- tests/test_cache_and_malformed.py +16 -0
- tests/test_reader_backend.py +23 -0
SEARCH_PERFORMANCE_REPORT.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Local Search Performance, 2026-09-27
|
| 2 |
+
|
| 3 |
+
These measurements describe the checked-out 97,560-record snapshot on this
|
| 4 |
+
device (Python 3.10.12), not production latency or cross-site corpus parity.
|
| 5 |
+
These measurements were collected before release; production acceptance is separate.
|
| 6 |
+
|
| 7 |
+
## Changes
|
| 8 |
+
|
| 9 |
+
- Reader source URL normalization quotes the complete path once and normalizes
|
| 10 |
+
escapes without per-character regular expression compilation/lookup.
|
| 11 |
+
- Wildcard matching rejects fields missing mandatory literals through the same
|
| 12 |
+
single-character IGNORECASE regexes before running the bounded bitset NFA.
|
| 13 |
+
- N-gram admission validates every delta-encoded posting without allocating
|
| 14 |
+
temporary sets. Word indexes still retain decoded sets. Duplicate-ID counts,
|
| 15 |
+
truncated varints, out-of-range IDs and trailing data retain their checks.
|
| 16 |
+
|
| 17 |
+
## Paired Measurements
|
| 18 |
+
|
| 19 |
+
Wildcard results below are three-run medians with both query caches cleared
|
| 20 |
+
before each measurement. The baseline matcher was loaded from the checkout's
|
| 21 |
+
HEAD, and old/new implementations ran alternately in one process. Complete
|
| 22 |
+
responses, including every result and total, were identical for all five queries.
|
| 23 |
+
|
| 24 |
+
| Query | Before (ms) | After (ms) |
|
| 25 |
+
| --- | ---: | ---: |
|
| 26 |
+
| `手*机` | 4912.13 | 246.80 |
|
| 27 |
+
| `手?机` | 5314.72 | 296.78 |
|
| 28 |
+
| `*文*` | 5626.70 | 1125.56 |
|
| 29 |
+
| `A?C` | 5207.27 | 1304.66 |
|
| 30 |
+
| `*` | 3529.14 | 3637.80 |
|
| 31 |
+
|
| 32 |
+
The small all-wildcard difference is not evidence of an improvement; this case
|
| 33 |
+
still returns all records and is dominated by response construction.
|
| 34 |
+
|
| 35 |
+
N-gram loader A/B used three alternating runs per implementation. Every index
|
| 36 |
+
key, offset, count and retained buffer byte was identical:
|
| 37 |
+
|
| 38 |
+
| Index | Entries | Before (ms) | After (ms) |
|
| 39 |
+
| --- | ---: | ---: | ---: |
|
| 40 |
+
| 2-gram | 151759 | 5133.24 | 3209.83 |
|
| 41 |
+
| 3-gram | 397957 | 5855.03 | 4026.82 |
|
| 42 |
+
|
| 43 |
+
Across every local record, canonical paths matched the former encoder exactly:
|
| 44 |
+
24.076 s before versus 8.017 s after in one full-snapshot comparison.
|
| 45 |
+
The subsequent same-process startup comparison measured 50.550 s before and
|
| 46 |
+
32.380 s after, with identical Reader ID indexes and search generation. Its
|
| 47 |
+
second run reused initialized jieba (about 0.639 s in the first run), so this
|
| 48 |
+
is not a strict isolated cold-process comparison. The independent optimized
|
| 49 |
+
benchmark startup measured 32.196 s on this device.
|
| 50 |
+
|
| 51 |
+
## Verification
|
| 52 |
+
|
| 53 |
+
- Backend fast suite: 241 tests passed before the n-gram change.
|
| 54 |
+
- N-gram/search/generated-snapshot suites: 67 tests passed after it.
|
| 55 |
+
- Real-backend HTTP, Chromium and shutdown integration: 12 tests passed.
|
| 56 |
+
- Local-function, HTTP and Chromium benchmark tiers: all three passed.
|
| 57 |
+
- Existing wildcard oracle retains Unicode IGNORECASE and newline semantics.
|
| 58 |
+
- Canonical-path regression covers all 256 escaped bytes, deterministic mixed
|
| 59 |
+
Unicode/malformed-percent paths and existing shared Reader ID vectors.
|
| 60 |
+
|
| 61 |
+
Runnable project commands:
|
| 62 |
+
|
| 63 |
+
```bash
|
| 64 |
+
HF_SEARCH_RUN_BENCHMARK=1 python3 -B -m unittest tests.test_benchmark -v
|
| 65 |
+
python3 -B -m unittest tests.test_search_behavior tests.test_cache_and_malformed tests.test_reader_backend.ReaderArchiveValidationTests -v
|
| 66 |
+
python3 -B -m unittest tests.test_generated_data_oracle tests.test_real_integration -v
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
The standard repeated-query benchmark median mainly measures cache hits; its
|
| 70 |
+
maximum includes the first computation. Use the explicit uncached A/B above
|
| 71 |
+
to judge matcher cost. Network/DNS/gateway latency is outside these changes.
|
app.py
CHANGED
|
@@ -264,11 +264,13 @@ def canonical_reader_source_url(value: str) -> str:
|
|
| 264 |
def path_replace(match):
|
| 265 |
def token_replace(token_match):
|
| 266 |
token = token_match.group()
|
| 267 |
-
if
|
| 268 |
char = chr(int(token[1:], 16))
|
| 269 |
-
return char if
|
| 270 |
-
return
|
| 271 |
-
|
|
|
|
|
|
|
| 272 |
return re.sub(r"^(https://huggingface\.co/datasets/VoiceOfML/)([^?#]*)", path_replace, value)
|
| 273 |
|
| 274 |
|
|
@@ -336,6 +338,9 @@ def compile_exact_matcher(query: str):
|
|
| 336 |
start = 1 | ((1 & stars) << 1)
|
| 337 |
|
| 338 |
def matches(text):
|
|
|
|
|
|
|
|
|
|
| 339 |
active = start
|
| 340 |
if active & end:
|
| 341 |
return True
|
|
|
|
| 264 |
def path_replace(match):
|
| 265 |
def token_replace(token_match):
|
| 266 |
token = token_match.group()
|
| 267 |
+
if len(token) == 3:
|
| 268 |
char = chr(int(token[1:], 16))
|
| 269 |
+
return char if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._~-" else token.upper()
|
| 270 |
+
return "%25"
|
| 271 |
+
# Quote the whole path once; only existing/generated escapes need callbacks.
|
| 272 |
+
path = quote(match[2], safe="/%")
|
| 273 |
+
return match[1] + re.sub(r"%[0-9a-fA-F]{2}|%", token_replace, path)
|
| 274 |
return re.sub(r"^(https://huggingface\.co/datasets/VoiceOfML/)([^?#]*)", path_replace, value)
|
| 275 |
|
| 276 |
|
|
|
|
| 338 |
start = 1 | ((1 & stars) << 1)
|
| 339 |
|
| 340 |
def matches(text):
|
| 341 |
+
# Every literal is mandatory; C-level scans reject unrelated fields early.
|
| 342 |
+
if any(regex.search(text) is None for regex, _ in literals):
|
| 343 |
+
return False
|
| 344 |
active = start
|
| 345 |
if active & end:
|
| 346 |
return True
|
search_indexes.py
CHANGED
|
@@ -47,7 +47,32 @@ def _bounded_slice(data: bytes, offset: int, length: int) -> tuple[int, int]:
|
|
| 47 |
return offset, end
|
| 48 |
|
| 49 |
|
| 50 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
"""Yield validated entries while leaving storage policy to each loader."""
|
| 52 |
for _ in range(count):
|
| 53 |
key_length, offset = decode_varint(data, offset)
|
|
@@ -56,8 +81,9 @@ def _read_posting_entries(data: bytes, offset: int, count: int, record_count: in
|
|
| 56 |
posting_count, offset = decode_varint(data, offset)
|
| 57 |
posting_length, offset = decode_varint(data, offset)
|
| 58 |
posting_start, offset = _bounded_slice(data, offset, posting_length)
|
| 59 |
-
decoded = decode_postings(memoryview(data)[posting_start:offset], record_count)
|
| 60 |
-
|
|
|
|
| 61 |
raise ValueError("posting count mismatch")
|
| 62 |
yield key, (posting_start, offset, posting_count), decoded
|
| 63 |
if offset != len(data):
|
|
@@ -83,7 +109,7 @@ def load_ngram_index(
|
|
| 83 |
return {}, b""
|
| 84 |
postings = {
|
| 85 |
key: location
|
| 86 |
-
for key, location, _ in _read_posting_entries(data, offset, count, record_count)
|
| 87 |
}
|
| 88 |
return postings, data
|
| 89 |
except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError):
|
|
|
|
| 47 |
return offset, end
|
| 48 |
|
| 49 |
|
| 50 |
+
def _validate_postings(data: bytes, start: int, end: int, record_count: int) -> int:
|
| 51 |
+
"""Count distinct monotonic IDs without allocating a temporary posting set."""
|
| 52 |
+
previous = 0
|
| 53 |
+
last = -1
|
| 54 |
+
count = 0
|
| 55 |
+
value = shift = 0
|
| 56 |
+
for offset in range(start, end):
|
| 57 |
+
byte = data[offset]
|
| 58 |
+
value |= (byte & 0x7F) << shift
|
| 59 |
+
if byte & 0x80:
|
| 60 |
+
shift += 7
|
| 61 |
+
continue
|
| 62 |
+
previous += value
|
| 63 |
+
if previous >= record_count:
|
| 64 |
+
raise ValueError("posting record id out of range")
|
| 65 |
+
if previous != last:
|
| 66 |
+
count += 1
|
| 67 |
+
last = previous
|
| 68 |
+
value = shift = 0
|
| 69 |
+
if shift:
|
| 70 |
+
raise ValueError("truncated varint")
|
| 71 |
+
return count
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _read_posting_entries(data: bytes, offset: int, count: int, record_count: int,
|
| 75 |
+
materialize: bool = True):
|
| 76 |
"""Yield validated entries while leaving storage policy to each loader."""
|
| 77 |
for _ in range(count):
|
| 78 |
key_length, offset = decode_varint(data, offset)
|
|
|
|
| 81 |
posting_count, offset = decode_varint(data, offset)
|
| 82 |
posting_length, offset = decode_varint(data, offset)
|
| 83 |
posting_start, offset = _bounded_slice(data, offset, posting_length)
|
| 84 |
+
decoded = decode_postings(memoryview(data)[posting_start:offset], record_count) if materialize else None
|
| 85 |
+
actual_count = len(decoded) if materialize else _validate_postings(data, posting_start, offset, record_count)
|
| 86 |
+
if actual_count != posting_count:
|
| 87 |
raise ValueError("posting count mismatch")
|
| 88 |
yield key, (posting_start, offset, posting_count), decoded
|
| 89 |
if offset != len(data):
|
|
|
|
| 109 |
return {}, b""
|
| 110 |
postings = {
|
| 111 |
key: location
|
| 112 |
+
for key, location, _ in _read_posting_entries(data, offset, count, record_count, materialize=False)
|
| 113 |
}
|
| 114 |
return postings, data
|
| 115 |
except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError):
|
tests/test_benchmark.py
CHANGED
|
@@ -24,8 +24,10 @@ RESULTS_PATH = os.path.join(os.path.dirname(__file__), "benchmark-results.json")
|
|
| 24 |
|
| 25 |
def _git_sha():
|
| 26 |
try:
|
|
|
|
| 27 |
return subprocess.run(
|
| 28 |
-
["git", "
|
|
|
|
| 29 |
capture_output=True, text=True, timeout=5,
|
| 30 |
).stdout.strip()
|
| 31 |
except Exception:
|
|
|
|
| 24 |
|
| 25 |
def _git_sha():
|
| 26 |
try:
|
| 27 |
+
repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 28 |
return subprocess.run(
|
| 29 |
+
["git", "-c", f"safe.directory={repo}", "-C", repo,
|
| 30 |
+
"log", "-1", "--format=%H"],
|
| 31 |
capture_output=True, text=True, timeout=5,
|
| 32 |
).stdout.strip()
|
| 33 |
except Exception:
|
tests/test_cache_and_malformed.py
CHANGED
|
@@ -159,5 +159,21 @@ class CacheAndMalformedTests(unittest.TestCase):
|
|
| 159 |
actual = app.load_word_index(path, 3, digest)
|
| 160 |
self.assertEqual(actual, {"a": {0, 2}} if entries == valid else {})
|
| 161 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
if __name__ == "__main__":
|
| 163 |
unittest.main()
|
|
|
|
| 159 |
actual = app.load_word_index(path, 3, digest)
|
| 160 |
self.assertEqual(actual, {"a": {0, 2}} if entries == valid else {})
|
| 161 |
|
| 162 |
+
def test_nonmaterialized_posting_validation_matches_set_decoder(self):
|
| 163 |
+
from search_indexes import _validate_postings, decode_postings
|
| 164 |
+
|
| 165 |
+
# Zero deltas may repeat an ID; a continuation must end within this posting.
|
| 166 |
+
cases = [b"", b"\x00\x00", b"\x01\x00\x02", b"\x80\x00",
|
| 167 |
+
b"\x80\x01\x01", b"\x80", b"\x00\x80", b"\xff\x7f"]
|
| 168 |
+
for body in cases:
|
| 169 |
+
with self.subTest(body=body):
|
| 170 |
+
try:
|
| 171 |
+
expected = len(decode_postings(body, 1000))
|
| 172 |
+
except ValueError:
|
| 173 |
+
with self.assertRaises(ValueError):
|
| 174 |
+
_validate_postings(b"prefix" + body + b"\x00", 6, 6 + len(body), 1000)
|
| 175 |
+
else:
|
| 176 |
+
self.assertEqual(_validate_postings(b"prefix" + body + b"suffix", 6, 6 + len(body), 1000), expected)
|
| 177 |
+
|
| 178 |
if __name__ == "__main__":
|
| 179 |
unittest.main()
|
tests/test_reader_backend.py
CHANGED
|
@@ -5,6 +5,8 @@ import contextlib
|
|
| 5 |
import gzip
|
| 6 |
import io
|
| 7 |
import json
|
|
|
|
|
|
|
| 8 |
import struct
|
| 9 |
import threading
|
| 10 |
import time
|
|
@@ -13,6 +15,7 @@ import zipfile
|
|
| 13 |
from pathlib import Path
|
| 14 |
from types import SimpleNamespace
|
| 15 |
from unittest.mock import AsyncMock, patch
|
|
|
|
| 16 |
|
| 17 |
IMPORT_ERROR = None
|
| 18 |
try:
|
|
@@ -49,6 +52,26 @@ def make_zip(files=None, comment=b"", zip64=False):
|
|
| 49 |
|
| 50 |
@unittest.skipIf(app is None, f"backend dependencies unavailable: {IMPORT_ERROR}")
|
| 51 |
class ReaderArchiveValidationTests(unittest.TestCase):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
def test_base36_independent_fixed_vectors(self):
|
| 53 |
for value, expected in ((0, "0"), (35, "z"), (36, "10"), (72, "20"), (1296, "100"), (2**64 - 1, "3w5e11264sgsf")):
|
| 54 |
with self.subTest(value=value):
|
|
|
|
| 5 |
import gzip
|
| 6 |
import io
|
| 7 |
import json
|
| 8 |
+
import random
|
| 9 |
+
import re
|
| 10 |
import struct
|
| 11 |
import threading
|
| 12 |
import time
|
|
|
|
| 15 |
from pathlib import Path
|
| 16 |
from types import SimpleNamespace
|
| 17 |
from unittest.mock import AsyncMock, patch
|
| 18 |
+
from urllib.parse import quote
|
| 19 |
|
| 20 |
IMPORT_ERROR = None
|
| 21 |
try:
|
|
|
|
| 52 |
|
| 53 |
@unittest.skipIf(app is None, f"backend dependencies unavailable: {IMPORT_ERROR}")
|
| 54 |
class ReaderArchiveValidationTests(unittest.TestCase):
|
| 55 |
+
def test_canonical_paths_preserve_character_encoder_semantics(self):
|
| 56 |
+
prefix = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/"
|
| 57 |
+
def reference(value):
|
| 58 |
+
def replace(match):
|
| 59 |
+
token = match.group()
|
| 60 |
+
if re.fullmatch(r"%[0-9a-fA-F]{2}", token):
|
| 61 |
+
char = chr(int(token[1:], 16))
|
| 62 |
+
return char if re.fullmatch(r"[A-Za-z0-9._~-]", char) else token.upper()
|
| 63 |
+
return quote(token, safe="")
|
| 64 |
+
return prefix + re.sub(r"%[0-9a-fA-F]{2}|[^A-Za-z0-9._~/-]", replace, value)
|
| 65 |
+
rng = random.Random(20260927)
|
| 66 |
+
tokens = [chr(i) for i in range(128) if chr(i) not in "?#"]
|
| 67 |
+
tokens += ["\u4e66", "\u00e9", "\U0001f600", "%2f", "%25", "%41", "%7e", "%G0", "%"]
|
| 68 |
+
paths = ["%" + f"{i:02x}" for i in range(256)]
|
| 69 |
+
paths += ["".join(rng.choices(tokens, k=40)) for _ in range(256)]
|
| 70 |
+
for path in paths:
|
| 71 |
+
self.assertEqual(app.canonical_reader_source_url(prefix + path), reference(path))
|
| 72 |
+
for value in ("https://example.com/%ab", prefix + "a?raw=%ab#fragment"):
|
| 73 |
+
self.assertEqual(app.canonical_reader_source_url(value), value)
|
| 74 |
+
|
| 75 |
def test_base36_independent_fixed_vectors(self):
|
| 76 |
for value, expected in ((0, "0"), (35, "z"), (36, "10"), (72, "20"), (1296, "100"), (2**64 - 1, "3w5e11264sgsf")):
|
| 77 |
with self.subTest(value=value):
|