"""``table_dsl_v1`` executor — exact-rational table program execution (P3). Evaluates ``COL``/``ROW``/``LOOKUP``/``SUM``/``AVG``/``COUNT``/``EXIST`` over a ``table_world_v1``. No P2 source compiles a table program (ChartQA is C2/P4 model-compiled), so this executor is exercised against synthetic table worlds; it shares the executor contract so the type checker and C2 layer cover the third DSL end-to-end. Exact ``Fraction`` arithmetic; same scalar/set referent rules. """ from __future__ import annotations from collections.abc import Mapping from fractions import Fraction from typing import Any from ..dsl.ast import Arg, AstNode, Program from ..sources.base import World from .base import ( AnswerValue, ExecutionResult, ExecutorError, _InvalidReferent, _MissingInformation, _Trace, literal_value, serialize_answer, ) NAME = "table_executor" VERSION = "table_dsl_v1/1" class TableExecutor: """Deterministic executor for ``table_dsl_v1``.""" name = NAME version = VERSION def execute(self, program: Program, *, world: World) -> ExecutionResult: trace = _Trace() try: self._check_referent(program, world, trace) answer = self._project(program.program, self._eval(program.program, world, trace)) _steps, deps, tsha = trace.finish() return ExecutionResult( status="UNIQUE", answer_value=answer, answer_canonical=serialize_answer(answer, return_type=program.program.return_type), dependency_node_ids=deps, referent_cardinality=None, trace_sha256=tsha, executor_name=self.name, executor_version=self.version, ) except _InvalidReferent: return self._non_unique(program, world, trace, "INVALID_REFERENT") except _MissingInformation: return self._non_unique(program, world, trace, "MISSING_INFORMATION") except ExecutorError: return self._non_unique(program, world, trace, "ERROR") def execute_selector(self, selector: AstNode, *, world: World) -> tuple[str, ...]: if selector.op == "COL": col = str( literal_value(selector.args[0]) if isinstance(selector.args[0], AstNode) else selector.args[0] ) return tuple( r["id"] for r in _rows(world) if isinstance(r, Mapping) and col in r.get("cells", {}) ) if selector.op == "ROW": return () # row selection is by id, resolved in LOOKUP return () def _check_referent(self, program: Program, world: World, trace: _Trace) -> int | None: selector = program.referent_selector required = program.required_referent_cardinality if selector is None or required is None: return None refs = self.execute_selector(selector, world=world) trace.record("REFERENT", refs, len(refs)) if len(refs) != required: raise _InvalidReferent("table referent cardinality mismatch") return len(refs) def _non_unique( self, program: Program, world: World, trace: _Trace, status: str ) -> ExecutionResult: _steps, deps, tsha = trace.finish() return ExecutionResult( status=status, # type: ignore[arg-type] answer_value=None, answer_canonical=None, dependency_node_ids=deps, referent_cardinality=None, trace_sha256=tsha, executor_name=self.name, executor_version=self.version, ) def _eval(self, node: Arg, world: World, trace: _Trace) -> Any: if not isinstance(node, AstNode): raise ExecutorError(f"expected an AST node, got {type(node).__name__}") op = node.op if op == "LITERAL": return literal_value(node) if op == "COL": return str( literal_value(node.args[0]) if isinstance(node.args[0], AstNode) else node.args[0] ) if op == "ROW": return str( literal_value(node.args[0]) if isinstance(node.args[0], AstNode) else node.args[0] ) if op == "LOOKUP": row_id = self._eval(node.args[0], world, trace) col = self._eval(node.args[1], world, trace) row = _row(world, str(row_id)) if row is None: raise _MissingInformation(f"row {row_id!r} not in table") cells = row.get("cells", {}) if col not in cells: raise _MissingInformation(f"column {col!r} not in row {row_id}") value = _as_number(cells[col]) trace.record("LOOKUP", row, value) return value if op in ("SUM", "AVG"): return self._eval_aggregate(op, node, world, trace) if op == "COUNT": col = self._eval(node.args[0], world, trace) count = sum( 1 for r in _rows(world) if isinstance(r, Mapping) and col in r.get("cells", {}) ) trace.record("COUNT", (col,), count) return count if op == "EXIST": col = self._eval(node.args[0], world, trace) exists = any(isinstance(r, Mapping) and col in r.get("cells", {}) for r in _rows(world)) trace.record("EXIST", (col,), exists) return exists raise ExecutorError(f"unsupported table op {op!r}") def _eval_aggregate(self, op: str, node: AstNode, world: World, trace: _Trace) -> Fraction: values: list[Fraction] = [] for arg in node.args: values.append(_as_number(self._eval(arg, world, trace))) if op == "SUM": total = sum(values, start=Fraction(0)) trace.record("SUM", (), total) return total if not values: raise _MissingInformation("AVG over empty set") avg = sum(values, start=Fraction(0)) / len(values) trace.record("AVG", (), avg) return avg def _project(self, root: AstNode, value: Any) -> AnswerValue: rt = root.return_type if rt == "integer": return int(value) if rt == "boolean": return bool(value) return _as_number(value) def _rows(world: World) -> list[Any]: rows = world.get("rows", []) return rows if isinstance(rows, list) else [] def _row(world: World, rid: str) -> Mapping[str, Any] | None: for row in _rows(world): if isinstance(row, Mapping) and row.get("id") == rid: return row return None def _as_number(value: Any) -> Fraction: if isinstance(value, bool): # noqa: FBT001 raise ExecutorError("boolean where a number was expected") if isinstance(value, Fraction): return value if isinstance(value, int): return Fraction(value) try: return Fraction(str(value)) except (ValueError, ZeroDivisionError) as exc: # unparseable → ERROR, never a crash/U raise ExecutorError(f"unparseable numeric value {value!r}") from exc __all__ = ["TableExecutor"]