File size: 35,942 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
"""Immutable certification and main-run validation for the controlled GPU smokes."""

from __future__ import annotations

import json
import math
from collections import Counter
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import Any

from ..atomic_io import read_jsonl
from ..hashing import canonical_json, canonical_json_hash, is_sha256
from .evi_po_contract import EVI_PO_ADAPTER_VERSION
from .papo_contract import (
    GAMMA_ZERO_GRADIENT_ABS_FLOOR,
    GAMMA_ZERO_GRADIENT_REL_TOL,
    PAPO_ADAPTER_VERSION,
    PAPO_UPSTREAM_SOURCE_SHA256,
)
from .rewards import GPU_SMOKE_ARMS, smoke_reference_arm

SMOKE_STEPS = 20


class SmokeGateError(RuntimeError):
    """Raised when smoke evidence is incomplete, drifted, or self-inconsistent."""


_COMMON_RUNTIME_FIELDS = (
    "training_contract_version",
    "model_revision",
    "model_snapshot_sha256",
    "environment_lock_sha256",
    "evaluation_manifest_sha256",
    "system_prompt_sha256",
    "precision",
    "attention_implementation",
    "max_prompt_tokens",
    "max_completion_tokens",
    "total_context_tokens",
    "per_device_train_batch_size",
    "gradient_accumulation_steps",
    "world_size",
    "generations_per_prompt",
    "checkpoint_interval",
    "max_completion_tokens_per_run",
    "learning_rate",
    "lora_rank",
    "lora_alpha",
    "lora_dropout",
    "lora_target_modules",
    "comparison_slot_manifest_sha256",
    "backend_entrypoint",
    "use_vllm",
    "vllm_config",
    "enable_thinking",
    "structured_output_regex",
    "optimizer",
    "scheduler",
    "gradient_checkpointing",
    "max_grad_norm",
    "freeze_vision_tower",
    "freeze_multimodal_projector",
    "train_full_weights",
    "lora_exclude_modules",
    "base_model_resource",
    "base_model_repo_id",
    "reject_overlength_samples",
    "temperature",
    "top_p",
)


def common_contract(
    runtime: Mapping[str, Any],
    manifest: Mapping[str, Any],
    *,
    source_config_sha256: str,
) -> dict[str, Any]:
    """Project behavior that must match between smoke and main.

    The whole repository commit and whole experiment-file hash are deliberately
    excluded: documentation, evaluator, or matrix edits do not invalidate a GPU
    trainer smoke.  Runtime/data/initialization identities below still pin every
    behavior-affecting input.
    """

    return {
        "dataset_manifest_sha256": manifest.get("dataset_manifest_sha256"),
        "initial_checkpoint_sha256": manifest.get("initial_checkpoint_sha256"),
        "runtime": {field: runtime.get(field) for field in _COMMON_RUNTIME_FIELDS},
        "papo_adapter_version": PAPO_ADAPTER_VERSION,
        "papo_upstream_source_sha256": PAPO_UPSTREAM_SOURCE_SHA256,
        "evi_po_adapter_version": EVI_PO_ADAPTER_VERSION,
    }


def method_contract(runtime: Mapping[str, Any]) -> dict[str, Any]:
    """Project arm-specific fields that main must match to its own smoke run."""

    def objective(value: Any) -> Any:
        if not isinstance(value, Mapping):
            return value
        projected = dict(value)
        projected.pop("require_gpu_contract_probe", None)
        return projected

    return {
        "arm": runtime.get("arm"),
        "trainer_kind": runtime.get("trainer_kind"),
        "loss_type": runtime.get("loss_type"),
        "beta": runtime.get("beta"),
        "papo_config": objective(runtime.get("papo_config")),
        "evi_po_config": objective(runtime.get("evi_po_config")),
    }


def smoke_compatibility_contract(runtime: Mapping[str, Any]) -> dict[str, Any]:
    """Project the GPU-tested implementation family, excluding ablated knobs.

    A direct EVI/PAPO/target ablation intentionally differs from its parent
    objective and therefore cannot exact-match the parent's method contract.
    It still has to use the same tested trainer, adapter implementation, loss
    family, and grouped-data relationship contract.
    """

    arm = str(runtime.get("arm", ""))
    evi = runtime.get("evi_po_config")
    papo = runtime.get("papo_config")
    if isinstance(evi, Mapping):
        evi = {
            key: value
            for key, value in evi.items()
            if key not in {"lambda_direction", "lambda_evidence", "margin", "require_gpu_contract_probe"}
        }
    if isinstance(papo, Mapping):
        papo = {
            key: value
            for key, value in papo.items()
            if key not in {"mask_ratio", "perception_loss_weight", "require_gpu_contract_probe"}
        }
    return {
        "smoke_reference_arm": smoke_reference_arm(arm),
        "trainer_kind": runtime.get("trainer_kind"),
        "loss_type": runtime.get("loss_type"),
        "beta": runtime.get("beta"),
        "papo_implementation": papo,
        "evi_po_implementation": evi,
    }


def _load_object(path: Path, label: str) -> dict[str, Any]:
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise SmokeGateError(f"cannot read {label} {path}: {exc}") from exc
    if not isinstance(value, dict):
        raise SmokeGateError(f"{label} must be a JSON object: {path}")
    return value


def _load_attested_object(row: Mapping[str, Any], label: str) -> dict[str, Any]:
    """Load one small external evidence file and match its embedded copy."""

    path = Path(str(row.get("path", "")))
    if not path.is_file():
        raise SmokeGateError(f"{label} file is missing: {path}")
    payload = _load_object(path, label)
    embedded = {key: value for key, value in row.items() if key not in {"path", "sha256"}}
    if canonical_json(payload) != canonical_json(embedded):
        raise SmokeGateError(f"{label} embedded copy differs from attested bytes")
    return payload


def _assert_finite(value: Any, label: str) -> None:
    if isinstance(value, bool | str) or value is None:
        return
    if isinstance(value, int | float):
        if not math.isfinite(float(value)):
            raise SmokeGateError(f"{label} contains NaN or Inf")
        return
    if isinstance(value, Mapping):
        for key, item in value.items():
            _assert_finite(item, f"{label}.{key}")
        return
    if isinstance(value, Sequence):
        for index, item in enumerate(value):
            _assert_finite(item, f"{label}[{index}]")


def _assert_phase_2_resume_audit(
    audit: Mapping[str, Any],
    *,
    arm: str,
) -> None:
    """Validate measured checkpoint/loaded digests without trusting booleans."""

    rng_components = audit.get("rng_components_equal")
    checkpoint_path = Path(str(audit.get("checkpoint", "")))
    digest_pairs = (
        ("checkpoint_trainable_parameter_sha256", "loaded_trainable_parameter_sha256"),
        ("checkpoint_optimizer_sha256", "loaded_optimizer_sha256"),
        ("checkpoint_scheduler_sha256", "loaded_scheduler_sha256"),
        ("checkpoint_rng_sha256", "loaded_rng_sha256"),
    )
    if (
        audit.get("status") != "passed"
        or audit.get("model_loader_called") is not True
        or audit.get("model_state_equal") is not True
        or audit.get("optimizer_state_equal") is not True
        or audit.get("scheduler_state_equal") is not True
        or audit.get("rng_state_equal") is not True
        or not isinstance(rng_components, dict)
        or set(rng_components) != {"python", "numpy", "cpu", "cuda"}
        or any(value is not True for value in rng_components.values())
        or not checkpoint_path.is_dir()
        or any(
            not is_sha256(str(audit.get(checkpoint_field)))
            or audit.get(checkpoint_field) != audit.get(loaded_field)
            for checkpoint_field, loaded_field in digest_pairs
        )
    ):
        raise SmokeGateError(f"{arm} phase-2 resume digests are inconsistent")


def _assert_evi_probe(
    probe: Mapping[str, Any],
    *,
    runtime_config: Mapping[str, Any],
) -> None:
    """Validate the measured first-batch EVI objective/attention contract."""

    relationship_states = probe.get("relationship_states")
    required_states = {
        "FULL": "FULL",
        "CONTROL": "A_SAME",
        "MISSING": "U_MISSING",
    }
    source = probe.get("evidence_source")
    attention_shape = probe.get("attention_shape")
    configured_sources = runtime_config.get("evidence_sources")
    if (
        probe.get("status") != "passed"
        or probe.get("adapter_version") != EVI_PO_ADAPTER_VERSION
        or runtime_config.get("adapter_version") != EVI_PO_ADAPTER_VERSION
        or runtime_config.get("required_relationships") != ["FULL", "CONTROL", "MISSING"]
        or runtime_config.get("optional_relationships") != ["SUBSTITUTE"]
        or runtime_config.get("candidate_support") != "group_answers_plus_unanswerable"
        or runtime_config.get("evidence_supervision_relation") != "FULL"
        or runtime_config.get("attention_capture") != "last_full_attention_layer_eager_forward_hook"
        or runtime_config.get("zero_weight_reduction") != "exact_parent_grpo_path"
        or runtime_config.get("require_gpu_contract_probe") is not True
        or not isinstance(relationship_states, dict)
        or any(relationship_states.get(key) != value for key, value in required_states.items())
        or set(relationship_states) - {*required_states, "SUBSTITUTE"}
        or (
            "SUBSTITUTE" in relationship_states and relationship_states["SUBSTITUTE"] != "A_CHANGED"
        )
        or probe.get("substitute_available") != ("SUBSTITUTE" in relationship_states)
        or probe.get("lambda_direction") != runtime_config.get("lambda_direction")
        or probe.get("lambda_evidence") != runtime_config.get("lambda_evidence")
        or probe.get("margin") != runtime_config.get("margin")
        or float(probe.get("lambda_direction", 0.0)) <= 0.0
        or float(probe.get("lambda_evidence", 0.0)) <= 0.0
        or float(probe.get("direction_loss", -1.0)) < 0.0
        or float(probe.get("evidence_loss", -1.0)) < 0.0
        or float(probe.get("direction_gradient_norm", 0.0)) <= 0.0
        or float(probe.get("evidence_gradient_norm", 0.0)) <= 0.0
        or probe.get("attention_requires_grad") is not True
        or not isinstance(probe.get("attention_layer"), str)
        or not probe.get("attention_layer")
        or not isinstance(attention_shape, list)
        or len(attention_shape) != 4
        or attention_shape[0] != 1
        or any(not isinstance(value, int) or value <= 0 for value in attention_shape)
        or not isinstance(probe.get("visual_token_count"), int)
        or int(probe["visual_token_count"]) <= 0
        or not isinstance(probe.get("evidence_visual_token_count"), int)
        or not 0 < int(probe["evidence_visual_token_count"]) <= int(probe["visual_token_count"])
        or not isinstance(configured_sources, list)
        or source not in configured_sources
        or not is_sha256(str(probe.get("evidence_contract_sha256")))
    ):
        raise SmokeGateError("EVI-PO GPU probe/config evidence is inconsistent")
    _assert_finite(probe, "evi_gpu_contract_probe")


def _assert_papo_probe(
    probe: Mapping[str, Any] | None,
    *,
    runtime_config: Mapping[str, Any],
) -> None:
    """Validate the measured first-batch PAPO perception contract.

    ``gamma_zero_loss_max_abs_diff`` must be bit-exact 0.0 (gamma=0 recovers the
    parent GRPO loss exactly); the gradient equality is checked up to the
    floating-point tolerance defined in :mod:`papo_contract`, since two
    ``autograd.grad`` traversals differ only by accumulation-order roundoff.
    """

    if not isinstance(probe, dict) or probe.get("status") != "passed":
        raise SmokeGateError("PAPO smoke lacks a passed real-batch GPU contract probe")
    unchanged = probe.get("input_tensors_unchanged")
    if (
        not isinstance(unchanged, dict)
        or not unchanged
        or not all(value is True for value in unchanged.values())
        or probe.get("deterministic_mask_replay") is not True
        or not 0.55 <= float(probe.get("observed_mask_ratio", -1.0)) <= 0.65
        or float(probe.get("perception_kl", 0.0)) <= 0.0
        or float(probe.get("perception_gradient_norm", 0.0)) <= 0.0
        or probe.get("gamma_zero_loss_max_abs_diff") != 0.0
        or probe.get("gamma_zero_gradient_structure_equal") is not True
        or float(probe.get("gamma_zero_gradient_max_abs_diff", 0.0))
        > GAMMA_ZERO_GRADIENT_REL_TOL
        * float(probe.get("gamma_zero_parent_gradient_max_abs", 0.0))
        + GAMMA_ZERO_GRADIENT_ABS_FLOOR
        or probe.get("der_loss_weight1") != 0.0
        or probe.get("der_loss_weight2") != 0.0
        or not isinstance(runtime_config, dict)
        or runtime_config.get("adapter_version") != PAPO_ADAPTER_VERSION
        or runtime_config.get("upstream_source_sha256") != PAPO_UPSTREAM_SOURCE_SHA256
        or runtime_config.get("require_gpu_contract_probe") is not True
    ):
        raise SmokeGateError("PAPO GPU probe/config evidence is inconsistent")
    _assert_finite(probe, "papo_gpu_contract_probe")


def _validate_marker_references(
    marker: Mapping[str, Any],
    *,
    generations_per_prompt: int,
) -> dict[str, int]:
    final_adapter = Path(str(marker.get("final_adapter", "")))
    if not final_adapter.is_dir() or not any(path.is_file() for path in final_adapter.iterdir()):
        raise SmokeGateError("smoke final adapter is missing or empty")
    observed_generations: dict[str, set[int]] = {}
    ledger_identities: Counter[tuple[str, str, int, int]] = Counter()
    trace_identities: Counter[tuple[str, str, int, int]] = Counter()
    ledger_tokens = 0
    ledger_rows = 0
    empty_answer_count = 0
    for field in ("rank_ledger_manifest", "rank_reward_trace_manifest"):
        rows = marker.get(field)
        if not isinstance(rows, list):
            raise SmokeGateError(f"smoke marker lacks {field}")
        for row in rows:
            if not isinstance(row, dict):
                raise SmokeGateError(f"{field} contains a malformed row")
            path = Path(str(row.get("path", "")))
            if not path.is_file():
                raise SmokeGateError(f"{field} referenced file is missing: {path}")
            if field == "rank_ledger_manifest":
                value = _load_object(path, "rank completion ledger")
                entries = value.get("entries")
                if not isinstance(entries, list) or len(entries) != row.get("completion_count"):
                    raise SmokeGateError(f"ledger entry count mismatch: {path}")
                if value.get("consumed_tokens") != row.get("consumed_tokens"):
                    raise SmokeGateError(f"ledger token total mismatch: {path}")
                for entry in entries:
                    if not isinstance(entry, dict):
                        raise SmokeGateError(f"malformed ledger entry: {path}")
                    slot_id = entry.get("slot_id")
                    generation = entry.get("generation_index")
                    measured_completion_id = entry.get("completion_id")
                    token_count = entry.get("token_count")
                    if (
                        not isinstance(slot_id, str)
                        or not isinstance(generation, int)
                        or not isinstance(measured_completion_id, str)
                        or not measured_completion_id
                        or not isinstance(token_count, int)
                        or token_count <= 0
                    ):
                        raise SmokeGateError(f"malformed measured ledger identity: {path}")
                    observed_generations.setdefault(slot_id, set()).add(generation)
                    ledger_identities[
                        (measured_completion_id, slot_id, generation, token_count)
                    ] += 1
                    ledger_tokens += token_count
                    ledger_rows += 1
            else:
                traces = list(read_jsonl(path))
                if len(traces) != row.get("row_count"):
                    raise SmokeGateError(f"reward trace row count mismatch: {path}")
                invalid = 0
                for trace in traces:
                    _assert_finite(trace, f"reward_trace:{path}")
                    slot_id = trace.get("slot_id")
                    generation = trace.get("generation_index")
                    measured_completion_id = trace.get("completion_id")
                    token_count = trace.get("completion_tokens")
                    if (
                        not isinstance(slot_id, str)
                        or not isinstance(generation, int)
                        or not isinstance(measured_completion_id, str)
                        or not measured_completion_id
                        or not isinstance(token_count, int)
                        or token_count <= 0
                    ):
                        raise SmokeGateError(f"malformed reward-trace identity: {path}")
                    trace_identities[
                        (measured_completion_id, slot_id, generation, token_count)
                    ] += 1
                    invalid += int(trace.get("parser_valid") is not True)
                    if trace.get("parser_error") == "empty_answer":
                        empty_answer_count += 1
                if invalid != row.get("malformed_completion_count"):
                    raise SmokeGateError(f"reward trace malformed count mismatch: {path}")
    checkpoints = marker.get("checkpoint_manifest")
    if not isinstance(checkpoints, list) or not checkpoints:
        raise SmokeGateError("smoke marker has no checkpoint manifest")
    for row in checkpoints:
        if not isinstance(row, dict):
            raise SmokeGateError("checkpoint manifest contains a malformed row")
        path = Path(str(row.get("path", "")))
        if not path.is_dir():
            raise SmokeGateError(f"checkpoint directory is missing: {path}")
    expected_generations = set(range(generations_per_prompt))
    if any(generations != expected_generations for generations in observed_generations.values()):
        raise SmokeGateError("ledger slot lacks the exact generation-index set")
    if ledger_identities != trace_identities:
        raise SmokeGateError("ledger and reward-trace completion identities differ")
    return {
        "completion_count": ledger_rows,
        "completion_tokens": ledger_tokens,
        "unique_slots": len(observed_generations),
        "empty_answer_count": empty_answer_count,
    }


def _validate_smoke_run(config_path: Path) -> dict[str, Any]:
    frozen = _load_object(config_path, "frozen smoke config")
    manifest_path = config_path.with_name("run-manifest.json")
    manifest = _load_object(manifest_path, "smoke run manifest")
    runtime = frozen.get("runtime")
    if not isinstance(runtime, dict):
        raise SmokeGateError(f"{config_path} has no runtime object")
    if runtime.get("run_mode") != "smoke" or runtime.get("max_optimizer_steps") != SMOKE_STEPS:
        raise SmokeGateError(
            f"smoke runtime must use run_mode=smoke and exactly {SMOKE_STEPS} steps"
        )
    if manifest.get("run_mode") != "smoke":
        raise SmokeGateError("smoke run manifest has the wrong run mode")
    frozen_sha = canonical_json_hash(frozen)
    if manifest.get("frozen_config_sha256") != frozen_sha:
        raise SmokeGateError("smoke frozen config hash differs from run manifest")
    completion_path = Path(str(runtime.get("output_dir", ""))) / "training-complete.json"
    marker = _load_object(completion_path, "smoke completion marker")
    if (
        marker.get("schema_version") != 4
        or marker.get("status") != "completed"
        or marker.get("trained") is not True
        or marker.get("run_mode") != "smoke"
        or marker.get("optimizer_steps") != SMOKE_STEPS
    ):
        raise SmokeGateError(f"incomplete {SMOKE_STEPS}-step smoke: {completion_path}")
    arm = str(runtime.get("arm", ""))
    if marker.get("arm") != arm or manifest.get("arm") != arm:
        raise SmokeGateError("smoke arm identity drift")
    expected_completions = (
        SMOKE_STEPS
        * int(runtime["per_device_train_batch_size"])
        * int(runtime["gradient_accumulation_steps"])
        * int(runtime["world_size"])
    )
    if marker.get("realized_sampled_completion_count") != expected_completions:
        raise SmokeGateError(f"{arm} completion count is not exactly {expected_completions}")
    expected_unique = expected_completions // int(runtime["generations_per_prompt"])
    if marker.get("unique_prompt_groups_consumed") != expected_unique:
        raise SmokeGateError(f"{arm} unique-prompt count is not exactly {expected_unique}")
    if marker.get("prompt_truncation_count") != 0:
        raise SmokeGateError(f"{arm} has non-zero prompt_truncation_count")
    if marker.get("completion_truncation_count") != 0:
        raise SmokeGateError(f"{arm} has non-zero completion_truncation_count")
    if marker.get("oom_count") != 0:
        raise SmokeGateError(f"{arm} has non-zero oom_count")
    realized_tokens = marker.get("realized_sampled_completion_tokens")
    if not isinstance(realized_tokens, int) or realized_tokens <= 0:
        raise SmokeGateError(f"{arm} has no positive sampled completion-token count")
    projected_main_tokens = math.ceil(realized_tokens * 5750 / SMOKE_STEPS)
    if projected_main_tokens > int(runtime["max_completion_tokens_per_run"]):
        raise SmokeGateError(
            f"{arm} smoke projects {projected_main_tokens} main completion tokens, "
            f"above the {runtime['max_completion_tokens_per_run']} safety ceiling"
        )
    resume = marker.get("forced_process_resume_probe")
    if (
        not isinstance(resume, dict)
        or resume.get("status") != "passed"
        or resume.get("checkpoint_step") != 5
        or resume.get("resumed_to_step") != SMOKE_STEPS
        or resume.get("first_process_pid") == resume.get("resumed_process_pid")
    ):
        raise SmokeGateError(f"{arm} lacks the forced step-5 new-process resume proof")
    world_size = int(runtime["world_size"])
    expected_ranks = set(range(world_size))
    rank_resume_audits = resume.get("rank_resume_load_audits")
    if not isinstance(rank_resume_audits, list) or len(rank_resume_audits) != world_size:
        raise SmokeGateError(f"{arm} rank resume-load evidence is incomplete")
    if any(not isinstance(audit, dict) for audit in rank_resume_audits):
        raise SmokeGateError(f"{arm} rank resume-load evidence is malformed")
    resume_by_rank: dict[int, dict[str, Any]] = {}
    for embedded_audit in rank_resume_audits:
        audit = _load_attested_object(embedded_audit, f"{arm} phase-2 resume audit")
        rank = audit.get("rank")
        if not isinstance(rank, int) or rank in resume_by_rank:
            raise SmokeGateError(f"{arm} phase-2 rank set is malformed")
        resume_by_rank[rank] = audit
        _assert_phase_2_resume_audit(
            audit,
            arm=arm,
        )
    if set(resume_by_rank) != expected_ranks:
        raise SmokeGateError(f"{arm} phase-2 rank set is incomplete")
    phase_1_rank_evidence = resume.get("phase_1_rank_evidence")
    if not isinstance(phase_1_rank_evidence, list) or len(phase_1_rank_evidence) != world_size:
        raise SmokeGateError(f"{arm} phase-1 rank evidence is incomplete")
    phase_1_by_rank: dict[int, dict[str, Any]] = {}
    for embedded_evidence in phase_1_rank_evidence:
        if not isinstance(embedded_evidence, dict):
            raise SmokeGateError(f"{arm} has malformed phase-1 rank evidence")
        evidence = _load_attested_object(
            embedded_evidence, f"{arm} phase-1 trainable-state evidence"
        )
        rank = evidence.get("rank")
        if (
            not isinstance(rank, int)
            or rank in phase_1_by_rank
            or not is_sha256(str(evidence.get("trainable_parameter_state_sha256")))
            or not isinstance(evidence.get("max_gpu_memory_allocated_bytes"), int)
            or int(evidence["max_gpu_memory_allocated_bytes"]) <= 0
            or not isinstance(evidence.get("max_gpu_memory_reserved_bytes"), int)
            or int(evidence["max_gpu_memory_reserved_bytes"]) <= 0
        ):
            raise SmokeGateError(f"{arm} phase-1 evidence content is malformed")
        phase_1_by_rank[rank] = evidence
    if set(phase_1_by_rank) != expected_ranks:
        raise SmokeGateError(f"{arm} phase-1 rank set is incomplete")
    for embedded_audit in rank_resume_audits:
        rank = int(embedded_audit["rank"])
        audit = resume_by_rank[rank]
        phase_1 = phase_1_by_rank.get(rank)
        phase_1_embedded = next(row for row in phase_1_rank_evidence if row.get("rank") == rank)
        if (
            phase_1 is None
            or audit.get("phase_1_evidence_path") != phase_1_embedded.get("path")
            or audit.get("checkpoint_trainable_parameter_sha256")
            != phase_1.get("trainable_parameter_state_sha256")
        ):
            raise SmokeGateError(f"{arm} resume model-state evidence drifted")
    if marker.get("frozen_config_sha256") != frozen_sha:
        raise SmokeGateError("completion marker frozen-config hash mismatch")
    if marker.get("run_manifest_sha256") != canonical_json_hash(manifest):
        raise SmokeGateError("completion marker run-manifest hash mismatch")
    if marker.get("dataset_sha256") != manifest.get("dataset_manifest_sha256"):
        raise SmokeGateError("completion marker dataset hash mismatch")
    if (
        not isinstance(marker.get("max_gpu_memory_allocated_bytes"), int)
        or int(marker["max_gpu_memory_allocated_bytes"]) <= 0
    ):
        raise SmokeGateError(f"{arm} has no positive GPU allocation measurement")
    if (
        not isinstance(marker.get("max_gpu_memory_reserved_bytes"), int)
        or int(marker["max_gpu_memory_reserved_bytes"]) <= 0
    ):
        raise SmokeGateError(f"{arm} has no positive GPU reservation measurement")
    metrics = marker.get("metrics")
    if not isinstance(metrics, dict) or float(metrics.get("train_runtime", 0.0)) <= 0:
        raise SmokeGateError(f"{arm} has no positive train_runtime")
    if "train_loss" not in metrics:
        raise SmokeGateError(f"{arm} metrics lack train_loss")
    _assert_finite(metrics, f"{arm}.metrics")
    log_history = marker.get("log_history")
    _assert_finite(log_history, f"{arm}.log_history")
    if not isinstance(log_history, list) or not any(
        isinstance(row, dict) and "grad_norm" in row for row in log_history
    ):
        raise SmokeGateError(f"{arm} log history lacks measured grad_norm")
    if arm == "papo_controlled":
        _assert_papo_probe(
            marker.get("papo_gpu_contract_probe"),
            runtime_config=runtime.get("papo_config") or {},
        )
    elif marker.get("papo_gpu_contract_probe") is not None:
        raise SmokeGateError(f"non-PAPO arm {arm} unexpectedly has a PAPO probe")
    if arm == "evi_po":
        probe = marker.get("evi_gpu_contract_probe")
        evi_config = runtime.get("evi_po_config")
        if (
            not isinstance(probe, dict)
            or not isinstance(evi_config, dict)
            or canonical_json(marker.get("evi_po_config")) != canonical_json(evi_config)
        ):
            raise SmokeGateError("EVI-PO smoke lacks its frozen config/probe evidence")
        _assert_evi_probe(probe, runtime_config=evi_config)
    elif (
        marker.get("evi_gpu_contract_probe") is not None or runtime.get("evi_po_config") is not None
    ):
        raise SmokeGateError(f"non-EVI arm {arm} unexpectedly has EVI-PO state")
    measured = _validate_marker_references(
        marker,
        generations_per_prompt=int(runtime["generations_per_prompt"]),
    )
    if (
        measured["completion_count"] != expected_completions
        or measured["completion_tokens"] != marker.get("realized_sampled_completion_tokens")
        or measured["unique_slots"] != expected_unique
    ):
        raise SmokeGateError(f"{arm} measured ledger totals differ from marker")
    # ADR-0003 hard gate: prompt-truncation 0 + completion-truncation 0 + a single
    # <answer> block.  An ``empty_answer`` is structurally conformant (one open, one
    # close, in order, terminated, no trailing text) -- a content-empty zero-reward
    # sample, not a structural decode failure -- so it is excluded from the gate's
    # malformed decision.  vLLM's regex backend enforces the single-block structure
    # but not the content min-bound ``{1,128}``, so empties are an inherent sampling
    # outcome; the raw count (incl. empty) stays in the marker for provenance and the
    # trace/marker cross-check above still holds for it.
    empty_answer_count = int(measured.get("empty_answer_count", 0))
    structural_malformed = int(marker.get("malformed_completion_count", 0)) - empty_answer_count
    if structural_malformed != 0:
        raise SmokeGateError(
            f"{arm} has {structural_malformed} structurally-malformed completions "
            f"(raw malformed={marker.get('malformed_completion_count')}, "
            f"empty_answer={empty_answer_count})"
        )
    source_config_sha = frozen.get("source_config_sha256")
    if not isinstance(source_config_sha, str):
        raise SmokeGateError("smoke frozen config lacks source_config_sha256")
    return {
        "arm": arm,
        "run_id": runtime.get("run_id"),
        "config_path": str(config_path.resolve()),
        "frozen_config_sha256": frozen_sha,
        "run_manifest_path": str(manifest_path.resolve()),
        "run_manifest_sha256": canonical_json_hash(manifest),
        "completion_path": str(completion_path.resolve()),
        "final_adapter": marker["final_adapter"],
        "realized_sampled_completion_tokens": marker["realized_sampled_completion_tokens"],
        "malformed_completion_count": marker["malformed_completion_count"],
        "method_contract": method_contract(runtime),
        "smoke_compatibility_contract": smoke_compatibility_contract(runtime),
        "projected_main_completion_tokens": projected_main_tokens,
        "common_contract": common_contract(
            runtime,
            manifest,
            source_config_sha256=source_config_sha,
        ),
    }


def certify_smoke_gate(
    config_paths: Sequence[Path],
    output: Path,
) -> dict[str, Any]:
    """Inspect each trainer-family smoke once and write a compatibility gate."""

    expected_count = len(GPU_SMOKE_ARMS)
    if len(config_paths) != expected_count:
        raise SmokeGateError(f"exactly {expected_count} smoke configs are required")
    runs = [_validate_smoke_run(path.resolve()) for path in config_paths]
    by_arm = {str(run["arm"]): run for run in runs}
    if set(by_arm) != set(GPU_SMOKE_ARMS) or len(by_arm) != expected_count:
        raise SmokeGateError("smoke gate requires each GPU trainer family exactly once")
    if (
        len({str(run["frozen_config_sha256"]) for run in runs}) != expected_count
        or len({str(run["run_id"]) for run in runs}) != expected_count
    ):
        raise SmokeGateError("smoke gate requires one unique artifact per controlled arm")
    contracts = {canonical_json_hash(run["common_contract"]) for run in runs}
    if len(contracts) != 1:
        raise SmokeGateError("controlled smoke arms do not share one common contract")
    contract = runs[0]["common_contract"]
    value = {
        "schema_version": 1,
        "kind": "three_trainer_20_step_gpu_smoke_gate",
        "status": "passed",
        "smoke_optimizer_steps_per_arm": SMOKE_STEPS,
        "forced_new_process_resume_step": 5,
        "common_contract": contract,
        "common_contract_sha256": canonical_json_hash(contract),
        "runs": [
            {key: item for key, item in run.items() if key != "common_contract"}
            for run in sorted(runs, key=lambda item: str(item["arm"]))
        ],
    }
    if output.exists():
        existing = _load_object(output, "existing smoke gate")
        if canonical_json(existing) != canonical_json(value):
            raise SmokeGateError(f"refusing to overwrite drifted smoke gate: {output}")
        return existing
    output.parent.mkdir(parents=True, exist_ok=True)
    from ..atomic_io import atomic_write_json

    atomic_write_json(output, value)
    return value


def main_gate_errors(
    runtime: Mapping[str, Any],
    manifest: Mapping[str, Any],
    *,
    source_config_sha256: str,
) -> list[str]:
    """Admit a main run from the once-certified gate summary.

    ``certify_smoke_gate`` performs the expensive evidence inspection once.
    Every main/ablation launch then checks only the small gate artifact and its
    semantic contracts; it deliberately does not walk old checkpoints, model
    adapters, ledgers, or reward traces again.
    """

    if runtime.get("run_mode") != "main":
        return []
    path = Path(str(runtime.get("compatibility_gate_path", "")))
    if not path.is_file():
        return [f"compatibility smoke gate not found: {path}"]
    try:
        gate = _load_object(path, "compatibility smoke gate")
        if (
            gate.get("schema_version") != 1
            or gate.get("kind") != "three_trainer_20_step_gpu_smoke_gate"
            or gate.get("status") != "passed"
        ):
            raise SmokeGateError("compatibility smoke gate is not a passed v1 gate")
        runs = gate.get("runs")
        expected_count = len(GPU_SMOKE_ARMS)
        if not isinstance(runs, list) or len(runs) != expected_count:
            raise SmokeGateError("compatibility smoke gate does not contain every controlled run")
        stored_runs = [run for run in runs if isinstance(run, dict)]
        stored_arms = [str(run.get("arm", "")) for run in stored_runs]
        if (
            len(stored_runs) != expected_count
            or set(stored_arms) != set(GPU_SMOKE_ARMS)
            or len(set(stored_arms)) != expected_count
        ):
            raise SmokeGateError("certified gate does not contain every unique controlled arm")
        certified_contract = gate.get("common_contract")
        if not isinstance(certified_contract, dict):
            raise SmokeGateError("certified gate has no common contract")
        expected_contract = common_contract(
            runtime,
            manifest,
            source_config_sha256=source_config_sha256,
        )
        if canonical_json(expected_contract) != canonical_json(certified_contract):
            raise SmokeGateError("main runtime differs from the certified smoke contract")
        if gate.get("common_contract_sha256") != canonical_json_hash(expected_contract):
            raise SmokeGateError("smoke gate common-contract hash mismatch")
        reference_arm = smoke_reference_arm(str(runtime.get("arm", "")))
        matching_smoke = next(
            (run for run in stored_runs if run.get("arm") == reference_arm),
            None,
        )
        if not isinstance(matching_smoke, dict):
            raise SmokeGateError(f"main arm has no {reference_arm} implementation smoke")
        if runtime.get("arm") == reference_arm:
            if canonical_json(matching_smoke.get("method_contract")) != canonical_json(
                method_contract(runtime)
            ):
                raise SmokeGateError("main arm-specific objective differs from its certified smoke")
        elif canonical_json(matching_smoke.get("smoke_compatibility_contract")) != canonical_json(
            smoke_compatibility_contract(runtime)
        ):
            raise SmokeGateError("ablation implementation differs from its parent smoke")
    except (
        KeyError,
        SmokeGateError,
        OSError,
        TypeError,
        ValueError,
        json.JSONDecodeError,
    ) as exc:
        return [f"compatibility smoke gate validation failed: {exc}"]
    return []