vomebook commited on
Commit
4eac8a3
·
1 Parent(s): 794135c

Harden Space benchmark corpus and temporary storage

Browse files
scripts/benchmarks/benchmark_search_compute.py CHANGED
@@ -1,16 +1,17 @@
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
@@ -98,6 +99,14 @@ def select_generation(directory: Path, generation: str) -> tuple[SelectedGenerat
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
 
@@ -123,6 +132,16 @@ def verify_unchanged(selected: SelectedGeneration, manifest: bytes, files: dict[
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
@@ -189,6 +208,7 @@ 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:
@@ -199,6 +219,9 @@ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
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)
@@ -217,11 +240,6 @@ def main(argv: Sequence[str] | None = None) -> int:
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.
@@ -246,10 +264,12 @@ def main(argv: Sequence[str] | None = None) -> int:
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,
 
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 outside the data directory:
5
 
6
  python -B scripts/benchmarks/benchmark_search_compute.py \
7
+ --data-dir DIRECTORY --generation EXPECTED_SHA256 --temp-dir LOCAL_TMP --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. It compares only the declared Pages corpus
12
+ hash and length, not Pages files or deployment. No data or book bodies are fetched
13
+ or written. A private Jieba cache is created under the explicitly provided local
14
+ writable temporary directory, outside the generation, and discarded afterwards.
15
 
16
  Each query has one untimed warmup and 1-100 timed warm in-process uncached
17
  orders, in fixed order. This bypasses response/order caches, pagination, API
 
99
  if manifest_path.read_bytes() != manifest_bytes:
100
  raise ValueError("generation manifest changed during verification")
101
  files: dict[str, dict[str, object]] = manifest["files"]["space"]
102
+ pages_files = manifest["files"].get("pages")
103
+ pages_corpus = pages_files.get("search_data.json.gz") if isinstance(pages_files, dict) else None
104
+ space_corpus = files["search_data.json.gz"]
105
+ if (not isinstance(pages_corpus, dict) or set(pages_corpus) != {"sha256", "bytes"}
106
+ or type(pages_corpus.get("bytes")) is not int
107
+ or pages_corpus.get("bytes") != space_corpus["bytes"]
108
+ or pages_corpus.get("sha256") != space_corpus["sha256"]):
109
+ raise ValueError("Pages and Space declared corpus hash or size mismatch")
110
  return selected, manifest_bytes, files
111
 
112
 
 
132
  raise RuntimeError(f"generation member changed during benchmark: {name}")
133
 
134
 
135
+ def cache_parent(directory: Path, selected: SelectedGeneration) -> Path:
136
+ """Resolve an existing caller-selected temporary root without a write probe."""
137
+ root = directory.resolve(strict=True)
138
+ if not root.is_dir():
139
+ raise ValueError("temporary cache root must be an existing directory")
140
+ if root == selected.directory or root.is_relative_to(selected.directory):
141
+ raise ValueError("temporary cache directory must be outside selected generation")
142
+ return root
143
+
144
+
145
  def configure_paths(root: Path) -> None:
146
  """Match all generation-owned paths selected by search_runtime_entry."""
147
  from backend import app
 
208
  parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
209
  parser.add_argument("--data-dir", type=Path, required=True, help="immutable materialized Space generation")
210
  parser.add_argument("--generation", required=True, help="independently expected generation SHA-256")
211
+ parser.add_argument("--temp-dir", type=Path, required=True, help="writable local temp root outside generation")
212
  parser.add_argument("--iterations", type=int, default=7, help="timed iterations per query, 1-100")
213
  options = parser.parse_args(argv)
214
  if not 1 <= options.iterations <= 100:
 
219
  def main(argv: Sequence[str] | None = None) -> int:
220
  options = parse_args(argv)
221
  selected, manifest, files = select_generation(options.data_dir, options.generation)
222
+ temp_root = cache_parent(options.temp_dir, selected)
223
+ if Path.cwd().resolve().is_relative_to(selected.directory):
224
+ raise ValueError("current directory must be outside selected generation")
225
  sources = source_hashes()
226
  # Application import mounts static files relative to the checkout root.
227
  os.chdir(ROOT)
 
240
  native_sha = sha256_file(native_file) if native_file is not None else None
241
  configure_paths(selected.directory)
242
  require_paths(selected)
 
 
 
 
 
243
  with tempfile.TemporaryDirectory(prefix="space-bench-jieba-", dir=temp_root) as cache_dir:
244
  app.jieba.dt.tmp_dir = cache_dir
245
  # A missing word index would otherwise be rebuilt silently by load_data.
 
264
  "scope": "warm in-process uncached search orders; fixed query order, one untimed warmup per query; "
265
  "no response/order cache, API, executor queue, HTTP, network, browser or rendering; "
266
  "not production latency, a comparison, or an independent correctness oracle",
267
+ "input_assurance": "manifest and all Space files verified; Pages corpus hash and size compared as "
268
+ "manifest declarations only; Pages files and deployment not verified; identity is not "
269
+ "authenticated provenance; full posting semantics not independently proven; "
270
  "directory must remain immutable during run",
271
  "generation": selected.generation,
272
+ "pages_corpus_declaration_matches_space": True,
273
  "data_dir": str(selected.directory),
274
  "manifest_sha256": hashlib.sha256(manifest).hexdigest(),
275
  "space_files": files,
tests/gates/ci-test-inventory.json CHANGED
@@ -124,7 +124,7 @@
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",
 
124
  },
125
  "tests/performance/test_search_compute_benchmark.py": {
126
  "kind": "direct",
127
+ "source": "@reader-workflow"
128
  },
129
  "tests/proxy/test_async_proxy.py": {
130
  "kind": "direct",
tests/performance/test_search_compute_benchmark.py CHANGED
@@ -21,6 +21,19 @@ class SearchComputeBenchmarkTests(unittest.TestCase):
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"),
@@ -28,7 +41,8 @@ class SearchComputeBenchmarkTests(unittest.TestCase):
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())
@@ -39,6 +53,8 @@ class SearchComputeBenchmarkTests(unittest.TestCase):
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"])
@@ -56,14 +72,14 @@ class SearchComputeBenchmarkTests(unittest.TestCase):
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)
@@ -72,42 +88,89 @@ with patch.object(socket.socket, "connect", side_effect=RuntimeError("network fo
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)
@@ -143,7 +206,8 @@ runpy.run_path(script, run_name="__main__")
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()
@@ -157,6 +221,29 @@ runpy.run_path(script, run_name="__main__")
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()
@@ -166,7 +253,8 @@ runpy.run_path(script, run_name="__main__")
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:])
@@ -187,7 +275,8 @@ runpy.run_path(script, run_name="__main__")
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)
 
21
  self.addCleanup(self.temp.cleanup)
22
  self.root = Path(self.temp.name) / "generation"
23
  self.generation = fixture(self.root)
24
+ # This benchmark verifies cross-surface corpus declarations as well as
25
+ # the selector's complete materialized Space fixture.
26
+ manifest = json.loads((self.root / "generation-manifest.json").read_bytes())
27
+ manifest["files"]["pages"]["search_data.json.gz"] = dict(manifest["files"]["space"]["search_data.json.gz"])
28
+ self.generation = self.write_manifest(manifest)
29
+ self.cache_root = Path(self.temp.name) / "local-temp"
30
+ self.cache_root.mkdir()
31
+
32
+ def write_manifest(self, manifest):
33
+ excluded = {"generation", "remote_writes", "publication_ready", "object_layout", "objects", "additional_checks"}
34
+ manifest["generation"] = hashlib.sha256(encode({k: v for k, v in manifest.items() if k not in excluded})).hexdigest()
35
+ (self.root / "generation-manifest.json").write_bytes(encode(manifest))
36
+ return manifest["generation"]
37
 
38
  def run_cli(self, *arguments):
39
  return subprocess.run([sys.executable, "-B", str(bench.ROOT / "scripts/benchmarks/benchmark_search_compute.py"),
 
41
  capture_output=True, timeout=90, check=False)
42
 
43
  def cli_args(self):
44
+ return ("--data-dir", self.root, "--generation", self.generation, "--temp-dir", self.cache_root,
45
+ "--iterations", "2")
46
 
47
  def test_actual_cli_uses_selected_generation_from_another_working_directory(self):
48
  result = self.run_cli(*self.cli_args())
 
53
  self.assertEqual((report["records"], report["iterations"], report["warmups_per_query"]), (1, 2, 1))
54
  manifest = json.loads((self.root / "generation-manifest.json").read_bytes())
55
  self.assertEqual(report["space_files"], manifest["files"]["space"])
56
+ self.assertTrue(report["pages_corpus_declaration_matches_space"])
57
+ self.assertIn("Pages files and deployment not verified", report["input_assurance"])
58
  self.assertEqual(report["manifest_sha256"], hashlib.sha256(encode(manifest)).hexdigest())
59
  self.assertEqual(report["source_sha256"]["backend/app.py"], bench.sha256_file(bench.ROOT / "backend/app.py"))
60
  self.assertTrue(report["tokenizer"]["initialized"])
 
72
  program = '''
73
  import runpy, socket, sys
74
  from unittest.mock import patch
75
+ sys.argv = [script, "--data-dir", directory, "--generation", generation, "--temp-dir", cache_root, "--iterations", "1"]
76
  with patch.object(socket.socket, "connect", side_effect=RuntimeError("network forbidden")), \\
77
  patch.object(socket.socket, "connect_ex", side_effect=RuntimeError("network forbidden")), \\
78
  patch.object(socket, "getaddrinfo", side_effect=RuntimeError("network forbidden")):
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}\ncache_root={str(self.cache_root)!r}\n")
83
  result = subprocess.run([sys.executable, "-B", "-c", prefix + program], cwd=self.root.parent,
84
  capture_output=True, text=True, timeout=90, check=False)
85
  self.assertEqual(result.returncode, 0, result.stderr)
 
88
  def test_temporary_cache_ignores_environment_inside_generation(self):
89
  program = '''
90
  import runpy, sys, tempfile
91
+ sys.argv = [script, "--data-dir", directory, "--generation", generation, "--temp-dir", cache_root]
92
  def forbidden_probe():
93
  raise AssertionError("unexpected tempdir probe")
94
  tempfile.gettempdir = forbidden_probe
95
  runpy.run_path(script, run_name="__main__")
96
  '''
97
  prefix = (f"script={str(bench.ROOT / 'scripts/benchmarks/benchmark_search_compute.py')!r}\n"
98
+ f"directory={str(self.root)!r}\ngeneration={self.generation!r}\ncache_root={str(self.cache_root)!r}\n")
99
  result = subprocess.run([sys.executable, "-B", "-c", prefix + program], cwd=self.root.parent,
100
  env={**os.environ, "TMPDIR": str(self.root)},
101
  capture_output=True, text=True, timeout=30, check=False)
102
  self.assertEqual(result.returncode, 0, result.stderr)
103
  self.assertEqual(json.loads(result.stdout)["generation"], self.generation)
104
  self.assertFalse(list(self.root.glob("space-bench-jieba-*")))
105
+ self.assertFalse(list(self.cache_root.glob("space-bench-jieba-*")))
106
+
107
+ def test_read_only_generation_parent_uses_explicit_external_temporary_root(self):
108
+ # Read-only generation/mount with a separate caller-controlled cache root.
109
+ mount = self.root.parent / "mount"
110
+ mount.mkdir()
111
+ mounted = mount / "generation"
112
+ self.root.rename(mounted)
113
+ self.root = mounted
114
+ mount.chmod(0o555)
115
+ self.root.chmod(0o555)
116
+ self.addCleanup(mount.chmod, 0o755)
117
+ self.addCleanup(self.root.chmod, 0o755)
118
+ result = self.run_cli(*self.cli_args())
119
+ self.assertEqual(result.returncode, 0, result.stderr)
120
+ self.assertEqual(json.loads(result.stdout)["generation"], self.generation)
121
+ self.assertEqual(sorted(path.name for path in mount.iterdir()), ["generation"])
122
+ self.assertFalse(list(self.cache_root.iterdir()))
123
+
124
+ def test_temporary_root_cannot_resolve_inside_generation(self):
125
+ link = self.root.parent / "cache-link"
126
+ link.symlink_to(self.root / "sidebar", target_is_directory=True)
127
+ for path in (self.root, self.root / "sidebar", link):
128
+ result = self.run_cli("--data-dir", self.root, "--generation", self.generation,
129
+ "--temp-dir", path)
130
+ with self.subTest(path=path):
131
+ self.assertNotEqual(result.returncode, 0)
132
+ self.assertIn("temporary cache directory must be outside", result.stderr)
133
+ self.assertEqual(result.stdout, "")
134
+ for path in (self.root.parent / "missing", self.root / "generation-manifest.json"):
135
+ result = self.run_cli("--data-dir", self.root, "--generation", self.generation,
136
+ "--temp-dir", path)
137
+ with self.subTest(path=path):
138
+ self.assertNotEqual(result.returncode, 0)
139
+ self.assertEqual(result.stdout, "")
140
+
141
+ def test_current_directory_cannot_be_the_generation(self):
142
+ result = subprocess.run([sys.executable, "-B", str(bench.ROOT / "scripts/benchmarks/benchmark_search_compute.py"),
143
+ *map(str, self.cli_args())], cwd=self.root, text=True,
144
+ capture_output=True, timeout=30, check=False)
145
+ self.assertNotEqual(result.returncode, 0)
146
+ self.assertIn("current directory must be outside selected generation", result.stderr)
147
+ self.assertFalse(list(self.root.rglob("space-bench-jieba-*")))
148
 
149
  def test_required_options_and_iteration_boundaries(self):
150
  for value in ("1", "100"):
151
  options = bench.parse_args(["--data-dir", str(self.root), "--generation", self.generation,
152
+ "--temp-dir", str(self.cache_root), "--iterations", value])
153
  self.assertEqual(options.iterations, int(value))
154
  for args in ([], ["--data-dir", str(self.root)],
155
  ["--generation", self.generation],
156
+ ["--data-dir", str(self.root), "--generation", self.generation],
157
+ ["--data-dir", str(self.root), "--generation", self.generation, "--temp-dir", str(self.cache_root),
158
+ "--iterations", "0"],
159
+ ["--data-dir", str(self.root), "--generation", self.generation, "--temp-dir", str(self.cache_root),
160
+ "--iterations", "101"],
161
+ ["--data-dir", str(self.root), "--generation", self.generation, "--temp-dir", str(self.cache_root),
162
+ "--iterations", "oops"]):
163
  with self.subTest(args=args), patch("sys.stderr"), self.assertRaises(SystemExit) as stopped:
164
  bench.parse_args(args)
165
  self.assertEqual(stopped.exception.code, 2)
166
+ result = self.run_cli("--data-dir", self.root, "--generation", self.generation,
167
+ "--temp-dir", self.cache_root, "--iterations", "0")
168
  self.assertNotEqual(result.returncode, 0)
169
  self.assertIn("between 1 and 100", result.stderr)
170
  self.assertEqual(result.stdout, "")
171
 
172
  def test_missing_corrupt_or_wrong_generation_fails_before_importing_app(self):
173
+ result = self.run_cli("--data-dir", self.root, "--generation", "f" * 64, "--temp-dir", self.cache_root)
174
  self.assertNotEqual(result.returncode, 0)
175
  self.assertEqual(result.stdout, "")
176
  self.assertIn("invalid search generation manifest", result.stderr)
 
206
  excluded = {"generation", "remote_writes", "publication_ready", "object_layout", "objects", "additional_checks"}
207
  manifest["generation"] = hashlib.sha256(encode({k: v for k, v in manifest.items() if k not in excluded})).hexdigest()
208
  manifest_path.write_bytes(encode(manifest))
209
+ result = self.run_cli("--data-dir", self.root, "--generation", manifest["generation"],
210
+ "--temp-dir", self.cache_root)
211
  self.assertNotEqual(result.returncode, 0)
212
  self.assertIn("record count mismatch", result.stderr)
213
  manifest_path.unlink()
 
221
  self.assertNotEqual(result.returncode, 0)
222
  self.assertIn("missing or oversized", result.stderr)
223
 
224
+ def test_pages_corpus_declaration_must_match_space_sha_and_length(self):
225
+ manifest_path = self.root / "generation-manifest.json"
226
+ original = json.loads(manifest_path.read_bytes())
227
+ space = original["files"]["space"]["search_data.json.gz"]
228
+ for declaration in (None, {}, {**space, "sha256": "f" * 64},
229
+ {**space, "bytes": space["bytes"] + 1},
230
+ {**space, "bytes": True}, {**space, "extra": "unexpected"}):
231
+ manifest = json.loads(json.dumps(original))
232
+ if declaration is None:
233
+ del manifest["files"]["pages"]["search_data.json.gz"]
234
+ else:
235
+ manifest["files"]["pages"]["search_data.json.gz"] = declaration
236
+ generation = self.write_manifest(manifest)
237
+ # Space's normal selector alone accepts this recomputed, self-consistent
238
+ # identity; the benchmark must additionally reject the cross-site mismatch.
239
+ self.assertEqual(bench.inspect_generation(self.root, generation).record_count, 1)
240
+ result = self.run_cli("--data-dir", self.root, "--generation", generation,
241
+ "--temp-dir", self.cache_root)
242
+ with self.subTest(declaration=declaration):
243
+ self.assertNotEqual(result.returncode, 0)
244
+ self.assertIn("Pages and Space declared corpus hash or size mismatch", result.stderr)
245
+ self.assertEqual(result.stdout, "")
246
+
247
  def test_noncanonical_manifest_types_and_duplicate_keys_are_rejected(self):
248
  manifest_path = self.root / "generation-manifest.json"
249
  original = manifest_path.read_bytes()
 
253
  excluded = {"generation", "remote_writes", "publication_ready", "object_layout", "objects", "additional_checks"}
254
  modified["generation"] = hashlib.sha256(encode({k: v for k, v in modified.items() if k not in excluded})).hexdigest()
255
  manifest_path.write_bytes(encode(modified))
256
+ result = self.run_cli("--data-dir", self.root, "--generation", modified["generation"],
257
+ "--temp-dir", self.cache_root)
258
  self.assertNotEqual(result.returncode, 0)
259
  self.assertIn("invalid generation manifest version or record count", result.stderr)
260
  manifest_path.write_bytes(b'{"version":1,' + original[1:])
 
275
  "search_ngrams_3.bin.gz"):
276
  original = (self.root / name).read_bytes()
277
  fault.rewrite(name, b"broken")
278
+ result = self.run_cli("--data-dir", self.root, "--generation", fault.generation,
279
+ "--temp-dir", self.cache_root)
280
  self.assertNotEqual(result.returncode, 0, name)
281
  self.assertEqual(result.stdout, "")
282
  fault.rewrite(name, original)