hf2q 0.1.30

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
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
"""Strict Q1 production-controller state and ledger composition; no runtime admission."""

import json
import math
from pathlib import Path
import re
import struct
from c2_matrix_io import SCALARS, Scope, acquisition, bound, extents, integer, require, resolve
from c2_matrix_plans import state
from c2_matrix_evidence import equal, semantic_state_pair
from q1_decision_policy import captured_records, verified_payload
from c2_controller_state_authority import PREFIX, LEDGER, closed, tokens, cell, config_document, bound_authority


KINDS = ("AnchorImage", "RestoreBefore", "RestoreAfter", "MixedBefore",
         "DecodeService", "PrefillAfter", "SettlementBefore", "SettlementAfter")


FULL = {"RestoreBefore", "RestoreAfter", "MixedBefore", "DecodeService", "PrefillAfter"}


def positive_or_none(value, label):
    if value is not None:
        integer(value, label, 1)


def handle(value):
    closed(value, "slot scheduler_generation", "Mixed handle")
    integer(value["slot"], "physical slot", 0, 3)
    integer(value["scheduler_generation"], "scheduler generation")
    return value


def owner(value):
    closed(value, "ticket lane turn slot native_generation scheduler_generation phase", "selected owner")
    require(type(value["ticket"]) is str and value["ticket"], "actual ticket absent")
    cell([value["lane"], value["turn"]])
    integer(value["slot"], "physical slot", 0, 3)
    positive_or_none(value["native_generation"], "native generation")
    # Scheduler starts at zero; native ownership starts at one. Never conflate.
    if value["scheduler_generation"] is not None:
        integer(value["scheduler_generation"], "scheduler generation")
    require(value["phase"] in ("Pending", "Prefill", "Decode"), "unknown actual phase")
    return value


def publication(value):
    closed(value, "origin epoch poisoned committed pending", "anchor publication")
    integer(value["origin"], "anchor origin", 1)
    integer(value["epoch"], "anchor epoch")
    require(value["poisoned"] is False, "poisoned anchor store")
    require(type(value["committed"]) is list, "committed anchor inventory absent")
    seen = set()
    for anchor in value["committed"] + ([] if value["pending"] is None else [value["pending"]]):
        closed(anchor, "id request prompt_tokens", "published anchor")
        integer(anchor["id"], "anchor id", 1)
        integer(anchor["request"], "anchor request")
        tokens(anchor["prompt_tokens"], "anchor prompt")
        require(anchor["id"] not in seen, "duplicate pending/committed anchor id")
        seen.add(anchor["id"])
    return value


def expected_inventory(events, mixed, creation, restore):
    """Validate independent whole-cut inventory, including legitimately nested settlement."""
    require(type(events) is list and 0 < len(events) <= 128, "finite whole event inventory required")
    require(type(mixed) is dict, "actual Mixed dispatcher record absent")
    closed(mixed, "sequence_ordinal prefill decode prefill_first actual_calls succeeded completed_services progress_log_required before_prefill", "Mixed")
    n = integer(mixed["actual_calls"], "actual dispatcher calls", 2, 4)
    integer(mixed["sequence_ordinal"], "actual Mixed sequence ordinal", 1)
    require(mixed["prefill_first"] is False and mixed["succeeded"] is True
            and mixed["progress_log_required"] is True, "not successful decode-first Mixed")
    require(mixed["completed_services"] == list(range(1, n + 1)), "whole completed-call inventory differs")
    require(type(mixed["completed_services"]) is list, "actual completed services must be an ordinal list")
    for value in mixed["completed_services"]:
        integer(value, "completed service ordinal", 1, n)
    handle(mixed["prefill"])
    require(type(mixed["decode"]) is list and mixed["decode"], "actual decode handle set absent")
    for item in mixed["decode"]:
        handle(item)
    require(len({item["slot"] for item in mixed["decode"]}) == len(mixed["decode"])
            and mixed["prefill"]["slot"] not in {item["slot"] for item in mixed["decode"]}, "prefill/decode physical slots overlap")
    by_kind = {kind: [] for kind in KINDS}
    for ordinal, event in enumerate(events):
        integer(event["ordinal"], "actual temporal event ordinal")
        require(event["ordinal"] == ordinal, "event ordinal omitted/reordered/duplicated")
        require(event["kind"] in by_kind, "unknown event kind")
        by_kind[event["kind"]].append(event)
        if event["kind"] != "DecodeService":
            require(event["service_ordinal"] is None, "nonservice has service ordinal")
        else:
            integer(event["service_ordinal"], "actual completed service ordinal", 1, n)
        selected = owner(event["selected_owner"])
        require([selected["lane"], selected["turn"]] == (creation if event["kind"] == "AnchorImage" else restore), "event belongs to another original cell")
        children = event["children"]
        require(type(children) is list, "whole physical child inventory absent")
        wanted = set(range(4)) if event["kind"] in FULL else {selected["slot"]}
        require(len(children) == len(wanted) and {child["slot"] for child in children} == wanted,
                "whole peer/selected child omitted or duplicated")
    for kind in KINDS:
        require(len(by_kind[kind]) == (n if kind == "DecodeService" else 1), "missing/duplicate required " + kind)
    cuts = {kind: values[0] for kind, values in by_kind.items() if kind != "DecodeService"}
    services = by_kind["DecodeService"]
    require([event["service_ordinal"] for event in services] == list(range(1, n + 1)), "service callback inventory shrank/reordered")
    order = [cuts[kind]["ordinal"] for kind in ("AnchorImage", "RestoreBefore", "RestoreAfter", "MixedBefore")]
    order += [event["ordinal"] for event in services] + [cuts["PrefillAfter"]["ordinal"]]
    require(order == sorted(set(order)), "restore/Mixed/prefill partial order differs")
    require(cuts["SettlementBefore"]["ordinal"] > cuts["RestoreAfter"]["ordinal"]
            and cuts["SettlementBefore"]["ordinal"] < cuts["SettlementAfter"]["ordinal"], "Settlement partial order differs")
    alias = closed(mixed["before_prefill"], "event_ordinal shared_cut no_intervening_native_or_ledger_work", "before-prefill shared cut")
    integer(alias["event_ordinal"], "actual shared-cut event ordinal")
    require(alias["shared_cut"] is True and alias["no_intervening_native_or_ledger_work"] is True,
            "shared-cut raw Boolean witnesses absent")
    require(alias == {"event_ordinal": services[-1]["ordinal"], "shared_cut": True,
                      "no_intervening_native_or_ledger_work": True}, "before-prefill not final complete service cut")
    return cuts, services


def debug_mixed(raw):
    """Count EVERY existing production Mixed debug event, never observer callbacks."""
    require(type(raw) is bytes, "completed bound server log bytes required")
    text = re.sub(r"\x1b\[[0-9;]*m", "", raw.decode("utf-8", errors="strict"))
    target = "hf2q::serve::api::engine_qwen35::progress"
    result = []
    for line in text.splitlines():
        if "Qwen mixed decode service" not in line or target not in line:
            continue
        values = None
        try:
            row = json.loads(line)
            fields = row.get("fields", {})
            if fields.get("message") == "Qwen mixed decode service" and row.get("target") == target:
                values = {name: fields[name] for name in ("prefill_slot", "prefill_generation", "prefill_first", "decode_service_calls")}
        except (ValueError, KeyError, TypeError):
            pass
        if values is None:
            values = {}
            for name in ("prefill_slot", "prefill_generation", "prefill_first", "decode_service_calls"):
                matches = re.findall(r"\b" + name + r"=(true|false|[0-9]+)\b", line)
                require(len(matches) == 1, "ambiguous/incomplete production Mixed log")
                values[name] = (matches[0] == "true" if matches[0] in ("true", "false") else int(matches[0]))
        integer(values["prefill_slot"], "logged prefill slot", 0, 3)
        integer(values["prefill_generation"], "logged scheduler generation")
        integer(values["decode_service_calls"], "logged dispatcher calls", 1, 4)
        require(type(values["prefill_first"]) is bool, "logged prefill-first is not Boolean")
        result.append(values)
    require(result, "no independent production Mixed debug inventory")
    return result


class ControllerStores:
    """Authenticate each before-read plan against all ordinary strictQ1 payloads."""
    def __init__(self, root, identity, actual, registration, payload_limit):
        self.root, self.identity, self.actual = Path(root), identity, actual
        self.registration, self.payload_limit = registration, payload_limit
        self.paths, self.total = set(), 0

    def child(self, event, child):
        closed(child, "slot role plan trace logical_bytes", "controller child")
        slot = integer(child["slot"], "child physical slot", 0, 3)
        role = "SavedAnchorExpected" if event["kind"] == "AnchorImage" else "ActualCache"
        require(child["role"] == role, "saved/live child role substituted")
        plan, plan_path = bound(self.root, child["plan"], absolute=True)
        closed(plan, "schema identity scope_acquisition registration event_ordinal kind service_ordinal slot role store_root layout expected derived_before_state_read ledger_source actual_ledger_at_capture", "controller state plan")
        require(plan["schema"] == PREFIX + "plan.v1" and plan["identity"] == self.identity
                and plan["registration"] == self.registration, "child source/reference identity differs")
        for key, value in (("event_ordinal", event["ordinal"]), ("kind", event["kind"]),
                           ("service_ordinal", event["service_ordinal"]), ("slot", slot), ("role", role)):
            require(plan[key] == value, "plan/event/child " + key + " differs")
        root = Path(plan["store_root"])
        require(root.is_absolute() and root.is_relative_to(self.root) and root.resolve(strict=True) == root,
                "child root aliases/escapes scope")
        trace_path = resolve(self.root, child["trace"], absolute=True)
        require(trace_path.parent == root and plan_path.parent == root and root not in self.paths,
                "child reused/aliased store root")
        self.paths.add(root)
        acquisition(plan["scope_acquisition"], self.actual, root)
        require(plan["derived_before_state_read"] is True, "before-read geometry absent")
        require(plan["ledger_source"] == ("saved_anchor_prefix" if role == "SavedAnchorExpected" else "engine.retained_tokens"),
                "saved prefix substituted for actual engine ledger")
        observed_ledger = tokens(plan["actual_ledger_at_capture"], "actual retained ledger")
        expected = state(plan["layout"], "controller/slot" + str(slot))
        require(extents(plan["expected"]) == extents(expected), "incomplete/altered allocator active-state extent")
        # Scope.trace authenticates every expected row and byte, not common rows.
        scope = Scope.__new__(Scope)
        scope.root, scope.identity, scope.actual = self.root, self.identity, self.actual
        scope.packet = {"host_payload_limit": self.payload_limit}
        scope.registration = {"grants": {"payload_bytes": self.payload_limit}}
        path, trace = scope.trace(child["trace"], expected) if not Path(child["trace"]["path"]).is_absolute() else scope.trace(
            {"path": str(trace_path.relative_to(self.root)), "sha256": child["trace"]["sha256"]}, expected)
        records = captured_records(path)
        selectors = [row for key, row in records.items() if key[4] == 1]
        require(len(selectors) == 1 and all(v in (0, 1) for v in verified_payload(selectors[0])), "raw Boolean selector invalid")
        ledger_rows = [row for key, row in records.items() if key[4] == LEDGER]
        raw_ledger = [] if not ledger_rows else list(struct.unpack("<" + "I" * plan["layout"]["ledger"], verified_payload(ledger_rows[0])))
        require(len(ledger_rows) == (1 if plan["layout"]["ledger"] else 0), "actual ledger extent absent")
        if role == "ActualCache":
            require(raw_ledger == observed_ledger, "strictQ1 ledger differs from verbatim actual engine ledger")
        cursors = next(row for key, row in records.items() if key[4] == 0)
        raw_cursors = verified_payload(cursors)
        cursors = list(struct.unpack("<" + "I" * (len(raw_cursors) // 4), raw_cursors))
        count = sum(math.prod(item["shape"]) * SCALARS[item["scalar"]] for item in expected)
        require(child["logical_bytes"] == count, "child exact logical bytes differ")
        self.total += count
        return {"plan": plan, "path": path, "records": records, "ledger": raw_ledger,
                "actual_ledger": observed_ledger, "cursors": cursors, "bytes": count}


def literal(left, right):
    require(left["actual_ledger"] == right["actual_ledger"], "actual engine ledger mutated at literal no-mutation cut")
    return equal(left["path"], right["path"])


def saved_restore(saved, restored, prefix):
    """Only named-reset selector normalization; actual inflight ledger is NOT saved prefix.

    The existing semantic comparator expects one complete slot with step0. Its
    result includes the ordinary ledger; compare cache separately only after
    independently authenticating both ledger sources, never rewriting a store.
    """
    require(saved["ledger"] == prefix, "saved expected ledger differs from independently declared prefix")
    # Reuse existing complete semantic comparator when ledger sources coincide.
    if saved["ledger"] == restored["ledger"]:
        result = semantic_state_pair(saved["path"], restored["path"])
        require(result["classification"] == "ExactEqual", "restored saved semantic state differs")
        return result
    left, right = saved["records"], restored["records"]
    cache_left = {key: value for key, value in left.items() if key[4] != LEDGER}
    cache_right = {key: value for key, value in right.items() if key[4] != LEDGER}
    require(set(cache_left) == set(cache_right) and cache_left, "complete restored cache extent differs")
    parity_equal = True
    for key in cache_left:
        a, b = cache_left[key], cache_right[key]
        require((a["scalar"], a["shape"]) == (b["scalar"], b["shape"]), "restored cache representation differs")
        aa, bb = verified_payload(a), verified_payload(b)
        if key[4] == 1:
            require(all(v in (0, 1) for v in aa + bb), "invalid named-reset selector")
            parity_equal = aa == bb
        else:
            require(aa == bb, "restored saved cursor/KV/linear cache differs")
    return {"classification": "ExactEqual", "semantic_rule": "NamedResetParity",
            "representation_parity_equal": parity_equal, "actual_ledger_checked_separately": True}


def snapshot_bindings(event, observations, joins):
    """Bind raw snapshots to the completed original HTTP/native observations."""
    selected = event["selected_owner"]
    require(selected["ticket"] in observations, "selected ticket has no completed outer observation")
    final = observations[selected["ticket"]]
    require([selected["lane"], selected["turn"]] == final["cell"]
            and selected["slot"] == final["terminal"]["slot"], "selected ticket/cell/physical slot differs")
    joined = joins[selected["ticket"]]
    require(selected["native_generation"] in (None, joined["native_generation"]),
            "stale selected native generation")
    require(selected["native_generation"] is not None or selected["phase"] in ("Pending", "Prefill"),
            "missing native generation is not pending admission")
    worker_slots = event["worker_slots"]
    require(type(worker_slots) is list and len(worker_slots) == 4, "whole actual worker slot inventory absent")
    for slot, worker in enumerate(worker_slots):
        closed(worker, "slot scheduler_generation phase", "worker slot")
        require(worker["slot"] == slot and worker["phase"] in ("Empty", "Prefill", "Decode"),
                "worker physical slot/phase differs")
        if worker["phase"] == "Empty":
            require(worker["scheduler_generation"] is None, "empty worker has invented scheduler generation")
        else:
            integer(worker["scheduler_generation"], "worker scheduler generation")
    worker = worker_slots[selected["slot"]]
    if selected["phase"] != "Pending":
        require(worker["phase"] == selected["phase"]
                and worker["scheduler_generation"] == selected["scheduler_generation"],
                "stale selected scheduler generation/phase")
    else:
        require(worker["phase"] == "Empty", "pending selected owner overwrote an actual worker")
    native = event["native_owners"]
    routes = event["route_observation"]
    require(type(native) is list and type(routes) is list, "complete native/route inventory absent")
    expected = {ticket for ticket, value in observations.items() if value["cell"][1] == selected["turn"]}
    require(len(native) == len(expected) and {row["ticket"] for row in native} == expected,
            "whole native owner omitted/duplicated")
    require(len(routes) == len(expected) and {row["ticket"] for row in routes} == expected,
            "whole route observation omitted/duplicated")
    for row in native:
        closed(row, "ticket lane turn slot native_generation terminal published prepared_prompt decisions raw_decisions", "native owner")
        observed = observations[row["ticket"]]
        require([row["lane"], row["turn"]] == observed["cell"], "native owner original cell differs")
        require(row["slot"] in (None, observed["terminal"]["slot"]), "stale native physical slot")
        positive_or_none(row["native_generation"], "native owner generation")
        if row["native_generation"] is not None:
            require(row["native_generation"] == observed["generation"]
                    and row["slot"] == observed["terminal"]["slot"], "stale native owner generation")
        else:
            require(row["slot"] is None and row["terminal"] is None and row["published"] is None,
                    "unadmitted owner claims native work/publication")
        require(row["prepared_prompt"] in (None, observed["prepared"]["prompt"]), "prepared prompt changed")
        for key, terminal_key in (("decisions", "decisions"), ("raw_decisions", "raw_decisions")):
            values = tokens(row[key], "actual " + key)
            target = observed["terminal"][terminal_key] if terminal_key == "decisions" else observed[terminal_key]
            require(target[:len(values)] == values, "actual decision witness is not original completed tape prefix")
        if row["terminal"] is not None:
            require(row["terminal"] == observed["terminal"], "actual terminal changed")
        if row["published"] is not None:
            require(row["terminal"] is not None and row["published"] == observed["published_completion_tokens"],
                    "native terminal publication differs")
    for row in routes:
        closed(row, "ticket routes forward_boundaries decisions raw_decisions gpu_selector gpu_argmax", "route observation")
        observed = observations[row["ticket"]]
        require(type(row["gpu_selector"]) is bool and type(row["routes"]) is list, "raw route Boolean/list absent")
        require(observed["actual_routes"][:len(row["routes"])] == row["routes"], "actual route witness changed")
        require(observed["actual_gpu_argmax"][:len(row["gpu_argmax"])] == row["gpu_argmax"],
                "actual GPU selection witness changed")
        require(not row["gpu_selector"] or observed["gpu_frozen_selector_used"] is True,
                "GPU selector source witness differs")
        boundaries = row["forward_boundaries"]
        if boundaries is not None:
            require(type(boundaries) is list and observed["prepared"]["transactions"][:len(boundaries)] == boundaries,
                    "actual forward boundary witness changed")
        for key in ("decisions", "raw_decisions"):
            wanted = observed["terminal"]["decisions"] if key == "decisions" else observed[key]
            require(type(row[key]) is list and wanted[:len(row[key])] == row[key], "route decision prefix changed")


def admission_joins(values, observations):
    require(type(values) is list and len(values) == len(observations), "whole actual admission join inventory absent")
    result, generations = {}, set()
    for row in values:
        closed(row, "ticket lane turn slot native_generation", "actual admission join")
        require(row["ticket"] in observations and row["ticket"] not in result, "duplicate/unknown admission ticket")
        observed = observations[row["ticket"]]
        require([row["lane"], row["turn"]] == observed["cell"]
                and row["slot"] == observed["terminal"]["slot"]
                and row["native_generation"] == observed["generation"], "pending admission later join differs")
        integer(row["native_generation"], "joined native generation", 1)
        require(row["native_generation"] not in generations, "native generation reused across original tickets")
        generations.add(row["native_generation"])
        result[row["ticket"]] = row
    require([row["native_generation"] for row in values] == sorted(generations),
            "actual global native admission generation order differs")
    return result


def publication_history(values, observations, event_count, event_limit):
    require(type(values) is list and len(values) == len(observations) and len(values) <= event_limit,
            "whole actual prerequisite publication inventory absent")
    result, tickets, prior_cut = [], set(), 0
    for ordinal, value in enumerate(values):
        closed(value, "ordinal event_ordinal_before ticket lane turn slot native_generation scheduler_generation success prepared_prompt terminal actual_retained_tokens target_cursors mtp_cursor graft_len anchor_publication", "actual ledger publication")
        integer(value["ordinal"], "actual publication ordinal")
        cell([value["lane"], value["turn"]])
        integer(value["slot"], "publication physical slot", 0, 3)
        integer(value["native_generation"], "publication native generation", 1)
        tokens(value["prepared_prompt"], "publication actual prepared prompt")
        require(value["ordinal"] == ordinal and value["ticket"] in observations and value["ticket"] not in tickets,
                "duplicate/reordered/unknown original publication")
        tickets.add(value["ticket"])
        observed = observations[value["ticket"]]
        require(value["success"] is True and [value["lane"], value["turn"]] == observed["cell"]
                and value["slot"] == observed["terminal"]["slot"]
                and value["native_generation"] == observed["generation"]
                and value["prepared_prompt"] == observed["prepared"]["prompt"]
                and value["terminal"] == observed["terminal"], "actual publication native observation/owner differs")
        integer(value["scheduler_generation"], "publication scheduler generation")
        cut = integer(value["event_ordinal_before"], "publication temporal cut", prior_cut, event_count)
        prior_cut = cut
        targets = tokens(value["target_cursors"], "actual target cursor")
        require(targets and len(set(targets)) == 1, "publication target cursor inventory inconsistent/absent")
        if value["mtp_cursor"] is not None:
            integer(value["mtp_cursor"], "actual MTP cursor", 0, LEDGER)
        graft = integer(value["graft_len"], "actual graft cursor", 0, LEDGER)
        require(targets[0] >= graft, "actual publication cursor precedes graft")
        logical = targets[0] - graft
        tape = value["prepared_prompt"] + value["terminal"]["generated"]
        ledger = tokens(value["actual_retained_tokens"], "actual publication retained ledger")
        require(ledger == tape[:logical], "actual publication ledger violates native retained_prefix policy")
        publication(value["anchor_publication"])
        require(value["anchor_publication"]["pending"] is None, "successful publication still pending")
        result.append(value)
    return result


def ledger_validity(event, slot, captured, observations, publications):
    """Exact actual-publication custody, never saved-prefix plausibility."""
    ledger = captured["actual_ledger"]
    own_settlement = event["kind"] in ("SettlementBefore", "SettlementAfter") and slot == event["selected_owner"]["slot"]
    if own_settlement:
        candidates = [value for value in publications if value["ticket"] == event["selected_owner"]["ticket"]]
    else:
        candidates = [value for value in publications if value["slot"] == slot
                      and value["event_ordinal_before"] <= event["ordinal"]]
    if candidates:
        source = candidates[-1]
        require(ledger == source["actual_retained_tokens"], "actual retained ledger differs from last physical-slot publication")
        if own_settlement:
            cursors = source["target_cursors"] + ([] if source["mtp_cursor"] is None else [source["mtp_cursor"]])
            require(captured["cursors"] == cursors, "Settlement actual native cursor publication differs")
    else:
        require(not ledger, "actual retained ledger has no original native publication")


def publication_transition(before, after, selected_anchor, selected, keep):
    a, b = publication(before), publication(after)
    require(a["origin"] == b["origin"] and b["epoch"] == a["epoch"] + 1,
            "successful commit store origin/epoch transition differs")
    require(a["pending"] is not None and b["pending"] is None, "successful pending->committed publication absent")
    pending = a["pending"]
    request_id = ((selected["scheduler_generation"] << 32) + selected["slot"]) & ((1 << 64) - 1)
    require(pending["request"] == request_id, "pending anchor belongs to stale scheduler request")
    integer(keep, "actual anchor depth", 1, 8)
    # Exactly production commit: replace equal prompt depth, sort, retain deepest.
    committed = [anchor for anchor in a["committed"] if len(anchor["prompt_tokens"]) != len(pending["prompt_tokens"])]
    committed.append(pending)
    committed.sort(key=lambda anchor: len(anchor["prompt_tokens"]))
    require(b["committed"] == committed[-keep:], "successful anchor publication differs from actual commit policy")
    require(any(anchor["id"] == selected_anchor["id"] and anchor["request"] == selected_anchor["request"]
                and anchor["prompt_tokens"] == selected_anchor["prompt_tokens"] for anchor in a["committed"]),
            "restored committed anchor absent at successful Settlement")


def controller_core(root, packet, config_binding, index_binding, actual, observations, log_raw):
    """Strict component evidence only; caller must authenticate the outer context.

    `observations` are all completed actual prerequisite/replay observations,
    keyed by ticket, with authenticated original [lane,turn] added as `cell`.
    This low-level API never emits a CASE verdict or attests Native execution.
    """
    root = Path(root)
    require(root.is_absolute() and root.resolve(strict=True) == root and packet["output"] == str(root),
            "outer/controller output root differs")
    config, _ = bound_authority(root, config_binding)
    config_document(config, packet)
    require(packet["controller_state"] == config_binding, "outer packet did not configure this observer")
    index, index_path = bound(root, index_binding, absolute=True, limit=config["limits"]["disk_bytes"])
    closed(index, "schema config identity scope_acquisition registration checkpoint_prefix creation_cell restore_cell events mixed admission_joins publications required_obligations complete peak_live_bytes readback_bytes disk_bytes whole_c2_pass", "controller index")
    require(index["schema"] == PREFIX + "index.v1" and index["complete"] is True
            and index["whole_c2_pass"] is False, "controller index incomplete/overclaimed")
    require(index["config"] == config_binding, "controller index config hash differs")
    for key in ("identity", "registration", "checkpoint_prefix", "creation_cell", "restore_cell"):
        require(index[key] == config[key], "index/config " + key + " differs")
    acquisition(index["scope_acquisition"], actual, root)
    prefix, _ = bound_authority(root, config["checkpoint_prefix"])
    tokens(prefix, "independently declared checkpoint prefix")
    require(prefix, "independent checkpoint prefix empty")
    original = [value for value in observations.values() if value["cell"] == config["creation_cell"]]
    restored = [value for value in observations.values() if value["cell"] == config["restore_cell"]]
    require(len(original) == len(restored) == 1 and original[0]["prepared"]["prompt"][:len(prefix)] == prefix
            and restored[0]["prepared"]["prompt"][:len(prefix)] == prefix,
            "checkpoint prefix not original registered prepared prompt prefix")
    require(index["required_obligations"] == {
        "creation_cell": config["creation_cell"], "restore_cell": config["restore_cell"],
        "kinds": list(KINDS), "min_calls": 2, "max_calls": 4, "all_physical_slots": [0, 1, 2, 3]},
        "producer narrowed independent whole-cut obligations")
    events = index["events"]
    for event in events:
        require(type(event) is dict, "closed controller event required")
        fields = "ordinal kind service_ordinal selected_owner worker_slots native_owners children anchor_publication route_observation selected_anchor"
        closed(event, fields + (" saved_anchor" if event.get("kind") == "AnchorImage" else ""), "controller event")
    cuts, services = expected_inventory(events, index["mixed"], config["creation_cell"], config["restore_cell"])
    joins = admission_joins(index["admission_joins"], observations)
    publications = publication_history(index["publications"], observations, len(events), config["limits"]["events"])
    selected_publication = next(value for value in publications if value["ticket"] == cuts["SettlementAfter"]["selected_owner"]["ticket"])
    require(selected_publication["event_ordinal_before"] == cuts["SettlementAfter"]["ordinal"]
            and selected_publication["scheduler_generation"] == cuts["SettlementAfter"]["selected_owner"]["scheduler_generation"]
            and selected_publication["anchor_publication"] == cuts["SettlementAfter"]["anchor_publication"],
            "selected Settlement publication/cut/owner join differs")
    selected = cuts["RestoreBefore"]["selected_owner"]
    for event in events:
        snapshot_bindings(event, observations, joins)
        if event["kind"] != "AnchorImage":
            require(all(event["selected_owner"][key] == selected[key]
                        for key in ("ticket", "lane", "turn", "slot", "scheduler_generation")),
                    "selected scheduler owner/generation reused")
    mixed = index["mixed"]
    scheduled = [mixed["prefill"]] + mixed["decode"]
    require(any(value == {"slot": selected["slot"], "scheduler_generation": selected["scheduler_generation"]}
                for value in scheduled), "selected owner never actual Mixed member")
    for value in scheduled:
        worker = cuts["MixedBefore"]["worker_slots"][value["slot"]]
        require(worker["scheduler_generation"] == value["scheduler_generation"]
                and worker["phase"] == ("Prefill" if value == mixed["prefill"] else "Decode"),
                "actual Mixed partition has stale worker handle")
    logs = debug_mixed(log_raw)
    ordinal = mixed["sequence_ordinal"]
    require(ordinal <= len(logs), "actual Mixed sequence missing from completed server log")
    logged = logs[ordinal - 1]
    require(logged == {"prefill_slot": mixed["prefill"]["slot"],
                       "prefill_generation": mixed["prefill"]["scheduler_generation"],
                       "prefill_first": False, "decode_service_calls": mixed["actual_calls"]},
            "callback-only reduced count/ordinal/slot/generation differs from production log")
    stores = ControllerStores(root, packet["identity"], actual, config["registration"], config["limits"]["disk_bytes"])
    captured = {}
    for event in events:
        captured[event["ordinal"]] = {}
        for child in event["children"]:
            value = stores.child(event, child)
            ledger_validity(event, child["slot"], value, observations, publications)
            captured[event["ordinal"]][child["slot"]] = value
    def at(event, slot):
        return captured[event["ordinal"]][slot]
    before, after = cuts["RestoreBefore"], cuts["RestoreAfter"]
    require(before["selected_anchor"] == after["selected_anchor"], "restored anchor identity changed")
    anchor = closed(before["selected_anchor"], "id request prompt_tokens length state_generation graft_len", "selected saved anchor")
    integer(anchor["id"], "actual restored anchor id", 1)
    integer(anchor["request"], "actual restored anchor request")
    creator = cuts["AnchorImage"]["selected_owner"]
    creator_request = ((creator["scheduler_generation"] << 32) + creator["slot"]) & ((1 << 64) - 1)
    require(anchor["request"] == creator_request, "saved anchor belongs to another original scheduler request")
    creation_publication = next(value for value in publications if value["ticket"] == creator["ticket"])
    require(creation_publication["scheduler_generation"] == creator["scheduler_generation"]
            and {"id": anchor["id"], "request": anchor["request"], "prompt_tokens": anchor["prompt_tokens"]}
            in creation_publication["anchor_publication"]["committed"],
            "original saved anchor identity never actually committed at its creation request")
    saved_meta = closed(cuts["AnchorImage"]["saved_anchor"], "length state_generation graft_len prefix", "saved anchor metadata")
    require(saved_meta["prefix"] == anchor["prompt_tokens"] == prefix and saved_meta["length"] == len(prefix),
            "selected saved image/prefix differs")
    for key in ("length", "state_generation", "graft_len"):
        integer(saved_meta[key], "saved " + key)
        require(saved_meta[key] == anchor[key], "saved/restore actual anchor geometry differs")
    require(anchor["graft_len"] == 0, "unapproved saved graft semantic rule")
    require(cuts["AnchorImage"]["selected_owner"]["slot"] == selected["slot"],
            "saved/restored physical slot differs")
    for event in events:
        if event["kind"] not in ("RestoreBefore", "RestoreAfter"):
            require(event["selected_anchor"] is None, "unobserved restore identity claimed")
        if event["kind"] not in ("SettlementBefore", "SettlementAfter"):
            require(event["anchor_publication"] is None, "unobserved anchor publication claimed")
    require(before["native_owners"] == after["native_owners"]
            and before["route_observation"] == after["route_observation"],
            "isolated restore changed raw native ownership/route/decision sources")
    peers = []
    for slot in range(4):
        if slot != selected["slot"]:
            require(before["worker_slots"][slot] == after["worker_slots"][slot], "isolated restore changed peer scheduler owner")
            peers.append(literal(at(before, slot), at(after, slot)))
        require(at(before, slot)["actual_ledger"] == at(after, slot)["actual_ledger"],
                "isolated restore changed actual retained ledger")
    restored_comparison = saved_restore(at(cuts["AnchorImage"], selected["slot"]), at(after, selected["slot"]), prefix)
    pending = mixed["prefill"]["slot"]
    pending_tickets = [ticket for ticket, value in observations.items()
                       if value["cell"][1] == selected["turn"] and value["terminal"]["slot"] == pending]
    require(len(pending_tickets) == 1, "pending-prefill original ticket join ambiguous/absent")
    pending_ticket = pending_tickets[0]
    def ticket_row(event, field, ticket):
        return next(value for value in event[field] if value["ticket"] == ticket)
    service_witnesses = []
    pending_comparisons = []
    previous = cuts["MixedBefore"]
    for event in services:
        require(event["worker_slots"][pending] == previous["worker_slots"][pending],
                "other-lane decode changed pending-prefill scheduler owner")
        for field in ("native_owners", "route_observation"):
            require(ticket_row(event, field, pending_ticket) == ticket_row(previous, field, pending_ticket),
                    "other-lane decode mutated pending-prefill raw owner/route witness")
        deltas = []
        for current in event["route_observation"]:
            prior = ticket_row(previous, "route_observation", current["ticket"])
            forward = current["forward_boundaries"] or []
            old_forward = prior["forward_boundaries"] or []
            require(forward[:len(old_forward)] == old_forward
                    and current["routes"][:len(prior["routes"])] == prior["routes"]
                    and current["decisions"][:len(prior["decisions"])] == prior["decisions"],
                    "actual route/forward/decision witness regressed")
            deltas.append({"ticket": current["ticket"], "new_routes": current["routes"][len(prior["routes"]):],
                           "new_forwards": forward[len(old_forward):],
                           "new_decisions": current["decisions"][len(prior["decisions"]):]})
        witnessed = any(value["new_routes"] or value["new_forwards"] or value["new_decisions"] for value in deltas)
        service_witnesses.append({"service_ordinal": event["service_ordinal"], "raw_deltas": deltas,
                                 "work_observation": "NewSourceWitness" if witnessed else "NoNewWitnessPossibleOutputDrain",
                                 "native_or_gpu_work_count": None})
        pending_comparisons.append(literal(at(previous, pending), at(event, pending)))
        previous = event
    settlement_before, settlement_after = cuts["SettlementBefore"], cuts["SettlementAfter"]
    settlement = literal(at(settlement_before, selected["slot"]), at(settlement_after, selected["slot"]))
    terminal_owner = ticket_row(settlement_after, "native_owners", selected["ticket"])
    require(terminal_owner["terminal"] == observations[selected["ticket"]]["terminal"]
            and terminal_owner["published"] == observations[selected["ticket"]]["published_completion_tokens"],
            "own successful Settlement lacks actual native terminal/completion publication")
    publication_transition(settlement_before["anchor_publication"], settlement_after["anchor_publication"], anchor, selected, packet["keep"])
    limits = config["limits"]
    require(len(events) <= limits["events"], "event cap breached")
    for key in ("peak_live_bytes", "readback_bytes", "disk_bytes"):
        grant = "live_bytes" if key == "peak_live_bytes" else key
        require(stores.total <= integer(index[key], key, 1) <= limits[grant], "aggregate " + key + " cap/accounting breached")
    # Include every file, including metadata, once; no aliases/hardlink credit.
    disk_files = [index_path]
    for store_root in stores.paths:
        disk_files.extend(path for path in store_root.rglob("*") if path.is_file())
    require(len(disk_files) == len(set(disk_files)), "controller disk extent aliases")
    measured_disk = 0
    for path in disk_files:
        require(path.resolve(strict=True) == path and path.is_relative_to(root), "disk file escaped/aliased root")
        measured_disk += path.stat().st_size
    require(measured_disk <= index["disk_bytes"] <= limits["disk_bytes"], "complete controller metadata/payload disk cap breached")
    return {"schema": PREFIX + "component-evidence.v1", "component": "single-controller-composition",
            "whole_c2_pass": False, "native_qualification": False, "numeric_qualification": False,
            "statistical_qualification": False, "events": len(events), "actual_calls": mixed["actual_calls"],
            "config": config_binding, "index": index_binding, "service_witnesses": service_witnesses,
            "peer_comparisons": peers, "pending_prefill_comparisons": pending_comparisons,
            "restored_cache": restored_comparison, "successful_settlement": settlement,
            "actual_ledgers_checked": sum(len(value) for value in captured.values()),
            "logical_bytes": stores.total, "measured_disk_bytes": measured_disk}