File size: 37,603 Bytes
794135c
 
4aabf5a
794135c
 
4eac8a3
794135c
4aabf5a
8ba1ac1
 
 
4aabf5a
 
8ba1ac1
 
 
 
 
 
d69b496
 
 
 
 
 
 
4eac8a3
 
794135c
 
 
 
 
 
 
 
 
 
 
4aabf5a
 
794135c
 
 
 
 
 
4aabf5a
794135c
 
 
 
4aabf5a
794135c
4aabf5a
794135c
 
 
 
 
 
 
7347da4
8ba1ac1
4aabf5a
794135c
 
 
 
 
 
 
 
4aabf5a
 
 
 
 
 
 
 
 
 
 
 
8ba1ac1
 
 
 
 
 
 
 
 
 
 
cf8cae5
d69b496
 
 
 
 
 
 
 
 
 
 
 
 
4aabf5a
 
794135c
 
 
 
 
 
 
 
 
 
7347da4
794135c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4aabf5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
794135c
 
 
4aabf5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eac8a3
4aabf5a
4eac8a3
4aabf5a
 
 
 
cf8cae5
4aabf5a
 
 
 
 
 
 
 
 
 
 
 
8ba1ac1
 
4aabf5a
 
 
d69b496
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ba1ac1
 
cf8cae5
d69b496
 
 
 
 
8ba1ac1
4aabf5a
 
 
8ba1ac1
4aabf5a
 
 
 
 
 
 
 
 
 
 
 
cf8cae5
8ba1ac1
 
 
cf8cae5
 
 
8ba1ac1
cf8cae5
 
d69b496
4aabf5a
cf8cae5
 
 
 
 
 
8ba1ac1
d69b496
 
 
 
 
 
 
cf8cae5
 
 
 
8ba1ac1
cf8cae5
 
 
8ba1ac1
cf8cae5
8ba1ac1
4aabf5a
 
d69b496
 
 
 
4aabf5a
 
 
d69b496
 
 
8ba1ac1
 
4aabf5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ba1ac1
4aabf5a
 
 
 
 
 
 
 
 
8ba1ac1
 
 
 
 
 
d69b496
4aabf5a
d69b496
8ba1ac1
 
4aabf5a
 
 
 
 
794135c
 
 
 
 
 
4aabf5a
 
 
 
794135c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eac8a3
 
 
 
 
 
 
 
 
 
794135c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4eac8a3
794135c
 
 
 
 
 
 
 
 
 
4eac8a3
 
 
794135c
 
 
7347da4
 
794135c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf8cae5
8ba1ac1
d69b496
 
 
 
 
 
4aabf5a
 
 
d69b496
794135c
4eac8a3
794135c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
"""Opt-in local Space search-order compute benchmark, with verified input.

Obtain the expected identity independently, then run outside the data directory:

    python -B scripts/benchmarks/benchmark_search_compute.py \
        --data-dir DIRECTORY --generation EXPECTED_SHA256 --temp-dir LOCAL_TMP --iterations 7

The streamed preflight is local to this benchmark; other selector entry points,
including scripts.search_data_config, do not have its gzip member limits.
The manifest must be a regular file with exactly one hard link, and the three
JSON gzips and required indexes must be regular non-symlink direct children.
The caller must ensure the directory, its ancestors and its files remain
immutable throughout the run, for example using a trusted read-only snapshot.
Before the selector reopens them, preflight limits each compressed gzip to
32 MiB and each expanded JSON to 256 MiB (indexes: 32/48/64 MiB for words,
2-grams and 3-grams), and requires a single gzip member, no optional header and
no trailing bytes. This accepts the generation builder's encoding, but rejects
otherwise valid snapshots with optional headers, multiple members or padding;
it is not a compatibility guarantee for historical materialized generations.
The local index preflight also bounds encoded varints, total varint bytes and
entries, and checks posting ID ranges while streaming generated VWI2/VNG3.
These limits can reject other valid indexes and do not independently prove
posting contents. These checks cannot make concurrently writable paths safe.
The selector checks manifest identity and all Space members, but does not
authenticate their origin or prove every posting's semantics. It compares only
the declared Pages corpus hash and length, not Pages files or deployment. No data or book bodies are fetched
or written. A private Jieba cache is created under the explicitly provided local
writable temporary directory, outside the generation, and discarded afterwards.

Each query has one untimed warmup and 1-100 timed warm in-process uncached
orders, in fixed order. This bypasses response/order caches, pagination, API
validation, executor queues, HTTP, network, browsers and rendering. It is not a
request or production latency measurement, a performance comparison, or an
independent search-correctness oracle. Complete orders are compared with the
warmup and hashed, not printed.
"""
from __future__ import annotations

import argparse
from collections.abc import Iterator, Sequence
from contextlib import contextmanager, redirect_stdout
import gzip
import hashlib
import json
import os
from pathlib import Path
import platform
import stat
import statistics
import sys
import tempfile
import time
from typing import BinaryIO, NoReturn
from unittest.mock import patch
import zlib


ROOT = Path(__file__).resolve().parents[2]
if __name__ == "__main__":
    sys.dont_write_bytecode = True
sys.path.insert(0, str(ROOT))

from backend.search.corpus.infrastructure.selection import (  # noqa: E402
    MANDATORY, MAX_EXPANDED, MAX_FILE, MAX_FILES, SHA, SelectedGeneration, canonical, inspect_generation, safe_name,
)


CASES = (
    ("手机", True), ("手机", False), ("文化革命", True), ("社会主义", False),
    ("手机 pdf", True), ("马克思 文", True), ("文化革命*.pdf", True),
    ("马克思*.pdf", True), ("?*.pdf", True), ("*.pdf", True), ("*.epub", True),
)

MANIFEST_NAME = "generation-manifest.json"
MAX_MANIFEST = 1024 * 1024
CHUNK_SIZE = 64 * 1024
# Actual candidate 5c80388b465f35f74711c17aef9e31f8bb1c04fc0553e9820ac271658d740639
# (120453 records): words 5,852,724, 2-gram 10,005,037, 3-gram 14,456,170
# expanded bytes. These limits allow at least 4.6x growth per index; together
# they do not promise a bound on the selector's RSS.
INDEX_EXPANDED_LIMITS = {
    "search_words.bin.gz": 32 * 1024 * 1024,
    "search_ngrams_2.bin.gz": 48 * 1024 * 1024,
    "search_ngrams_3.bin.gz": 64 * 1024 * 1024,
}
# The selector and pipeline snapshot allow at most 256 MiB per expanded JSON
# and 32 MiB per compressed member. Candidate 5c80388 expanded bytes: corpus
# 9,237,795, tree 212,708, browser 11,077,772. Keep those existing bounds,
# rather than assuming future corpora have the current generation's sizes.
JSON_EXPANDED_LIMITS = dict.fromkeys(
    ("search_data.json.gz", "folder_tree.json.gz", "folder_browser.json.gz"), MAX_EXPANDED,
)
# Pipeline search_generation.build_generation calls gzip.compress once for
# each JSON and uses sync_to_space's two index writers, which do the same.
# Historical snapshots can contain other valid gzip encodings; this local
# benchmark deliberately fails closed on optional headers and trailing data.
GZIP_HEADER_SIZE = 10
# sync_to_space encodes nonnegative integers minimally. Its lengths and entry
# counts are bounded by index expansion; record counts, posting counts and
# deltas are bounded by the number of records, itself below expanded corpus
# bytes. With the above limits all require at most five base-128 bytes. This
# guard also allows non-minimal encodings through five bytes, but does not
# impose these producer-specific numeric bounds on each decoded field.
MAX_INDEX_VARINT_BYTES = (max(MAX_EXPANDED, *INDEX_EXPANDED_LIMITS.values()).bit_length() + 6) // 7
# Across all three indexes, candidate 5c80388 contains 24,871,100 varint
# bytes and 724,372 entries. Leave ~1.6x/~1.65x headroom respectively, not
# a promise to accept every larger or non-minimal valid index. Count bytes,
# not just decoded integers: repeated zero deltas still require work.
MAX_TOTAL_INDEX_VARINT_BYTES = 40_000_000
MAX_TOTAL_INDEX_ENTRIES = 1_200_000
IDENTITY_EXCLUDED = {"generation", "remote_writes", "publication_ready", "object_layout", "objects", "additional_checks"}


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").rglob("*.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}")


@contextmanager
def open_directory(directory: Path) -> Iterator[int]:
    """Pin the generation directory while preflighting its direct children."""
    try:
        fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC)
    except OSError as error:
        raise ValueError("generation directory must be an ordinary directory") from error
    try:
        yield fd
    finally:
        os.close(fd)


@contextmanager
def open_regular_at(directory_fd: int, name: str, message: str) -> Iterator[BinaryIO]:
    # Avoid opening known special files; O_NONBLOCK also prevents a substituted
    # FIFO from blocking. This is not a lock against concurrent substitution.
    try:
        before = os.stat(name, dir_fd=directory_fd, follow_symlinks=False)
        if not stat.S_ISREG(before.st_mode):
            raise ValueError(message)
        fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, dir_fd=directory_fd)
    except OSError as error:
        raise ValueError(message) from error
    try:
        opened = os.fstat(fd)
        if not stat.S_ISREG(opened.st_mode) or stat_identity(opened) != stat_identity(before):
            raise ValueError(message)
        with os.fdopen(fd, "rb", closefd=False) as stream:
            yield stream
    finally:
        os.close(fd)


def stat_identity(info: os.stat_result) -> tuple[int, ...]:
    # Access time is intentionally excluded: reads can update it.
    return (info.st_dev, info.st_ino, info.st_mode, info.st_nlink, info.st_size,
            info.st_mtime_ns, info.st_ctime_ns)


def read_manifest(directory_fd: int) -> tuple[bytes, tuple[int, ...]]:
    with open_regular_at(directory_fd, MANIFEST_NAME, "missing or oversized generation manifest") as stream:
        info = os.fstat(stream.fileno())
        before = stat_identity(info)
        if info.st_nlink != 1:
            raise ValueError("generation manifest must not have hard links")
        if info.st_size > MAX_MANIFEST:
            raise ValueError("missing or oversized generation manifest")
        raw = stream.read(MAX_MANIFEST + 1)
        if len(raw) > MAX_MANIFEST or len(raw) != info.st_size or stat_identity(os.fstat(stream.fileno())) != before:
            raise ValueError("generation manifest changed or exceeds size limit")
        return raw, before


def validate_manifest(raw: bytes, generation: str) -> dict[str, dict[str, object]]:
    """Validate every Space declaration before opening any named index."""
    manifest = json.loads(raw, 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")
    if (not SHA.fullmatch(generation) or manifest["version"] != 1
            or manifest.get("kind") != "search-snapshot-local" or manifest.get("generation") != generation
            or manifest.get("object_layout") != "objects/sha256/<first-two>/<sha256>"):
        raise ValueError("invalid search generation manifest")
    identity = {key: value for key, value in manifest.items() if key not in IDENTITY_EXCLUDED}
    if hashlib.sha256(canonical(identity)).hexdigest() != generation:
        raise ValueError("search manifest identity mismatch")
    files, objects = manifest.get("files"), manifest.get("objects")
    if not isinstance(files, dict) or not isinstance(objects, dict):
        raise ValueError("invalid generation files or objects")
    space, entries, pages = files.get("space"), objects.get("space"), files.get("pages")
    if (not isinstance(space, dict) or not isinstance(entries, dict) or not isinstance(pages, dict)
            or not isinstance(objects.get("pages"), dict)):
        raise ValueError("invalid generation surface structure")
    if set(space) != set(entries):
        raise ValueError("Space manifest member mismatch")
    if not MANDATORY <= set(space) or len(space) > MAX_FILES:
        raise ValueError("Space generation is incomplete")
    for name, metadata in space.items():
        item = entries[name]
        if not safe_name(name) or not isinstance(metadata, dict) or not isinstance(item, dict):
            raise ValueError("invalid Space member")
        digest, size = metadata.get("sha256"), metadata.get("bytes")
        if (set(metadata) != {"sha256", "bytes"} or not isinstance(digest, str) or not SHA.fullmatch(digest)
                or type(size) is not int or not 1 <= size <= MAX_FILE or type(item.get("bytes")) is not int
                or item != {"sha256": digest, "bytes": size, "object": f"objects/sha256/{digest[:2]}/{digest}"}):
            raise ValueError("Space member identity mismatch")
    pages_corpus = pages.get("search_data.json.gz")
    space_corpus = space["search_data.json.gz"]
    if (not isinstance(pages_corpus, dict) or set(pages_corpus) != {"sha256", "bytes"}
            or type(pages_corpus.get("bytes")) is not int or pages_corpus != space_corpus):
        raise ValueError("Pages and Space declared corpus hash or size mismatch")
    return space


class BoundedCompressedReader:
    """Do not consume bytes appended after the initial fstat."""

    def __init__(self, stream: BinaryIO, size: int) -> None:
        self.stream = stream
        self.remaining = size

    def read(self, size: int = -1) -> bytes:
        if size < 0:
            size = self.remaining
        if not self.remaining or not size:
            return b""
        chunk = self.stream.read(min(size, self.remaining))
        if not chunk:
            raise ValueError("compressed stream ended before declared size")
        self.remaining -= len(chunk)
        return chunk


class IndexPreflightBudget:
    """Bound work on varints and entry starts across all three indexes."""

    def __init__(self) -> None:
        self.varint_bytes = 0
        self.entries = 0

    def consume_varint_bytes(self, count: int, name: str) -> None:
        self.varint_bytes += count
        if self.varint_bytes > MAX_TOTAL_INDEX_VARINT_BYTES:
            raise ValueError(f"total index varint byte budget exceeded: {name}")

    def consume_entry(self, name: str) -> None:
        self.entries += 1
        if self.entries > MAX_TOTAL_INDEX_ENTRIES:
            raise ValueError(f"total index entry budget exceeded: {name}")


class IndexVarintPreflight:
    """Stream the generator's VWI2/VNG3 framing, bounding only actual varints.

    sync_to_space writes VWI2 + tokenizer length/bytes + digest, or VNG3 +
    width + digest; both then write record count, entry count and entries of
    key length/bytes, posting count, posting length and delta-coded IDs. Skip
    tokenizer, digest and key bytes verbatim, including across chunk boundaries.
    A loop iteration consumes bytes, advances a zero-length field/entry, or
    returns for more input. All integer shifts and cumulative IDs stay bounded.
    This is a resource guard, not a replacement for the selector's validation.
    """

    def __init__(self, name: str, limit: int, budget: IndexPreflightBudget | None = None) -> None:
        self.name = name
        self.limit = limit
        self.budget = budget if budget is not None else IndexPreflightBudget()
        self.prefix = {"search_words.bin.gz": b"VWI2", "search_ngrams_2.bin.gz": b"VNG3\x02",
                       "search_ngrams_3.bin.gz": b"VNG3\x03"}[name]
        self.state = "prefix"
        self.remaining = len(self.prefix)
        self.next_state = ""
        self.value = 0
        self.varint_bytes = 0
        self.record_count = 0
        self.entries_remaining = 0
        self.previous_id = 0

    def skip(self, length: int, next_state: str) -> None:
        self.state = "skip"
        self.remaining = length
        self.next_state = next_state

    def feed(self, chunk: bytes) -> None:
        offset = 0
        while True:
            if self.state == "skip":
                if not self.remaining:
                    self.state = self.next_state
                    continue
                if offset == len(chunk):
                    break
                size = min(self.remaining, len(chunk) - offset)
                offset += size
                self.remaining -= size
            elif self.state == "prefix":
                if offset == len(chunk):
                    break
                size = min(self.remaining, len(chunk) - offset)
                start = len(self.prefix) - self.remaining
                if chunk[offset:offset + size] != self.prefix[start:start + size]:
                    raise ValueError(f"invalid index header: {self.name}")
                offset += size
                self.remaining -= size
                if not self.remaining:
                    if self.prefix == b"VWI2":
                        self.state = "tokenizer_length"
                    else:
                        self.skip(32, "record_count")
            elif self.state == "postings":
                if not self.remaining:
                    if self.varint_bytes:
                        raise ValueError(f"truncated index posting varint: {self.name}")
                    self.entries_remaining -= 1
                    self.state = "key_length" if self.entries_remaining else "done"
                    continue
                if offset == len(chunk):
                    break
                end = offset + min(self.remaining, len(chunk) - offset)
                # Every posting byte is part of a varint. Charge the segment
                # before iterating it; skipped tokenizer/digest/keys are opaque.
                self.budget.consume_varint_bytes(end - offset, self.name)
                self.remaining -= end - offset
                while offset < end:
                    byte = chunk[offset]
                    offset += 1
                    self.read_varint_byte(byte)
                    if not byte & 0x80:
                        self.previous_id += self.value
                        if self.previous_id >= self.record_count:
                            raise ValueError(f"index posting record id out of range: {self.name}")
                        self.value = self.varint_bytes = 0
            elif self.state == "done":
                if offset != len(chunk):
                    raise ValueError(f"trailing index bytes: {self.name}")
                break
            else:
                if offset == len(chunk):
                    break
                byte = chunk[offset]
                offset += 1
                self.budget.consume_varint_bytes(1, self.name)
                self.read_varint_byte(byte)
                if not byte & 0x80:
                    value = self.value
                    self.value = self.varint_bytes = 0
                    if self.state == "tokenizer_length":
                        self.check_length(value)
                        self.skip(value + 32, "record_count")
                    elif self.state == "record_count":
                        self.record_count = value
                        self.state = "entry_count"
                    elif self.state == "entry_count":
                        self.entries_remaining = value
                        self.state = "key_length" if value else "done"
                    elif self.state == "key_length":
                        self.budget.consume_entry(self.name)
                        self.check_length(value)
                        self.skip(value, "posting_count")
                    elif self.state == "posting_count":
                        self.state = "posting_length"
                    elif self.state == "posting_length":
                        self.check_length(value)
                        self.remaining = value
                        self.previous_id = 0
                        self.state = "postings"
                    else:
                        raise RuntimeError(f"unexpected index preflight state: {self.state}")

    def read_varint_byte(self, byte: int) -> None:
        self.value |= (byte & 0x7f) << (7 * self.varint_bytes)
        self.varint_bytes += 1
        if self.varint_bytes >= MAX_INDEX_VARINT_BYTES and byte & 0x80:
            raise ValueError(f"index varint exceeds {MAX_INDEX_VARINT_BYTES} bytes: {self.name}")

    def check_length(self, value: int) -> None:
        if value > self.limit:
            raise ValueError(f"index length exceeds expanded limit: {self.name}")

    def finish(self) -> None:
        self.feed(b"")  # Complete zero-length fields and postings, if any.
        if self.state != "done":
            raise ValueError(f"truncated index structure: {self.name}")


def preflight_gzip(directory_fd: int, name: str, metadata: dict[str, object], limit: int,
                   kind: str) -> tuple[int, ...]:
    """Verify one bounded gzip member without retaining its expansion."""
    return _preflight_gzip(directory_fd, name, metadata, limit, kind, None)


def _preflight_gzip(directory_fd: int, name: str, metadata: dict[str, object], limit: int,
                    kind: str, index: IndexVarintPreflight | None) -> tuple[int, ...]:
    with open_regular_at(directory_fd, name, f"missing or unlisted required {kind}: {name}") as stream:
        info = os.fstat(stream.fileno())
        before = stat_identity(info)
        size = info.st_size
        if not 1 <= size <= MAX_FILE or size != metadata["bytes"]:
            raise ValueError(f"Space member wrong size: {name}")
        digest = hashlib.sha256()
        compressed = 0
        while chunk := stream.read(min(CHUNK_SIZE, size + 1 - compressed)):
            compressed += len(chunk)
            if compressed > size:
                raise ValueError(f"Space member changed during preflight: {name}")
            digest.update(chunk)
        if compressed != size or digest.hexdigest() != metadata["sha256"]:
            raise ValueError(f"Space member digest mismatch: {name}")
        stream.seek(0)
        expanded = 0
        bounded = BoundedCompressedReader(stream, size)
        header = b""
        while len(header) < GZIP_HEADER_SIZE and bounded.remaining:
            header += bounded.read(GZIP_HEADER_SIZE - len(header))
        # Forbid optional headers (including unbounded FNAME/FCOMMENT) and
        # reserved flags; neither the producer nor the benchmark needs them.
        if len(header) != GZIP_HEADER_SIZE or header[:3] != b"\x1f\x8b\x08" or header[3] != 0:
            raise ValueError(f"invalid compressed {kind} header: {name}")
        decoder = zlib.decompressobj(16 + zlib.MAX_WBITS)
        pending = header
        index_error: ValueError | None = None
        try:
            while True:
                if not pending:
                    pending = bounded.read(CHUNK_SIZE)
                chunk = decoder.decompress(pending, min(CHUNK_SIZE, limit + 1 - expanded))
                expanded += len(chunk)
                if expanded > limit:
                    raise ValueError(f"expanded {kind} exceeds limit: {name}")
                if index is not None and index_error is None:
                    try:
                        index.feed(chunk)
                    except ValueError as error:
                        # Still validate gzip/expansion first, as before. No
                        # more index bytes are interpreted after the error.
                        index_error = error
                if decoder.eof:
                    # zlib stops after one member, unlike gzip.GzipFile and
                    # gzip.decompress. Reject even a single padding byte.
                    if decoder.unused_data or bounded.remaining:
                        raise ValueError(f"{kind} gzip must have one member and no trailing data: {name}")
                    break
                pending = decoder.unconsumed_tail
                if not pending and not bounded.remaining and not chunk:
                    raise ValueError(f"invalid compressed {kind}: {name}")
        except (OSError, zlib.error) as error:
            raise ValueError(f"invalid compressed {kind}: {name}") from error
        if stat_identity(os.fstat(stream.fileno())) != before:
            raise ValueError(f"Space member changed during preflight: {name}")
        if index_error is not None:
            raise index_error
        if index is not None:
            index.finish()
        return before


def preflight_index(directory_fd: int, name: str, metadata: dict[str, object], limit: int,
                    budget: IndexPreflightBudget | None = None) -> tuple[int, ...]:
    return _preflight_gzip(directory_fd, name, metadata, limit, "index", IndexVarintPreflight(name, limit, budget))


def require_stable_paths(directory: Path, root: Path, directory_fd: int, directory_stat: tuple[int, ...],
                         members: dict[str, tuple[int, ...]]) -> None:
    """Detect ordinary replacements; this is not a lock against concurrent writers."""
    try:
        if (stat_identity(os.fstat(directory_fd)) != directory_stat
                or stat_identity(os.stat(directory, follow_symlinks=False)) != directory_stat
                or stat_identity(os.stat(root, follow_symlinks=False)) != directory_stat
                or any(stat_identity(os.stat(name, dir_fd=directory_fd, follow_symlinks=False)) != before
                       for name, before in members.items())):
            raise ValueError("generation paths changed during verification")
    except OSError as error:
        raise ValueError("generation paths changed during verification") from error


def select_generation(directory: Path, generation: str) -> tuple[SelectedGeneration, bytes, dict[str, dict[str, object]]]:
    """Preflight all consumed gzips, then use the Space entry point's complete verifier."""
    # The production selector reopens paths. The caller must prevent concurrent
    # replacement/in-place writes for this entire operation and the benchmark;
    # these fd/stat checks only detect some violations, not adversarial races.
    with open_directory(directory) as directory_fd:
        directory_stat = stat_identity(os.fstat(directory_fd))
        root = directory.resolve(strict=True)
        manifest_bytes, manifest_stat = read_manifest(directory_fd)
        files = validate_manifest(manifest_bytes, generation)
        members = {MANIFEST_NAME: manifest_stat}
        # Check all six direct paths before streaming any, then reopen with the
        # same nonblocking/no-follow flags. This is not a concurrent-write lock.
        for names, kind in ((INDEX_EXPANDED_LIMITS, "index"), (JSON_EXPANDED_LIMITS, "JSON")):
            for name in names:
                with open_regular_at(directory_fd, name, f"missing or unlisted required {kind}: {name}"):
                    pass
        index_budget = IndexPreflightBudget()
        for name, limit in INDEX_EXPANDED_LIMITS.items():
            members[name] = preflight_index(directory_fd, name, files[name], limit, index_budget)
        for name, limit in JSON_EXPANDED_LIMITS.items():
            members[name] = preflight_gzip(directory_fd, name, files[name], limit, "JSON")
        require_stable_paths(directory, root, directory_fd, directory_stat, members)
        selected = inspect_generation(root, generation)
        require_stable_paths(directory, root, directory_fd, directory_stat, members)
        if read_manifest(directory_fd)[0] != manifest_bytes:
            raise ValueError("generation manifest changed during verification")
    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 / MANIFEST_NAME
    with open_directory(root) as directory_fd:
        if read_manifest(directory_fd)[0] != 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 cache_parent(directory: Path, selected: SelectedGeneration) -> Path:
    """Resolve an existing caller-selected temporary root without a write probe."""
    root = directory.resolve(strict=True)
    if not root.is_dir():
        raise ValueError("temporary cache root must be an existing directory")
    if root == selected.directory or root.is_relative_to(selected.directory):
        raise ValueError("temporary cache directory must be outside selected generation")
    return root


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("--temp-dir", type=Path, required=True, help="writable local temp root outside generation")
    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)
    temp_root = cache_parent(options.temp_dir, selected)
    if Path.cwd().resolve().is_relative_to(selected.directory):
        raise ValueError("current directory must be outside selected generation")
    sources = source_hashes()
    # Application import mounts static files relative to the checkout root.
    os.chdir(ROOT)
    from backend import app
    from backend.search.corpus.infrastructure import indexes as 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)
    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; indexes locally preflighted as one gzip member "
                           "and three JSON gzips likewise, with no optional header or trailing bytes, 32 MiB "
                           "compressed, 256 MiB JSON, and 32/48/64 MiB index expansion limits; index varints "
                           "and posting ID ranges are locally bounded; all three indexes share a 40,000,000 "
                           "varint-byte and 1,200,000 entry preflight budget; other valid gzip encodings may be "
                           "rejected; index encodings may also be rejected, including valid large or non-minimal "
                           "indexes; this benchmark does not "
                           "protect production selector calls; "
                           "Pages corpus hash and size compared as manifest declarations only; Pages files and "
                           "deployment not verified; identity is not authenticated provenance; full posting semantics "
                           "not independently proven; directory, ancestors and files must remain immutable during run; "
                           "preflight is not a lock or a total CPU or memory bound",
        "generation": selected.generation,
        "pages_corpus_declaration_matches_space": True,
        "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())