"""Deterministic mutation suite for C2 program equivalence (``docs/02`` §7.3). §7.3: full-source answer agreement alone cannot filter out a *coincidental* program, so the mutation suite is mandatory. For each dependency leaf the proposer program reads, generate ``≥8`` valid alternative mutations of the world; execute *both* programs on each mutated world and require equal ``(status, answer)``. The suite uses the deterministic P3 executor (no model calls) and is fully seed-determined: the same ``(world, leaves, seed)`` always reproduces the same mutations. Two mutation kinds, both keeping the world well-formed: * ``SUBSTITUTE`` — replace a leaf's numeric value with a distinct seeded rational (the program stays ``UNIQUE`` with a different answer). * ``REDACT`` — remove the leaf (point / row / series / stating constraint); the program may go ``MISSING_INFORMATION`` / ``INVALID_REFERENT``, but two equivalent programs diverge identically, so they still agree. Per leaf the generator emits ``per_leaf`` (default 8) ``SUBSTITUTE`` variants plus one ``REDACT`` when the leaf is cleanly removable — always ``≥8``. """ from __future__ import annotations import copy import hashlib from dataclasses import dataclass from fractions import Fraction from typing import Any from ..dsl.ast import Dsl, canonical_number_str, parse_number from ..sources.base import World from ..sources.world_ops import ( find_point, find_row, find_series, find_stating_constraint, is_geometry, is_plot, is_table, looks_numeric, ) @dataclass(frozen=True) class Mutation: """One seeded, valid alternative world for the §7.3 suite.""" world: World leaf: str kind: str # "SUBSTITUTE" | "REDACT" description: str def deterministic_mutations( world: World, leaves: tuple[str, ...], *, dsl: Dsl, seed: int, per_leaf: int = 8, ) -> list[Mutation]: """Generate ``≥per_leaf`` valid mutations per dependency leaf (seed-determined). Leaves with no mutable value fall back to substituting the nearest mutable value in the world, so every leaf still yields ``per_leaf`` distinct valid alternatives. The output order is deterministic: leaves in input order, then ``SUBSTITUTE`` (offset 0..per_leaf-1) then ``REDACT``. """ out: list[Mutation] = [] for leaf in leaves: for i in range(per_leaf): mut = _substitute(world, leaf, dsl, seed, i) if mut is not None: out.append(mut) redact = _redact(world, leaf, dsl, seed) if redact is not None: out.append(redact) # A leaf set may be empty (e.g., a pure-literal program); still emit ≥8 # global substitutes so the suite is non-vacuous. if not leaves: for i in range(max(per_leaf, 8)): mut = _substitute_global(world, dsl, seed, i) if mut is not None: out.append(mut) return out # --- seeded offsets --------------------------------------------------------- def _offset(seed: int, leaf: str, kind: str, i: int) -> int: """A deterministic 1..99 offset (distinct per ``(leaf, kind, i)``).""" digest = hashlib.sha256(f"{seed}|{leaf}|{kind}|{i}".encode()).hexdigest() return 1 + (int(digest[:12], 16) % 99) def _bump(value: Any, by: int) -> str: """Add ``by`` to a numeric world value, returning its canonical string.""" frac = parse_number(value) + Fraction(by) return canonical_number_str(frac) # --- SUBSTITUTE ------------------------------------------------------------ def _substitute(world: World, leaf: str, dsl: Dsl, seed: int, i: int) -> Mutation | None: by = _offset(seed, leaf, "SUBSTITUTE", i) new_world = copy.deepcopy(world) desc = _apply_substitute(new_world, leaf, by) if desc is None: # Fall back to a global mutable value so this leaf still yields a valid # alternative mutation. desc = _apply_substitute_global(new_world, by) if desc is None: return None return Mutation(new_world, leaf, "SUBSTITUTE", f"{desc} (+{by})") def _apply_substitute(world: World, leaf: str, by: int) -> str | None: """Substitute the leaf's own value; return a description or ``None``.""" if _is_plot(world): return _substitute_plot(world, leaf, by) if _is_table(world): return _substitute_table(world, leaf, by) if _is_geometry(world): return _substitute_geometry(world, leaf, by) return None def _substitute_plot(world: World, leaf: str, by: int) -> str | None: point = _find_point(world, leaf) if point is not None: sidx, pidx, p = point p["y"] = _bump(p.get("y", "0"), by) world["series"][sidx]["points"][pidx] = p return f"point {leaf} y" series = _find_series(world, leaf) if series is not None: sidx, s = series pts = s.get("points", []) or [] if pts: pts[0]["y"] = _bump(pts[0].get("y", "0"), by) world["series"][sidx]["points"] = pts return f"series {leaf} first-point y" return None def _substitute_table(world: World, leaf: str, by: int) -> str | None: row = _find_row(world, leaf) if row is None: return None ridx, r = row cells = r.get("cells", {}) or {} if not cells: return None key = next(iter(cells)) cells[key] = _bump(cells[key], by) world["rows"][ridx]["cells"] = cells return f"row {leaf} cell {key}" def _substitute_geometry(world: World, leaf: str, by: int) -> str | None: found = _find_stating_constraint(world, leaf) if found is None: return None cidx, c = found args = list(c.get("args") or []) pred = c.get("predicate") if pred == "MeasureOf" and len(args) >= 2 and args[0] == leaf: args[1] = _bump(args[1], by) elif pred == "Equals" and len(args) == 2: if args[0] == leaf and _looks_numeric(args[1]): args[1] = _bump(args[1], by) elif args[1] == leaf and _looks_numeric(args[0]): args[0] = _bump(args[0], by) else: return None else: return None c["args"] = args world["constraints"][cidx] = c return f"constraint {pred}({leaf}) value" # --- REDACT ----------------------------------------------------------------- def _redact(world: World, leaf: str, dsl: Dsl, seed: int) -> Mutation | None: new_world = copy.deepcopy(world) desc = _apply_redact(new_world, leaf) if desc is None: return None return Mutation(new_world, leaf, "REDACT", desc) def _apply_redact(world: World, leaf: str) -> str | None: if _is_plot(world): point = _find_point(world, leaf) if point is not None: sidx, _pidx, p = point pts = world["series"][sidx].get("points", []) world["series"][sidx]["points"] = [q for q in pts if q.get("id") != leaf] return f"remove point {leaf}" series = _find_series(world, leaf) if series is not None: world["series"] = [s for s in world.get("series", []) if s.get("id") != leaf] return f"remove series {leaf}" return None if _is_table(world): if _find_row(world, leaf) is not None: world["rows"] = [r for r in world.get("rows", []) if r.get("id") != leaf] return f"remove row {leaf}" return None if _is_geometry(world): found = _find_stating_constraint(world, leaf) if found is not None: cidx, _c = found world["constraints"] = [ x for k, x in enumerate(world.get("constraints", [])) if k != cidx ] return f"remove stating constraint for {leaf}" if any(e.get("id") == leaf for e in world.get("entities", [])): world["entities"] = [e for e in world.get("entities", []) if e.get("id") != leaf] return f"remove entity {leaf}" return None return None # --- global fallback -------------------------------------------------------- def _substitute_global(world: World, dsl: Dsl, seed: int, i: int) -> Mutation | None: by = _offset(seed, "__global__", "SUBSTITUTE", i) new_world = copy.deepcopy(world) desc = _apply_substitute_global(new_world, by) if desc is None: return None return Mutation(new_world, "__global__", "SUBSTITUTE", f"{desc} (+{by})") def _apply_substitute_global(world: World, by: int) -> str | None: if _is_plot(world): for s in world.get("series", []): pts = s.get("points", []) or [] if pts: pts[0]["y"] = _bump(pts[0].get("y", "0"), by) s["points"] = pts return f"series {s.get('id')} first-point y" return None if _is_table(world): for r in world.get("rows", []): cells = r.get("cells", {}) or {} if cells: key = next(iter(cells)) cells[key] = _bump(cells[key], by) r["cells"] = cells return f"row {r.get('id')} cell {key}" return None if _is_geometry(world): for c in world.get("constraints", []): if c.get("predicate") == "MeasureOf" and len(c.get("args") or []) >= 2: args = list(c["args"]) if _looks_numeric(args[1]): args[1] = _bump(args[1], by) c["args"] = args return f"constraint MeasureOf({args[0]}) value" return None return None # --- world locators (shared with the P5 intervention layer) ---------------- # The locators live in :mod:`explicit_learning.sources.world_ops`; the leading # underscore aliases keep this module's call sites unchanged. _is_plot = is_plot _is_table = is_table _is_geometry = is_geometry _find_point = find_point _find_series = find_series _find_row = find_row _find_stating_constraint = find_stating_constraint _looks_numeric = looks_numeric __all__ = ["Mutation", "deterministic_mutations"]