"""bridge_logic.py: the pure rules of the bridge runner (no torch, no simulator), so they can be tested anywhere. Used by bridge_adapt2.py; tested by test_bridge_logic.py. Added after the audits review/CURSOR-BRIDGE-V2-L4-2026-10-09.md and review/ASTRA-BRIDGE-V2-CHECK-2026-10-09.md: write-once result files, the CHECK verdict, and the replay accounting.""" import json import math import os HEADS = ("_reward", "_pi", "_Qs", "_termination") TARGET = "_target_Qs_params" # the Polyak-averaged value copy; not a parameter, checked explicitly # Loss keys every record of a mode must carry (termination may be absent: the walker is not episodic). FULL_LOSSES = ("consistency_loss", "reward_loss", "value_loss", "pi_loss") REQUIRED_LOSSES = {"full": FULL_LOSSES, "heads_frozen": FULL_LOSSES, "consistency": ("consistency_loss",), "dynamics_fixed": ("consistency_loss",), "anchored": FULL_LOSSES, "rehearsal": FULL_LOSSES} # Groups every record must have measured (termination optional for the same reason). REQUIRED_GROUPS = ("_encoder", "_dynamics", "_reward", "_pi", "_Qs", "_task_emb", TARGET) # What may move on one update, per mode. "must" groups must change; "never" groups must not. ALL_MOVE = ("_encoder", "_dynamics", "_reward", "_Qs", "_pi") EXPECTED = { "full": {"must": ALL_MOVE, "never": ()}, "heads_frozen": {"must": ("_encoder", "_dynamics"), "never": HEADS + (TARGET,)}, "consistency": {"must": ("_encoder", "_dynamics"), "never": HEADS + ("_task_emb", TARGET)}, "dynamics_fixed": {"must": ("_dynamics",), "never": HEADS + ("_task_emb", "_encoder", TARGET)}, "anchored": {"must": ALL_MOVE, "never": ()}, "rehearsal": {"must": ALL_MOVE, "never": ()}, } # which modes a check record must contain, by the runner that wrote it (v2.1 records carry no runner field) V21_MODES = ("full", "heads_frozen", "consistency") V22_MODES = V21_MODES + ("dynamics_fixed", "anchored") def required_modes(check): if check.get("runner") == "bridge_adapt3": return V22_MODES + (("rehearsal",) if check.get("rehearsal_data") else ()) return V21_MODES def write_once(path, obj): """Writes JSON to a file that must not exist yet (mode 'x'): results are never overwritten.""" with open(path, "x") as f: json.dump(obj, f, indent=1, default=str) def claim_out_dir(out_dir): """Creates out_dir, or accepts it only if it exists and is empty. Anything inside means an earlier attempt left evidence there, and it is kept: choose a fresh out_dir.""" os.makedirs(out_dir, exist_ok=True) left = sorted(os.listdir(out_dir)) if left: raise SystemExit(f"refusing non-empty out_dir {out_dir} (holds {left[:5]}): results are never overwritten") def unflushed_steps(pending_len): """Transitions of the episode still pending when the step loop ends. pending_len counts the stored entries of that episode including its initial observation (0 when none is pending). The pending episode is never added to replay, whether or not it finished on the last decision.""" return max(pending_len - 1, 0) def accounting(decisions, replay_transitions, pending_len, updates, seconds): u = unflushed_steps(pending_len) if decisions != replay_transitions + u: raise AssertionError(f"accounting: decisions {decisions} != replay {replay_transitions} + unflushed {u}") return {"decisions": decisions, "replay_transitions": replay_transitions, "gradient_updates": updates, "unflushed_final_episode_steps": u, "adapt_seconds": seconds} def finite(x): return isinstance(x, (int, float)) and math.isfinite(x) def episode_list(x): """A non-empty list of finite numbers, or None.""" if not isinstance(x, list) or not x or not all(finite(v) for v in x): return None return x def check_verdict(check): """The CHECK gate. Returns (passed, reasons). Pairing is recomputed from the episode arrays (never trusted from a supplied flag): same-bank arrays must be non-empty, finite, equal length and equal; the other bank must differ. Per mode: every required loss present and finite; every required group measured; the groups that must move moved and the groups that must not did not (changed == 0).""" reasons = [] pairing = check.get("pairing", {}) b1, b2, ob = (episode_list(pairing.get(k)) for k in ("same_bank_1", "same_bank_2", "other_bank")) if b1 is None or b2 is None or ob is None: reasons.append("pairing: episode arrays missing, empty or not finite") else: if len(b1) != len(b2) or len(b1) != len(ob): reasons.append("pairing: episode arrays differ in length") elif b1 != b2: reasons.append("pairing: two evaluations on the same bank differ") elif b1 == ob: reasons.append("pairing: a different bank gave identical episodes (seeding has no effect)") modes = check.get("modes", {}) for mode in required_modes(check): rule = EXPECTED[mode] m = modes.get(mode) if m is None: reasons.append(f"{mode}: missing"); continue losses = m.get("losses", {}) for k in REQUIRED_LOSSES[mode]: if k not in losses: reasons.append(f"{mode}: loss {k} missing") for k, v in losses.items(): if not finite(v): reasons.append(f"{mode}: loss {k} not finite ({v})") change = m.get("param_change", {}) for g in REQUIRED_GROUPS: if g not in change: reasons.append(f"{mode}: group {g} not measured") for g in rule["must"]: if change.get(g, {}).get("changed", 0) <= 0: reasons.append(f"{mode}: {g} did not move") for g in rule["never"]: if g in change and change[g].get("changed", 0) != 0: reasons.append(f"{mode}: {g} moved ({change[g]['changed']} values)") if mode != "full" and TARGET not in change: reasons.append(f"{mode}: target value copy not inspected") if check.get("runner") == "bridge_adapt3": two = check.get("anchor_two_update_rel_change", {}) if not (finite(two.get("full")) and finite(two.get("anchored"))): reasons.append("anchored: two-update comparison missing") elif not two["anchored"] < two["full"]: reasons.append("anchored: the anchor did not reduce movement over two updates") return (not reasons), reasons def pairing_verdict(a_block, after_block): """The no-update arm N: the after block repeats A on the same bank and must match it exactly.""" if set(a_block) != set(after_block): return float("inf") diffs = [] for t in a_block: a, b = episode_list(a_block[t].get("episodes")), episode_list(after_block[t].get("episodes")) if a is None or b is None or len(a) != len(b): return float("inf") diffs += [abs(x - y) for x, y in zip(a, b)] return max(diffs)