"""Core types for question-preserving visual interventions (``docs/02`` §10). An *intervention operator* transforms a structured ``World`` into a new ``World`` (plus bookkeeping) **without touching the human-authored question or choices** and **without assigning a gold state**. The operator's only job is to produce a well-formed transformed world and record what it did; the resulting state (``FULL`` / ``A_SAME`` / ``A_CHANGED`` / ``U_MISSING`` / ``U_INVALID``) is decided later by the P7 state-proof builder, which executes the program before and after (``docs/02`` §11.1). This separation is a hard P5 gate ("operator가 state를 직접 assign하지 않음"). Design rules every operator obeys (``docs/07`` §7 P5 completion gate): * **Source world immutable** — :func:`apply` returns a brand-new world; the passed dict is never mutated. * **Deterministic** — the same ``(world, target_node, seed, operation)`` always reproduces the same ``transformed_world_sha256``; a different seed or operation changes it. * **Reject invalid mutations** — an operator that would break world well-formedness (a dangling geometry constraint, a label collision, an out-of-range substitute, a multiple-choice answer leaving the unchanged choice set) raises :class:`InterventionError` rather than emitting a broken world. Never a silent accept. * **No state assignment** — :class:`TransformedWorld` carries no ``state`` field by construction. """ from __future__ import annotations from dataclasses import dataclass, field from typing import Any, Literal, Protocol from ..dsl.ast import canonical_number_str, parse_number from ..hashing import canonical_json_hash from ..ingest.base import IngestError from ..sources.base import World from ..sources.world_ops import ( NODE_VISIBILITY_KEY, clone_world, find_point, find_row, find_series, find_stating_constraint, hidden_nodes, looks_numeric, node_kind, world_sha256, ) # The four deterministic intervention operators (``docs/02`` §10). REDACT_BLUR_V1 # is deliberately absent: it is a shortcut stress test only and never appears in # a primary U certificate (§10.2). OperatorName = Literal[ "REDACT_SOLID_V1", "CLEAN_DELETE_V1", "SUBSTITUTE_V1", "CONTROL_MATCHED_V1", ] class InterventionError(IngestError): """A requested intervention is infeasible / would break the world. Raised for an invalid geometry or plot mutation, a label collision, an out-of-range substitute, or a multiple-choice answer that leaves the unchanged choice set (``docs/02`` §10.4). An infeasible intervention is rejected — never silently coerced into a broken world or a faked state. """ @dataclass(frozen=True) class TransformedWorld: """One operator's deterministic output over a source world. ``world`` is the transformed (or, for REDACT_SOLID_V1, visibility-marked) world. ``hidden_nodes`` lists semantic node ids a renderer must patch (REDACT_SOLID_V1 keeps the node in the world but hides its pixels, §10.1). ``substitute_value`` records the new value a SUBSTITUTE_V1 / completion placed on the target (canonical string, or ``None`` for non-substitute operators). ``transformed_world_sha256`` is the content-addressed identity of the *transformation* — deterministic over the full record, so the same ``(seed, operation, target, source)`` reproduces it byte-for-byte. There is deliberately **no** ``state`` field: the operator never assigns a gold state (P5 gate). P7's state-proof builder derives state by execution. """ world: World operator: OperatorName target_node: str seed: int transformed_world_sha256: str hidden_nodes: frozenset[str] = field(default_factory=frozenset) substitute_value: str | None = None description: str = "" @property def is_hidden(self) -> bool: return bool(self.hidden_nodes) class InterventionOperator(Protocol): """One deterministic intervention operator (``docs/02`` §10).""" name: OperatorName def apply( self, world: World, target_node: str, *, seed: int, **kwargs: Any, ) -> TransformedWorld: """Return a transformed world; never mutate ``world``, never assign state.""" ... # --- transformation hashing ------------------------------------------------ def transformed_hash( *, operator: OperatorName, target_node: str, seed: int, source_world_sha256: str, transformed_world_sha256: str, hidden_nodes: frozenset[str], substitute_value: str | None, ) -> str: """Content-addressed identity of one transformation (deterministic). Hashed over the full operator record — not just the world — so two operators that happen to leave the world identical (e.g. REDACT_SOLID over a node vs. a no-op) still differ, and the same transformation reproduces the same hash across runs (P5 gate: "seed/operation → same transformed world hash"). """ return canonical_json_hash( { "operator": operator, "target_node": target_node, "seed": seed, "source_world_sha256": source_world_sha256, "transformed_world_sha256": transformed_world_sha256, "hidden_nodes": sorted(hidden_nodes), "substitute_value": substitute_value, } ) # --- value setters (read-only in, new world out) --------------------------- def with_value(world: World, node_id: str, value: Any) -> World: """Return a new world with ``node_id``'s value set to ``value``. The value is written to the same field the executor reads (a plot point's ``y``, a row cell, the stating constraint's numeric arg), so a completion built this way is executable. Raises :class:`InterventionError` when the node has no mutable value site. The source world is unchanged. """ new = clone_world(world) if not _set_value(new, node_id, value): raise InterventionError(f"node {node_id!r} has no mutable value site") return new def _set_value(world: World, node_id: str, value: Any) -> bool: """Write ``value`` onto ``node_id`` in place; return whether a site was found. The write site follows :func:`~explicit_learning.sources.world_ops.node_kind`: a plot point's ``y``, a series' ``label``, a row's first cell, a geometry entity's ``label``, or a stating constraint's numeric arg. Dispatching on the *node* kind (not the world kind) keeps a category substitute (a series/entity label) from being mis-written onto a numeric site. """ kind = node_kind(world, node_id) if kind == "point": point = find_point(world, node_id) if point is None: return False sidx, pidx, p = point p["y"] = _canonical(value) world["series"][sidx]["points"][pidx] = p return True if kind == "series": series = find_series(world, node_id) if series is None: return False sidx, s = series s["label"] = _canonical(value) world["series"][sidx] = s return True if kind == "row": row = find_row(world, node_id) if row is None: return False ridx, r = row cells = r.get("cells", {}) or {} if not cells: return False key = next(iter(cells)) cells[key] = _canonical(value) world["rows"][ridx]["cells"] = cells return True if kind == "entity": for i, e in enumerate(world.get("entities", []) or []): if e.get("id") == node_id: e["label"] = _canonical(value) world["entities"][i] = e return True return False if kind == "constraint": found = find_stating_constraint(world, node_id) if found is None: return False cidx, c = found args = list(c.get("args") or []) pred = c.get("predicate") if pred == "MeasureOf" and len(args) >= 2 and args[0] == node_id: args[1] = _canonical(value) elif pred == "Equals" and len(args) == 2: if args[0] == node_id and looks_numeric(args[1]): args[1] = _canonical(value) elif args[1] == node_id and looks_numeric(args[0]): args[0] = _canonical(value) else: return False else: return False c["args"] = args world["constraints"][cidx] = c return True return False def _canonical(value: Any) -> str: """Canonical string form of a substitute value (numbers via §3.2/§3.3).""" if isinstance(value, str): return value try: return canonical_number_str(parse_number(value)) except (ValueError, ZeroDivisionError): return str(value) def set_hidden(world: World, node_ids: frozenset[str]) -> World: """Return a new world carrying a visibility marker hiding ``node_ids``. The nodes stay in the world (REDACT_SOLID_V1, §10.1: "semantic node는 world에 남기고 node_visibility[node]=hidden"); only the reserved :data:`~explicit_learning.sources.world_ops.NODE_VISIBILITY_KEY` map is set, which the renderer (P6) reads and executors ignore. """ new = clone_world(world) visibility = dict(new.get(NODE_VISIBILITY_KEY, {})) for nid in node_ids: visibility[nid] = "hidden" new[NODE_VISIBILITY_KEY] = visibility return new def remove_observed_value(world: World, node_id: str) -> World: """Return a copy whose target node remains identifiable but has no value. REDACT is an epistemic operation: the renderer hides the value and the executor evaluating the *observed* transformed world must not retain a privileged copy of that value. Identity/position fields remain so the question referent and a content-independent redaction anchor still exist. Completion witnesses can restore alternative values with :func:`with_value` while retaining the same visibility marker. """ new = clone_world(world) kind = node_kind(new, node_id) if kind == "point": found_point = find_point(new, node_id) if found_point is None: raise InterventionError(f"point {node_id!r} not found") sidx, pidx, point = found_point point["y"] = None new["series"][sidx]["points"][pidx] = point return new if kind == "row": found_row = find_row(new, node_id) if found_row is None: raise InterventionError(f"row {node_id!r} not found") ridx, row = found_row cells = dict(row.get("cells", {}) or {}) if not cells: raise InterventionError(f"row {node_id!r} has no observable cells") cells[next(iter(cells))] = None new["rows"][ridx]["cells"] = cells return new if kind == "constraint": found_constraint = find_stating_constraint(new, node_id) if found_constraint is None: raise InterventionError(f"no stating constraint for {node_id!r}") cidx, constraint = found_constraint args = list(constraint.get("args") or []) if constraint.get("predicate") == "MeasureOf" and len(args) >= 2: args[1] = None elif constraint.get("predicate") == "Equals" and len(args) == 2: if str(args[0]) == node_id: args[1] = None elif str(args[1]) == node_id: args[0] = None else: raise InterventionError(f"constraint for {node_id!r} has no value site") else: raise InterventionError(f"constraint for {node_id!r} has no value site") constraint["args"] = args new["constraints"][cidx] = constraint return new if kind == "series": found_series = find_series(new, node_id) if found_series is None: raise InterventionError(f"series {node_id!r} not found") sidx, series = found_series series["label"] = None new["series"][sidx] = series return new if kind == "entity": for idx, entity in enumerate(new.get("entities", []) or []): if entity.get("id") == node_id: entity["label"] = None new["entities"][idx] = entity return new raise InterventionError(f"node {node_id!r} has no redactable observed value") __all__ = [ "InterventionError", "InterventionOperator", "OperatorName", "TransformedWorld", "hidden_nodes", "set_hidden", "remove_observed_value", "transformed_hash", "with_value", "world_sha256", ]