vomebook commited on
Commit ·
794135c
1
Parent(s): aecabd8
Add verified offline Space search compute benchmark
Browse filesFiles changed (4)
33 unmodified lines34353637383933 unmodified lines&& python -B -m unittest -v \tests.search.backend.test_search_data_selector \tests.search.backend.test_search_data_selector_faults \tests.search.backend.test_search_runtime_entry \tests.search.backend.test_search_start_script33 unmodified lines3435363738394033 unmodified lines&& python -B -m unittest -v \tests.search.backend.test_search_data_selector \tests.search.backend.test_search_data_selector_faults \tests.performance.test_search_compute_benchmark \tests.search.backend.test_search_runtime_entry \tests.search.backend.test_search_start_script
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280"""Opt-in local Space search-order compute benchmark, with verified input.
Obtain the expected identity independently (or inspect a trusted local copy viapython -m scripts.search_data_config DIRECTORY), then run from any directory:
python -B scripts/benchmarks/benchmark_search_compute.py \ --data-dir DIRECTORY --generation EXPECTED_SHA256 --iterations 7
The directory must remain immutable throughout the run. The selector checksmanifest identity and all Space members, but does not authenticate their originor prove every posting's semantics. No data or book bodies are fetched orwritten. The generation's parent must be writable for Jieba's private,temporary dictionary cache, which is discarded afterwards.
Each query has one untimed warmup and 1-100 timed warm in-process uncachedorders, in fixed order. This bypasses response/order caches, pagination, APIvalidation, executor queues, HTTP, network, browsers and rendering. It is not arequest or production latency measurement, a performance comparison, or anindependent search-correctness oracle. Complete orders are compared with thewarmup and hashed, not printed."""from __future__ import annotations
import argparsefrom collections.abc import Sequencefrom contextlib import redirect_stdoutimport gzipimport hashlibimport jsonimport osfrom pathlib import Pathimport platformimport statisticsimport sysimport tempfileimport timefrom typing import NoReturnfrom unittest.mock import patch
ROOT = Path(__file__).resolve().parents[2]if __name__ == "__main__": sys.dont_write_bytecode = Truesys.path.insert(0, str(ROOT))
from backend.search_data_selector import SelectedGeneration, inspect_generation # noqa: E402
CASES = ( ("手机", True), ("手机", False), ("文化革命", True), ("社会主义", False), ("手机 pdf", True), ("马克思 文", True), ("文化革命*.pdf", True), ("马克思*.pdf", True), ("?*.pdf", True), ("*.pdf", True), ("*.epub", True),)
def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def source_hashes() -> dict[str, str]: paths = sorted((ROOT / "backend").glob("*.py")) + [ ROOT / "backend/native/search_index_native.c", ROOT / "requirements.txt", ROOT / "static/index.html", Path(__file__), ] return {path.relative_to(ROOT).as_posix(): sha256_file(path) for path in paths}
def unique_json_object(pairs: list[tuple[str, object]]) -> dict[str, object]: result: dict[str, object] = {} for key, value in pairs: if key in result: raise ValueError(f"duplicate manifest key: {key}") result[key] = value return result
def reject_json_constant(value: str) -> NoReturn: raise ValueError(f"invalid manifest JSON constant: {value}")
def select_generation(directory: Path, generation: str) -> tuple[SelectedGeneration, bytes, dict[str, dict[str, object]]]: """Use the same complete, fail-closed verifier as the Space entry point.""" manifest_path = directory / "generation-manifest.json" if manifest_path.is_symlink() or not manifest_path.is_file() or manifest_path.stat().st_size > 1024 * 1024: raise ValueError("missing or oversized generation manifest") manifest_bytes = manifest_path.read_bytes() manifest = json.loads(manifest_bytes, object_pairs_hook=unique_json_object, parse_constant=reject_json_constant) if (not isinstance(manifest, dict) or type(manifest.get("version")) is not int or type(manifest.get("record_count")) is not int or manifest["record_count"] < 1): raise ValueError("invalid generation manifest version or record count") selected = inspect_generation(directory, generation) if manifest_path.read_bytes() != manifest_bytes: raise ValueError("generation manifest changed during verification") files: dict[str, dict[str, object]] = manifest["files"]["space"] return selected, manifest_bytes, files
def verify_unchanged(selected: SelectedGeneration, manifest: bytes, files: dict[str, dict[str, object]]) -> None: """Detect changes around loading/measurement, including the manifest itself.""" root = selected.directory manifest_path = root / "generation-manifest.json" if manifest_path.is_symlink() or manifest_path.read_bytes() != manifest: raise RuntimeError("generation manifest changed during benchmark") actual: set[str] = set() for path in root.rglob("*"): if path.is_symlink(): raise RuntimeError("generation contains a symlink") if path.is_file() and path != manifest_path: actual.add(path.relative_to(root).as_posix()) elif not path.is_dir() and path != manifest_path: raise RuntimeError("generation contains a non-file object") if actual != set(files): raise RuntimeError("generation members changed during benchmark") for name, metadata in files.items(): path = root / name if not path.is_file() or path.stat().st_size != metadata["bytes"] or sha256_file(path) != metadata["sha256"]: raise RuntimeError(f"generation member changed during benchmark: {name}")
def configure_paths(root: Path) -> None: """Match all generation-owned paths selected by search_runtime_entry.""" from backend import app
app.DATA_PATH = root / "search_data.json.gz" app.NGRAM_PATHS = {2: root / "search_ngrams_2.bin.gz", 3: root / "search_ngrams_3.bin.gz"} app.WORD_INDEX_PATH = root / "search_words.bin.gz" app.FOLDER_TREE_PATH = root / "folder_tree.json.gz" app.FOLDER_BROWSER_PATH = root / "folder_browser.json.gz" app.SIDEBAR_DATA_PATH = root / "sidebar"
def require_paths(selected: SelectedGeneration) -> None: from backend import app
root = selected.directory if (app.DATA_PATH != root / "search_data.json.gz" or app.NGRAM_PATHS != {2: root / "search_ngrams_2.bin.gz", 3: root / "search_ngrams_3.bin.gz"} or app.WORD_INDEX_PATH != root / "search_words.bin.gz" or app.FOLDER_TREE_PATH != root / "folder_tree.json.gz" or app.FOLDER_BROWSER_PATH != root / "folder_browser.json.gz" or app.SIDEBAR_DATA_PATH != root / "sidebar"): raise RuntimeError("application paths do not match selected generation")
def require_loaded(selected: SelectedGeneration) -> None: from backend import app
require_paths(selected) if (len(app.records) != selected.record_count or not app.word_index or not app.word_index_buffer or any(not app.ngram_postings.get(width) or not app.ngram_posting_buffers.get(width) for width in (2, 3))): raise RuntimeError("selected generation did not load all records and generated indexes") raw = gzip.decompress(app.DATA_PATH.read_bytes()) expected = app.search_data_generation(raw, [app.WORD_INDEX_PATH, *app.NGRAM_PATHS.values()]) if app.search_generation() != expected: raise RuntimeError("loaded API fingerprint does not match selected corpus and indexes")
def order_hash(order: Sequence[int]) -> str: """SHA-256 of compact ASCII JSON array of all zero-based corpus indices.""" return hashlib.sha256(json.dumps(list(order), separators=(",", ":")).encode("ascii")).hexdigest()
def measure_orders(iterations: int) -> list[dict[str, object]]: from backend import app
rows: list[dict[str, object]] = [] for query, exact in CASES: expected = list(app._search_order_uncached(q=query, exact=exact)) timings: list[float] = [] for _ in range(iterations): started = time.perf_counter() order = list(app._search_order_uncached(q=query, exact=exact)) timings.append((time.perf_counter() - started) * 1000) if order != expected: raise RuntimeError(f"unstable complete order: {query!r}, exact={exact}") rows.append({"query": query, "exact": exact, "total": len(expected), "order_sha256": order_hash(expected), "median_ms": statistics.median(timings), "min_ms": min(timings), "max_ms": max(timings)}) return rows
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--data-dir", type=Path, required=True, help="immutable materialized Space generation") parser.add_argument("--generation", required=True, help="independently expected generation SHA-256") parser.add_argument("--iterations", type=int, default=7, help="timed iterations per query, 1-100") options = parser.parse_args(argv) if not 1 <= options.iterations <= 100: parser.error("--iterations must be between 1 and 100") return options
def main(argv: Sequence[str] | None = None) -> int: options = parse_args(argv) selected, manifest, files = select_generation(options.data_dir, options.generation) sources = source_hashes() # Application import mounts static files relative to the checkout root. os.chdir(ROOT) from backend import app, search_indexes
if Path(app.__file__).resolve() != ROOT / "backend/app.py": raise RuntimeError("application imported from a different checkout") if search_indexes.WORD_INDEX_TOKENIZER != f"jieba-{app.jieba.__version__}-cjk-char-v1": raise RuntimeError("installed Jieba version does not match generated index tokenizer") if app.jieba.dt.initialized or app.jieba.dt.dictionary is not None: raise RuntimeError("benchmark requires a fresh default Jieba tokenizer") with app.jieba.dt.get_dict_file() as dictionary: dictionary_sha = hashlib.sha256(dictionary.read()).hexdigest() native = search_indexes._native_index native_file = Path(native.__file__) if native is not None else None native_sha = sha256_file(native_file) if native_file is not None else None configure_paths(selected.directory) require_paths(selected) # Resolve an existing parent without gettempdir()'s write probe, and pass # it explicitly to TemporaryDirectory so no writes touch the generation. temp_root = selected.directory.parent if temp_root == selected.directory or temp_root.is_relative_to(selected.directory): raise RuntimeError("temporary cache directory must be outside selected generation") with tempfile.TemporaryDirectory(prefix="space-bench-jieba-", dir=temp_root) as cache_dir: app.jieba.dt.tmp_dir = cache_dir # A missing word index would otherwise be rebuilt silently by load_data. with patch.object(app, "build_word_index", side_effect=RuntimeError("generated word index not loaded")): started = time.perf_counter() with redirect_stdout(sys.stderr): app.load_data() startup_ms = (time.perf_counter() - started) * 1000 require_loaded(selected) if not app.jieba.dt.initialized: raise RuntimeError("Jieba tokenizer was not initialized") verify_unchanged(selected, manifest, files) rows = measure_orders(options.iterations) verify_unchanged(selected, manifest, files) require_loaded(selected) with app.jieba.dt.get_dict_file() as dictionary: if hashlib.sha256(dictionary.read()).hexdigest() != dictionary_sha: raise RuntimeError("tokenizer dictionary changed during benchmark") if source_hashes() != sources or (native_file is not None and sha256_file(native_file) != native_sha): raise RuntimeError("source or native module changed during benchmark") report = { "scope": "warm in-process uncached search orders; fixed query order, one untimed warmup per query; " "no response/order cache, API, executor queue, HTTP, network, browser or rendering; " "not production latency, a comparison, or an independent correctness oracle", "input_assurance": "manifest and all Space files verified; identity is not authenticated provenance; " "index format/corpus linkage checked, full posting semantics not independently proven; " "directory must remain immutable during run", "generation": selected.generation, "data_dir": str(selected.directory), "manifest_sha256": hashlib.sha256(manifest).hexdigest(), "space_files": files, "records": len(app.records), "api_generation": app.search_generation(), "source_sha256": sources, "python": sys.version, "platform": platform.platform(), "machine": platform.machine(), "tokenizer": {"name": "jieba", "version": app.jieba.__version__, "initialized": app.jieba.dt.initialized, "dictionary_sha256": dictionary_sha, "index_format": search_indexes.WORD_INDEX_TOKENIZER, "cache": "private temporary cache from default dictionary"}, "native": {"loaded": native is not None, "sha256": native_sha, "note": "binary and source hashes do not establish build provenance", "read_entries": search_indexes._native_read_entries is not None, "decode_postings": search_indexes._native_decode_postings is not None}, "iterations": options.iterations, "warmups_per_query": 1, "startup_ms_single_observation_not_container_cold_start": startup_ms, "order_hash_format": "sha256 of compact ASCII JSON array of all zero-based corpus indices", "queries": rows, } print(json.dumps(report, ensure_ascii=False, indent=2)) return 0
if __name__ == "__main__": raise SystemExit(main())121 unmodified lines122123124125126127121 unmodified lines"kind": "direct","source": "@reader-workflow"},"tests/proxy/test_async_proxy.py": {"kind": "direct","source": "@reader-workflow"121 unmodified lines122123124125126127128129130131121 unmodified lines"kind": "direct","source": "@reader-workflow"},"tests/performance/test_search_compute_benchmark.py": {"kind": "direct","source": "Dockerfile"},"tests/proxy/test_async_proxy.py": {"kind": "direct","source": "@reader-workflow"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232"""Synthetic offline contracts for the opt-in Space compute benchmark."""import hashlibimport jsonimport osfrom pathlib import Pathimport subprocessimport sysimport tempfileimport unittestfrom unittest.mock import patch
from backend import appfrom scripts.benchmarks import benchmark_search_compute as benchfrom tests.search.backend.test_search_data_selector import encode, fixturefrom tests.search.backend import test_search_data_selector_faults as selector_faults
class SearchComputeBenchmarkTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory(prefix="space-benchmark-fixture-") self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name) / "generation" self.generation = fixture(self.root)
def run_cli(self, *arguments): return subprocess.run([sys.executable, "-B", str(bench.ROOT / "scripts/benchmarks/benchmark_search_compute.py"), *map(str, arguments)], cwd=self.root.parent, text=True, capture_output=True, timeout=90, check=False)
def cli_args(self): return ("--data-dir", self.root, "--generation", self.generation, "--iterations", "2")
def test_actual_cli_uses_selected_generation_from_another_working_directory(self): result = self.run_cli(*self.cli_args()) self.assertEqual(result.returncode, 0, result.stderr) report = json.loads(result.stdout) self.assertEqual(report["data_dir"], str(self.root)) self.assertEqual(report["generation"], self.generation) self.assertEqual((report["records"], report["iterations"], report["warmups_per_query"]), (1, 2, 1)) manifest = json.loads((self.root / "generation-manifest.json").read_bytes()) self.assertEqual(report["space_files"], manifest["files"]["space"]) self.assertEqual(report["manifest_sha256"], hashlib.sha256(encode(manifest)).hexdigest()) self.assertEqual(report["source_sha256"]["backend/app.py"], bench.sha256_file(bench.ROOT / "backend/app.py")) self.assertTrue(report["tokenizer"]["initialized"]) self.assertEqual(report["tokenizer"]["version"], app.jieba.__version__) self.assertEqual(len(report["queries"]), len(bench.CASES)) # *.pdf really searches the selected one-record fixture, not bundled data. pdf = next(row for row in report["queries"] if row["query"] == "*.pdf") self.assertEqual((pdf["total"], pdf["order_sha256"]), (1, bench.order_hash([0]))) self.assertIn("uncached", report["scope"]) self.assertIn("not production latency", report["scope"]) self.assertIn("not independently proven", report["input_assurance"]) self.assertFalse((self.root / "jieba.cache").exists())
def test_cli_succeeds_when_all_network_connections_are_blocked(self): program = '''import runpy, socket, sysfrom unittest.mock import patchsys.argv = [script, "--data-dir", directory, "--generation", generation, "--iterations", "1"]with patch.object(socket.socket, "connect", side_effect=RuntimeError("network forbidden")), \\ patch.object(socket.socket, "connect_ex", side_effect=RuntimeError("network forbidden")), \\ patch.object(socket, "getaddrinfo", side_effect=RuntimeError("network forbidden")): runpy.run_path(script, run_name="__main__")''' prefix = (f"script={str(bench.ROOT / 'scripts/benchmarks/benchmark_search_compute.py')!r}\n" f"directory={str(self.root)!r}\ngeneration={self.generation!r}\n") result = subprocess.run([sys.executable, "-B", "-c", prefix + program], cwd=self.root.parent, capture_output=True, text=True, timeout=90, check=False) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(json.loads(result.stdout)["generation"], self.generation)
def test_temporary_cache_ignores_environment_inside_generation(self): program = '''import runpy, sys, tempfilesys.argv = [script, "--data-dir", directory, "--generation", generation]def forbidden_probe(): raise AssertionError("unexpected tempdir probe")tempfile.gettempdir = forbidden_proberunpy.run_path(script, run_name="__main__")''' prefix = (f"script={str(bench.ROOT / 'scripts/benchmarks/benchmark_search_compute.py')!r}\n" f"directory={str(self.root)!r}\ngeneration={self.generation!r}\n") result = subprocess.run([sys.executable, "-B", "-c", prefix + program], cwd=self.root.parent, env={**os.environ, "TMPDIR": str(self.root)}, capture_output=True, text=True, timeout=30, check=False) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(json.loads(result.stdout)["generation"], self.generation) self.assertFalse(list(self.root.glob("space-bench-jieba-*"))) self.assertFalse(list(self.root.parent.glob("space-bench-jieba-*")))
def test_required_options_and_iteration_boundaries(self): for value in ("1", "100"): options = bench.parse_args(["--data-dir", str(self.root), "--generation", self.generation, "--iterations", value]) self.assertEqual(options.iterations, int(value)) for args in ([], ["--data-dir", str(self.root)], ["--generation", self.generation], ["--data-dir", str(self.root), "--generation", self.generation, "--iterations", "0"], ["--data-dir", str(self.root), "--generation", self.generation, "--iterations", "101"], ["--data-dir", str(self.root), "--generation", self.generation, "--iterations", "oops"]): with self.subTest(args=args), patch("sys.stderr"), self.assertRaises(SystemExit) as stopped: bench.parse_args(args) self.assertEqual(stopped.exception.code, 2) result = self.run_cli("--data-dir", self.root, "--generation", self.generation, "--iterations", "0") self.assertNotEqual(result.returncode, 0) self.assertIn("between 1 and 100", result.stderr) self.assertEqual(result.stdout, "")
def test_missing_corrupt_or_wrong_generation_fails_before_importing_app(self): result = self.run_cli("--data-dir", self.root, "--generation", "f" * 64) self.assertNotEqual(result.returncode, 0) self.assertEqual(result.stdout, "") self.assertIn("invalid search generation manifest", result.stderr) for name in ("search_data.json.gz", "search_words.bin.gz", "search_ngrams_2.bin.gz", "search_ngrams_3.bin.gz", "folder_tree.json.gz", "folder_browser.json.gz"): path = self.root / name original = path.read_bytes() with self.subTest(missing=name): path.unlink() result = self.run_cli(*self.cli_args()) self.assertNotEqual(result.returncode, 0) self.assertEqual(result.stdout, "") self.assertIn("missing or unlisted", result.stderr) path.write_bytes(original) with self.subTest(corrupt=name): path.write_bytes(bytes([original[0] ^ 1]) + original[1:]) result = self.run_cli(*self.cli_args()) self.assertNotEqual(result.returncode, 0) self.assertEqual(result.stdout, "") self.assertIn("digest mismatch", result.stderr) path.write_bytes(original)
def test_manifest_tampering_missing_symlink_and_record_count_are_rejected(self): manifest_path = self.root / "generation-manifest.json" original = manifest_path.read_bytes() manifest = json.loads(original) manifest["record_count"] = 2 manifest_path.write_bytes(encode(manifest)) result = self.run_cli(*self.cli_args()) self.assertNotEqual(result.returncode, 0) self.assertIn("identity mismatch", result.stderr) # Even a recomputed identity must agree with the actual corpus count. excluded = {"generation", "remote_writes", "publication_ready", "object_layout", "objects", "additional_checks"} manifest["generation"] = hashlib.sha256(encode({k: v for k, v in manifest.items() if k not in excluded})).hexdigest() manifest_path.write_bytes(encode(manifest)) result = self.run_cli("--data-dir", self.root, "--generation", manifest["generation"]) self.assertNotEqual(result.returncode, 0) self.assertIn("record count mismatch", result.stderr) manifest_path.unlink() result = self.run_cli(*self.cli_args()) self.assertNotEqual(result.returncode, 0) self.assertIn("missing or oversized", result.stderr) other = self.root.parent / "manifest" other.write_bytes(original) manifest_path.symlink_to(other) result = self.run_cli(*self.cli_args()) self.assertNotEqual(result.returncode, 0) self.assertIn("missing or oversized", result.stderr)
def test_noncanonical_manifest_types_and_duplicate_keys_are_rejected(self): manifest_path = self.root / "generation-manifest.json" original = manifest_path.read_bytes() manifest = json.loads(original) for key in ("version", "record_count"): modified = {**manifest, key: True} excluded = {"generation", "remote_writes", "publication_ready", "object_layout", "objects", "additional_checks"} modified["generation"] = hashlib.sha256(encode({k: v for k, v in modified.items() if k not in excluded})).hexdigest() manifest_path.write_bytes(encode(modified)) result = self.run_cli("--data-dir", self.root, "--generation", modified["generation"]) self.assertNotEqual(result.returncode, 0) self.assertIn("invalid generation manifest version or record count", result.stderr) manifest_path.write_bytes(b'{"version":1,' + original[1:]) result = self.run_cli(*self.cli_args()) self.assertNotEqual(result.returncode, 0) self.assertIn("duplicate manifest key", result.stderr) manifest_path.write_bytes(b'{"extra":NaN,' + original[1:]) result = self.run_cli(*self.cli_args()) self.assertNotEqual(result.returncode, 0) self.assertIn("invalid manifest JSON constant", result.stderr)
def test_validly_hashed_but_broken_index_and_corpus_are_rejected(self): # Reuse the selector's coherent-fixture mutation helper to ensure that # merely updating the manifest hash cannot conceal a malformed index. fault = selector_faults.SelectorFaultTests() fault.root, fault.generation = self.root, self.generation for name in ("search_data.json.gz", "search_words.bin.gz", "search_ngrams_2.bin.gz", "search_ngrams_3.bin.gz"): original = (self.root / name).read_bytes() fault.rewrite(name, b"broken") result = self.run_cli("--data-dir", self.root, "--generation", fault.generation) self.assertNotEqual(result.returncode, 0, name) self.assertEqual(result.stdout, "") fault.rewrite(name, original)
def test_paths_and_loaded_state_fail_closed(self): selected, manifest, files = bench.select_generation(self.root, self.generation) names = ("DATA_PATH", "NGRAM_PATHS", "WORD_INDEX_PATH", "FOLDER_TREE_PATH", "FOLDER_BROWSER_PATH", "SIDEBAR_DATA_PATH") with patch.multiple(app, **{name: getattr(app, name) for name in names}): bench.configure_paths(selected.directory) bench.require_paths(selected) for name in names: with self.subTest(path=name), patch.object(app, name, {} if name == "NGRAM_PATHS" else Path("/wrong")): with self.assertRaisesRegex(RuntimeError, "application paths"): bench.require_paths(selected) with patch.object(app, "records", []), self.assertRaisesRegex(RuntimeError, "did not load"): bench.require_loaded(selected) bench.verify_unchanged(selected, manifest, files) (self.root / "unexpected").write_bytes(b"x") with self.assertRaisesRegex(RuntimeError, "members changed"): bench.verify_unchanged(selected, manifest, files)
def test_detects_full_tail_permutation_and_hashes_complete_order(self): expected = list(range(600)) changed = expected[:500] + list(reversed(expected[500:])) self.assertEqual(expected[:500], changed[:500]) self.assertNotEqual(bench.order_hash(expected), bench.order_hash(changed)) self.assertEqual(bench.order_hash([1, 2]), hashlib.sha256(b"[1,2]").hexdigest()) with patch.object(bench, "CASES", (("tail", True),)), \ patch.object(app, "_search_order_uncached", side_effect=[expected, expected, changed]): with self.assertRaisesRegex(RuntimeError, "unstable complete order"): bench.measure_orders(2) with patch.object(bench, "CASES", (("stable", False),)), \ patch.object(app, "_search_order_uncached", side_effect=[expected, expected, expected]) as search: rows = bench.measure_orders(2) self.assertEqual(search.call_count, 3) self.assertEqual(rows[0]["order_sha256"], bench.order_hash(expected)) self.assertEqual(rows[0]["total"], len(expected))
if __name__ == "__main__": unittest.main()Dockerfile+1
scripts/benchmarks/benchmark_search_compute.pyAdded+280
tests/gates/ci-test-inventory.json+4
tests/performance/test_search_compute_benchmark.pyAdded+232