"""Deterministic executor for official CLEVR functional programs.""" from __future__ import annotations from collections.abc import Mapping, Sequence from typing import Any from ..dsl.ast import Arg, AstNode, Program from ..sources.base import World from .base import ( AnswerValue, ExecutionResult, ExecutionStatus, ExecutorError, _InvalidReferent, _MissingInformation, _Trace, literal_value, serialize_answer, ) NAME = "clevr_executor" VERSION = "clevr_dsl_v1/1" _ATTRIBUTES = frozenset({"color", "material", "shape", "size"}) _RELATIONS = frozenset({"left", "right", "front", "behind"}) class ClevrExecutor: """Evaluate a CLEVR AST over a normalized ``clevr_world_v1`` scene.""" name = NAME version = VERSION def execute(self, program: Program, *, world: World) -> ExecutionResult: trace = _Trace() referent_cardinality: int | None = None status: ExecutionStatus try: if program.dsl != "clevr_dsl_v1" or program.compile_status != "compiled": raise ExecutorError("executor requires a compiled clevr_dsl_v1 program") if world.get("world_schema") != "clevr_world_v1": raise ExecutorError( f"clevr executor cannot read world_schema {world.get('world_schema')!r}" ) referent_cardinality = self._check_referent(program, world, trace) value = self._eval(program.program, world, trace) answer = self._project_answer(program.program, value) _steps, dependencies, trace_hash = trace.finish() return ExecutionResult( status="UNIQUE", answer_value=answer, answer_canonical=serialize_answer( answer, return_type=program.program.return_type, ), dependency_node_ids=dependencies, referent_cardinality=referent_cardinality, trace_sha256=trace_hash, executor_name=self.name, executor_version=self.version, ) except _MissingInformation: status = "MISSING_INFORMATION" except _InvalidReferent: status = "INVALID_REFERENT" except ExecutorError: status = "ERROR" _steps, dependencies, trace_hash = trace.finish() return ExecutionResult( status=status, answer_value=None, answer_canonical=None, dependency_node_ids=dependencies, referent_cardinality=( referent_cardinality if referent_cardinality is not None else self._safe_referent_cardinality(program, world) ), trace_sha256=trace_hash, executor_name=self.name, executor_version=self.version, ) def execute_selector(self, selector: AstNode, *, world: World) -> tuple[str, ...]: """Resolve an object/object-set selector without applying ``UNIQUE``.""" trace = _Trace() if selector.op == "UNIQUE": if len(selector.args) != 1 or not isinstance(selector.args[0], AstNode): raise ExecutorError("UNIQUE selector is malformed") value = self._eval(selector.args[0], world, trace) else: value = self._eval(selector, world, trace) if isinstance(value, Mapping): node_id = value.get("id") return (str(node_id),) if node_id else () if isinstance(value, tuple): return tuple( str(item["id"]) for item in value if isinstance(item, Mapping) and item.get("id") ) raise ExecutorError(f"selector {selector.op!r} did not produce objects") 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: return None refs = self.execute_selector(selector, world=world) trace.record("REFERENT", refs, len(refs)) if required is not None and len(refs) != required: raise _InvalidReferent( f"scalar referent cardinality {len(refs)} != required {required}" ) return len(refs) def _safe_referent_cardinality(self, program: Program, world: World) -> int | None: if program.referent_selector is None: return None try: return len(self.execute_selector(program.referent_selector, world=world)) except (ExecutorError, _MissingInformation, _InvalidReferent): return None def _eval(self, node: Arg, world: World, trace: _Trace) -> Any: if not isinstance(node, AstNode): raise ExecutorError(f"expected AST node, got {type(node).__name__}") op = node.op if op == "LITERAL": return literal_value(node) if op == "SCENE": objects = _objects(world) trace.record("SCENE", (), len(objects)) return objects if op.startswith("FILTER_"): return self._filter(op.removeprefix("FILTER_").lower(), node, world, trace) if op == "UNIQUE": unique_values = _object_set(self._eval_arg(node, 0, world, trace), op) trace.record(op, unique_values, len(unique_values)) if len(unique_values) != 1: raise _InvalidReferent(f"UNIQUE received {len(unique_values)} objects") return unique_values[0] if op == "RELATE": source = _object(self._eval_arg(node, 0, world, trace), op) relation = _string(self._eval_arg(node, 1, world, trace), op) related_values = _related(world, str(source["id"]), relation) trace.record(op, (source, *related_values), len(related_values)) return related_values if op.startswith("SAME_"): attribute = op.removeprefix("SAME_").lower() source = _object(self._eval_arg(node, 0, world, trace), op) target = _attribute(source, attribute) same_values: list[Mapping[str, Any]] = [] for candidate in _objects(world): if candidate.get("id") == source.get("id"): continue if _attribute(candidate, attribute) == target: same_values.append(candidate) same_result = _ordered(same_values) trace.record(op, (source, *same_result), len(same_result)) return same_result if op in {"UNION", "INTERSECT"}: left = _object_set(self._eval_arg(node, 0, world, trace), op) right = _object_set(self._eval_arg(node, 1, world, trace), op) left_by_id = {str(item["id"]): item for item in left} right_by_id = {str(item["id"]): item for item in right} ids = ( set(left_by_id).union(right_by_id) if op == "UNION" else set(left_by_id).intersection(right_by_id) ) set_result = tuple((left_by_id | right_by_id)[node_id] for node_id in sorted(ids)) trace.record(op, set_result, len(set_result)) return set_result if op == "COUNT": count_values = _object_set(self._eval_arg(node, 0, world, trace), op) trace.record(op, count_values, len(count_values)) return len(count_values) if op == "EXIST": exist_values = _object_set(self._eval_arg(node, 0, world, trace), op) exists = bool(exist_values) trace.record(op, exist_values, exists) return exists if op.startswith("QUERY_"): attribute = op.removeprefix("QUERY_").lower() obj = _object(self._eval_arg(node, 0, world, trace), op) value = _attribute(obj, attribute) trace.record(op, obj, value) return value if op.startswith("EQUAL_"): left = self._eval_arg(node, 0, world, trace) right = self._eval_arg(node, 1, world, trace) comparison = _comparable(left) == _comparable(right) trace.record(op, (), comparison) return comparison if op in {"LESS_THAN", "GREATER_THAN"}: left_integer = _integer(self._eval_arg(node, 0, world, trace), op) right_integer = _integer(self._eval_arg(node, 1, world, trace), op) comparison = ( left_integer < right_integer if op == "LESS_THAN" else left_integer > right_integer ) trace.record(op, (), comparison) return comparison raise ExecutorError(f"unsupported CLEVR op {op!r}") def _eval_arg( self, node: AstNode, position: int, world: World, trace: _Trace, ) -> Any: try: arg = node.args[position] except IndexError as exc: raise ExecutorError(f"{node.op} has no operand {position}") from exc if not isinstance(arg, AstNode): raise ExecutorError(f"{node.op} operand {position} is not an AST node") return self._eval(arg, world, trace) def _filter( self, attribute: str, node: AstNode, world: World, trace: _Trace, ) -> tuple[Mapping[str, Any], ...]: values = _object_set(self._eval_arg(node, 0, world, trace), node.op) wanted = _string(self._eval_arg(node, 1, world, trace), node.op) selected = tuple(item for item in values if _attribute(item, attribute) == wanted) trace.record(node.op, selected, len(selected)) return selected def _project_answer(self, root: AstNode, value: Any) -> AnswerValue: if root.return_type == "integer": return _integer(value, root.op) if root.return_type == "boolean": return bool(value) if root.return_type == "string": return _string(value, root.op) raise ExecutorError( f"CLEVR root {root.op!r} has non-answer return type {root.return_type!r}" ) def _objects(world: World) -> tuple[Mapping[str, Any], ...]: raw = world.get("objects") if not isinstance(raw, list): raise ExecutorError("CLEVR world objects is not an array") values: list[Mapping[str, Any]] = [] seen: set[str] = set() for item in raw: if not isinstance(item, Mapping) or not item.get("id"): raise ExecutorError("CLEVR world contains an object without an id") node_id = str(item["id"]) if node_id in seen: raise ExecutorError(f"CLEVR world has duplicate object id {node_id!r}") seen.add(node_id) values.append(item) return _ordered(values) def _ordered(values: Sequence[Mapping[str, Any]]) -> tuple[Mapping[str, Any], ...]: return tuple(sorted(values, key=lambda item: str(item.get("id", "")))) def _object_set(value: Any, op: str) -> tuple[Mapping[str, Any], ...]: if not isinstance(value, tuple) or any(not isinstance(item, Mapping) for item in value): raise ExecutorError(f"{op} expected an object set") return _ordered(value) def _object(value: Any, op: str) -> Mapping[str, Any]: if not isinstance(value, Mapping) or not value.get("id"): raise ExecutorError(f"{op} expected one object") return value def _attribute(obj: Mapping[str, Any], attribute: str) -> str: if attribute not in _ATTRIBUTES: raise ExecutorError(f"unknown CLEVR attribute {attribute!r}") value = obj.get(attribute) if value is None: raise _MissingInformation(f"object {obj.get('id')} {attribute} is hidden") if not isinstance(value, str) or not value: raise ExecutorError(f"object {obj.get('id')} has invalid {attribute}") return value def _related( world: World, source_id: str, relation: str, ) -> tuple[Mapping[str, Any], ...]: if relation not in _RELATIONS: raise ExecutorError(f"unknown CLEVR relation {relation!r}") relationships = world.get("relationships") if not isinstance(relationships, Mapping): raise ExecutorError("CLEVR relationships is not an object") relation_map = relationships.get(relation) if not isinstance(relation_map, Mapping): raise ExecutorError(f"CLEVR relationship {relation!r} is missing") raw_targets = relation_map.get(source_id, []) if not isinstance(raw_targets, list): raise ExecutorError(f"CLEVR relationship {relation!r}/{source_id!r} is malformed") by_id = {str(item["id"]): item for item in _objects(world)} targets: list[Mapping[str, Any]] = [] for node_id in raw_targets: target = by_id.get(str(node_id)) if target is None: raise ExecutorError( f"CLEVR relationship {relation!r} references absent object {node_id!r}" ) targets.append(target) return _ordered(targets) def _string(value: Any, op: str) -> str: if not isinstance(value, str): raise ExecutorError(f"{op} expected a string, got {type(value).__name__}") return value def _integer(value: Any, op: str) -> int: if isinstance(value, bool) or not isinstance(value, int): raise ExecutorError(f"{op} expected an integer, got {type(value).__name__}") return int(value) def _comparable(value: Any) -> Any: if isinstance(value, Mapping): node_id = value.get("id") if not node_id: raise ExecutorError("object comparison received an object without an id") return ("object", str(node_id)) if isinstance(value, (str, int, bool)): return value raise ExecutorError(f"value {value!r} is not comparable") __all__ = ["ClevrExecutor"]