"""Deterministic question-program executors (``docs/02`` §8, ``docs/07`` §5 P3). An executor turns a typed :class:`~explicit_learning.dsl.ast.Program` plus a structured :class:`~explicit_learning.sources.base.World` into an :class:`ExecutionResult` — a *deterministic, replayable* record of what the program computed, which world nodes it depended on, and whether the referent selector's cardinality precondition held. P3 is the gold-authority layer: the executor trace (not a human label) decides the answer and the dependency closure ``D(P,W)`` (``docs/02`` §8). Four terminal statuses, and a hard rule: a timeout/internal error is ``ERROR`` and is **never** silently coerced into a ``U`` label (``docs/07`` §5: "timeout/error가 U label로 변환되지 않음"): * ``UNIQUE`` — the program produced exactly one answer. * ``MISSING_INFORMATION`` — a value the program needed is absent (a redacted point, an x not present in a series). This is the ``U_MISSING`` precursor. * ``INVALID_REFERENT`` — the scalar referent selector's cardinality precondition broke (``required_referent_cardinality == 1`` but the selector resolved to ``!= 1``). This is the ``U_INVALID`` precursor. COUNT/EXIST are *set* selectors and declare ``None`` — a zero-cardinality referent runs to ``0``/``No`` and stays ``UNIQUE`` (``A_CHANGED``), never ``U_INVALID`` (``docs/02`` §11.3). * ``ERROR`` — executor bug / unsupported operator / timeout. Answers are exact (``fractions.Fraction``); serialization follows ``docs/02`` §3.3 (integer → int, number → canonical rational string, boolean → ``yes``/``no``, year/short-text → string). Choice uniqueness is a separate, choice-aware helper the certificate builder (P7) applies — the executor itself is choice-agnostic. """ from __future__ import annotations from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass, field from fractions import Fraction from typing import Any, Literal, Protocol from ..dsl.ast import AstNode, Program, canonical_number_str, parse_number from ..hashing import canonical_json_hash from ..ingest.base import Choice from ..sources.base import World ExecutionStatus = Literal["UNIQUE", "MISSING_INFORMATION", "INVALID_REFERENT", "ERROR"] # The exact in-memory answer an executor computes (pre-serialization). AnswerValue = Fraction | int | str | bool # One step of the deterministic execution trace: the op evaluated, the resolved # world node ids it read, and a canonical repr of its result. Hashed for replay. type TraceStep = tuple[str, tuple[str, ...], str] class ExecutorError(Exception): """An internal executor failure (unsupported op, type error, timeout). An :class:`ExecutorError` surfaces as ``status="ERROR"`` and is never coerced into a ``U`` label (``docs/07`` §5). """ class _MissingInformation(Exception): """Internal signal: the program needs a value absent from the world.""" class _InvalidReferent(Exception): """Internal signal: the scalar referent selector cardinality broke.""" @dataclass(frozen=True) class ExecutionResult: """The deterministic outcome of executing one program over one world. ``answer_value`` is the exact computed answer (or ``None`` for non-``UNIQUE`` statuses). ``answer_canonical`` is its §3.3 serialization (``str|int|bool|None``) — the form embedded in the certificate. ``trace_sha256`` anchors replay: the same ``(program, world)`` must reproduce it byte-for-byte. ``referent_cardinality`` is the resolved size of the referent selector (the ``U_INVALID`` proof's ``after`` cardinality). """ status: ExecutionStatus answer_value: AnswerValue | None answer_canonical: str | int | bool | None dependency_node_ids: tuple[str, ...] referent_cardinality: int | None trace_sha256: str executor_name: str executor_version: str @property def is_unique(self) -> bool: return self.status == "UNIQUE" class Executor(Protocol): """One DSL's deterministic executor.""" name: str version: str def execute(self, program: Program, *, world: World) -> ExecutionResult: ... def execute_selector(self, selector: AstNode, *, world: World) -> tuple[str, ...]: """Resolve a referent selector to the world node ids it denotes.""" ... # --- answer serialization (§3.3) + choice matching ------------------------- def serialize_answer( value: AnswerValue | None, *, return_type: str = "" ) -> str | int | bool | None: """Serialize an exact answer value per ``docs/02`` §3.3. Booleans → ``yes``/``no``; ``Fraction`` → canonical rational string; ``int`` → ``int``; strings (year/short-text/expression) pass through. ``None`` stays ``None`` (non-``UNIQUE`` statuses carry no answer). """ if value is None: return None if isinstance(value, bool): return "yes" if value else "no" if isinstance(value, Fraction): return canonical_number_str(value) if isinstance(value, int): return value return str(value) def match_choice( answer_value: AnswerValue | None, choices: Sequence[Choice], answer_type: str ) -> tuple[str, ...]: """The choice keys whose text equals ``answer_value`` (``docs/07`` §5 uniqueness). Type-aware: a numeric answer matches a choice by exact rational equality (``30`` == ``"30"`` == ``"30.0"``); a string answer matches by exact text. Returns zero/one/many keys — the certificate builder asserts exactly one (``choice_uniqueness_passed``). Choice-agnostic for non-multiple-choice items. """ if answer_type != "multiple_choice" or answer_value is None: return () if isinstance(answer_value, bool): target = "yes" if answer_value else "no" return tuple(c.key for c in choices if str(c.text).strip().lower() == target) if isinstance(answer_value, (Fraction, int)): try: target_frac = parse_number(answer_value) except (ValueError, ZeroDivisionError): return () keys: list[str] = [] for c in choices: try: if parse_number(str(c.text)) == target_frac: keys.append(c.key) except (ValueError, ZeroDivisionError): continue return tuple(keys) target = str(answer_value).strip() return tuple(c.key for c in choices if str(c.text).strip() == target) # --- trace hashing --------------------------------------------------------- def trace_sha256(steps: Sequence[TraceStep]) -> str: """SHA-256 of the canonical-JSON of the execution trace (the replay anchor).""" return canonical_json_hash([list(s) for s in steps]) def dependency_closure(steps: Sequence[TraceStep]) -> tuple[str, ...]: """Sorted union of every world node id the trace read — ``D(P,W)`` (§8).""" ids: set[str] = set() for _op, nodes, _result in steps: ids.update(nodes) return tuple(sorted(ids)) @dataclass(frozen=True) class _Trace: """Accumulating trace buffer shared across one evaluation.""" steps: list[TraceStep] = field(default_factory=list) def record(self, op: str, nodes: Mapping[str, Any] | Iterable[Any], result: Any) -> None: node_ids = _node_ids(nodes) self.steps.append((op, tuple(sorted(node_ids)), _result_repr(result))) def finish(self) -> tuple[tuple[TraceStep, ...], tuple[str, ...], str]: frozen_steps = tuple(self.steps) return frozen_steps, dependency_closure(frozen_steps), trace_sha256(frozen_steps) def _node_ids(nodes: Mapping[str, Any] | Iterable[Any]) -> set[str]: """Extract world node ids from a record's ``nodes`` argument. A single :class:`Mapping` (one world node) → its ``id``; an iterable of Mappings (a point-set) → each member's ``id``; an iterable of strings → the strings themselves. Never the dict repr — so ``D(P,W)`` holds real ids. """ if isinstance(nodes, Mapping): return {str(nodes["id"])} if nodes.get("id") else set() out: set[str] = set() for n in nodes: if isinstance(n, Mapping): if n.get("id"): out.add(str(n["id"])) else: out.add(str(n)) return out def _result_repr(result: Any) -> str: if isinstance(result, bool): return "true" if result else "false" if isinstance(result, Fraction): return canonical_number_str(result) if isinstance(result, int): return str(result) if isinstance(result, str): return result if isinstance(result, tuple): return "[" + ",".join(_result_repr(r) for r in result) + "]" return str(result) # --- shared evaluation helpers -------------------------------------------- def literal_value(node: AstNode) -> AnswerValue: """Extract an exact value from a ``LITERAL`` leaf (numbers as ``Fraction``).""" if not node.is_literal() or not node.args: raise ExecutorError(f"expected a literal, got {node.op!r}") raw = node.args[0] if isinstance(raw, AstNode): raise ExecutorError(f"literal {node.op!r} carries a nested node") if node.return_type in ("number", "integer"): if isinstance(raw, bool): # noqa: FBT001 raise ExecutorError("boolean where a number was expected") return parse_number(raw) if node.return_type == "boolean": return bool(raw) return str(raw) __all__ = [ "AnswerValue", "ExecutionResult", "ExecutionStatus", "Executor", "ExecutorError", "dependency_closure", "literal_value", "match_choice", "serialize_answer", "trace_sha256", ]