File size: 10,101 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
"""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"]