vomebook commited on
Commit ·
794135c
1
Parent(s): aecabd8
Add verified offline Space search compute benchmark
Browse files
Dockerfile
CHANGED
|
@@ -34,6 +34,7 @@ RUN python -B scripts/check_python_static.py \
|
|
| 34 |
&& python -B -m unittest -v \
|
| 35 |
tests.search.backend.test_search_data_selector \
|
| 36 |
tests.search.backend.test_search_data_selector_faults \
|
|
|
|
| 37 |
tests.search.backend.test_search_runtime_entry \
|
| 38 |
tests.search.backend.test_search_start_script
|
| 39 |
|
|
|
|
| 34 |
&& python -B -m unittest -v \
|
| 35 |
tests.search.backend.test_search_data_selector \
|
| 36 |
tests.search.backend.test_search_data_selector_faults \
|
| 37 |
+
tests.performance.test_search_compute_benchmark \
|
| 38 |
tests.search.backend.test_search_runtime_entry \
|
| 39 |
tests.search.backend.test_search_start_script
|
| 40 |
|
scripts/benchmarks/benchmark_search_compute.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Opt-in local Space search-order compute benchmark, with verified input.
|
| 2 |
+
|
| 3 |
+
Obtain the expected identity independently (or inspect a trusted local copy via
|
| 4 |
+
python -m scripts.search_data_config DIRECTORY), then run from any directory:
|
| 5 |
+
|
| 6 |
+
python -B scripts/benchmarks/benchmark_search_compute.py \
|
| 7 |
+
--data-dir DIRECTORY --generation EXPECTED_SHA256 --iterations 7
|
| 8 |
+
|
| 9 |
+
The directory must remain immutable throughout the run. The selector checks
|
| 10 |
+
manifest identity and all Space members, but does not authenticate their origin
|
| 11 |
+
or prove every posting's semantics. No data or book bodies are fetched or
|
| 12 |
+
written. The generation's parent must be writable for Jieba's private,
|
| 13 |
+
temporary dictionary cache, which is discarded afterwards.
|
| 14 |
+
|
| 15 |
+
Each query has one untimed warmup and 1-100 timed warm in-process uncached
|
| 16 |
+
orders, in fixed order. This bypasses response/order caches, pagination, API
|
| 17 |
+
validation, executor queues, HTTP, network, browsers and rendering. It is not a
|
| 18 |
+
request or production latency measurement, a performance comparison, or an
|
| 19 |
+
independent search-correctness oracle. Complete orders are compared with the
|
| 20 |
+
warmup and hashed, not printed.
|
| 21 |
+
"""
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import argparse
|
| 25 |
+
from collections.abc import Sequence
|
| 26 |
+
from contextlib import redirect_stdout
|
| 27 |
+
import gzip
|
| 28 |
+
import hashlib
|
| 29 |
+
import json
|
| 30 |
+
import os
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
import platform
|
| 33 |
+
import statistics
|
| 34 |
+
import sys
|
| 35 |
+
import tempfile
|
| 36 |
+
import time
|
| 37 |
+
from typing import NoReturn
|
| 38 |
+
from unittest.mock import patch
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 42 |
+
if __name__ == "__main__":
|
| 43 |
+
sys.dont_write_bytecode = True
|
| 44 |
+
sys.path.insert(0, str(ROOT))
|
| 45 |
+
|
| 46 |
+
from backend.search_data_selector import SelectedGeneration, inspect_generation # noqa: E402
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
CASES = (
|
| 50 |
+
("手机", True), ("手机", False), ("文化革命", True), ("社会主义", False),
|
| 51 |
+
("手机 pdf", True), ("马克思 文", True), ("文化革命*.pdf", True),
|
| 52 |
+
("马克思*.pdf", True), ("?*.pdf", True), ("*.pdf", True), ("*.epub", True),
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def sha256_file(path: Path) -> str:
|
| 57 |
+
digest = hashlib.sha256()
|
| 58 |
+
with path.open("rb") as stream:
|
| 59 |
+
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
|
| 60 |
+
digest.update(chunk)
|
| 61 |
+
return digest.hexdigest()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def source_hashes() -> dict[str, str]:
|
| 65 |
+
paths = sorted((ROOT / "backend").glob("*.py")) + [
|
| 66 |
+
ROOT / "backend/native/search_index_native.c",
|
| 67 |
+
ROOT / "requirements.txt",
|
| 68 |
+
ROOT / "static/index.html",
|
| 69 |
+
Path(__file__),
|
| 70 |
+
]
|
| 71 |
+
return {path.relative_to(ROOT).as_posix(): sha256_file(path) for path in paths}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def unique_json_object(pairs: list[tuple[str, object]]) -> dict[str, object]:
|
| 75 |
+
result: dict[str, object] = {}
|
| 76 |
+
for key, value in pairs:
|
| 77 |
+
if key in result:
|
| 78 |
+
raise ValueError(f"duplicate manifest key: {key}")
|
| 79 |
+
result[key] = value
|
| 80 |
+
return result
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def reject_json_constant(value: str) -> NoReturn:
|
| 84 |
+
raise ValueError(f"invalid manifest JSON constant: {value}")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def select_generation(directory: Path, generation: str) -> tuple[SelectedGeneration, bytes, dict[str, dict[str, object]]]:
|
| 88 |
+
"""Use the same complete, fail-closed verifier as the Space entry point."""
|
| 89 |
+
manifest_path = directory / "generation-manifest.json"
|
| 90 |
+
if manifest_path.is_symlink() or not manifest_path.is_file() or manifest_path.stat().st_size > 1024 * 1024:
|
| 91 |
+
raise ValueError("missing or oversized generation manifest")
|
| 92 |
+
manifest_bytes = manifest_path.read_bytes()
|
| 93 |
+
manifest = json.loads(manifest_bytes, object_pairs_hook=unique_json_object, parse_constant=reject_json_constant)
|
| 94 |
+
if (not isinstance(manifest, dict) or type(manifest.get("version")) is not int
|
| 95 |
+
or type(manifest.get("record_count")) is not int or manifest["record_count"] < 1):
|
| 96 |
+
raise ValueError("invalid generation manifest version or record count")
|
| 97 |
+
selected = inspect_generation(directory, generation)
|
| 98 |
+
if manifest_path.read_bytes() != manifest_bytes:
|
| 99 |
+
raise ValueError("generation manifest changed during verification")
|
| 100 |
+
files: dict[str, dict[str, object]] = manifest["files"]["space"]
|
| 101 |
+
return selected, manifest_bytes, files
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def verify_unchanged(selected: SelectedGeneration, manifest: bytes, files: dict[str, dict[str, object]]) -> None:
|
| 105 |
+
"""Detect changes around loading/measurement, including the manifest itself."""
|
| 106 |
+
root = selected.directory
|
| 107 |
+
manifest_path = root / "generation-manifest.json"
|
| 108 |
+
if manifest_path.is_symlink() or manifest_path.read_bytes() != manifest:
|
| 109 |
+
raise RuntimeError("generation manifest changed during benchmark")
|
| 110 |
+
actual: set[str] = set()
|
| 111 |
+
for path in root.rglob("*"):
|
| 112 |
+
if path.is_symlink():
|
| 113 |
+
raise RuntimeError("generation contains a symlink")
|
| 114 |
+
if path.is_file() and path != manifest_path:
|
| 115 |
+
actual.add(path.relative_to(root).as_posix())
|
| 116 |
+
elif not path.is_dir() and path != manifest_path:
|
| 117 |
+
raise RuntimeError("generation contains a non-file object")
|
| 118 |
+
if actual != set(files):
|
| 119 |
+
raise RuntimeError("generation members changed during benchmark")
|
| 120 |
+
for name, metadata in files.items():
|
| 121 |
+
path = root / name
|
| 122 |
+
if not path.is_file() or path.stat().st_size != metadata["bytes"] or sha256_file(path) != metadata["sha256"]:
|
| 123 |
+
raise RuntimeError(f"generation member changed during benchmark: {name}")
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def configure_paths(root: Path) -> None:
|
| 127 |
+
"""Match all generation-owned paths selected by search_runtime_entry."""
|
| 128 |
+
from backend import app
|
| 129 |
+
|
| 130 |
+
app.DATA_PATH = root / "search_data.json.gz"
|
| 131 |
+
app.NGRAM_PATHS = {2: root / "search_ngrams_2.bin.gz", 3: root / "search_ngrams_3.bin.gz"}
|
| 132 |
+
app.WORD_INDEX_PATH = root / "search_words.bin.gz"
|
| 133 |
+
app.FOLDER_TREE_PATH = root / "folder_tree.json.gz"
|
| 134 |
+
app.FOLDER_BROWSER_PATH = root / "folder_browser.json.gz"
|
| 135 |
+
app.SIDEBAR_DATA_PATH = root / "sidebar"
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def require_paths(selected: SelectedGeneration) -> None:
|
| 139 |
+
from backend import app
|
| 140 |
+
|
| 141 |
+
root = selected.directory
|
| 142 |
+
if (app.DATA_PATH != root / "search_data.json.gz"
|
| 143 |
+
or app.NGRAM_PATHS != {2: root / "search_ngrams_2.bin.gz", 3: root / "search_ngrams_3.bin.gz"}
|
| 144 |
+
or app.WORD_INDEX_PATH != root / "search_words.bin.gz"
|
| 145 |
+
or app.FOLDER_TREE_PATH != root / "folder_tree.json.gz"
|
| 146 |
+
or app.FOLDER_BROWSER_PATH != root / "folder_browser.json.gz"
|
| 147 |
+
or app.SIDEBAR_DATA_PATH != root / "sidebar"):
|
| 148 |
+
raise RuntimeError("application paths do not match selected generation")
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def require_loaded(selected: SelectedGeneration) -> None:
|
| 152 |
+
from backend import app
|
| 153 |
+
|
| 154 |
+
require_paths(selected)
|
| 155 |
+
if (len(app.records) != selected.record_count or not app.word_index or not app.word_index_buffer
|
| 156 |
+
or any(not app.ngram_postings.get(width) or not app.ngram_posting_buffers.get(width) for width in (2, 3))):
|
| 157 |
+
raise RuntimeError("selected generation did not load all records and generated indexes")
|
| 158 |
+
raw = gzip.decompress(app.DATA_PATH.read_bytes())
|
| 159 |
+
expected = app.search_data_generation(raw, [app.WORD_INDEX_PATH, *app.NGRAM_PATHS.values()])
|
| 160 |
+
if app.search_generation() != expected:
|
| 161 |
+
raise RuntimeError("loaded API fingerprint does not match selected corpus and indexes")
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def order_hash(order: Sequence[int]) -> str:
|
| 165 |
+
"""SHA-256 of compact ASCII JSON array of all zero-based corpus indices."""
|
| 166 |
+
return hashlib.sha256(json.dumps(list(order), separators=(",", ":")).encode("ascii")).hexdigest()
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def measure_orders(iterations: int) -> list[dict[str, object]]:
|
| 170 |
+
from backend import app
|
| 171 |
+
|
| 172 |
+
rows: list[dict[str, object]] = []
|
| 173 |
+
for query, exact in CASES:
|
| 174 |
+
expected = list(app._search_order_uncached(q=query, exact=exact))
|
| 175 |
+
timings: list[float] = []
|
| 176 |
+
for _ in range(iterations):
|
| 177 |
+
started = time.perf_counter()
|
| 178 |
+
order = list(app._search_order_uncached(q=query, exact=exact))
|
| 179 |
+
timings.append((time.perf_counter() - started) * 1000)
|
| 180 |
+
if order != expected:
|
| 181 |
+
raise RuntimeError(f"unstable complete order: {query!r}, exact={exact}")
|
| 182 |
+
rows.append({"query": query, "exact": exact, "total": len(expected),
|
| 183 |
+
"order_sha256": order_hash(expected), "median_ms": statistics.median(timings),
|
| 184 |
+
"min_ms": min(timings), "max_ms": max(timings)})
|
| 185 |
+
return rows
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
| 189 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 190 |
+
parser.add_argument("--data-dir", type=Path, required=True, help="immutable materialized Space generation")
|
| 191 |
+
parser.add_argument("--generation", required=True, help="independently expected generation SHA-256")
|
| 192 |
+
parser.add_argument("--iterations", type=int, default=7, help="timed iterations per query, 1-100")
|
| 193 |
+
options = parser.parse_args(argv)
|
| 194 |
+
if not 1 <= options.iterations <= 100:
|
| 195 |
+
parser.error("--iterations must be between 1 and 100")
|
| 196 |
+
return options
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def main(argv: Sequence[str] | None = None) -> int:
|
| 200 |
+
options = parse_args(argv)
|
| 201 |
+
selected, manifest, files = select_generation(options.data_dir, options.generation)
|
| 202 |
+
sources = source_hashes()
|
| 203 |
+
# Application import mounts static files relative to the checkout root.
|
| 204 |
+
os.chdir(ROOT)
|
| 205 |
+
from backend import app, search_indexes
|
| 206 |
+
|
| 207 |
+
if Path(app.__file__).resolve() != ROOT / "backend/app.py":
|
| 208 |
+
raise RuntimeError("application imported from a different checkout")
|
| 209 |
+
if search_indexes.WORD_INDEX_TOKENIZER != f"jieba-{app.jieba.__version__}-cjk-char-v1":
|
| 210 |
+
raise RuntimeError("installed Jieba version does not match generated index tokenizer")
|
| 211 |
+
if app.jieba.dt.initialized or app.jieba.dt.dictionary is not None:
|
| 212 |
+
raise RuntimeError("benchmark requires a fresh default Jieba tokenizer")
|
| 213 |
+
with app.jieba.dt.get_dict_file() as dictionary:
|
| 214 |
+
dictionary_sha = hashlib.sha256(dictionary.read()).hexdigest()
|
| 215 |
+
native = search_indexes._native_index
|
| 216 |
+
native_file = Path(native.__file__) if native is not None else None
|
| 217 |
+
native_sha = sha256_file(native_file) if native_file is not None else None
|
| 218 |
+
configure_paths(selected.directory)
|
| 219 |
+
require_paths(selected)
|
| 220 |
+
# Resolve an existing parent without gettempdir()'s write probe, and pass
|
| 221 |
+
# it explicitly to TemporaryDirectory so no writes touch the generation.
|
| 222 |
+
temp_root = selected.directory.parent
|
| 223 |
+
if temp_root == selected.directory or temp_root.is_relative_to(selected.directory):
|
| 224 |
+
raise RuntimeError("temporary cache directory must be outside selected generation")
|
| 225 |
+
with tempfile.TemporaryDirectory(prefix="space-bench-jieba-", dir=temp_root) as cache_dir:
|
| 226 |
+
app.jieba.dt.tmp_dir = cache_dir
|
| 227 |
+
# A missing word index would otherwise be rebuilt silently by load_data.
|
| 228 |
+
with patch.object(app, "build_word_index", side_effect=RuntimeError("generated word index not loaded")):
|
| 229 |
+
started = time.perf_counter()
|
| 230 |
+
with redirect_stdout(sys.stderr):
|
| 231 |
+
app.load_data()
|
| 232 |
+
startup_ms = (time.perf_counter() - started) * 1000
|
| 233 |
+
require_loaded(selected)
|
| 234 |
+
if not app.jieba.dt.initialized:
|
| 235 |
+
raise RuntimeError("Jieba tokenizer was not initialized")
|
| 236 |
+
verify_unchanged(selected, manifest, files)
|
| 237 |
+
rows = measure_orders(options.iterations)
|
| 238 |
+
verify_unchanged(selected, manifest, files)
|
| 239 |
+
require_loaded(selected)
|
| 240 |
+
with app.jieba.dt.get_dict_file() as dictionary:
|
| 241 |
+
if hashlib.sha256(dictionary.read()).hexdigest() != dictionary_sha:
|
| 242 |
+
raise RuntimeError("tokenizer dictionary changed during benchmark")
|
| 243 |
+
if source_hashes() != sources or (native_file is not None and sha256_file(native_file) != native_sha):
|
| 244 |
+
raise RuntimeError("source or native module changed during benchmark")
|
| 245 |
+
report = {
|
| 246 |
+
"scope": "warm in-process uncached search orders; fixed query order, one untimed warmup per query; "
|
| 247 |
+
"no response/order cache, API, executor queue, HTTP, network, browser or rendering; "
|
| 248 |
+
"not production latency, a comparison, or an independent correctness oracle",
|
| 249 |
+
"input_assurance": "manifest and all Space files verified; identity is not authenticated provenance; "
|
| 250 |
+
"index format/corpus linkage checked, full posting semantics not independently proven; "
|
| 251 |
+
"directory must remain immutable during run",
|
| 252 |
+
"generation": selected.generation,
|
| 253 |
+
"data_dir": str(selected.directory),
|
| 254 |
+
"manifest_sha256": hashlib.sha256(manifest).hexdigest(),
|
| 255 |
+
"space_files": files,
|
| 256 |
+
"records": len(app.records),
|
| 257 |
+
"api_generation": app.search_generation(),
|
| 258 |
+
"source_sha256": sources,
|
| 259 |
+
"python": sys.version,
|
| 260 |
+
"platform": platform.platform(),
|
| 261 |
+
"machine": platform.machine(),
|
| 262 |
+
"tokenizer": {"name": "jieba", "version": app.jieba.__version__, "initialized": app.jieba.dt.initialized,
|
| 263 |
+
"dictionary_sha256": dictionary_sha, "index_format": search_indexes.WORD_INDEX_TOKENIZER,
|
| 264 |
+
"cache": "private temporary cache from default dictionary"},
|
| 265 |
+
"native": {"loaded": native is not None, "sha256": native_sha,
|
| 266 |
+
"note": "binary and source hashes do not establish build provenance",
|
| 267 |
+
"read_entries": search_indexes._native_read_entries is not None,
|
| 268 |
+
"decode_postings": search_indexes._native_decode_postings is not None},
|
| 269 |
+
"iterations": options.iterations,
|
| 270 |
+
"warmups_per_query": 1,
|
| 271 |
+
"startup_ms_single_observation_not_container_cold_start": startup_ms,
|
| 272 |
+
"order_hash_format": "sha256 of compact ASCII JSON array of all zero-based corpus indices",
|
| 273 |
+
"queries": rows,
|
| 274 |
+
}
|
| 275 |
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
| 276 |
+
return 0
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
if __name__ == "__main__":
|
| 280 |
+
raise SystemExit(main())
|
tests/gates/ci-test-inventory.json
CHANGED
|
@@ -122,6 +122,10 @@
|
|
| 122 |
"kind": "direct",
|
| 123 |
"source": "@reader-workflow"
|
| 124 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
"tests/proxy/test_async_proxy.py": {
|
| 126 |
"kind": "direct",
|
| 127 |
"source": "@reader-workflow"
|
|
|
|
| 122 |
"kind": "direct",
|
| 123 |
"source": "@reader-workflow"
|
| 124 |
},
|
| 125 |
+
"tests/performance/test_search_compute_benchmark.py": {
|
| 126 |
+
"kind": "direct",
|
| 127 |
+
"source": "Dockerfile"
|
| 128 |
+
},
|
| 129 |
"tests/proxy/test_async_proxy.py": {
|
| 130 |
"kind": "direct",
|
| 131 |
"source": "@reader-workflow"
|
tests/performance/test_search_compute_benchmark.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synthetic offline contracts for the opt-in Space compute benchmark."""
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import subprocess
|
| 7 |
+
import sys
|
| 8 |
+
import tempfile
|
| 9 |
+
import unittest
|
| 10 |
+
from unittest.mock import patch
|
| 11 |
+
|
| 12 |
+
from backend import app
|
| 13 |
+
from scripts.benchmarks import benchmark_search_compute as bench
|
| 14 |
+
from tests.search.backend.test_search_data_selector import encode, fixture
|
| 15 |
+
from tests.search.backend import test_search_data_selector_faults as selector_faults
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SearchComputeBenchmarkTests(unittest.TestCase):
|
| 19 |
+
def setUp(self):
|
| 20 |
+
self.temp = tempfile.TemporaryDirectory(prefix="space-benchmark-fixture-")
|
| 21 |
+
self.addCleanup(self.temp.cleanup)
|
| 22 |
+
self.root = Path(self.temp.name) / "generation"
|
| 23 |
+
self.generation = fixture(self.root)
|
| 24 |
+
|
| 25 |
+
def run_cli(self, *arguments):
|
| 26 |
+
return subprocess.run([sys.executable, "-B", str(bench.ROOT / "scripts/benchmarks/benchmark_search_compute.py"),
|
| 27 |
+
*map(str, arguments)], cwd=self.root.parent, text=True,
|
| 28 |
+
capture_output=True, timeout=90, check=False)
|
| 29 |
+
|
| 30 |
+
def cli_args(self):
|
| 31 |
+
return ("--data-dir", self.root, "--generation", self.generation, "--iterations", "2")
|
| 32 |
+
|
| 33 |
+
def test_actual_cli_uses_selected_generation_from_another_working_directory(self):
|
| 34 |
+
result = self.run_cli(*self.cli_args())
|
| 35 |
+
self.assertEqual(result.returncode, 0, result.stderr)
|
| 36 |
+
report = json.loads(result.stdout)
|
| 37 |
+
self.assertEqual(report["data_dir"], str(self.root))
|
| 38 |
+
self.assertEqual(report["generation"], self.generation)
|
| 39 |
+
self.assertEqual((report["records"], report["iterations"], report["warmups_per_query"]), (1, 2, 1))
|
| 40 |
+
manifest = json.loads((self.root / "generation-manifest.json").read_bytes())
|
| 41 |
+
self.assertEqual(report["space_files"], manifest["files"]["space"])
|
| 42 |
+
self.assertEqual(report["manifest_sha256"], hashlib.sha256(encode(manifest)).hexdigest())
|
| 43 |
+
self.assertEqual(report["source_sha256"]["backend/app.py"], bench.sha256_file(bench.ROOT / "backend/app.py"))
|
| 44 |
+
self.assertTrue(report["tokenizer"]["initialized"])
|
| 45 |
+
self.assertEqual(report["tokenizer"]["version"], app.jieba.__version__)
|
| 46 |
+
self.assertEqual(len(report["queries"]), len(bench.CASES))
|
| 47 |
+
# *.pdf really searches the selected one-record fixture, not bundled data.
|
| 48 |
+
pdf = next(row for row in report["queries"] if row["query"] == "*.pdf")
|
| 49 |
+
self.assertEqual((pdf["total"], pdf["order_sha256"]), (1, bench.order_hash([0])))
|
| 50 |
+
self.assertIn("uncached", report["scope"])
|
| 51 |
+
self.assertIn("not production latency", report["scope"])
|
| 52 |
+
self.assertIn("not independently proven", report["input_assurance"])
|
| 53 |
+
self.assertFalse((self.root / "jieba.cache").exists())
|
| 54 |
+
|
| 55 |
+
def test_cli_succeeds_when_all_network_connections_are_blocked(self):
|
| 56 |
+
program = '''
|
| 57 |
+
import runpy, socket, sys
|
| 58 |
+
from unittest.mock import patch
|
| 59 |
+
sys.argv = [script, "--data-dir", directory, "--generation", generation, "--iterations", "1"]
|
| 60 |
+
with patch.object(socket.socket, "connect", side_effect=RuntimeError("network forbidden")), \\
|
| 61 |
+
patch.object(socket.socket, "connect_ex", side_effect=RuntimeError("network forbidden")), \\
|
| 62 |
+
patch.object(socket, "getaddrinfo", side_effect=RuntimeError("network forbidden")):
|
| 63 |
+
runpy.run_path(script, run_name="__main__")
|
| 64 |
+
'''
|
| 65 |
+
prefix = (f"script={str(bench.ROOT / 'scripts/benchmarks/benchmark_search_compute.py')!r}\n"
|
| 66 |
+
f"directory={str(self.root)!r}\ngeneration={self.generation!r}\n")
|
| 67 |
+
result = subprocess.run([sys.executable, "-B", "-c", prefix + program], cwd=self.root.parent,
|
| 68 |
+
capture_output=True, text=True, timeout=90, check=False)
|
| 69 |
+
self.assertEqual(result.returncode, 0, result.stderr)
|
| 70 |
+
self.assertEqual(json.loads(result.stdout)["generation"], self.generation)
|
| 71 |
+
|
| 72 |
+
def test_temporary_cache_ignores_environment_inside_generation(self):
|
| 73 |
+
program = '''
|
| 74 |
+
import runpy, sys, tempfile
|
| 75 |
+
sys.argv = [script, "--data-dir", directory, "--generation", generation]
|
| 76 |
+
def forbidden_probe():
|
| 77 |
+
raise AssertionError("unexpected tempdir probe")
|
| 78 |
+
tempfile.gettempdir = forbidden_probe
|
| 79 |
+
runpy.run_path(script, run_name="__main__")
|
| 80 |
+
'''
|
| 81 |
+
prefix = (f"script={str(bench.ROOT / 'scripts/benchmarks/benchmark_search_compute.py')!r}\n"
|
| 82 |
+
f"directory={str(self.root)!r}\ngeneration={self.generation!r}\n")
|
| 83 |
+
result = subprocess.run([sys.executable, "-B", "-c", prefix + program], cwd=self.root.parent,
|
| 84 |
+
env={**os.environ, "TMPDIR": str(self.root)},
|
| 85 |
+
capture_output=True, text=True, timeout=30, check=False)
|
| 86 |
+
self.assertEqual(result.returncode, 0, result.stderr)
|
| 87 |
+
self.assertEqual(json.loads(result.stdout)["generation"], self.generation)
|
| 88 |
+
self.assertFalse(list(self.root.glob("space-bench-jieba-*")))
|
| 89 |
+
self.assertFalse(list(self.root.parent.glob("space-bench-jieba-*")))
|
| 90 |
+
|
| 91 |
+
def test_required_options_and_iteration_boundaries(self):
|
| 92 |
+
for value in ("1", "100"):
|
| 93 |
+
options = bench.parse_args(["--data-dir", str(self.root), "--generation", self.generation,
|
| 94 |
+
"--iterations", value])
|
| 95 |
+
self.assertEqual(options.iterations, int(value))
|
| 96 |
+
for args in ([], ["--data-dir", str(self.root)],
|
| 97 |
+
["--generation", self.generation],
|
| 98 |
+
["--data-dir", str(self.root), "--generation", self.generation, "--iterations", "0"],
|
| 99 |
+
["--data-dir", str(self.root), "--generation", self.generation, "--iterations", "101"],
|
| 100 |
+
["--data-dir", str(self.root), "--generation", self.generation, "--iterations", "oops"]):
|
| 101 |
+
with self.subTest(args=args), patch("sys.stderr"), self.assertRaises(SystemExit) as stopped:
|
| 102 |
+
bench.parse_args(args)
|
| 103 |
+
self.assertEqual(stopped.exception.code, 2)
|
| 104 |
+
result = self.run_cli("--data-dir", self.root, "--generation", self.generation, "--iterations", "0")
|
| 105 |
+
self.assertNotEqual(result.returncode, 0)
|
| 106 |
+
self.assertIn("between 1 and 100", result.stderr)
|
| 107 |
+
self.assertEqual(result.stdout, "")
|
| 108 |
+
|
| 109 |
+
def test_missing_corrupt_or_wrong_generation_fails_before_importing_app(self):
|
| 110 |
+
result = self.run_cli("--data-dir", self.root, "--generation", "f" * 64)
|
| 111 |
+
self.assertNotEqual(result.returncode, 0)
|
| 112 |
+
self.assertEqual(result.stdout, "")
|
| 113 |
+
self.assertIn("invalid search generation manifest", result.stderr)
|
| 114 |
+
for name in ("search_data.json.gz", "search_words.bin.gz", "search_ngrams_2.bin.gz",
|
| 115 |
+
"search_ngrams_3.bin.gz", "folder_tree.json.gz", "folder_browser.json.gz"):
|
| 116 |
+
path = self.root / name
|
| 117 |
+
original = path.read_bytes()
|
| 118 |
+
with self.subTest(missing=name):
|
| 119 |
+
path.unlink()
|
| 120 |
+
result = self.run_cli(*self.cli_args())
|
| 121 |
+
self.assertNotEqual(result.returncode, 0)
|
| 122 |
+
self.assertEqual(result.stdout, "")
|
| 123 |
+
self.assertIn("missing or unlisted", result.stderr)
|
| 124 |
+
path.write_bytes(original)
|
| 125 |
+
with self.subTest(corrupt=name):
|
| 126 |
+
path.write_bytes(bytes([original[0] ^ 1]) + original[1:])
|
| 127 |
+
result = self.run_cli(*self.cli_args())
|
| 128 |
+
self.assertNotEqual(result.returncode, 0)
|
| 129 |
+
self.assertEqual(result.stdout, "")
|
| 130 |
+
self.assertIn("digest mismatch", result.stderr)
|
| 131 |
+
path.write_bytes(original)
|
| 132 |
+
|
| 133 |
+
def test_manifest_tampering_missing_symlink_and_record_count_are_rejected(self):
|
| 134 |
+
manifest_path = self.root / "generation-manifest.json"
|
| 135 |
+
original = manifest_path.read_bytes()
|
| 136 |
+
manifest = json.loads(original)
|
| 137 |
+
manifest["record_count"] = 2
|
| 138 |
+
manifest_path.write_bytes(encode(manifest))
|
| 139 |
+
result = self.run_cli(*self.cli_args())
|
| 140 |
+
self.assertNotEqual(result.returncode, 0)
|
| 141 |
+
self.assertIn("identity mismatch", result.stderr)
|
| 142 |
+
# Even a recomputed identity must agree with the actual corpus count.
|
| 143 |
+
excluded = {"generation", "remote_writes", "publication_ready", "object_layout", "objects", "additional_checks"}
|
| 144 |
+
manifest["generation"] = hashlib.sha256(encode({k: v for k, v in manifest.items() if k not in excluded})).hexdigest()
|
| 145 |
+
manifest_path.write_bytes(encode(manifest))
|
| 146 |
+
result = self.run_cli("--data-dir", self.root, "--generation", manifest["generation"])
|
| 147 |
+
self.assertNotEqual(result.returncode, 0)
|
| 148 |
+
self.assertIn("record count mismatch", result.stderr)
|
| 149 |
+
manifest_path.unlink()
|
| 150 |
+
result = self.run_cli(*self.cli_args())
|
| 151 |
+
self.assertNotEqual(result.returncode, 0)
|
| 152 |
+
self.assertIn("missing or oversized", result.stderr)
|
| 153 |
+
other = self.root.parent / "manifest"
|
| 154 |
+
other.write_bytes(original)
|
| 155 |
+
manifest_path.symlink_to(other)
|
| 156 |
+
result = self.run_cli(*self.cli_args())
|
| 157 |
+
self.assertNotEqual(result.returncode, 0)
|
| 158 |
+
self.assertIn("missing or oversized", result.stderr)
|
| 159 |
+
|
| 160 |
+
def test_noncanonical_manifest_types_and_duplicate_keys_are_rejected(self):
|
| 161 |
+
manifest_path = self.root / "generation-manifest.json"
|
| 162 |
+
original = manifest_path.read_bytes()
|
| 163 |
+
manifest = json.loads(original)
|
| 164 |
+
for key in ("version", "record_count"):
|
| 165 |
+
modified = {**manifest, key: True}
|
| 166 |
+
excluded = {"generation", "remote_writes", "publication_ready", "object_layout", "objects", "additional_checks"}
|
| 167 |
+
modified["generation"] = hashlib.sha256(encode({k: v for k, v in modified.items() if k not in excluded})).hexdigest()
|
| 168 |
+
manifest_path.write_bytes(encode(modified))
|
| 169 |
+
result = self.run_cli("--data-dir", self.root, "--generation", modified["generation"])
|
| 170 |
+
self.assertNotEqual(result.returncode, 0)
|
| 171 |
+
self.assertIn("invalid generation manifest version or record count", result.stderr)
|
| 172 |
+
manifest_path.write_bytes(b'{"version":1,' + original[1:])
|
| 173 |
+
result = self.run_cli(*self.cli_args())
|
| 174 |
+
self.assertNotEqual(result.returncode, 0)
|
| 175 |
+
self.assertIn("duplicate manifest key", result.stderr)
|
| 176 |
+
manifest_path.write_bytes(b'{"extra":NaN,' + original[1:])
|
| 177 |
+
result = self.run_cli(*self.cli_args())
|
| 178 |
+
self.assertNotEqual(result.returncode, 0)
|
| 179 |
+
self.assertIn("invalid manifest JSON constant", result.stderr)
|
| 180 |
+
|
| 181 |
+
def test_validly_hashed_but_broken_index_and_corpus_are_rejected(self):
|
| 182 |
+
# Reuse the selector's coherent-fixture mutation helper to ensure that
|
| 183 |
+
# merely updating the manifest hash cannot conceal a malformed index.
|
| 184 |
+
fault = selector_faults.SelectorFaultTests()
|
| 185 |
+
fault.root, fault.generation = self.root, self.generation
|
| 186 |
+
for name in ("search_data.json.gz", "search_words.bin.gz", "search_ngrams_2.bin.gz",
|
| 187 |
+
"search_ngrams_3.bin.gz"):
|
| 188 |
+
original = (self.root / name).read_bytes()
|
| 189 |
+
fault.rewrite(name, b"broken")
|
| 190 |
+
result = self.run_cli("--data-dir", self.root, "--generation", fault.generation)
|
| 191 |
+
self.assertNotEqual(result.returncode, 0, name)
|
| 192 |
+
self.assertEqual(result.stdout, "")
|
| 193 |
+
fault.rewrite(name, original)
|
| 194 |
+
|
| 195 |
+
def test_paths_and_loaded_state_fail_closed(self):
|
| 196 |
+
selected, manifest, files = bench.select_generation(self.root, self.generation)
|
| 197 |
+
names = ("DATA_PATH", "NGRAM_PATHS", "WORD_INDEX_PATH", "FOLDER_TREE_PATH", "FOLDER_BROWSER_PATH",
|
| 198 |
+
"SIDEBAR_DATA_PATH")
|
| 199 |
+
with patch.multiple(app, **{name: getattr(app, name) for name in names}):
|
| 200 |
+
bench.configure_paths(selected.directory)
|
| 201 |
+
bench.require_paths(selected)
|
| 202 |
+
for name in names:
|
| 203 |
+
with self.subTest(path=name), patch.object(app, name, {} if name == "NGRAM_PATHS" else Path("/wrong")):
|
| 204 |
+
with self.assertRaisesRegex(RuntimeError, "application paths"):
|
| 205 |
+
bench.require_paths(selected)
|
| 206 |
+
with patch.object(app, "records", []), self.assertRaisesRegex(RuntimeError, "did not load"):
|
| 207 |
+
bench.require_loaded(selected)
|
| 208 |
+
bench.verify_unchanged(selected, manifest, files)
|
| 209 |
+
(self.root / "unexpected").write_bytes(b"x")
|
| 210 |
+
with self.assertRaisesRegex(RuntimeError, "members changed"):
|
| 211 |
+
bench.verify_unchanged(selected, manifest, files)
|
| 212 |
+
|
| 213 |
+
def test_detects_full_tail_permutation_and_hashes_complete_order(self):
|
| 214 |
+
expected = list(range(600))
|
| 215 |
+
changed = expected[:500] + list(reversed(expected[500:]))
|
| 216 |
+
self.assertEqual(expected[:500], changed[:500])
|
| 217 |
+
self.assertNotEqual(bench.order_hash(expected), bench.order_hash(changed))
|
| 218 |
+
self.assertEqual(bench.order_hash([1, 2]), hashlib.sha256(b"[1,2]").hexdigest())
|
| 219 |
+
with patch.object(bench, "CASES", (("tail", True),)), \
|
| 220 |
+
patch.object(app, "_search_order_uncached", side_effect=[expected, expected, changed]):
|
| 221 |
+
with self.assertRaisesRegex(RuntimeError, "unstable complete order"):
|
| 222 |
+
bench.measure_orders(2)
|
| 223 |
+
with patch.object(bench, "CASES", (("stable", False),)), \
|
| 224 |
+
patch.object(app, "_search_order_uncached", side_effect=[expected, expected, expected]) as search:
|
| 225 |
+
rows = bench.measure_orders(2)
|
| 226 |
+
self.assertEqual(search.call_count, 3)
|
| 227 |
+
self.assertEqual(rows[0]["order_sha256"], bench.order_hash(expected))
|
| 228 |
+
self.assertEqual(rows[0]["total"], len(expected))
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
if __name__ == "__main__":
|
| 232 |
+
unittest.main()
|