hf2q 0.1.32

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
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
"""Offline authentication of actual Native9, diagnostic, source and original-reference evidence."""

import json
from pathlib import Path
import re
from c2_matrix_io import acquisition, digest, integer, payload, read_json, require, resolve
from c2_controller_state_authority import PREFIX, NATIVE9_PROOF_SHA, NATIVE9_SOURCES, ORIGINAL_INVENTORY_SHA, NATIVE_CHECKSUM, closed, tokens, authority, file_bytes, check_sources, current_identity
from c2_controller_state_disk import mounted_attempt, prepared_sources_checked, retained_disk_checked, working_disk


def native9_checked(context):
    require(context["native9_proof"]["sha256"] == NATIVE9_PROOF_SHA, "unapproved Native9 proof identity")
    proof = authority(context["native9_proof"])
    files = context["native9_source_bindings"]
    check_sources(files)
    require(len(files) == len(NATIVE9_SOURCES)
            and {Path(path).name: sha for path, sha in files.items()} == NATIVE9_SOURCES,
            "Native9 complete reviewed source closure differs")
    require(proof["schema"] == "hf2q.private.native-real-transition-proof.v3"
            and proof["passed"] is True and proof["retain_lease"] is False
            and type(proof["models_loaded"]) is int and proof["models_loaded"] == 0
            and proof["qualification_claim"] is False and files.items() <= proof["source_sha256"].items(),
            "actual frozen source-bound Native9 proof incomplete")
    check_sources(proof["source_sha256"])
    return files


def native_cleanup(receipt):
    cleanup = receipt["cleanup"]
    require(cleanup["schema"] == "hf2q.private.native-owned-lifetime.v1"
            and cleanup["proven"] is True and cleanup["direct_child_reaped"] is True
            and cleanup["exit_codes"] == [0] and cleanup["remaining"] == []
            and cleanup["errors"] == [] and cleanup["refused_pgids"] == []
            and integer(cleanup["native_observations"], "actual native lifetime observations", 1),
            "actual Native9 zero-exit/reaped/empty-collection proof absent")
    require(receipt["retain_lease"] is False and receipt["errors"] == [], "native outer failed/retained")


def diagnostic_cleanup(receipt):
    native_cleanup(receipt)
    cleanup = receipt["cleanup"]
    require(receipt["exit"] == 0 and receipt["interruption_signals"] == [] and receipt["sampler_error"] is None
            and receipt["sampler_alive"] is False
            and receipt["spawn_ns"] <= integer(cleanup["empty_ns"], "native empty time") <= receipt["completed_monotonic_ns"],
            "diagnostic incomplete, interrupted or not actually stopped")
    known = receipt["known_owned_lifetimes"]
    require(type(known) is list and known
            and len({(row["pid"], row["lifetime_id"]) for row in known}) == len(known)
            and any(row["pid"] == row["pgid"] == receipt["pid"] for row in known)
            and all(type(row["pid"]) is int and row["pid"] > 1 and type(row["pgid"]) is int and row["pgid"] > 1
                    and type(row["lifetime_id"]) is str and row["lifetime_id"].startswith("darwin-unique:")
                    and type(row["pid_version"]) is int and row["pid_version"] >= 0 for row in known)
            and cleanup["pgids"] == sorted({row["pgid"] for row in known}), "actual native lifetime cohort absent")


def reaction_checked(receipt, prepared, series):
    from q5_policy import effective_floor
    policy, cfg = prepared["policy"], prepared["config"]
    spec = policy["measured_admission"]
    require(spec["schema"] == "hf2q.private.c2-measured-admission.v1", "actual measured RAM policy absent")
    control, manifest, seed = authority(spec["stop_control"]), authority(spec["control_inputs"]), authority(spec["depletion_seed"])
    require(control["schema"] == "hf2q.private.native9-bounded-stop-probe.v1"
            and control["passed"] is True and control["retain_lease"] is False
            and control["models_loaded"] == 0 and control["model_admission"] is False
            and control["signals"] == [] and control["error"] is None and control["exit"] == -15
            and control["accepted_manifest_sha256"] == spec["control_inputs"]["sha256"]
            and control["boot_time"] == manifest["boot_time"] and manifest["model_loads_authorized"] == 0
            and control["observer"] == cfg["observers"], "actual nonmodel Native9 measured stop control absent")
    check_sources(manifest["files"])
    native_hashes = [sha for path, sha in prepared["file_sha256"].items() if Path(path).name == "native_owned.py"]
    identity_hashes = [sha for path, sha in prepared["file_sha256"].items() if Path(path).name == "cache_release_orchestrator.py"]
    require(control["native_source_sha256"] in native_hashes
            and control["identity_source_sha256"] in identity_hashes,
            "actual measured stop control used another native ownership/identity source")
    cleanup = control["cleanup"]
    require(cleanup["proven"] is True and cleanup["direct_child_reaped"] is True
            and cleanup["remaining"] == [] and cleanup["errors"] == [] and cleanup["refused_pgids"] == [],
            "measured stop control did not prove native empty cohort")
    latency = cleanup["empty_ns"] - control["stop"]["sample_start_ns"]
    require(integer(latency, "measured complete sample-to-empty latency", 1) == control["sample_to_empty_ns"]
            and control["ceiling_bytes"] == manifest["ceiling_bytes"] == 8 * 1024**3
            and control["footprint_stop_bytes"] == manifest["footprint_stop_bytes"] == 4 * 1024**3
            and control["stop"]["footprint_bytes"] > control["footprint_stop_bytes"], "actual measured stop latency differs")
    require(seed["schema"] == "hf2q.private.c2-depletion-seed.v1"
            and seed["scope"] == "whole-child-lifetime-including-load" and seed["family"] == policy["family"]
            and seed["physical_fit_claim"] is False and seed["footprint_cap_claim"] is False and seed["series"],
            "source-bound whole-lifetime depletion seed absent")
    archive = resolve(Path("/"), seed["archive"], absolute=True)
    payload(archive, seed["archive"]["sha256"], archive.stat().st_size)
    for row in seed["series"]:
        for key in ("drop_bytes", "interval_ns", "max_rate_bytes_per_second"):
            integer(row[key], "actual depletion seed " + key, 1)
        require(row["max_rate_bytes_per_second"] == (row["drop_bytes"] * 1_000_000_000 + row["interval_ns"] - 1) // row["interval_ns"],
                "source-bound depletion seed rate differs")
    seed_rate = max(row["max_rate_bytes_per_second"] for row in seed["series"])
    require(seed_rate == seed["max_rate_bytes_per_second"], "source-bound maximum depletion seed differs")
    gap = integer(spec["max_sample_gap_ns"], "actual maximum sampler gap", 1, 1_000_000_000)
    base = integer(spec["base_floor_bytes"], "actual RAM base floor", 4 * 1024**3)
    prior_rate = 0 if prepared["matched_cap"] is None else prepared["matched_cap"]["max_drop_rate_bytes_per_second"]
    rate, observed = max(seed_rate, prior_rate), 0
    previous = (receipt["prelaunch_observation"]["start_ns"],
                receipt["prelaunch_observation"]["physical"]["free"] + receipt["prelaunch_observation"]["physical"]["cached_files"])
    for row in series:
        at, free = receipt["spawn_ns"] + row["t_ns"], row["free_plus_cached"]
        elapsed = at - previous[0]
        require(0 < elapsed <= gap, "actual reaction observation interval invalid")
        drop = max(0, previous[1] - free)
        observed = max(observed, (drop * 1_000_000_000 + elapsed - 1) // elapsed)
        rate = max(rate, observed)
        previous = (at, free)
    expected = {"schema": "hf2q.private.c2-measured-reaction.v1", "seed_scope": "whole-child-lifetime-including-load",
                "seed_rate_bytes_per_second": seed_rate, "observed_max_rate_bytes_per_second": observed,
                "max_drop_rate_bytes_per_second": rate, "max_sample_gap_ns": gap,
                "sample_to_empty_latency_ns": latency, "effective_floor_bytes": effective_floor(base, rate, gap / 1e9, latency)}
    require(receipt["reaction"] == expected, "whole measured RAM reaction floor differs")
    require(policy["preload_available_floor_bytes"] == policy["runtime_available_floor_bytes"]
            == effective_floor(base, seed_rate, gap / 1e9, latency), "source RAM initial reaction policy differs")


def measured_attempt(receipt, prepared):
    """Recompute raw process/host peaks, per-sample caps and complete disk charge."""
    root, policy = Path(prepared["output"]), prepared["policy"]
    raw = authority(receipt["memory_series"])
    require(raw["schema"] == "hf2q.q1.endpoint-memory-series.v1"
            and Path(receipt["memory_series"]["path"]) == root / "memory-series.json",
            "actual bound diagnostic memory series absent")
    series = raw["series"]
    memory = receipt["memory"]
    require(type(series) is list and series and len(series) == memory["runtime_samples"], "whole measured memory series absent")
    baseline = receipt["baseline_observations"]
    require(type(baseline) is list and len(baseline) == 12, "whole actual twelve-sample preload baseline absent")
    static = integer(prepared["retained_outputs"]["bytes"], "separate retained disk charge")
    require(receipt["other_listed_out_bytes"] == static, "retained-output charge changed")
    allocation = prepared["allocation"]
    paths = sorted(root.glob("process-*.json"), key=lambda path: int(path.stem.split("-")[1]))
    require([path.name for path in paths] == [f"process-{i}.json" for i in range(len(series))],
            "whole raw owned process sample inventory absent")
    baseline_swap = baseline[0]["sample"]["swap_bytes"]
    minimum = min(entry["sample"]["physical"]["free"] + entry["sample"]["physical"]["cached_files"] for entry in baseline)
    require(memory["baseline"]["min_free_plus_cached_bytes"] == minimum, "measured baseline minimum differs")
    floor = max(integer(policy["runtime_available_floor_bytes"], "runtime floor", 1),
                integer(receipt["reaction"]["effective_floor_bytes"], "observed reaction floor", 1))
    require(floor >= policy["runtime_available_floor_bytes"], "actual recorded RAM/reaction floor weakened")
    require(allocation["internal_free_floor_bytes"] >= 12884901888
            and allocation["output_free_floor_bytes"] >= 12884901888,
            "frozen independent filesystem free floor weakened")
    disk_cap = integer(allocation["disk_upper_bytes"], "source allocation output grant", 1)
    def disk(value):
        integer(value, "actual owned output bytes")
        require(value <= disk_cap and static + value <= 843671408455, "independent raw disk ceiling/grant breached")
        require(static + disk_cap <= policy["paired_disk_working_limit_bytes"],
                "complete paired diagnostic disk working cap breached")
    for entry in baseline:
        sample = entry["sample"]
        disk(entry["owned_output_bytes"])
        available = sample["physical"]["free"] + sample["physical"]["cached_files"]
        require(sample["pressure_raw"] == "1" and sample["swap_bytes"] == baseline_swap
                and available >= max(floor, policy["preload_available_floor_bytes"]), "baseline pressure/swap/floor breached")
    reserve = receipt["admission_reservation"]
    fresh = receipt["prelaunch_observation"]
    disk(reserve["live_output_bytes"])
    require(reserve["retained_output_bytes"] == static
            and reserve["source_known_payload_bytes"] == allocation["peak_known_payload_bytes"]
            and reserve["available_bytes"] == fresh["physical"]["free"] + fresh["physical"]["cached_files"]
            and reserve["available_bytes"] - reserve["charged_bytes"] >= floor,
            "actual measured prelaunch reservation differs")
    values, previous, process_identity = [], fresh["start_ns"], None
    for index, (row, path) in enumerate(zip(series, paths)):
        ledger, _ = read_json(path)
        value = json.loads(ledger["stdout"])
        at = receipt["spawn_ns"] + integer(row["t_ns"], "raw sample time")
        require(previous <= at <= ledger["begin_ns"] <= ledger["end_ns"]
                and at - previous <= policy["measured_admission"]["max_sample_gap_ns"]
                and row["pressure_raw"] == "1" and row["available"] == row["free_plus_cached"]
                and row["available"] >= floor and row["swap"] <= baseline_swap
                and row["compressor"] - baseline[0]["sample"]["physical"]["compressor"] <= policy["max_compressor_growth_bytes"],
                "actual raw operating sample pressure/swap/floor/compressor breached")
        previous = at
        disk(row["owned_output_bytes"])
        require(row["disk_bytes"] == static + row["owned_output_bytes"], "raw disk charge differs")
        require(ledger["argv"] == [prepared["config"]["observers"]["proc"]["path"], str(receipt["pid"])],
                "raw process probe observed another process")
        if ledger["exit"] == 0 and value.get("available") is True:
            require(value["pid"] == receipt["pid"] and row["footprint"] == value["phys_footprint"]
                    and row["resident"] == value["resident_size"], "raw owned process memory differs")
            require(value["flavor"] == 4 and value["scope"] == "raw_Darwin_process_ledger_not_unique_host_partition"
                    and re.fullmatch(r"[0-9a-f]{32}", value["uuid"]), "raw owned process ledger identity/scope invalid")
            for key in ("begin_abstime", "end_abstime", "start_abstime", "resident_size", "wired_size",
                        "phys_footprint", "lifetime_max_phys_footprint", "interval_max_phys_footprint"):
                integer(value[key], "raw process " + key)
            require(value["start_abstime"] <= value["begin_abstime"] <= value["end_abstime"], "raw process time order differs")
            identity = (value["start_abstime"], value["uuid"])
            require(process_identity is None or identity == process_identity, "raw owned target PID identity changed")
            process_identity = identity
            require(0 <= ledger["end_ns"] - ledger["begin_ns"] <= 500_000_000,
                    "raw owned process ledger exceeded reviewed query duration")
            values.append(value)
        else:
            require(index == len(series) - 1 and ledger == receipt["terminal_ledger_race"]
                    and row["footprint"] is None and row["resident"] is None, "unproved process sample gap")
    require(values, "no actual owned process measurement")
    peak, rss = max(value["phys_footprint"] for value in values), max(value["resident_size"] for value in values)
    charge = max(0, minimum - min(row["free_plus_cached"] for row in series))
    require((memory["peak_phys_footprint_bytes"], memory["peak_resident_bytes"], memory["charged_bytes"]) == (peak, rss, charge),
            "raw measured footprint/resident/depletion boundary differs")
    terminal = receipt["terminal_observation"]
    require(receipt["cleanup"]["empty_ns"] <= terminal["start_ns"] <= receipt["completed_monotonic_ns"]
            and terminal["pressure_raw"] == "1" and terminal["swap_bytes"] <= baseline_swap
            and terminal["physical"]["free"] + terminal["physical"]["cached_files"] >= floor,
            "post-cleanup actual terminal observation absent/unsafe")
    disk(receipt["terminal_owned_output_bytes"])
    measured_disk = working_disk(prepared)
    # Postreceipt metadata is charged, never refunded or mistaken for RAM.
    disk(max(measured_disk, receipt["terminal_owned_output_bytes"]))
    mounted_attempt(receipt, prepared, series, measured_disk)
    retained_disk_checked(prepared)
    reaction_checked(receipt, prepared, series)
    return peak, rss, charge


def diagnostic_attempt(prepared_binding, receipt_binding, expected_mode):
    prepared, receipt = authority(prepared_binding), authority(receipt_binding)
    cfg = prepared["config"]
    closed(cfg, "schema name mode endpoint test_binary production_binary source_manifest build_receipt packet env allocation resource_policy observers production_predecessor previous_cleanup footprint_record root_identity operating_review retained_outputs resource_compatibility", "actual diagnostic configuration")
    require(prepared["schema"] == "hf2q.private.c2-diagnostic-prepared.v1"
            and receipt["schema"] == "hf2q.private.c2-diagnostic-attempt.v1"
            and cfg["schema"] == "hf2q.private.c2-diagnostic-config.v1"
            and cfg["mode"] == receipt["mode"] == expected_mode
            and authority(prepared["config_binding"]) == cfg
            and receipt["diagnostic_key_sha256"] == prepared["diagnostic_key_sha256"]
            and receipt["packet"] == cfg["packet"] and receipt["env"] == cfg["env"]
            and receipt["file_sha256"] == prepared["file_sha256"]
            and receipt["allocation"] == cfg["allocation"]
            and receipt["matched_cap"] == prepared["matched_cap"]
            and receipt["diagnostic_pass"] is True and receipt["model_launch_attempted"] is True
            and receipt["acquisition_complete"] is True and receipt["physical_admission"] is False
            and receipt["calibration_kind"] == "Q1FootprintRecordNotQ5CalibrationPass",
            "actual source-bound measured diagnostic attempt incomplete")
    digest(prepared["diagnostic_key_sha256"])
    require(Path(receipt_binding["path"]) == Path(prepared["output"]) / "receipt.json"
            and Path(prepared_binding["path"]) == Path(prepared["output"]).parent / "prepared.json",
            "diagnostic prepared/attempt namespace differs")
    prepared_sources_checked(prepared)
    diagnostic_cleanup(receipt)
    raw_stdout, raw_stderr = file_bytes(receipt["stdout"]), file_bytes(receipt["stderr"])
    test = prepared["plan"]["test"]
    require(b"test result: ok. 1 passed; 0 failed; 0 ignored;" in raw_stdout
            and ("test " + test + " ... ").encode() in raw_stdout
            and receipt["argv"] == [cfg["test_binary"]["path"], "--ignored", "--exact", test, "--nocapture", "--test-threads=1"],
            "actual completed exact libtest endpoint differs")
    require(prepared["plan"]["kind"] == "fresh-http" and prepared["plan"]["packet_env"] == "HF2Q_C2_FRESH_HTTP_PACKET",
            "not actual production fresh HTTP endpoint")
    peak = measured_attempt(receipt, prepared)
    return prepared, receipt, peak, raw_stderr


def strict_production_predecessor(reference, cfg, identity):
    chain = authority(reference)
    require(chain["schema"] == "hf2q.private.c2-diagnostic-production-predecessor.v1",
            "actual production predecessor chain absent")
    production, strict, outer = (authority(chain[key]) for key in ("q5_receipt", "strict_receipt", "outer_receipt"))
    manifest, case = authority(chain["outer_manifest"]), authority(chain["case"])
    request, completed = authority(chain["producer_request"]), authority(chain["producer_result"])
    source = authority(cfg["source_manifest"])
    require(request["source_commit"] == source["source_commit"] == identity["source_commit"]
            and request["case"] == chain["case"] and request["manifest"] == chain["outer_manifest"]
            and request["role_id"] == completed["role_id"]
            and request["role"]["kind"] == "fresh canonical production Q5 calibration"
            and completed["accepted"] is True and completed["cleanup_proven"] is True
            and completed["retain_lease"] is False and completed["request"] == chain["producer_request"]
            and completed["outer"] == chain["outer_receipt"] and completed["strict"] == chain["strict_receipt"],
            "production predecessor is not actual completed same-current-source Native9 calibration")
    check_sources(request["file_sha256"])
    require(source["file_sha256"].items() <= request["file_sha256"].items(),
            "production predecessor omitted current compiled source closure")
    require(production["schema"] == "hf2q.q5.calibration-receipt.v1"
            and production["verdict"] == {"verdict": "CalibrationPass", "reason": None}
            and production["run_kind"] == "calibration"
            and production["cleanup_proven"] is True and production["cleanup"]["proven"] is True
            and production["sampler_error"] is None
            and production["binary"]["sha256"] == cfg["production_binary"]["sha256"] != identity["binary_sha256"]
            and production["artifact"]["sha256"] == identity["model_sha256"]
            and production["host"] == chain["host"] and production["workload"] == case["workload"]
            and production["family"] == case["family"] == identity["family"].lower()
            and case["workload"]["slots"] == 4 and case["workload"]["context_per_slot"] == 262144
            and case["workload"]["anchors_per_slot"] == chain["depth"] == 4 and chain["route"] == "legacy-off",
            "not actual full same-model production Q5 predecessor")
    native_cleanup(outer)
    require(strict["passed"] is True and strict["cleanup_proven"] is True
            and strict["cleanup"]["proven"] is True and strict["cleanup"]["remaining"] == []
            and outer["passed"] is True and outer["cleanup_proven"] is True
            and outer["manifest_sha256"] == chain["outer_manifest"]["sha256"]
            and outer["argv"] == manifest["units"]["outer"]["argv"], "strict/native predecessor supervision failed")
    command = outer["argv"]
    require(type(command) is list and "--" in command and all(type(arg) is str for arg in command), "actual strict outer command absent")
    split = command.index("--")
    prefix, canonical = command[:split], command[split + 1:]
    require(prefix.count("--output") == 1 and canonical
            and strict["argv"] == strict["canonical_binding"]["argv"] == canonical,
            "strict/native command chain differs")
    require(Path(prefix[prefix.index("--output") + 1]) / "receipt.json" == Path(chain["strict_receipt"]["path"])
            and Path(strict["canonical_binding"]["receipt_path"]) == Path(chain["q5_receipt"]["path"]),
            "strict/native actual output/production Q5 receipt differs")
    for key in ("q5_receipt", "strict_receipt", "outer_receipt", "outer_manifest"):
        file_bytes(chain[key])
    if "file_sha256" in chain:
        check_sources(chain["file_sha256"])
    return chain


def source_review_checked(context, identity, prepared):
    sources = authority(context["source_manifest"])
    require(sources["schema"] == "hf2q.private.c2-diagnostic-source-manifest.v1"
            and sources["source_commit"] == identity["source_commit"], "current compiled source manifest identity differs")
    root = Path(sources["root"])
    require(root.is_absolute() and root.resolve(strict=True) == root, "current reviewed source root aliases")
    required = {str(path) for path in (root / "src").rglob("*.rs")}
    required.update(str(root / name) for name in ("Cargo.toml", "Cargo.lock", "build.rs") if (root / name).is_file())
    require(required and required <= sources["file_sha256"].keys(), "complete current Rust/Cargo build source closure absent")
    check_sources(sources["file_sha256"])
    cfg = prepared["config"]
    build = authority(cfg["build_receipt"])
    require(cfg["source_manifest"] == context["source_manifest"] and cfg["test_binary"] == context["test_binary"]
            and build["schema"] == "hf2q.private.c2-diagnostic-build.v1" and build["kind"] == "cfg(test)-libtest"
            and build["binary"] == context["test_binary"] and build["source_manifest"] == context["source_manifest"]
            and build["source_commit"] == identity["source_commit"] and prepared["plan"]["test"] in build["exact_tests"],
            "current TEST IMAGE compiled source/list identity differs")
    binary = resolve(Path("/"), context["test_binary"], absolute=True)
    payload(binary, identity["binary_sha256"], binary.stat().st_size)
    require(context["test_binary"]["sha256"] == identity["binary_sha256"], "production/application digest substituted for TEST IMAGE")
    import tomllib
    lock = tomllib.loads((root / "Cargo.lock").read_text())
    pins = [entry for entry in lock["package"] if entry["name"] == "mlx-native"]
    require(len(pins) == 1 and pins[0]["version"] == "0.24.0" and pins[0]["checksum"] == NATIVE_CHECKSUM,
            "actual published Native pin differs")
    review = authority(context["layout_source_review"])
    closed(review, "schema subject_identity source_manifest test_binary reviewer files properties verdict", "layout source review")
    require(review["schema"] == PREFIX + "layout-source-review.v1" and review["subject_identity"] == identity
            and review["source_manifest"] == context["source_manifest"] and review["test_binary"] == context["test_binary"]
            and type(review["reviewer"]) is str and review["reviewer"].strip()
            and review["verdict"] == "Accepted", "independent current compiled layout source review absent")
    properties = closed(review["properties"],
        "complete_before_read target_mtp_linear_parity_ledger aggregate_preread_ram_readback_disk native_scheduler_owner_joins missing_events_fail_closed checked_terminal_synchronization",
        "layout source review properties")
    require(all(value is True for value in properties.values()), "reviewed before-read/source custody obligations incomplete")
    check_sources(review["files"])
    require(review["files"].items() <= sources["file_sha256"].items(), "reviewed writer/geometry source differs from actual compiled closure")
    required_names = {"engine.rs", "controller_state.rs", "controller_state_anchor.rs", "state_layout.rs", "trace.rs"}
    require(required_names <= {Path(path).name for path in review["files"]}
            and any("kv_cache" in path for path in review["files"]), "complete writer/cache geometry source review closure absent")
    operating = authority(cfg["operating_review"])
    require(review["reviewer"] != cfg["root_identity"] and operating["root_identity"] == cfg["root_identity"]
            and operating["verdict"] == "AcceptedForOneAttempt"
            and operating["source_manifest"] == context["source_manifest"]
            and operating["test_binary"] == context["test_binary"] and operating["packet"] == cfg["packet"],
            "layout source review not distinct from producer/operating subject")
    return sources


def packet_acquisition(packet, packet_binding, actual):
    identity = packet["identity"]
    composition = authority(packet["acquisition"]["composition"])
    review = authority(packet["acquisition"]["independent_review"])
    closed(packet["acquisition"], "composition independent_review", "native acquisition bindings")
    closed(composition, "schema comparison_key model_file full_content_receipt", "source acquisition composition")
    require(composition["schema"] == "hf2q.q1.acquisition-composition.v1" and composition["comparison_key"] == identity
            and review == {"schema": "hf2q.q1.acquisition-review.v1", "verdict": "Accepted",
                           "composition_sha256": packet["acquisition"]["composition"]["sha256"]},
            "actual independently reviewed acquisition composition differs")
    full = authority(composition["full_content_receipt"])
    def contains(value):
        if type(value) is dict:
            return any(contains(child) for child in value.values())
        if type(value) is list:
            return any(contains(child) for child in value)
        return value == identity["model_sha256"]
    require(contains(full), "bound full-content receipt does not identify original model")
    model = Path(packet["model"])
    require(model.is_absolute() and model.resolve(strict=True) == model, "opened model source aliases")
    info = model.stat()
    descriptor = dict(device=info.st_dev, inode=info.st_ino, bytes=info.st_size,
        mtime=info.st_mtime_ns // 1_000_000_000, mtime_ns=info.st_mtime_ns % 1_000_000_000,
        ctime=info.st_ctime_ns // 1_000_000_000, ctime_ns=info.st_ctime_ns % 1_000_000_000)
    require(actual["opened_model"] == composition["model_file"] == descriptor
            and actual["actual_binary_sha256"] == identity["binary_sha256"]
            and actual["packet_sha256"] == packet_binding["sha256"]
            and actual["composition_sha256"] == packet["acquisition"]["composition"]["sha256"]
            and actual["independent_review_sha256"] == packet["acquisition"]["independent_review"]["sha256"],
            "actual opened model/TEST IMAGE/config/source/packet acquisition differs")
    acquisition(actual, actual, Path(packet["output"]))


def original_inputs(binding, family):
    inputs = authority(binding)
    closed(inputs, "schema family case workload_kind variant_fixture lanes origin_inventory origin", "original registered inputs")
    require(inputs["schema"] == "hf2q.c2.fresh-fixed-inputs.v1" and inputs["family"] == family
            and inputs["origin_inventory"]["sha256"] == ORIGINAL_INVENTORY_SHA, "original input inventory identity differs")
    inventory = authority(inputs["origin_inventory"])
    require(inventory["schema"] == "hf2q.private.c2-original-http-input-inventory.v1"
            and inventory["requests"] == 116 and len(inventory["origins"]) == 4, "independent original inventory incomplete")
    def projection(lanes):
        return [{"lane": lane["lane"], "summary": lane["summary"],
                 "turns": [{key: item[key] for key in ("turn", "request", "receipt", "response")}
                           for item in lane["turns"]]} for lane in lanes]
    matches = [origin for origin in inventory["origins"]
               if origin["family"] == family and origin["origin"] == inputs["origin"]
               and origin["variant"].split("-")[0] == inputs["workload_kind"]
               and projection(origin["lanes"]) == projection(inputs["lanes"])]
    require(len(matches) == 1, "registered inputs omitted/changed original request/receipt/response inventory")
    case = authority(inputs["case"])
    require(case["schema"] == "hf2q.q5.calibration-case.v1" and case["family"] == family.lower()
            and case["workload"]["slots"] == 4 and case["workload"]["context_per_slot"] == 262144
            and case["workload"]["anchors_per_slot"] == 4, "not unchanged original four-agent full-context case")
    requests = {}
    require(type(inputs["lanes"]) is list and len(inputs["lanes"]) == 4, "whole original four-lane input inventory absent")
    for lane, entry in enumerate(inputs["lanes"]):
        closed(entry, "lane summary turns", "original lane")
        require(entry["lane"] == lane and len(entry["turns"]) == matches[0]["turn_counts"][lane], "original lane/turn extent differs")
        summary = authority(entry["summary"])
        require(summary["agent_id"] == f"agent-{lane}" and len(summary["turns"]) == len(entry["turns"]), "archived input summary differs")
        for turn, item in enumerate(entry["turns"]):
            closed(item, "turn request receipt response", "original HTTP input triple")
            raw, response, receipt = file_bytes(item["request"]), file_bytes(item["response"]), authority(item["receipt"])
            require(item["turn"] == turn and receipt == summary["turns"][turn]
                    and receipt["turn"] == turn and receipt["http_status"] == 200
                    and receipt["request_sha256"] == item["request"]["sha256"]
                    and receipt["request_bytes"] == len(raw) and receipt["response_sha256"] == item["response"]["sha256"]
                    and receipt["response_bytes"] == len(response), "original archived input triple custody differs")
            request = json.loads(raw)
            require(request["max_completion_tokens"] == 8192 and request["tool_choice"] == "auto"
                    and request["hf2q_overflow_policy"] == "reject" and request["stream"] is bool(turn % 2),
                    "original request controls changed")
            requests[lane, turn] = (item["request"], raw)
    return inputs, requests


def observation_document(binding, request, packet, packet_binding, actual=None, unforced=False):
    value = authority(binding)
    closed(value, "ticket generation prepared terminal stop_selection request response response_headers server_request request_headers server_response server_response_sha256 server_response_bytes http_finish_reason completion_counter published_completion_tokens acquisition actual_routes raw_decisions gpu_frozen_selector_used actual_gpu_argmax", "completed native HTTP observation")
    prepared, terminal = value["prepared"], value["terminal"]
    closed(prepared, "request_sha256 prompt params registration_architecture cached_tokens transactions", "actual native preparation")
    closed(terminal, "request_sha256 slot decisions generated finish_reason native_step", "actual native terminal")
    require(type(value["ticket"]) is str and re.fullmatch(r"[A-Za-z0-9_-]{1,192}", value["ticket"]),
            "actual HTTP ticket absent")
    integer(value["generation"], "actual native generation", 1)
    integer(terminal["slot"], "actual native physical slot", 0, 3)
    integer(terminal["native_step"], "actual native terminal step", 1)
    request_binding, raw = request
    require(file_bytes(value["request"]) == file_bytes(value["server_request"]) == raw
            and prepared["request_sha256"] == terminal["request_sha256"] == request_binding["sha256"],
            "actual client/server/native original request custody differs")
    headers = authority(value["request_headers"])
    closed(headers, "ticket headers", "actual ingress headers")
    require(headers["ticket"] == value["ticket"]
            and [bytes(row[1]) for row in headers["headers"] if row[0].lower() == "x-hf2q-c2-ticket"] == [value["ticket"].encode()],
            "actual native ingress ticket join differs")
    prompt, decisions, generated = (tokens(prepared["prompt"], "actual prompt"),
                                   tokens(terminal["decisions"], "actual decisions"),
                                   tokens(terminal["generated"], "actual generated"))
    require(prompt and len(prompt) + 8192 <= 262144 and decisions
            and len(generated) <= len(decisions) <= len(generated) + 1 and len(decisions) <= 8192
            and decisions[:len(generated)] == generated and terminal["finish_reason"] in ("stop", "length")
            and (terminal["finish_reason"] != "length" or len(generated) == 8192),
            "actual native continuation/terminal allowance differs")
    stop = value["stop_selection"]
    if stop is None:
        require(len(decisions) == len(generated), "suppressed terminal selection not observed")
    else:
        closed(stop, "token cause", "actual native stopping selection")
        require(stop["cause"] in ("eos", "grammar") and terminal["finish_reason"] == "stop"
                and len(decisions) == len(generated) + 1 and decisions[-1] == stop["token"], "native stop selection differs")
    integer(prepared["cached_tokens"], "actual admitted cached tokens", 0, len(prompt))
    require(prepared["registration_architecture"] and prepared["params"]["max_tokens"] == 8192,
            "actual native frozen architecture/allowance absent")
    tape, covered = prompt + decisions, set()
    require(type(prepared["transactions"]) is list and prepared["transactions"], "actual native forward input boundaries absent")
    for call in prepared["transactions"]:
        closed(call, "start input logit_rows hidden_rows route", "native forward boundary")
        start = integer(call["start"], "actual native input start")
        consumed = tokens(call["input"], "actual consumed input")
        require(consumed and len(consumed) <= 8192 and start + len(consumed) <= 262144,
                "actual native input extent invalid")
        end = start + len(consumed)
        integer(call["logit_rows"], "actual projected logit rows", 1, len(consumed))
        integer(call["hidden_rows"], "actual projected hidden rows", 0, len(consumed))
        require(type(call["route"]) is str and call["route"] in value["actual_routes"], "actual forward route witness missing")
        for index in range(len(decisions)):
            position = len(prompt) - 1 + index
            if end - call["logit_rows"] <= position < end and consumed[:position - start + 1] == tape[start:position + 1]:
                covered.add(index)
    require(covered == set(range(len(decisions))), "whole original native decision input provenance absent")
    response = file_bytes(value["response"])
    require(response == file_bytes(value["server_response"])
            and value["server_response_sha256"] == value["response"]["sha256"] == value["server_response"]["sha256"]
            and value["server_response_bytes"] == len(response) and authority(value["response_headers"])["status"] == 200
            and value["completion_counter"] == "generated_tokens" and value["published_completion_tokens"] == len(generated),
            "actual successful native/HTTP response/publication differs")
    tokens(value["raw_decisions"], "raw decisions")
    require(len(value["raw_decisions"]) == len(decisions) and type(value["gpu_frozen_selector_used"]) is bool,
            "raw native decision/selector extent differs")
    if unforced:
        require(value["raw_decisions"] == decisions and value["gpu_frozen_selector_used"] is False, "registered original reference was forced")
    if actual is not None:
        acquisition(value["acquisition"], actual, Path(packet["output"]))
    else:
        packet_acquisition(packet, packet_binding, value["acquisition"])
    return value


def registered_observations(packet):
    registration = authority(packet["registration"])
    closed(registration, "schema capture independent_audit run_receipt reference_id", "original registration")
    require(registration["schema"] == "hf2q.c2.fresh-fixed-input-registration.v1"
            and registration["reference_id"] == registration["capture"]["sha256"], "original registration content ID differs")
    capture, audit, run = (authority(registration[key]) for key in ("capture", "independent_audit", "run_receipt"))
    closed(capture, "schema inputs owner_decision identity packet token_table lanes reference_route prefill_chunk acquisition_nonce complete unforced historical_native_identity_recovered whole_c2_pass", "original unforced capture")
    require(capture["schema"] == "hf2q.c2.fresh-fixed-input-capture.v1"
            and capture["inputs"] == packet["inputs"] and capture["complete"] is True and capture["unforced"] is True
            and capture["whole_c2_pass"] is False and capture["historical_native_identity_recovered"] is False
            and capture["reference_route"] == "fresh-fixed-input-HTTP-OFF-unforced-K4",
            "original independently registered unforced reference differs")
    require(audit["schema"] == "hf2q.c2.fresh-fixed-input-audit.v1" and audit["verdict"] == "Accepted"
            and audit["capture_sha256"] == registration["capture"]["sha256"]
            and audit["run_receipt_sha256"] == registration["run_receipt"]["sha256"]
            and audit["owner_decision_sha256"] == capture["owner_decision"]["sha256"]
            and audit["all_lanes_all_turns"] is True and audit["unforced_native_tapes"] is True
            and audit["historical_archives_unchanged"] is True and audit["real_task_quality_proved"] is False,
            "original independent registration audit absent")
    require(run["schema"] == "hf2q.c2.fresh-fixed-input-run-receipt.v1"
            and run["capture_sha256"] == registration["capture"]["sha256"]
            and run["acquisition_nonce"] == capture["acquisition_nonce"]
            and run["admitted"] is True and run["complete"] is True and run["cleanup"] is True
            and run["stopped"] is False and run["whole_c2_pass"] is False
            and run["physical_admission"] is False and run["admission_kind"] == "MatchedDiagnosticFootprint"
            and run["phase"] == "independent-reference-acquisition", "original registered acquisition receipt incomplete")
    inputs, requests = original_inputs(packet["inputs"], packet["family"])
    original_packet = authority(capture["packet"])
    require(original_packet["inputs"] == packet["inputs"] and original_packet["identity"] == capture["identity"]
            and original_packet["mode"] == "capture" and original_packet["keep"] == 4,
            "original reference source packet differs")
    current_identity(capture["identity"])
    require(len(capture["lanes"]) == 4, "whole registered reference lane inventory absent")
    result = {}
    for lane, entry in enumerate(capture["lanes"]):
        closed(entry, "lane observations", "registered reference lane")
        turns = sorted(turn for l, turn in requests if l == lane)
        require(entry["lane"] == lane and len(entry["observations"]) == len(turns), "whole registered reference turns absent")
        for turn, binding in zip(turns, entry["observations"]):
            observed = observation_document(binding, requests[lane, turn], original_packet, capture["packet"], unforced=True)
            require(observed["acquisition"]["nonce"] == capture["acquisition_nonce"], "original reference acquisition cohort differs")
            result[lane, turn] = observed
    return inputs, requests, result