File size: 11,331 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
"""``SUBSTITUTE_V1`` — sample a new typed value for a node (§10.4).

The substitute is drawn from the node's typed domain, deterministically seeded:

  * **numeric** (a plot point's ``y``, a table cell, a geometry measure) — a
    value within the source range and at the source precision, distinct from the
    current value.
  * **category** (a series / entity label) — a label that does not collide with
    any existing label.
  * **geometry** — after the substitute, the constraint graph must stay feasible
    (no contradiction); :mod:`feasibility` guards this.
  * **multiple choice** — when the problem is multiple-choice, the *new* answer
    the executor computes on the substituted world must match **exactly one** of
    the unchanged choices. A substitute that drives the answer out of the choice
    set (zero or >1 matches) is rejected (P5 gate: "objective choice outside
    unchanged choices reject").

The operator never labels the resulting state — it only validates that the
substitute is *admissible*; P7 derives ``A_SAME`` / ``A_CHANGED`` by execution.
"""

from __future__ import annotations

import hashlib
import math
from collections.abc import Iterator, Sequence
from fractions import Fraction
from typing import Any

from ..dsl.ast import Dsl, Program, canonical_number_str, parse_number
from ..executors.base import Executor, match_choice
from ..ingest.base import Choice
from ..sources.base import World
from ..sources.world_ops import (
    clone_world,
    find_point,
    find_row,
    find_series,
    find_stating_constraint,
    is_geometry,
    looks_numeric,
    node_kind,
    world_sha256,
)
from .base import (
    InterventionError,
    OperatorName,
    TransformedWorld,
    _set_value,
    transformed_hash,
)
from .feasibility import FeasibilityError, is_feasible

_NAME: OperatorName = "SUBSTITUTE_V1"


class SubstituteOperator:
    """Substitute a seeded, typed, admissible new value onto ``target_node``."""

    name = _NAME

    def apply(
        self,
        world: World,
        target_node: str,
        *,
        seed: int,
        dsl: Dsl,
        executor: Executor | None = None,
        program: Program | None = None,
        choices: Sequence[Choice] = (),
        answer_type: str = "",
        **_kwargs: Any,
    ) -> TransformedWorld:
        kind = node_kind(world, target_node)
        if kind is None:
            raise InterventionError(f"SUBSTITUTE_V1: target {target_node!r} is not a world node")
        value, desc = _sample_value(world, target_node, kind, seed)
        new = clone_world(world)
        if not _set_value(new, target_node, value):
            raise InterventionError(
                f"SUBSTITUTE_V1: target {target_node!r} has no mutable value site"
            )
        if is_geometry(new):
            try:
                is_feasible(new, dsl=dsl)
            except FeasibilityError as exc:
                raise InterventionError(
                    f"SUBSTITUTE_V1: infeasible substitute on {target_node!r}: {exc}"
                ) from exc
        # Multiple-choice admissibility: the new answer must be exactly one of
        # the unchanged choices (§10.4). This is a feasibility check, not a
        # state label — the operator still does not assign state.
        if answer_type == "multiple_choice":
            _assert_choice_admissible(new, executor, program, choices, target_node)
        return TransformedWorld(
            world=new,
            operator=_NAME,
            target_node=target_node,
            seed=seed,
            transformed_world_sha256=transformed_hash(
                operator=_NAME,
                target_node=target_node,
                seed=seed,
                source_world_sha256=world_sha256(world),
                transformed_world_sha256=world_sha256(new),
                hidden_nodes=frozenset(),
                substitute_value=value,
            ),
            hidden_nodes=frozenset(),
            substitute_value=value,
            description=desc,
        )


# --- admissibility ---------------------------------------------------------


def _assert_choice_admissible(
    world: World,
    executor: Executor | None,
    program: Program | None,
    choices: Sequence[Choice],
    target_node: str,
) -> None:
    if executor is None or program is None:
        raise InterventionError(
            "SUBSTITUTE_V1: multiple-choice admissibility requires an executor and program"
        )
    result = executor.execute(program, world=world)
    if result.status != "UNIQUE":
        raise InterventionError(
            f"SUBSTITUTE_V1: {target_node!r} substitute made the answer "
            f"non-unique ({result.status}); rejected"
        )
    keys = match_choice(result.answer_value, choices, "multiple_choice")
    if len(keys) != 1:
        raise InterventionError(
            f"SUBSTITUTE_V1: new answer {result.answer_canonical!r} matches "
            f"{len(keys)} unchanged choices (must be exactly one); rejected"
        )


# --- typed sampling --------------------------------------------------------


def _sample_value(world: World, node_id: str, kind: str, seed: int) -> tuple[str, str]:
    if kind == "point":
        return _sample_point_y(world, node_id, seed)
    if kind == "series":
        return _sample_series_label(world, node_id, seed)
    if kind == "row":
        return _sample_row_cell(world, node_id, seed)
    if kind == "constraint":
        return _sample_geometry_measure(world, node_id, seed)
    if kind == "entity":
        return _sample_entity_label(world, node_id, seed)
    raise InterventionError(f"SUBSTITUTE_V1: no sampler for kind {kind!r}")


def _sample_point_y(world: World, pid: str, seed: int) -> tuple[str, str]:
    point = find_point(world, pid)
    if point is None:
        raise InterventionError(f"point {pid!r} not found")
    sidx, _pidx, p = point
    siblings = world["series"][sidx].get("points", []) or []
    values = [_frac(q.get("y", "0")) for q in siblings]
    cur = _frac(p.get("y", "0"))
    lo = min(values) if values else cur
    hi = max(values) if values else cur
    new = _seeded_in_range(seed, pid, "point_y", lo, hi, {cur})
    return canonical_number_str(new), f"substitute point {pid} y → {new}"


def _sample_row_cell(world: World, rid: str, seed: int) -> tuple[str, str]:
    row = find_row(world, rid)
    if row is None:
        raise InterventionError(f"row {rid!r} not found")
    _ridx, r = row
    cells = r.get("cells", {}) or {}
    if not cells:
        raise InterventionError(f"row {rid!r} has no cells")
    key = next(iter(cells))
    cur = _frac(cells[key])
    # Range across the same column in every row, if identifiable by shared key.
    col_vals = [
        _frac(row_.get("cells", {}).get(key, cells[key]))
        for row_ in (world.get("rows", []) or [])
        if key in (row_.get("cells", {}) or {})
    ]
    lo = min(col_vals) if col_vals else cur
    hi = max(col_vals) if col_vals else cur
    new = _seeded_in_range(seed, rid, f"cell:{key}", lo, hi, {cur})
    return canonical_number_str(new), f"substitute row {rid} cell {key} → {new}"


def _sample_series_label(world: World, sid: str, seed: int) -> tuple[str, str]:
    series = find_series(world, sid)
    if series is None:
        raise InterventionError(f"series {sid!r} not found")
    _sidx, s = series
    existing = {str(t.get("label", "")) for t in world.get("series", []) or []}
    cur = str(s.get("label", sid))
    prefix = _label_prefix(cur)
    for n in _seeded_offsets(seed, sid, "label", span=1000):
        cand = f"{prefix}_{n}"
        if cand not in existing:
            return cand, f"substitute series {sid} label → {cand}"
    raise InterventionError(f"series {sid!r}: no non-colliding label found")


def _sample_geometry_measure(world: World, entity: str, seed: int) -> tuple[str, str]:
    found = find_stating_constraint(world, entity)
    if found is None:
        raise InterventionError(f"no stating constraint for {entity!r}")
    _cidx, c = found
    args = list(c.get("args") or [])
    pred = c.get("predicate")
    if pred == "MeasureOf" and len(args) >= 2:
        cur = _frac(args[1])
    elif pred == "Equals" and len(args) == 2:
        cur = _frac(args[1]) if looks_numeric(args[1]) else _frac(args[0])
    else:
        raise InterventionError(f"stating constraint for {entity!r} is not numeric")
    # Geometry measures are unbounded; sample a distinct integer near the source
    # (feasibility, not range, is the binding constraint here).
    new = cur + Fraction(next(_seeded_offsets(seed, entity, "measure", span=200)) - 100)
    return canonical_number_str(new), f"substitute measure {entity} → {new}"


def _sample_entity_label(world: World, eid: str, seed: int) -> tuple[str, str]:
    entity = next((e for e in world.get("entities", []) or [] if e.get("id") == eid), None)
    if entity is None:
        raise InterventionError(f"entity {eid!r} not found")
    cur = str(entity.get("label", entity.get("id", eid)))
    existing = {str(e.get("label", e.get("id", ""))) for e in world.get("entities", []) or []}
    prefix = _label_prefix(cur)
    for n in _seeded_offsets(seed, eid, "elabel", span=1000):
        cand = f"{prefix}_{n}"
        if cand not in existing:
            return cand, f"substitute entity {eid} label → {cand}"
    raise InterventionError(f"entity {eid!r}: no non-colliding label found")


# --- seeded helpers (deterministic, Math.random-free) ----------------------


def _seeded_in_range(
    seed: int, tag: str, kind: str, lo: Fraction, hi: Fraction, exclude: set[Fraction]
) -> Fraction:
    """A deterministic integer in ``[lo, hi]`` (extended by ±1 when degenerate),
    not in ``exclude``, at source integer precision."""
    lo_i = int(lo)
    hi_i = int(hi)
    if hi_i < lo_i:
        lo_i, hi_i = hi_i, lo_i
    if hi_i - lo_i < 1:  # degenerate range: relax by ±1 to allow a distinct value
        lo_i -= 1
        hi_i += 1
    span = hi_i - lo_i + 1
    # An affine full-cycle permutation needs at most ``len(exclude) + 1``
    # probes to find a non-excluded integer.  Never enumerate a numeric range:
    # PlotQA values can make ``span`` billions wide.
    for probe, n in enumerate(_seeded_offsets(seed, tag, kind, span=span)):
        if probe > len(exclude):
            break
        cand = Fraction(lo_i + (n % (hi_i - lo_i + 1)))
        if cand not in exclude:
            return cand
    raise InterventionError(f"no in-range substitute for {tag!r} ({kind})")


def _seeded_offsets(seed: int, tag: str, kind: str, *, span: int) -> Iterator[int]:
    """Yield a deterministic O(1)-memory permutation of ``[0, span)``."""

    span = max(span, 1)
    digest = hashlib.sha256(f"{seed}|{tag}|{kind}|affine-v1".encode()).digest()
    start = int.from_bytes(digest[:16], "big") % span
    step = int.from_bytes(digest[16:], "big") % span
    if step == 0:
        step = 1
    while math.gcd(step, span) != 1:
        step = (step + 1) % span
        if step == 0:
            step = 1
    for index in range(span):
        yield (start + index * step) % span


def _frac(value: Any) -> Fraction:
    return parse_number(value)


def _label_prefix(label: str) -> str:
    return label.rstrip("0123456789_") or label or "node"


__all__ = ["SubstituteOperator"]