vomebook commited on
Commit ·
0bb3eae
1
Parent(s): f5a2f9a
Optimize search startup and uncached wildcards
Browse filesFiles changed (6)
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071# Local Search Performance, 2026-09-27
These measurements describe the checked-out 97,560-record snapshot on thisdevice (Python 3.10.12), not production latency or cross-site corpus parity.These measurements were collected before release; production acceptance is separate.
## Changes
- Reader source URL normalization quotes the complete path once and normalizes escapes without per-character regular expression compilation/lookup.- Wildcard matching rejects fields missing mandatory literals through the same single-character IGNORECASE regexes before running the bounded bitset NFA.- N-gram admission validates every delta-encoded posting without allocating temporary sets. Word indexes still retain decoded sets. Duplicate-ID counts, truncated varints, out-of-range IDs and trailing data retain their checks.
## Paired Measurements
Wildcard results below are three-run medians with both query caches clearedbefore each measurement. The baseline matcher was loaded from the checkout'sHEAD, and old/new implementations ran alternately in one process. Completeresponses, including every result and total, were identical for all five queries.
| Query | Before (ms) | After (ms) || --- | ---: | ---: || `手*机` | 4912.13 | 246.80 || `手?机` | 5314.72 | 296.78 || `*文*` | 5626.70 | 1125.56 || `A?C` | 5207.27 | 1304.66 || `*` | 3529.14 | 3637.80 |
The small all-wildcard difference is not evidence of an improvement; this casestill returns all records and is dominated by response construction.
N-gram loader A/B used three alternating runs per implementation. Every indexkey, offset, count and retained buffer byte was identical:
| Index | Entries | Before (ms) | After (ms) || --- | ---: | ---: | ---: || 2-gram | 151759 | 5133.24 | 3209.83 || 3-gram | 397957 | 5855.03 | 4026.82 |
Across every local record, canonical paths matched the former encoder exactly:24.076 s before versus 8.017 s after in one full-snapshot comparison.The subsequent same-process startup comparison measured 50.550 s before and32.380 s after, with identical Reader ID indexes and search generation. Itssecond run reused initialized jieba (about 0.639 s in the first run), so thisis not a strict isolated cold-process comparison. The independent optimizedbenchmark startup measured 32.196 s on this device.
## Verification
- Backend fast suite: 241 tests passed before the n-gram change.- N-gram/search/generated-snapshot suites: 67 tests passed after it.- Real-backend HTTP, Chromium and shutdown integration: 12 tests passed.- Local-function, HTTP and Chromium benchmark tiers: all three passed.- Existing wildcard oracle retains Unicode IGNORECASE and newline semantics.- Canonical-path regression covers all 256 escaped bytes, deterministic mixed Unicode/malformed-percent paths and existing shared Reader ID vectors.
Runnable project commands:
```bashHF_SEARCH_RUN_BENCHMARK=1 python3 -B -m unittest tests.test_benchmark -vpython3 -B -m unittest tests.test_search_behavior tests.test_cache_and_malformed tests.test_reader_backend.ReaderArchiveValidationTests -vpython3 -B -m unittest tests.test_generated_data_oracle tests.test_real_integration -v```
The standard repeated-query benchmark median mainly measures cache hits; itsmaximum includes the first computation. Use the explicit uncached A/B aboveto judge matcher cost. Network/DNS/gateway latency is outside these changes.263 unmodified lines26426526626726726826927027126927027127227327427527661 unmodified lines338339340341342343344345346263 unmodified lines def path_replace(match): def token_replace(token_match): token = token_match.group() if re.fullmatch(r"%[0-9a-fA-F]{2}", token): if len(token) == 3: char = chr(int(token[1:], 16)) return char if re.fullmatch(r"[A-Za-z0-9._~-]", char) else token.upper() return quote(token, safe="") return match[1] + re.sub(r"%[0-9a-fA-F]{2}|[^A-Za-z0-9._~/-]", token_replace, match[2]) return char if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._~-" else token.upper() return "%25" # Quote the whole path once; only existing/generated escapes need callbacks. path = quote(match[2], safe="/%") return match[1] + re.sub(r"%[0-9a-fA-F]{2}|%", token_replace, path) return re.sub(r"^(https://huggingface\.co/datasets/VoiceOfML/)([^?#]*)", path_replace, value)
61 unmodified lines start = 1 | ((1 & stars) << 1)
def matches(text): # Every literal is mandatory; C-level scans reject unrelated fields early. if any(regex.search(text) is None for regex, _ in literals): return False active = start if active & end: return True46 unmodified lines4748495051525354555657585960616263646566676869707172735074757677782 unmodified lines818283596084858687888919 unmodified lines1091101118611211311411546 unmodified lines return offset, end
def _validate_postings(data: bytes, start: int, end: int, record_count: int) -> int: """Count distinct monotonic IDs without allocating a temporary posting set.""" previous = 0 last = -1 count = 0 value = shift = 0 for offset in range(start, end): byte = data[offset] value |= (byte & 0x7F) << shift if byte & 0x80: shift += 7 continue previous += value if previous >= record_count: raise ValueError("posting record id out of range") if previous != last: count += 1 last = previous value = shift = 0 if shift: raise ValueError("truncated varint") return count
def _read_posting_entries(data: bytes, offset: int, count: int, record_count: int):def _read_posting_entries(data: bytes, offset: int, count: int, record_count: int, materialize: bool = True): """Yield validated entries while leaving storage policy to each loader.""" for _ in range(count): key_length, offset = decode_varint(data, offset)2 unmodified lines posting_count, offset = decode_varint(data, offset) posting_length, offset = decode_varint(data, offset) posting_start, offset = _bounded_slice(data, offset, posting_length) decoded = decode_postings(memoryview(data)[posting_start:offset], record_count) if len(decoded) != posting_count: decoded = decode_postings(memoryview(data)[posting_start:offset], record_count) if materialize else None actual_count = len(decoded) if materialize else _validate_postings(data, posting_start, offset, record_count) if actual_count != posting_count: raise ValueError("posting count mismatch") yield key, (posting_start, offset, posting_count), decoded if offset != len(data):19 unmodified lines return {}, b"" postings = { key: location for key, location, _ in _read_posting_entries(data, offset, count, record_count) for key, location, _ in _read_posting_entries(data, offset, count, record_count, materialize=False) } return postings, data except (OSError, ValueError, UnicodeDecodeError, EOFError, IndexError, OverflowError):23 unmodified lines242526272829283031323323 unmodified lines
def _git_sha(): try: repo = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) return subprocess.run( ["git", "-c", f"safe.directory={repo}", "-C", repo, ["git", "log", "-1", "--format=%H"], "log", "-1", "--format=%H"], capture_output=True, text=True, timeout=5, ).stdout.strip() except Exception:158 unmodified lines159160161162163164165166167168169170171172173174175176177178179158 unmodified lines actual = app.load_word_index(path, 3, digest) self.assertEqual(actual, {"a": {0, 2}} if entries == valid else {})
def test_nonmaterialized_posting_validation_matches_set_decoder(self): from search_indexes import _validate_postings, decode_postings
# Zero deltas may repeat an ID; a continuation must end within this posting. cases = [b"", b"\x00\x00", b"\x01\x00\x02", b"\x80\x00", b"\x80\x01\x01", b"\x80", b"\x00\x80", b"\xff\x7f"] for body in cases: with self.subTest(body=body): try: expected = len(decode_postings(body, 1000)) except ValueError: with self.assertRaises(ValueError): _validate_postings(b"prefix" + body + b"\x00", 6, 6 + len(body), 1000) else: self.assertEqual(_validate_postings(b"prefix" + body + b"suffix", 6, 6 + len(body), 1000), expected)
if __name__ == "__main__": unittest.main()4 unmodified lines567891011122 unmodified lines1516171819202130 unmodified lines52535455565758596061626364656667686970717273747576774 unmodified linesimport gzipimport ioimport jsonimport randomimport reimport structimport threadingimport time2 unmodified linesfrom pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, patchfrom urllib.parse import quote
IMPORT_ERROR = Nonetry:30 unmodified lines
@unittest.skipIf(app is None, f"backend dependencies unavailable: {IMPORT_ERROR}")class ReaderArchiveValidationTests(unittest.TestCase): def test_canonical_paths_preserve_character_encoder_semantics(self): prefix = "https://huggingface.co/datasets/VoiceOfML/Test/resolve/main/" def reference(value): def replace(match): token = match.group() if re.fullmatch(r"%[0-9a-fA-F]{2}", token): char = chr(int(token[1:], 16)) return char if re.fullmatch(r"[A-Za-z0-9._~-]", char) else token.upper() return quote(token, safe="") return prefix + re.sub(r"%[0-9a-fA-F]{2}|[^A-Za-z0-9._~/-]", replace, value) rng = random.Random(20260927) tokens = [chr(i) for i in range(128) if chr(i) not in "?#"] tokens += ["\u4e66", "\u00e9", "\U0001f600", "%2f", "%25", "%41", "%7e", "%G0", "%"] paths = ["%" + f"{i:02x}" for i in range(256)] paths += ["".join(rng.choices(tokens, k=40)) for _ in range(256)] for path in paths: self.assertEqual(app.canonical_reader_source_url(prefix + path), reference(path)) for value in ("https://example.com/%ab", prefix + "a?raw=%ab#fragment"): self.assertEqual(app.canonical_reader_source_url(value), value)
def test_base36_independent_fixed_vectors(self): for value, expected in ((0, "0"), (35, "z"), (36, "10"), (72, "20"), (1296, "100"), (2**64 - 1, "3w5e11264sgsf")): with self.subTest(value=value):SEARCH_PERFORMANCE_REPORT.mdAdded+71
app.py+9-4
search_indexes.py+30-4
tests/test_benchmark.py+3-1
tests/test_cache_and_malformed.py+16
tests/test_reader_backend.py+23