File size: 7,252 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
"""``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"]