From f77ff0743ab467ae6ec4fc2788880967be7f5b63 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:01:59 +0800 Subject: [PATCH 1/5] DG-METTA-12: preregister courier action-set transfer, frozen roots and oracle contract --- .../courier_transfer/ORACLE_CONTRACT.md | 45 +++++ .../courier_transfer/README.md | 44 +++++ .../courier_transfer/RESULT_SCHEMA.json | 169 ++++++++++++++++++ .../courier_transfer/protocol.json | 73 ++++++++ .../courier_transfer/roots_manifest.json | 36 ++++ 5 files changed, 367 insertions(+) create mode 100644 metta_research_bench/courier_transfer/ORACLE_CONTRACT.md create mode 100644 metta_research_bench/courier_transfer/README.md create mode 100644 metta_research_bench/courier_transfer/RESULT_SCHEMA.json create mode 100644 metta_research_bench/courier_transfer/protocol.json create mode 100644 metta_research_bench/courier_transfer/roots_manifest.json diff --git a/metta_research_bench/courier_transfer/ORACLE_CONTRACT.md b/metta_research_bench/courier_transfer/ORACLE_CONTRACT.md new file mode 100644 index 00000000..65eef0a6 --- /dev/null +++ b/metta_research_bench/courier_transfer/ORACLE_CONTRACT.md @@ -0,0 +1,45 @@ +# DG-METTA-12 | Oracle and native courier adapter contract + +The native Storyworld/MeTTa runtime is the authority for courier state transitions. A courier state is an immutable ledger containing the current location, independent witnessed-source IDs, held permits, carried parcels, and completed deliveries. Typed actions are `move(node)`, `inspect(witness)`, `permit(id)`, `pickup(id)`, `deliver(id)`, and `STOP`. Permits may require distinct independent source identities. Two aliases backed by one source count once. An episode succeeds only when every required parcel was delivered and the policy emitted a correct STOP. + +## Required native adapter + +Before any train or evaluation claim, fetch and pin the **full** Storyworld SHA for the locally reported courier kernel `4cfe171` and its exact Hyperon dependencies. Implement: + +```python +class NativeCourierAdapter: + def initial(self, root_id: str, root_seed: int) -> object: ... + def legal(self, state: object) -> tuple[str, ...]: ... + def verify_step(self, state: object, action: str) -> tuple[bool, object, str]: ... + def delivered(self, state: object) -> frozenset[str]: ... + def required_deliveries(self, state: object) -> frozenset[str]: ... + def state_sha256(self, state: object) -> str: ... + def public_features(self, state: object) -> object: ... + def certify_macro(self, state: object, actions: tuple[str, ...]) -> tuple[bool, object, str]: ... +``` + +Every result must carry proof/transition receipts and an input-state digest. `verify_step` consumes a policy verifier call, including a rejected proposal. Grading checks are a separate meter. The Looped Transformer sees typed public features and the ordered allowed-action vocabulary; it never sees gold labels or the oracle value table at inference. No state mutation may occur on a failed proof. + +## Exact set oracle + +For remaining action horizon `h`, define a lexicographic Bellman value: + +``` +V(s,0) = (delivered_count(s), 0) +V(s,h) = max_lex( + (delivered_count(s), 0), # STOP + { (V(step(s,a),h-1).deliveries, V(step(s,a),h-1).negative_steps - 1) + for a in legal(s) excluding STOP } +) +A*(s,h) = { a in legal(s) : continuation_value(s,a,h) == V(s,h) } +``` + +The second coordinate prefers the fewest accepted steps for the best attainable delivery count, preserving multiple shortest successful action sequences. Keep only states where a full completion is attainable for successful-action training. Recheck every oracle label against an independent replay. Canonical A uses `min(sorted(A*))`; hashed B takes SHA-256 of `root_id|seed|state|sorted(A*)` and chooses an index modulo `len(A*)`; C uses the full set loss. The three fitted arms share the identical normalized legal-action logits. An optimal action set may contain more than one member while still representing a single supervised state presentation. + +## STOP macro contract + +The learned C checkpoint is reused byte-for-byte in D. With a shared ceiling of five **policy verifier calls**, D reserves up to two checks until the policy proposes STOP. A macro is a bounded atomic transaction: both typed state changes are certified against the native kernel, including their joint final state, before either is committed. Failures leave the original world unchanged. A native implementation lacking transaction/rollback support blocks D; a Python simulation may validate plumbing but cannot be counted as a native MeTTa repair. Record actual verifier calls, partial-check failures, macro attempts, certified and committed macros, and paired regressions. + +## Reproducibility and release gates + +Check split ID/seed disjointness and both oracle value and tie-set correctness. Require independent witness-source handling, permit ordering, graph topology, STOP, and atomicity tests. Pin the generator, MeTTa rule hashes, full native commit, tokenizer, protocol, source and training data hashes, initial-model hashes, checkpoint hashes, optimizer budget and the development report before any frozen run. Abort on changed inputs or attempts to tune on frozen labels. Frozen primary runs once per locked fitting cohort. `reference_wiring` is never conflated with `native` results. diff --git a/metta_research_bench/courier_transfer/README.md b/metta_research_bench/courier_transfer/README.md new file mode 100644 index 00000000..46e9e0b8 --- /dev/null +++ b/metta_research_bench/courier_transfer/README.md @@ -0,0 +1,44 @@ +# DG-METTA-12 | Storyworld courier action-set transfer + +**Status: CPU reference wiring (2026-11-23).** The reported native Storyworld courier commit `4cfe171` could not be resolved on the remote `MoralityLabAI/metta-storyworld` repository; its main tree currently has no courier kernel. The local three-test native report and uncommitted DataGoblin comparison could not be audited here. Native transfer remains gated. + +## Preregistered question + +Does teaching the Looped Transformer to assign probability to **all equally good actions** improve verified completion when the actions are courier navigation, evidence collection, permit acquisition, pickup, delivery, and STOP? + +| Arm | Training objective | Inference | +| --- | --- | --- | +| A | Lexicographically first action among all exact optima | Looped Transformer | +| B | SHA-256 hashed singleton from the exact same optimal set | Looped Transformer | +| C | Full optimal-action-set log-sum-exp objective | Looped Transformer | +| D | Exactly C's frozen checkpoint | Transformer plus certified MeTTa STOP macro | +| E | No training | Exact bounded oracle reference | + +The **primary confirmation** is C minus B on full verified deliveries followed by a correct STOP. A is the additional canonical-label control. D minus C is the separate inference comparison. Prior MeTTa curation and docket gains motivate this test and are not courier outcomes. + +## Split firewall + +`roots_manifest.json` freezes 520 deterministic root IDs, root-seed derivation, and a SHA-256 fingerprint of the complete ordered ID list. Train/development/frozen use distinct roots from four families; transfer uses withheld family names. + +| Split | Families | Roots each | +| --- | --- | ---: | +| Train | route_ties, permit_gate, multi_drop, evidence_ledger | 48 | +| Development | same four | 12 | +| Frozen primary | same four with fresh roots | 40 | +| Transfer | permit_chain, evidence_collision, unseen_topology | 40 | + +For each seed 1101, 1102, 1103, use the same initial weights, public state features, valid-action vocabulary, state presentations, batch indices, 600 AdamW updates and 48 examples per update. Choose B by the documented stable hash. C uses `-log(sum_{a in A*(s,h)} softmax(z)[a])`. Count one training presentation per state regardless of tie multiplicity. + +A root qualifies for successful-action training only when the exact bounded oracle can finish all deliveries. Root-local and seed-local effects are preserved. Frozen primary is held closed until the source, data and checkpoint SHA-256 receipts and the development report are locked. Paired 95% root-clustered bootstrap retains all model seeds within each resampled root. The prespecified C-B success gate is an interval lower bound above zero. Always report every seed and transfer result, including failures. + +## Gates and reproduction + +1. Run `python -m unittest discover -s tests/unit -p test_dg_metta12_reference.py -v` and `python -m metta_research_bench.courier_transfer.manifest_check` on CPU. This independently implemented courier model only establishes a wiring gate. +2. Push the complete native courier commit to Storyworld, pin its full SHA and runtime, run the three original targeted tests, then implement the adapter specified in `ORACLE_CONTRACT.md`. Differentially replay small shared states against the Python reference and inspect all disagreements. +3. Train A/B/C using native verified oracle action sets; pin the upstream LoopedDecoderLM revision stated in `protocol.json`. Lock source and checkpoints before opening frozen roots. +4. Evaluate D with a native two-check atomic macro only when C's model proposes STOP and at least two checks remain. Compare C and D with the same five-call ceiling, reporting actual calls, calls per success, vetoes, false stops and paired regressions. Abort if no native rollback/macro transition exists. +5. Emit one `RESULT_SCHEMA.json`-valid receipt per root, arm and seed. Distinguish grading checks from budgeted policy checks, persist proof identities, and label any Python-only record `reference_wiring`. + +A green wiring workflow cannot be reported as native-domain transfer or as a trained Looped Transformer result. + +Files: `protocol.json` preregisters all arms and metrics; `roots_manifest.json` freezes the cohort allocation; `ORACLE_CONTRACT.md` defines admissibility, Bellman ties and transaction semantics; `RESULT_SCHEMA.json` defines receipts; `reference.py` and the unit tests are CPU controls. diff --git a/metta_research_bench/courier_transfer/RESULT_SCHEMA.json b/metta_research_bench/courier_transfer/RESULT_SCHEMA.json new file mode 100644 index 00000000..b2366ab4 --- /dev/null +++ b/metta_research_bench/courier_transfer/RESULT_SCHEMA.json @@ -0,0 +1,169 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/MoralityLabAI/DataGoblin/blob/master/metta_research_bench/courier_transfer/RESULT_SCHEMA.json", + "title": "DG-METTA-12 per-root, per-seed, per-arm receipt", + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", + "mode", + "experiment_id", + "split", + "family", + "root_id", + "root_seed", + "arm", + "model_seed", + "source_sha256", + "protocol_sha256", + "native_kernel_sha", + "checkpoint_sha256", + "complete", + "stopped", + "verifier_calls", + "actions", + "proof_receipts", + "macro" + ], + "properties": { + "schema_version": { + "const": "dg-metta12-result-v1" + }, + "mode": { + "enum": [ + "reference_wiring", + "native" + ] + }, + "experiment_id": { + "const": "DG-METTA-12" + }, + "split": { + "enum": [ + "train", + "development", + "frozen", + "transfer" + ] + }, + "family": { + "type": "string", + "minLength": 1 + }, + "root_id": { + "type": "string", + "minLength": 1 + }, + "root_seed": { + "type": "integer", + "minimum": 0 + }, + "arm": { + "enum": [ + "A", + "B", + "C", + "D", + "E" + ] + }, + "model_seed": { + "type": "integer" + }, + "source_sha256": { + "$ref": "#/$defs/sha256" + }, + "protocol_sha256": { + "$ref": "#/$defs/sha256" + }, + "native_kernel_sha": { + "type": [ + "string", + "null" + ], + "pattern": "^[0-9a-f]{40}$" + }, + "checkpoint_sha256": { + "type": [ + "string", + "null" + ], + "pattern": "^[0-9a-f]{64}$" + }, + "complete": { + "type": "boolean" + }, + "stopped": { + "type": "boolean" + }, + "verifier_calls": { + "type": "integer", + "minimum": 0 + }, + "grading_calls": { + "type": "integer", + "minimum": 0 + }, + "invalid_proposals": { + "type": "integer", + "minimum": 0 + }, + "premature_stop": { + "type": "boolean" + }, + "accepted_action_count": { + "type": "integer", + "minimum": 0 + }, + "actions": { + "type": "array", + "items": { + "type": "string" + } + }, + "proof_receipts": { + "type": "array", + "items": { + "type": "string" + } + }, + "macro": { + "type": "object", + "additionalProperties": false, + "required": [ + "attempted", + "certified", + "committed", + "verifier_calls" + ], + "properties": { + "attempted": { + "type": "boolean" + }, + "certified": { + "type": "boolean" + }, + "committed": { + "type": "boolean" + }, + "verifier_calls": { + "type": "integer", + "minimum": 0 + }, + "final_state_sha256": { + "type": [ + "string", + "null" + ], + "pattern": "^[0-9a-f]{64}$" + } + } + } + }, + "$defs": { + "sha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + } + } +} diff --git a/metta_research_bench/courier_transfer/protocol.json b/metta_research_bench/courier_transfer/protocol.json new file mode 100644 index 00000000..f2b00aab --- /dev/null +++ b/metta_research_bench/courier_transfer/protocol.json @@ -0,0 +1,73 @@ +{ + "experiment_id": "DG-METTA-12", + "schema_version": "courier-transfer-preregistered-v1", + "registration_date": "2026-11-23", + "status": "wiring_only_until_native_kernel_pinned", + "source": { + "data_goblin_base": "a1646c0318df6942db6c58bc78da4084599df7d6", + "native_storyworld_repository": "MoralityLabAI/metta-storyworld", + "claimed_local_courier_commit": "4cfe171", + "native_storyworld_full_commit": null, + "looped_transformers_upstream": "950d4d594d87a1f74c6139a928a9b6cb4ab70617" + }, + "architecture": { + "model": "upstream-LoopedDecoderLM", + "physical_attention_blocks": 1, + "recurrent_visits": 3, + "hidden_size": 32, + "attention_heads": 4, + "action_head": "shared_parameter_pointer_over_sorted_typed_actions", + "tokenizer": "courier-public-typed-state-v1" + }, + "training": { + "seeds": [ + 1101, + 1102, + 1103 + ], + "adamw_updates_per_arm": 600, + "examples_per_update": 48, + "learning_rate": 0.0015, + "weight_decay": 0.01, + "matched_initial_weights": true, + "matched_examples_by_state": true, + "arms": { + "A": "lexicographically_canonical_best_action", + "B": "sha256_hashed_singleton_from_full_optimal_set", + "C": "full_optimal_action_set_logsumexp_loss", + "D": "C_weights_plus_certified_stop_macro", + "E": "exact_bounded_oracle_reference_not_trained" + } + }, + "evaluation": { + "primary_endpoint": "verified_full_delivery_and_correct_STOP", + "paired_contrast": "C_minus_B", + "secondary_contrast": "D_minus_C", + "secondary_metrics": [ + "verifier_calls_per_verified_completion", + "mean_verifier_calls", + "premature_stops", + "invalid_proposals", + "accepted_action_count", + "macro_repair_count", + "paired_regressions" + ], + "five_call_cap_per_episode_for_C_and_D": 5, + "stop_macro_max_verifier_calls": 2, + "stop_macro_policy": "reserve_until_stop; certify_final_state_before_atomic_commit; unused_budget_not_reallocated", + "root_clustered_confidence_interval": "95% paired root bootstrap, seeds remain within root cluster", + "bootstrap_repetitions": 10000, + "decision_rule": "C-B strictly positive with bootstrap lower endpoint above zero; report raw seed effects", + "negative_result_handling": "report all endpoints and seed-level effects even when gate fails" + }, + "release_gates": { + "reference_oracle_tests": "all_green", + "native_storyworld_kernel_pinned_full_sha": "required_for_native_results", + "native_three_targeted_tests": "all_green", + "reference_native_differential_test": "all_green_on_shared_small_states", + "fresh_split_disjointness": "required", + "dataset_and_checkpoint_hashes_locked_before_frozen": "required", + "frozen_evaluation_uses_only_committed_code": "required", + "no_applied_invalid_transition": "required" + } +} diff --git a/metta_research_bench/courier_transfer/roots_manifest.json b/metta_research_bench/courier_transfer/roots_manifest.json new file mode 100644 index 00000000..9e478b9c --- /dev/null +++ b/metta_research_bench/courier_transfer/roots_manifest.json @@ -0,0 +1,36 @@ +{ + "experiment_id": "DG-METTA-12", + "schema_version": "courier-roots-v1", + "seed_namespace": "DG-METTA-12-20261123-v1", + "id_format": "DG12/{split}/{family}/{index:04d}", + "index_origin": 0, + "seed_derivation": "int.from_bytes(sha256((seed_namespace+'|'+root_id).encode()).digest()[:8], 'big')", + "ordered_traversal": "split order then family insertion order then ascending index", + "split_roots": { + "train": { + "route_ties": 48, + "permit_gate": 48, + "multi_drop": 48, + "evidence_ledger": 48 + }, + "development": { + "route_ties": 12, + "permit_gate": 12, + "multi_drop": 12, + "evidence_ledger": 12 + }, + "frozen": { + "route_ties": 40, + "permit_gate": 40, + "multi_drop": 40, + "evidence_ledger": 40 + }, + "transfer": { + "permit_chain": 40, + "evidence_collision": 40, + "unseen_topology": 40 + } + }, + "total_roots": 520, + "root_ids_sha256": "4a618bb948f677a0b25987b3bb2d83347353ace7abcd7b89dc5d2e2482faf3cc" +} From 90264533da3c22f6f6dc7e3d7af817f873aed24c Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:03:43 +0800 Subject: [PATCH 2/5] DG-METTA-12: implement finite courier oracle, tied-action loss and CPU gate --- .github/workflows/dg-metta12-courier.yml | 26 +++ .../courier_transfer/README.md | 2 +- .../courier_transfer/__init__.py | 1 + .../courier_transfer/manifest_check.py | 47 +++++ .../courier_transfer/reference.py | 181 ++++++++++++++++++ tests/unit/test_dg_metta12_reference.py | 97 ++++++++++ 6 files changed, 353 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/dg-metta12-courier.yml create mode 100644 metta_research_bench/courier_transfer/__init__.py create mode 100644 metta_research_bench/courier_transfer/manifest_check.py create mode 100644 metta_research_bench/courier_transfer/reference.py create mode 100644 tests/unit/test_dg_metta12_reference.py diff --git a/.github/workflows/dg-metta12-courier.yml b/.github/workflows/dg-metta12-courier.yml new file mode 100644 index 00000000..81624713 --- /dev/null +++ b/.github/workflows/dg-metta12-courier.yml @@ -0,0 +1,26 @@ +name: DG-METTA-12 courier CPU contract + +on: + pull_request: + paths: + - "metta_research_bench/courier_transfer/**" + - "tests/unit/test_dg_metta12_reference.py" + - ".github/workflows/dg-metta12-courier.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + reference-wiring: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Check exact CPU courier reference semantics + run: python -m unittest discover -s tests/unit -p test_dg_metta12_reference.py -v + - name: Verify pinned split ID fingerprint and result schema + run: python metta_research_bench/courier_transfer/manifest_check.py diff --git a/metta_research_bench/courier_transfer/README.md b/metta_research_bench/courier_transfer/README.md index 46e9e0b8..3b4b7eed 100644 --- a/metta_research_bench/courier_transfer/README.md +++ b/metta_research_bench/courier_transfer/README.md @@ -33,7 +33,7 @@ A root qualifies for successful-action training only when the exact bounded orac ## Gates and reproduction -1. Run `python -m unittest discover -s tests/unit -p test_dg_metta12_reference.py -v` and `python -m metta_research_bench.courier_transfer.manifest_check` on CPU. This independently implemented courier model only establishes a wiring gate. +1. Run `python -m unittest discover -s tests/unit -p test_dg_metta12_reference.py -v` and `python metta_research_bench/courier_transfer/manifest_check.py` on CPU. This independently implemented courier model only establishes a wiring gate. 2. Push the complete native courier commit to Storyworld, pin its full SHA and runtime, run the three original targeted tests, then implement the adapter specified in `ORACLE_CONTRACT.md`. Differentially replay small shared states against the Python reference and inspect all disagreements. 3. Train A/B/C using native verified oracle action sets; pin the upstream LoopedDecoderLM revision stated in `protocol.json`. Lock source and checkpoints before opening frozen roots. 4. Evaluate D with a native two-check atomic macro only when C's model proposes STOP and at least two checks remain. Compare C and D with the same five-call ceiling, reporting actual calls, calls per success, vetoes, false stops and paired regressions. Abort if no native rollback/macro transition exists. diff --git a/metta_research_bench/courier_transfer/__init__.py b/metta_research_bench/courier_transfer/__init__.py new file mode 100644 index 00000000..801ec7ae --- /dev/null +++ b/metta_research_bench/courier_transfer/__init__.py @@ -0,0 +1 @@ +"""DG-METTA-12 native courier transfer contract and CPU reference oracle.""" diff --git a/metta_research_bench/courier_transfer/manifest_check.py b/metta_research_bench/courier_transfer/manifest_check.py new file mode 100644 index 00000000..facd2829 --- /dev/null +++ b/metta_research_bench/courier_transfer/manifest_check.py @@ -0,0 +1,47 @@ +"""Independent manifest fingerprint and schema shape checks for CI.""" +import hashlib +import json +from pathlib import Path + +BASE = Path(__file__).resolve().parent + + +def roots_for(manifest: dict) -> tuple[str, ...]: + return tuple( + f"DG12/{split}/{family}/{index:04d}" + for split, counts in manifest["split_roots"].items() + for family, count in counts.items() + for index in range(count) + ) + + +def root_seed(manifest: dict, root_id: str) -> int: + key = (manifest["seed_namespace"] + "|" + root_id).encode("utf-8") + return int.from_bytes(hashlib.sha256(key).digest()[:8], "big") + + +def validate() -> dict: + manifest = json.loads((BASE / "roots_manifest.json").read_text()) + protocol = json.loads((BASE / "protocol.json").read_text()) + schema = json.loads((BASE / "RESULT_SCHEMA.json").read_text()) + roots = roots_for(manifest) + digest = hashlib.sha256(("\\n".join(roots) + "\\n").encode()).hexdigest() + assert digest == manifest["root_ids_sha256"], "root-ID manifest changed" + assert len(roots) == len(set(roots)) == manifest["total_roots"] + assert len({root_seed(manifest, r) for r in roots}) == len(roots) + assert protocol["experiment_id"] == schema["properties"]["experiment_id"]["const"] + assert protocol["evaluation"]["five_call_cap_per_episode_for_C_and_D"] == 5 + if protocol["status"] == "wiring_only_until_native_kernel_pinned": + assert protocol["source"]["native_storyworld_full_commit"] is None + else: + native = protocol["source"]["native_storyworld_full_commit"] + assert isinstance(native, str) and len(native) == 40 + assert set(manifest["split_roots"]["train"]) == set(manifest["split_roots"]["development"]) + assert set(manifest["split_roots"]["train"]) == set(manifest["split_roots"]["frozen"]) + assert not set(manifest["split_roots"]["train"]) & set(manifest["split_roots"]["transfer"]) + return {"roots": len(roots), "root_ids_sha256": digest, + "status": protocol["status"]} + + +if __name__ == "__main__": + print(json.dumps(validate(), indent=2)) diff --git a/metta_research_bench/courier_transfer/reference.py b/metta_research_bench/courier_transfer/reference.py new file mode 100644 index 00000000..c665e30a --- /dev/null +++ b/metta_research_bench/courier_transfer/reference.py @@ -0,0 +1,181 @@ +"""Finite deterministic CPU oracle for DG-METTA-12 adapter wiring. + +This independently implemented Python reference is not the native Storyworld +MeTTa kernel. Its outputs cannot count as native domain-transfer results. +""" +from __future__ import annotations + +from dataclasses import dataclass, replace +from functools import cache +import hashlib +import json + +STOP = "STOP" + + +@dataclass(frozen=True) +class CourierWorld: + start: str + # Undirected edges: (node_a, node_b, required_permit), "" if unrestricted. + edges: tuple[tuple[str, str, str], ...] + # (permit_id, office_node) + offices: tuple[tuple[str, str], ...] + # (parcel_id, pickup_node, destination_node, required_delivery_permit) + parcels: tuple[tuple[str, str, str, str], ...] + # (witness_alias, witness_node, independent_source_id) + witnesses: tuple[tuple[str, str, str], ...] = () + # (permit_id, tuple of required independent source ids) + permit_sources: tuple[tuple[str, tuple[str, ...]], ...] = () + + def __post_init__(self) -> None: + if not self.start: + raise ValueError("missing starting node") + for ids in ( + [p for p, _ in self.offices], + [p for p, *_ in self.parcels], + [w for w, *_ in self.witnesses], + [p for p, _ in self.permit_sources], + ): + if len(set(ids)) != len(ids): + raise ValueError("duplicate typed IDs") + if any(a == b for a, b, _ in self.edges): + raise ValueError("self-loop edges are unsupported by the reference") + + +@dataclass(frozen=True) +class CourierState: + at: str + permits: frozenset[str] = frozenset() + observed_sources: frozenset[str] = frozenset() + carrying: frozenset[str] = frozenset() + delivered: frozenset[str] = frozenset() + + +def initial(world: CourierWorld) -> CourierState: + return CourierState(at=world.start) + + +def legal_actions(world: CourierWorld, state: CourierState) -> tuple[str, ...]: + actions = {STOP} + for a, b, permit in world.edges: + if not permit or permit in state.permits: + if state.at == a: + actions.add(f"move:{b}") + elif state.at == b: + actions.add(f"move:{a}") + requirements = dict(world.permit_sources) + for permit, office in world.offices: + if (office == state.at and permit not in state.permits + and set(requirements.get(permit, ())).issubset(state.observed_sources)): + actions.add(f"permit:{permit}") + for alias, node, source in world.witnesses: + if node == state.at and source not in state.observed_sources: + actions.add(f"inspect:{alias}") + for parcel, pickup, destination, required in world.parcels: + if (parcel not in state.carrying and parcel not in state.delivered + and state.at == pickup): + actions.add(f"pickup:{parcel}") + if (parcel in state.carrying and state.at == destination + and (not required or required in state.permits)): + actions.add(f"deliver:{parcel}") + return tuple(sorted(actions)) + + +def transition(world: CourierWorld, state: CourierState, action: str) -> CourierState: + if action == STOP or action not in legal_actions(world, state): + raise ValueError(f"invalid state-changing action: {action}") + kind, identifier = action.split(":", 1) + if kind == "move": + return replace(state, at=identifier) + if kind == "permit": + return replace(state, permits=state.permits | {identifier}) + if kind == "inspect": + source = next(src for alias, _, src in world.witnesses if alias == identifier) + return replace(state, observed_sources=state.observed_sources | {source}) + if kind == "pickup": + return replace(state, carrying=state.carrying | {identifier}) + if kind == "deliver": + return replace(state, carrying=state.carrying - {identifier}, + delivered=state.delivered | {identifier}) + raise AssertionError(action) + + +def success(world: CourierWorld, state: CourierState, stopped: bool) -> bool: + return stopped and state.delivered == frozenset(p for p, *_ in world.parcels) + + +class FiniteOracle: + """Lexicographic exact optimum: (delivered count, negative action count). + + STOP scores the current state. Every accepted action costs one step. + Different shortest successful continuations all receive supervision. + Unsolvable states are excluded from the successful-action training pool. + """ + + def __init__(self, world: CourierWorld) -> None: + self.world = world + + @cache + def value(self, state: CourierState, remaining: int) -> tuple[int, int]: + if remaining < 0: + raise ValueError("remaining must be nonnegative") + best = (len(state.delivered), 0) + if remaining: + for action in legal_actions(self.world, state): + if action != STOP: + nxt = self.value(transition(self.world, state, action), remaining - 1) + best = max(best, (nxt[0], nxt[1] - 1)) + return best + + def action_set(self, state: CourierState, remaining: int) -> tuple[str, ...]: + best = self.value(state, remaining) + choices = [] + for action in legal_actions(self.world, state): + if action == STOP: + score = (len(state.delivered), 0) + elif remaining: + nxt = self.value(transition(self.world, state, action), remaining - 1) + score = (nxt[0], nxt[1] - 1) + else: + continue + if score == best: + choices.append(action) + return tuple(choices) + + def can_finish(self, state: CourierState, remaining: int) -> bool: + return self.value(state, remaining)[0] == len(self.world.parcels) + + +def serialize_state(state: CourierState) -> str: + """Canonical across Python hash seeds and frozenset iteration orders.""" + return json.dumps({ + "at": state.at, + "permits": sorted(state.permits), + "observed_sources": sorted(state.observed_sources), + "carrying": sorted(state.carrying), + "delivered": sorted(state.delivered), + }, sort_keys=True, separators=(",", ":")) + + +def hashed_singleton( + root_id: str, state: CourierState, actions: tuple[str, ...], seed: int +) -> str: + """Stable action-tie control independent of Python hash randomization.""" + if not actions or len(set(actions)) != len(actions): + raise ValueError("expected nonempty unique action set") + ordered = sorted(actions) + key = "|".join((root_id, str(seed), serialize_state(state), *ordered)).encode() + j = int.from_bytes(hashlib.sha256(key).digest()[:8], "big") % len(ordered) + return ordered[j] + + +def set_nll(logits, allowed_indices: tuple[int, ...]): + """PyTorch action-set NLL with full legal-action normalization.""" + import torch + if not allowed_indices: + raise ValueError("empty optimal action set") + indices = torch.tensor(sorted(set(allowed_indices)), device=logits.device) + if (logits.ndim != 1 or indices.min().item() < 0 + or indices.max().item() >= len(logits)): + raise ValueError("indices must select valid logits") + return torch.logsumexp(logits, dim=0) - torch.logsumexp(logits[indices], dim=0) diff --git a/tests/unit/test_dg_metta12_reference.py b/tests/unit/test_dg_metta12_reference.py new file mode 100644 index 00000000..db03aefa --- /dev/null +++ b/tests/unit/test_dg_metta12_reference.py @@ -0,0 +1,97 @@ +"""DG-METTA-12 CPU wiring tests with no runtime dependencies.""" +import sys +import unittest +from pathlib import Path + +# Import the isolated reference without importing metta_research_bench.__init__, +# which loads the heavy pinned Verifiers runtime. +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / + "metta_research_bench" / "courier_transfer")) + +from reference import ( # noqa: E402 + CourierWorld, FiniteOracle, CourierState, initial, legal_actions, + transition, success, hashed_singleton, serialize_state, +) + + +class CourierReferenceTests(unittest.TestCase): + def test_two_equal_routes_produce_two_optimal_actions(self): + world = CourierWorld( + start="A", edges=(("A", "B", ""), ("A", "C", ""), + ("B", "D", ""), ("C", "D", "")), + offices=(), parcels=(("p", "A", "D", ""),), + ) + oracle = FiniteOracle(world) + state = transition(world, initial(world), "pickup:p") + self.assertEqual(oracle.action_set(state, 3), ("move:B", "move:C")) + self.assertTrue(oracle.can_finish(state, 3)) + for action in oracle.action_set(state, 3): + nxt = transition(world, state, action) + self.assertEqual(oracle.value(nxt, 2)[0], 1) + + def test_permit_and_pickup_tie_on_optimal_path(self): + world = CourierWorld("A", (("A", "B", "gate"),), (("gate", "A"),), + (("p", "A", "B", "gate"),)) + oracle = FiniteOracle(world) + self.assertEqual(oracle.action_set(initial(world), 4), + ("permit:gate", "pickup:p")) + with self.assertRaises(ValueError): + transition(world, initial(world), "move:B") + + def test_shared_source_aliases_are_not_independent_proofs(self): + world = CourierWorld( + "A", (("A", "B", "gate"),), (("gate", "A"),), + (("p", "A", "B", ""),), + witnesses=(("one", "A", "source-1"), + ("alias", "A", "source-1"), + ("two", "A", "source-2")), + permit_sources=(("gate", ("source-1", "source-2")),), + ) + state = transition(world, initial(world), "inspect:one") + self.assertNotIn("inspect:alias", legal_actions(world, state)) + self.assertNotIn("permit:gate", legal_actions(world, state)) + state = transition(world, state, "inspect:two") + self.assertIn("permit:gate", legal_actions(world, state)) + + def test_stop_requires_verified_delivery(self): + world = CourierWorld("A", (), (), (("p", "A", "A", ""),)) + state = initial(world) + self.assertFalse(success(world, state, stopped=True)) + state = transition(world, state, "pickup:p") + state = transition(world, state, "deliver:p") + self.assertFalse(success(world, state, stopped=False)) + self.assertTrue(success(world, state, stopped=True)) + self.assertEqual(FiniteOracle(world).action_set(state, 3), ("STOP",)) + + def test_oracle_horizon_and_hash_control(self): + world = CourierWorld("A", (("A", "B", ""),), (), + (("p", "B", "B", ""),)) + state = initial(world) + oracle = FiniteOracle(world) + self.assertEqual(oracle.action_set(state, 0), ("STOP",)) + self.assertFalse(oracle.can_finish(state, 2)) + self.assertTrue(oracle.can_finish(state, 3)) + choices = ("move:B", "permit:x") + a = hashed_singleton("test", state, choices, 1101) + self.assertEqual(a, hashed_singleton("test", state, tuple(reversed(choices)), 1101)) + shuffled = CourierState("A", frozenset(("p2", "p1"))) + self.assertEqual(serialize_state(shuffled), + serialize_state(CourierState("A", frozenset(("p1", "p2"))))) + + def test_pytorch_set_loss_if_installed(self): + try: + import torch + except ImportError: + self.skipTest("PyTorch optional in stdlib smoke") + from reference import set_nll + logits = torch.zeros(4, requires_grad=True) + self.assertAlmostEqual(float(set_nll(logits, (0, 2)).detach()), + 0.69314718, places=5) + set_nll(logits, (0, 2)).backward() + self.assertIsNotNone(logits.grad) + self.assertAlmostEqual(float(set_nll(logits, (0, 1, 2, 3)).detach()), + 0.0, places=6) + + +if __name__ == "__main__": + unittest.main() From e52973e590a501551b988589de8a5b2c0fbfd294 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:04:21 +0800 Subject: [PATCH 3/5] DG-METTA-12: correct canonical newline hashing in root manifest check --- metta_research_bench/courier_transfer/manifest_check.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/metta_research_bench/courier_transfer/manifest_check.py b/metta_research_bench/courier_transfer/manifest_check.py index facd2829..308df80a 100644 --- a/metta_research_bench/courier_transfer/manifest_check.py +++ b/metta_research_bench/courier_transfer/manifest_check.py @@ -25,7 +25,7 @@ def validate() -> dict: protocol = json.loads((BASE / "protocol.json").read_text()) schema = json.loads((BASE / "RESULT_SCHEMA.json").read_text()) roots = roots_for(manifest) - digest = hashlib.sha256(("\\n".join(roots) + "\\n").encode()).hexdigest() + digest = hashlib.sha256(("\n".join(roots) + "\n").encode()).hexdigest() assert digest == manifest["root_ids_sha256"], "root-ID manifest changed" assert len(roots) == len(set(roots)) == manifest["total_roots"] assert len({root_seed(manifest, r) for r in roots}) == len(roots) From d649b3cac006718317c6ec4dfac2708ce3655d32 Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:08:39 +0800 Subject: [PATCH 4/5] DG-METTA-12: equalize all arm call ceilings and verify 520 feasible CPU roots --- .github/workflows/dg-metta12-courier.yml | 6 +- .../courier_transfer/ORACLE_CONTRACT.md | 4 +- .../courier_transfer/README.md | 6 +- .../courier_transfer/generator.py | 113 ++++++++++++++++++ .../courier_transfer/manifest_check.py | 2 +- .../courier_transfer/protocol.json | 5 +- tests/unit/test_dg_metta12_generator.py | 36 ++++++ 7 files changed, 162 insertions(+), 10 deletions(-) create mode 100644 metta_research_bench/courier_transfer/generator.py create mode 100644 tests/unit/test_dg_metta12_generator.py diff --git a/.github/workflows/dg-metta12-courier.yml b/.github/workflows/dg-metta12-courier.yml index 81624713..f57ac2ab 100644 --- a/.github/workflows/dg-metta12-courier.yml +++ b/.github/workflows/dg-metta12-courier.yml @@ -21,6 +21,8 @@ jobs: with: python-version: "3.12" - name: Check exact CPU courier reference semantics - run: python -m unittest discover -s tests/unit -p test_dg_metta12_reference.py -v + run: python -m unittest discover -s tests/unit -p 'test_dg_metta12_*.py' -v - name: Verify pinned split ID fingerprint and result schema - run: python metta_research_bench/courier_transfer/manifest_check.py + run: | + python metta_research_bench/courier_transfer/manifest_check.py + python metta_research_bench/courier_transfer/generator.py diff --git a/metta_research_bench/courier_transfer/ORACLE_CONTRACT.md b/metta_research_bench/courier_transfer/ORACLE_CONTRACT.md index 65eef0a6..83cd46fa 100644 --- a/metta_research_bench/courier_transfer/ORACLE_CONTRACT.md +++ b/metta_research_bench/courier_transfer/ORACLE_CONTRACT.md @@ -34,11 +34,11 @@ V(s,h) = max_lex( A*(s,h) = { a in legal(s) : continuation_value(s,a,h) == V(s,h) } ``` -The second coordinate prefers the fewest accepted steps for the best attainable delivery count, preserving multiple shortest successful action sequences. Keep only states where a full completion is attainable for successful-action training. Recheck every oracle label against an independent replay. Canonical A uses `min(sorted(A*))`; hashed B takes SHA-256 of `root_id|seed|state|sorted(A*)` and chooses an index modulo `len(A*)`; C uses the full set loss. The three fitted arms share the identical normalized legal-action logits. An optimal action set may contain more than one member while still representing a single supervised state presentation. +The second coordinate prefers the fewest accepted steps for the best attainable delivery count, preserving multiple shortest successful action sequences. Keep only states where a full completion is attainable for successful-action training. Recheck every oracle label against an independent replay. Canonical A uses `min(sorted(A*))`; hashed B takes SHA-256 of `root_id|seed|state|sorted(A*)` and chooses an index modulo `len(A*)`; C uses the full set loss. The three fitted arms share the identical normalized legal-action logits and verifier-call ceiling. An optimal action set may contain more than one member while still representing a single supervised state presentation. ## STOP macro contract -The learned C checkpoint is reused byte-for-byte in D. With a shared ceiling of five **policy verifier calls**, D reserves up to two checks until the policy proposes STOP. A macro is a bounded atomic transaction: both typed state changes are certified against the native kernel, including their joint final state, before either is committed. Failures leave the original world unchanged. A native implementation lacking transaction/rollback support blocks D; a Python simulation may validate plumbing but cannot be counted as a native MeTTa repair. Record actual verifier calls, partial-check failures, macro attempts, certified and committed macros, and paired regressions. +The learned C checkpoint is reused byte-for-byte in D. A, B, C and D all share a ceiling of five **policy verifier calls**. D reserves up to two checks until the policy proposes STOP. A macro is a bounded atomic transaction: both typed state changes are certified against the native kernel, including their joint final state, before either is committed. Failures leave the original world unchanged. A native implementation lacking transaction/rollback support blocks D; a Python simulation may validate plumbing but cannot be counted as a native MeTTa repair. Record actual verifier calls, partial-check failures, macro attempts, certified and committed macros, and paired regressions. ## Reproducibility and release gates diff --git a/metta_research_bench/courier_transfer/README.md b/metta_research_bench/courier_transfer/README.md index 3b4b7eed..9c44ec64 100644 --- a/metta_research_bench/courier_transfer/README.md +++ b/metta_research_bench/courier_transfer/README.md @@ -14,7 +14,7 @@ Does teaching the Looped Transformer to assign probability to **all equally good | D | Exactly C's frozen checkpoint | Transformer plus certified MeTTa STOP macro | | E | No training | Exact bounded oracle reference | -The **primary confirmation** is C minus B on full verified deliveries followed by a correct STOP. A is the additional canonical-label control. D minus C is the separate inference comparison. Prior MeTTa curation and docket gains motivate this test and are not courier outcomes. +The **primary confirmation** is C minus B on full verified deliveries followed by a correct STOP. A is the additional canonical-label control. All learned arms A/B/C/D share the same five-call verifier ceiling, so the primary C-B comparison is budget-matched. D minus C is the separate inference comparison. Prior MeTTa curation and docket gains motivate this test and are not courier outcomes. ## Split firewall @@ -29,11 +29,11 @@ The **primary confirmation** is C minus B on full verified deliveries followed b For each seed 1101, 1102, 1103, use the same initial weights, public state features, valid-action vocabulary, state presentations, batch indices, 600 AdamW updates and 48 examples per update. Choose B by the documented stable hash. C uses `-log(sum_{a in A*(s,h)} softmax(z)[a])`. Count one training presentation per state regardless of tie multiplicity. -A root qualifies for successful-action training only when the exact bounded oracle can finish all deliveries. Root-local and seed-local effects are preserved. Frozen primary is held closed until the source, data and checkpoint SHA-256 receipts and the development report are locked. Paired 95% root-clustered bootstrap retains all model seeds within each resampled root. The prespecified C-B success gate is an interval lower bound above zero. Always report every seed and transfer result, including failures. +Every generated root must have a completed path with at most five charged primitive checks. A root qualifies for successful-action training only when the exact bounded oracle can finish all deliveries. Root-local and seed-local effects are preserved. Frozen primary is held closed until the source, data and checkpoint SHA-256 receipts and the development report are locked. Paired 95% root-clustered bootstrap retains all model seeds within each resampled root. The prespecified C-B success gate is an interval lower bound above zero. Always report every seed and transfer result, including failures. ## Gates and reproduction -1. Run `python -m unittest discover -s tests/unit -p test_dg_metta12_reference.py -v` and `python metta_research_bench/courier_transfer/manifest_check.py` on CPU. This independently implemented courier model only establishes a wiring gate. +1. Run `python metta_research_bench/courier_transfer/generator.py`, `python -m unittest discover -s tests/unit -p test_dg_metta12_reference.py -v` and `python metta_research_bench/courier_transfer/manifest_check.py` on CPU. This independently implemented courier model only establishes a wiring gate. 2. Push the complete native courier commit to Storyworld, pin its full SHA and runtime, run the three original targeted tests, then implement the adapter specified in `ORACLE_CONTRACT.md`. Differentially replay small shared states against the Python reference and inspect all disagreements. 3. Train A/B/C using native verified oracle action sets; pin the upstream LoopedDecoderLM revision stated in `protocol.json`. Lock source and checkpoints before opening frozen roots. 4. Evaluate D with a native two-check atomic macro only when C's model proposes STOP and at least two checks remain. Compare C and D with the same five-call ceiling, reporting actual calls, calls per success, vetoes, false stops and paired regressions. Abort if no native rollback/macro transition exists. diff --git a/metta_research_bench/courier_transfer/generator.py b/metta_research_bench/courier_transfer/generator.py new file mode 100644 index 00000000..37f16b4f --- /dev/null +++ b/metta_research_bench/courier_transfer/generator.py @@ -0,0 +1,113 @@ +"""Deterministic courier worlds for oracle wiring ONLY, never native data.""" +from __future__ import annotations + +import json +from pathlib import Path +import random + +from reference import CourierWorld, CourierState, initial, FiniteOracle +from manifest_check import root_seed + +HERE = Path(__file__).resolve().parent + + +def reference_root(root_id: str, manifest: dict) -> tuple[CourierWorld, CourierState]: + chunks = root_id.split("/") + if len(chunks) != 4 or chunks[0] != "DG12" or not chunks[3].isdigit(): + raise ValueError("invalid root ID") + _, split, family, index = chunks + if root_id != f"DG12/{split}/{family}/{int(index):04d}": + raise ValueError("noncanonical root ID") + if (family not in manifest["split_roots"].get(split, ()) + or not (0 <= int(index) < manifest["split_roots"][split][family])): + raise ValueError("root is outside registered split") + seed = root_seed(manifest, root_id) + rnd = random.Random(seed) + suffix = f"{seed & 0xffff:04x}" + node = lambda x: f"{x}_{suffix}" + parcel = lambda x: f"parcel-{x}-{suffix}" + permit = lambda x: f"permit-{x}-{suffix}" + witness = lambda x: f"witness-{x}-{suffix}" + source = lambda x: f"source-{x}-{suffix}" + + edges = [] + offices = [] + parcels = [] + witnesses = [] + permit_sources = [] + if family == "route_ties": + edges = [("A", "B", ""), ("B", "D", ""), + ("A", "C", ""), ("C", "D", "")] + parcels = [("p", "A", "D", "")] + elif family == "permit_gate": + edges = [("A", "B", "g")] + offices = [("g", "A")] + parcels = [("p", "A", "B", "g")] + elif family == "multi_drop": + edges = [("A", "B", "")] + parcels = [("p", "A", "B", ""), ("q", "A", "B", "")] + elif family == "evidence_ledger": + edges = [("A", "B", "g")] + offices = [("g", "A")] + witnesses = [("w1", "A", "s1")] + permit_sources = [("g", ("s1",))] + parcels = [("p", "A", "B", "")] + elif family == "permit_chain": + edges = [("A", "B", "g1")] + offices = [("g1", "A"), ("g2", "A")] + parcels = [("p", "A", "B", "g2")] + elif family == "evidence_collision": + edges = [("A", "B", "")] + offices = [("g", "A")] + witnesses = [("w1", "A", "s1"), ("alias", "A", "s1"), + ("w2", "A", "s2")] + permit_sources = [("g", ("s1", "s2"))] + parcels = [("p", "A", "A", "g")] + elif family == "unseen_topology": + edges = [("A", "B", ""), ("B", "E", ""), + ("A", "C", ""), ("C", "D", ""), ("D", "E", "")] + parcels = [("p", "A", "E", "")] + else: + raise ValueError(f"unknown family {family}") + + # A seeded distractor never shortens the valid path. + if seed % 2: + edges.append(("A", "Z", "")) + rnd.shuffle(edges) + rnd.shuffle(offices) + rnd.shuffle(parcels) + rnd.shuffle(witnesses) + world = CourierWorld( + start=node("A"), + edges=tuple((node(a), node(b), permit(g) if g else "") + for a, b, g in edges), + offices=tuple((permit(g), node(a)) for g, a in offices), + parcels=tuple((parcel(p), node(a), node(b), permit(g) if g else "") + for p, a, b, g in parcels), + witnesses=tuple((witness(w), node(a), source(s)) for w, a, s in witnesses), + permit_sources=tuple((permit(g), tuple(source(s) for s in ss)) + for g, ss in permit_sources), + ) + return world, initial(world) + + +def reference_probe(per_family: int = 3) -> dict: + manifest = json.loads((HERE / "roots_manifest.json").read_text()) + results = [] + for split, families in manifest["split_roots"].items(): + for family, count in families.items(): + for index in range(min(count, per_family)): + root_id = f"DG12/{split}/{family}/{index:04d}" + world, state = reference_root(root_id, manifest) + oracle = FiniteOracle(world) + results.append({"root": root_id, "reachable_under_five": oracle.can_finish(state, 5), + "optimal_first_action_count": len(oracle.action_set(state, 5))}) + if not all(row["reachable_under_five"] for row in results): + raise AssertionError("unsolvable five-call wiring root") + return {"mode": "reference_wiring", "roots_checked": len(results), "all_feasible": True, + "roots_with_tied_first_actions": sum(x["optimal_first_action_count"] > 1 + for x in results)} + + +if __name__ == "__main__": + print(json.dumps(reference_probe(), indent=2)) diff --git a/metta_research_bench/courier_transfer/manifest_check.py b/metta_research_bench/courier_transfer/manifest_check.py index 308df80a..05a280a5 100644 --- a/metta_research_bench/courier_transfer/manifest_check.py +++ b/metta_research_bench/courier_transfer/manifest_check.py @@ -30,7 +30,7 @@ def validate() -> dict: assert len(roots) == len(set(roots)) == manifest["total_roots"] assert len({root_seed(manifest, r) for r in roots}) == len(roots) assert protocol["experiment_id"] == schema["properties"]["experiment_id"]["const"] - assert protocol["evaluation"]["five_call_cap_per_episode_for_C_and_D"] == 5 + assert protocol["evaluation"]["five_call_cap_per_episode_for_A_B_C_D"] == 5 if protocol["status"] == "wiring_only_until_native_kernel_pinned": assert protocol["source"]["native_storyworld_full_commit"] is None else: diff --git a/metta_research_bench/courier_transfer/protocol.json b/metta_research_bench/courier_transfer/protocol.json index f2b00aab..3b66fe2b 100644 --- a/metta_research_bench/courier_transfer/protocol.json +++ b/metta_research_bench/courier_transfer/protocol.json @@ -52,13 +52,14 @@ "macro_repair_count", "paired_regressions" ], - "five_call_cap_per_episode_for_C_and_D": 5, "stop_macro_max_verifier_calls": 2, "stop_macro_policy": "reserve_until_stop; certify_final_state_before_atomic_commit; unused_budget_not_reallocated", "root_clustered_confidence_interval": "95% paired root bootstrap, seeds remain within root cluster", "bootstrap_repetitions": 10000, "decision_rule": "C-B strictly positive with bootstrap lower endpoint above zero; report raw seed effects", - "negative_result_handling": "report all endpoints and seed-level effects even when gate fails" + "negative_result_handling": "report all endpoints and seed-level effects even when gate fails", + "five_call_cap_per_episode_for_A_B_C_D": 5, + "requires_native_root_solvable_under_five_policy_calls": true }, "release_gates": { "reference_oracle_tests": "all_green", diff --git a/tests/unit/test_dg_metta12_generator.py b/tests/unit/test_dg_metta12_generator.py new file mode 100644 index 00000000..a710ea3e --- /dev/null +++ b/tests/unit/test_dg_metta12_generator.py @@ -0,0 +1,36 @@ +"""All registered reference roots must be reachable under a five-call ceiling.""" +import json +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] / "metta_research_bench" / "courier_transfer" +sys.path.insert(0, str(ROOT)) +from generator import reference_root # noqa: E402 +from manifest_check import roots_for # noqa: E402 +from reference import FiniteOracle # noqa: E402 + + +class AllReferenceRootsTests(unittest.TestCase): + def test_exact_oracle_five_call_feasibility_and_ties(self): + manifest = json.loads((ROOT / "roots_manifest.json").read_text()) + roots = roots_for(manifest) + self.assertEqual(len(roots), 520) + tied = 0 + for root in roots: + world, state = reference_root(root, manifest) + oracle = FiniteOracle(world) + self.assertTrue(oracle.can_finish(state, 5), root) + options = oracle.action_set(state, 5) + self.assertGreater(len(options), 0, root) + tied += len(options) > 1 + self.assertGreater(tied, 0) + + def test_invalid_root_is_rejected(self): + manifest = json.loads((ROOT / "roots_manifest.json").read_text()) + with self.assertRaises(ValueError): + reference_root("DG12/frozen/route_ties/9999", manifest) + + +if __name__ == "__main__": + unittest.main() From 88c910993b3a86438c6de85d7efa039dcdb68cac Mon Sep 17 00:00:00 2001 From: Patrick Dugan Date: Mon, 23 Nov 2026 21:10:24 +0800 Subject: [PATCH 5/5] DG-METTA-12: fix strict Ruff imports and bound oracle memo lifetime --- .../courier_transfer/generator.py | 23 +++++++++++++------ .../courier_transfer/reference.py | 9 +++++--- tests/unit/test_dg_metta12_generator.py | 6 ++--- tests/unit/test_dg_metta12_reference.py | 13 ++++++++--- 4 files changed, 35 insertions(+), 16 deletions(-) diff --git a/metta_research_bench/courier_transfer/generator.py b/metta_research_bench/courier_transfer/generator.py index 37f16b4f..1292e0a0 100644 --- a/metta_research_bench/courier_transfer/generator.py +++ b/metta_research_bench/courier_transfer/generator.py @@ -2,11 +2,11 @@ from __future__ import annotations import json -from pathlib import Path import random +from pathlib import Path -from reference import CourierWorld, CourierState, initial, FiniteOracle from manifest_check import root_seed +from reference import CourierState, CourierWorld, FiniteOracle, initial HERE = Path(__file__).resolve().parent @@ -24,11 +24,20 @@ def reference_root(root_id: str, manifest: dict) -> tuple[CourierWorld, CourierS seed = root_seed(manifest, root_id) rnd = random.Random(seed) suffix = f"{seed & 0xffff:04x}" - node = lambda x: f"{x}_{suffix}" - parcel = lambda x: f"parcel-{x}-{suffix}" - permit = lambda x: f"permit-{x}-{suffix}" - witness = lambda x: f"witness-{x}-{suffix}" - source = lambda x: f"source-{x}-{suffix}" + def node(x: str) -> str: + return f"{x}_{suffix}" + + def parcel(x: str) -> str: + return f"parcel-{x}-{suffix}" + + def permit(x: str) -> str: + return f"permit-{x}-{suffix}" + + def witness(x: str) -> str: + return f"witness-{x}-{suffix}" + + def source(x: str) -> str: + return f"source-{x}-{suffix}" edges = [] offices = [] diff --git a/metta_research_bench/courier_transfer/reference.py b/metta_research_bench/courier_transfer/reference.py index c665e30a..5142fc2f 100644 --- a/metta_research_bench/courier_transfer/reference.py +++ b/metta_research_bench/courier_transfer/reference.py @@ -5,10 +5,9 @@ """ from __future__ import annotations -from dataclasses import dataclass, replace -from functools import cache import hashlib import json +from dataclasses import dataclass, replace STOP = "STOP" @@ -114,17 +113,21 @@ class FiniteOracle: def __init__(self, world: CourierWorld) -> None: self.world = world + self._memo: dict[tuple[CourierState, int], tuple[int, int]] = {} - @cache def value(self, state: CourierState, remaining: int) -> tuple[int, int]: if remaining < 0: raise ValueError("remaining must be nonnegative") + key = (state, remaining) + if key in self._memo: + return self._memo[key] best = (len(state.delivered), 0) if remaining: for action in legal_actions(self.world, state): if action != STOP: nxt = self.value(transition(self.world, state, action), remaining - 1) best = max(best, (nxt[0], nxt[1] - 1)) + self._memo[key] = best return best def action_set(self, state: CourierState, remaining: int) -> tuple[str, ...]: diff --git a/tests/unit/test_dg_metta12_generator.py b/tests/unit/test_dg_metta12_generator.py index a710ea3e..c9a98d06 100644 --- a/tests/unit/test_dg_metta12_generator.py +++ b/tests/unit/test_dg_metta12_generator.py @@ -6,9 +6,9 @@ ROOT = Path(__file__).resolve().parents[2] / "metta_research_bench" / "courier_transfer" sys.path.insert(0, str(ROOT)) -from generator import reference_root # noqa: E402 -from manifest_check import roots_for # noqa: E402 -from reference import FiniteOracle # noqa: E402 +from generator import reference_root +from manifest_check import roots_for +from reference import FiniteOracle class AllReferenceRootsTests(unittest.TestCase): diff --git a/tests/unit/test_dg_metta12_reference.py b/tests/unit/test_dg_metta12_reference.py index db03aefa..ccf17447 100644 --- a/tests/unit/test_dg_metta12_reference.py +++ b/tests/unit/test_dg_metta12_reference.py @@ -8,9 +8,16 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "metta_research_bench" / "courier_transfer")) -from reference import ( # noqa: E402 - CourierWorld, FiniteOracle, CourierState, initial, legal_actions, - transition, success, hashed_singleton, serialize_state, +from reference import ( + CourierState, + CourierWorld, + FiniteOracle, + hashed_singleton, + initial, + legal_actions, + serialize_state, + success, + transition, )