"""Deterministic executor for native GQA-v1.2 semantic programs. GQA questions carry a dependency-indexed list of semantic steps rather than a tree-shaped DSL AST. This module keeps that native representation immutable, validates a deliberately compact operation subset, and executes it directly against the released scene graph. No image model or answer-derived repair is used. Supported operation families are ``select``, ``filter``, ``relate``, ``query``, ``exist``, ``verify``, ``choose``, ``count``, and ``compare``. Native operation qualifiers such as ``filter hposition`` and ``choose color`` are retained. Anything outside this set is a typed compile rejection, never a guessed result. """ from __future__ import annotations import re from collections.abc import Mapping, Sequence from dataclasses import dataclass from typing import Any, Literal from ..hashing import canonical_json_hash from ..sources.base import World from .base import ( AnswerValue, ExecutionResult, ExecutorError, _InvalidReferent, _MissingInformation, _Trace, serialize_answer, ) NAME = "gqa_semantic_executor" VERSION = "gqa_semantic_v1/1" GQA_WORLD_SCHEMA = "gqa_scene_graph_v1" GQA_HIDDEN_OBJECTS_KEY = "_gqa_hidden_object_ids" _SUPPORTED_FAMILIES = frozenset( {"select", "filter", "relate", "query", "exist", "verify", "choose", "count", "compare"} ) _TERMINAL_FAMILIES = frozenset({"query", "exist", "verify", "choose", "count", "compare"}) _DIRECTIONS = { "s": "subject", "subject": "subject", "subj": "subject", "o": "object", "object": "object", "obj": "object", } _ENTITY = re.compile(r"^(?P.*?)(?:\s*\((?P[^()]+)\))?\s*$") _COLORS = frozenset( { "beige", "black", "blond", "blue", "brown", "clear", "colorful", "cream", "gold", "golden", "gray", "green", "grey", "multicolored", "orange", "pink", "purple", "red", "silver", "tan", "transparent", "white", "yellow", } ) _MATERIALS = frozenset( { "brick", "cardboard", "ceramic", "cloth", "concrete", "fabric", "glass", "leather", "metal", "metallic", "paper", "plastic", "porcelain", "rubber", "stone", "wood", "wooden", } ) _SHAPES = frozenset( { "circular", "curved", "flat", "oval", "rectangular", "round", "square", "triangular", } ) _SIZES = frozenset( {"big", "large", "little", "long", "narrow", "short", "small", "tall", "tiny", "wide"} ) _ATTRIBUTE_CLASSES: dict[str, frozenset[str]] = { "color": _COLORS, "material": _MATERIALS, "shape": _SHAPES, "size": _SIZES, } type GQAValue = tuple[str, ...] | str | int | bool | _Scene class GQASemanticError(ExecutorError): """A native GQA program or scene-graph value is outside the fixed subset.""" @dataclass(frozen=True) class GQASemanticStep: """One normalized native GQA semantic step.""" operation: str dependencies: tuple[int, ...] argument: str @property def family(self) -> str: return self.operation.split(maxsplit=1)[0] @property def qualifier(self) -> str: parts = self.operation.split(maxsplit=1) return parts[1] if len(parts) == 2 else "" def to_dict(self) -> dict[str, Any]: return { "operation": self.operation, "dependencies": list(self.dependencies), "argument": self.argument, } @dataclass(frozen=True) class GQASemanticProgram: """A validated, immutable GQA-v1.2 native semantic program.""" question_id: str image_id: str steps: tuple[GQASemanticStep, ...] semantic_str: str canonical_program_sha256: str def to_dict(self) -> dict[str, Any]: return { "dsl": "gqa_semantic_v1", "question_id": self.question_id, "image_id": self.image_id, "semantic": [step.to_dict() for step in self.steps], "semantic_str": self.semantic_str, "canonical_program_sha256": self.canonical_program_sha256, } @dataclass(frozen=True) class _Scene: """Sentinel value used by native ``select: scene`` programs.""" _SCENE = _Scene() def compile_gqa_program( question_id: str, row: Mapping[str, Any], ) -> GQASemanticProgram: """Validate and freeze one native GQA-v1.2 ``semantic`` list. Missing ``dependencies`` follow GQA's sequential shorthand: the first step has none and every later step depends on its immediate predecessor. An explicit dependency must point strictly backwards. Unsupported operations, malformed fields, and a non-terminal final operation are hard rejections. """ qid = str(question_id).strip() image_id = str(row.get("imageId", "")).strip() if not qid: raise GQASemanticError("GQA question id must be non-empty") if not image_id: raise GQASemanticError(f"GQA/{qid}: imageId missing/empty") raw_steps = row.get("semantic") if not isinstance(raw_steps, list) or not raw_steps: raise GQASemanticError(f"GQA/{qid}: semantic must be a non-empty list") steps: list[GQASemanticStep] = [] for index, raw in enumerate(raw_steps): if not isinstance(raw, Mapping): raise GQASemanticError(f"GQA/{qid}: semantic[{index}] must be an object") operation = " ".join(str(raw.get("operation", "")).strip().lower().split()) if not operation: raise GQASemanticError(f"GQA/{qid}: semantic[{index}].operation missing") family = operation.split(maxsplit=1)[0] if family not in _SUPPORTED_FAMILIES: raise GQASemanticError( f"GQA/{qid}: unsupported semantic operation {operation!r} at step {index}" ) argument_value = raw.get("argument", "") if argument_value is None: argument_value = "" if not isinstance(argument_value, (str, int, float, bool)): raise GQASemanticError(f"GQA/{qid}: semantic[{index}].argument must be scalar") argument = str(argument_value).strip() raw_dependencies = raw.get("dependencies") if raw_dependencies is None: dependencies = () if index == 0 else (index - 1,) else: if not isinstance(raw_dependencies, list) or any( not isinstance(dep, int) or isinstance(dep, bool) for dep in raw_dependencies ): raise GQASemanticError( f"GQA/{qid}: semantic[{index}].dependencies must be integer indices" ) dependencies = tuple(raw_dependencies) if len(set(dependencies)) != len(dependencies): raise GQASemanticError(f"GQA/{qid}: semantic[{index}] has duplicate dependencies") if any(dep < 0 or dep >= index for dep in dependencies): raise GQASemanticError( f"GQA/{qid}: semantic[{index}] dependency must point strictly backwards" ) if family == "select" and dependencies: raise GQASemanticError(f"GQA/{qid}: select step {index} cannot have dependencies") if family != "select" and not dependencies: raise GQASemanticError(f"GQA/{qid}: {operation!r} step {index} requires a dependency") steps.append( GQASemanticStep( operation=operation, dependencies=dependencies, argument=argument, ) ) if steps[-1].family not in _TERMINAL_FAMILIES: raise GQASemanticError( f"GQA/{qid}: final semantic operation {steps[-1].operation!r} is not supported terminal" ) semantic_str = str(row.get("semanticStr", "") or "") payload = { "dsl": "gqa_semantic_v1", "question_id": qid, "image_id": image_id, "semantic": [step.to_dict() for step in steps], "semantic_str": semantic_str, } return GQASemanticProgram( question_id=qid, image_id=image_id, steps=tuple(steps), semantic_str=semantic_str, canonical_program_sha256=canonical_json_hash(payload), ) class GQASemanticExecutor: """Execute the fixed native GQA semantic subset over a source scene graph.""" name = NAME version = VERSION def execute(self, program: GQASemanticProgram, *, world: World) -> ExecutionResult: trace = _Trace() referent_cardinality: int | None = None try: self._validate_world(program, world) values: list[GQAValue] = [] for step in program.steps: inputs = tuple(values[index] for index in step.dependencies) value, object_ids = self._eval(step, inputs, world) trace.record(step.operation.upper(), object_ids, _trace_value(value)) values.append(value) final = values[-1] answer = _answer(final) if program.steps[-1].dependencies: last_input = values[program.steps[-1].dependencies[0]] if isinstance(last_input, tuple): referent_cardinality = len(last_input) _steps, dependencies, trace_hash = trace.finish() return ExecutionResult( status="UNIQUE", answer_value=answer, answer_canonical=serialize_answer(answer), dependency_node_ids=dependencies, referent_cardinality=referent_cardinality, trace_sha256=trace_hash, executor_name=self.name, executor_version=self.version, ) except _MissingInformation: return self._failure("MISSING_INFORMATION", trace, referent_cardinality) except _InvalidReferent: return self._failure("INVALID_REFERENT", trace, referent_cardinality) except (ExecutorError, KeyError, TypeError, ValueError): return self._failure("ERROR", trace, referent_cardinality) def _failure( self, status: Literal["MISSING_INFORMATION", "INVALID_REFERENT", "ERROR"], trace: _Trace, referent_cardinality: int | None, ) -> ExecutionResult: _steps, dependencies, trace_hash = trace.finish() return ExecutionResult( status=status, answer_value=None, answer_canonical=None, dependency_node_ids=dependencies, referent_cardinality=referent_cardinality, trace_sha256=trace_hash, executor_name=self.name, executor_version=self.version, ) def _validate_world(self, program: GQASemanticProgram, world: World) -> None: if world.get("world_schema") != GQA_WORLD_SCHEMA: raise GQASemanticError( f"expected {GQA_WORLD_SCHEMA!r}, got {world.get('world_schema')!r}" ) if str(world.get("image_id", "")) != program.image_id: raise GQASemanticError( f"program image {program.image_id!r} != world image {world.get('image_id')!r}" ) if not isinstance(world.get("objects"), Mapping): raise GQASemanticError("GQA world objects must be a mapping") def _eval( self, step: GQASemanticStep, inputs: tuple[GQAValue, ...], world: World, ) -> tuple[GQAValue, tuple[str, ...]]: family = step.family if family == "select": return self._select(step.argument, world) if family == "filter": objects = _one_object_set(inputs, step.operation) return self._filter(objects, step.argument, step.qualifier, world) if family == "relate": objects = _one_object_set(inputs, step.operation) return self._relate(objects, step.argument, world) if family == "query": value = _one_input(inputs, step.operation) answer, ids = self._query(value, step.argument or step.qualifier, world) return answer, ids if family == "exist": objects = _one_object_set(inputs, step.operation) return bool(objects), objects if family == "verify": value = _one_input(inputs, step.operation) verified, ids = self._verify(value, step.argument, step.qualifier, world) return verified, ids if family == "choose": value = _one_input(inputs, step.operation) choice, ids = self._choose(value, step.argument, step.qualifier, world) return choice, ids if family == "count": objects = _one_object_set(inputs, step.operation) return len(objects), objects if family == "compare": compared, ids = self._compare(inputs, step.argument, step.qualifier, world) return compared, ids raise GQASemanticError(f"unsupported semantic operation {step.operation!r}") def _select(self, argument: str, world: World) -> tuple[GQAValue, tuple[str, ...]]: name, object_id = _parse_entity(argument) if name.casefold() == "scene" and object_id is None: return _SCENE, () if not name: raise GQASemanticError("select requires an object name") if object_id is not None: obj = _object(world, object_id) if _name(obj) != name.casefold(): raise _InvalidReferent( f"grounded object {object_id!r} is {_name(obj)!r}, not {name!r}" ) return (object_id,), (object_id,) matching: list[str] = [] for candidate_id, obj in _objects(world).items(): if _name(obj) != name.casefold(): continue if _is_hidden(world, candidate_id): raise _MissingInformation(f"selected {name!r} object {candidate_id!r} is hidden") matching.append(candidate_id) result = tuple(sorted(matching)) return result, result def _filter( self, objects: tuple[str, ...], argument: str, qualifier: str, world: World, ) -> tuple[tuple[str, ...], tuple[str, ...]]: if not argument: raise GQASemanticError("filter requires an argument") kept: list[str] = [] for object_id in objects: obj = _object(world, object_id) if _has_property(obj, argument, qualifier, world): kept.append(object_id) return tuple(kept), objects def _relate( self, dependencies: tuple[str, ...], argument: str, world: World, ) -> tuple[tuple[str, ...], tuple[str, ...]]: entity_name, entity_id, relation, direction = _parse_relation(argument) dependency_set = frozenset(dependencies) for dependency_id in dependencies: _object(world, dependency_id) matched: set[str] = set() accessed: set[str] = set(dependencies) if direction == "subject": candidates = ( ((entity_id, _object(world, entity_id)),) if entity_id is not None else tuple( (object_id, obj) for object_id, obj in _objects(world).items() if _name(obj) == entity_name.casefold() ) ) for candidate_id, candidate in candidates: if _name(candidate) != entity_name.casefold(): continue if _is_hidden(world, candidate_id): raise _MissingInformation(f"related subject {candidate_id!r} is hidden") accessed.add(candidate_id) targets = { target for rel_name, target in _relations(candidate) if rel_name.casefold() == relation.casefold() } if targets & dependency_set: matched.add(candidate_id) else: for source_id in dependencies: source = _object(world, source_id) for rel_name, target_id in _relations(source): if rel_name.casefold() != relation.casefold(): continue if entity_id is not None and target_id != entity_id: continue target = _object(world, target_id) if _name(target) != entity_name.casefold(): continue accessed.add(target_id) matched.add(target_id) return tuple(sorted(matched)), tuple(sorted(accessed)) def _query( self, value: GQAValue, category: str, world: World, ) -> tuple[str, tuple[str, ...]]: category = category.strip().casefold() if isinstance(value, _Scene): if category not in {"location", "weather"}: raise GQASemanticError(f"scene query {category!r} is unsupported") answer = world.get(category) if not isinstance(answer, str) or not answer.strip(): raise _MissingInformation(f"scene {category} is absent") return answer.strip(), () objects = _as_object_set(value, "query") if len(objects) != 1: raise _InvalidReferent(f"query requires one object, got {len(objects)}") object_id = objects[0] obj = _object(world, object_id) return _property_value(obj, category, world), (object_id,) def _verify( self, value: GQAValue, argument: str, qualifier: str, world: World, ) -> tuple[bool, tuple[str, ...]]: if isinstance(value, _Scene): category = qualifier.casefold() if category not in {"location", "weather"}: raise GQASemanticError(f"scene verify {category!r} is unsupported") actual = str(world.get(category, "")).strip().casefold() return actual == argument.strip().casefold(), () objects = _as_object_set(value, "verify") if not objects: return False, () return ( all( _has_property(_object(world, object_id), argument, qualifier, world) for object_id in objects ), objects, ) def _choose( self, value: GQAValue, argument: str, qualifier: str, world: World, ) -> tuple[str, tuple[str, ...]]: choices = tuple(part.strip() for part in argument.split("|")) if len(choices) != 2 or any(not choice for choice in choices): raise GQASemanticError("choose requires exactly two 'left|right' alternatives") if isinstance(value, _Scene): category = qualifier.casefold() if category not in {"location", "weather"}: raise GQASemanticError(f"scene choose {category!r} is unsupported") actual = str(world.get(category, "")).strip().casefold() matches = [choice for choice in choices if choice.casefold() == actual] ids: tuple[str, ...] = () else: objects = _as_object_set(value, "choose") if len(objects) != 1: raise _InvalidReferent(f"choose requires one object, got {len(objects)}") obj = _object(world, objects[0]) matches = [choice for choice in choices if _has_property(obj, choice, qualifier, world)] ids = objects if len(matches) != 1: raise _InvalidReferent( f"choose alternatives must have exactly one match, got {len(matches)}" ) return matches[0], ids def _compare( self, inputs: tuple[GQAValue, ...], argument: str, qualifier: str, world: World, ) -> tuple[bool, tuple[str, ...]]: if len(inputs) == 1 and isinstance(inputs[0], tuple) and len(inputs[0]) == 2: left: GQAValue = (inputs[0][0],) right: GQAValue = (inputs[0][1],) elif len(inputs) == 2: left, right = inputs else: raise GQASemanticError("compare requires two dependencies (or one two-object set)") relation, category = _comparison_spec(argument, qualifier) ids = tuple( sorted( { object_id for value in (left, right) if isinstance(value, tuple) for object_id in value } ) ) if relation in {"more", "greater", "less", "fewer", "equal"}: left_number = _numeric_comparand(left) right_number = _numeric_comparand(right) if relation in {"more", "greater"}: return left_number > right_number, ids if relation in {"less", "fewer"}: return left_number < right_number, ids return left_number == right_number, ids left_value = _comparison_property(left, category, world) right_value = _comparison_property(right, category, world) same = left_value.casefold() == right_value.casefold() return (not same if relation == "different" else same), ids def _objects(world: World) -> dict[str, Mapping[str, Any]]: raw = world.get("objects") if not isinstance(raw, Mapping): raise GQASemanticError("GQA world objects must be a mapping") out: dict[str, Mapping[str, Any]] = {} for object_id, obj in raw.items(): if isinstance(obj, Mapping): out[str(object_id)] = obj return out def _object(world: World, object_id: str) -> Mapping[str, Any]: objects = _objects(world) if object_id not in objects: raise _InvalidReferent(f"GQA object {object_id!r} is absent") if _is_hidden(world, object_id): raise _MissingInformation(f"GQA object {object_id!r} is hidden") return objects[object_id] def _is_hidden(world: World, object_id: str) -> bool: hidden = world.get(GQA_HIDDEN_OBJECTS_KEY, ()) return isinstance(hidden, (list, tuple, set, frozenset)) and object_id in { str(value) for value in hidden } def _name(obj: Mapping[str, Any]) -> str: return str(obj.get("name", "")).strip().casefold() def _attributes(obj: Mapping[str, Any]) -> tuple[str, ...]: raw = obj.get("attributes", ()) if not isinstance(raw, (list, tuple)): raise GQASemanticError("GQA object attributes must be a sequence") return tuple(str(value).strip() for value in raw if str(value).strip()) def _relations(obj: Mapping[str, Any]) -> tuple[tuple[str, str], ...]: raw = obj.get("relations", ()) values = raw.values() if isinstance(raw, Mapping) else raw if not isinstance(values, Sequence) and not isinstance(raw, Mapping): raise GQASemanticError("GQA object relations must be a sequence or mapping") out: list[tuple[str, str]] = [] for relation in values: if not isinstance(relation, Mapping): raise GQASemanticError("GQA relation must be an object") name = str(relation.get("name", "")).strip() target = str(relation.get("object", "")).strip() if not name or not target: raise GQASemanticError("GQA relation requires name and object") out.append((name, target)) return tuple(out) def _parse_entity(argument: str) -> tuple[str, str | None]: match = _ENTITY.fullmatch(argument.strip()) if match is None: raise GQASemanticError(f"malformed GQA entity argument {argument!r}") name = match.group("name").strip() object_id = match.group("object_id") return name, object_id.strip() if object_id else None def _parse_relation(argument: str) -> tuple[str, str | None, str, str]: parts = [part.strip() for part in argument.split(",")] if len(parts) != 3: raise GQASemanticError(f"relate requires three comma-separated fields, got {argument!r}") if parts[1].casefold() in _DIRECTIONS: relation = parts[0] direction = _DIRECTIONS[parts[1].casefold()] entity_raw = parts[2] elif parts[2].split(maxsplit=1)[0].casefold() in _DIRECTIONS: entity_raw = parts[0] relation = parts[1] direction_token, *suffix = parts[2].split(maxsplit=1) direction = _DIRECTIONS[direction_token.casefold()] if suffix: entity_raw = f"{entity_raw} {suffix[0]}" else: raise GQASemanticError(f"relate direction is unsupported in {argument!r}") entity_name, object_id = _parse_entity(entity_raw) if not entity_name or not relation: raise GQASemanticError(f"malformed relate argument {argument!r}") return entity_name, object_id, relation, direction def _one_input(inputs: tuple[GQAValue, ...], operation: str) -> GQAValue: if len(inputs) != 1: raise GQASemanticError(f"{operation!r} requires one dependency, got {len(inputs)}") return inputs[0] def _one_object_set(inputs: tuple[GQAValue, ...], operation: str) -> tuple[str, ...]: return _as_object_set(_one_input(inputs, operation), operation) def _as_object_set(value: GQAValue, operation: str) -> tuple[str, ...]: if not isinstance(value, tuple): raise GQASemanticError(f"{operation!r} requires an object-set dependency") return value def _has_property( obj: Mapping[str, Any], expected: str, qualifier: str, world: World, ) -> bool: value = expected.strip().casefold() category = qualifier.strip().casefold() if category in {"name", "category", "object"}: return _name(obj) == value attributes = {attribute.casefold() for attribute in _attributes(obj)} if value in attributes: return True if category == "hposition" or value in {"left", "right", "center"}: return _horizontal_position(obj, world) == value if category == "vposition" or value in {"top", "bottom", "middle"}: return _vertical_position(obj, world) == value return _name(obj) == value def _property_value(obj: Mapping[str, Any], category: str, world: World) -> str: if category in {"name", "category", "object"}: value = str(obj.get("name", "")).strip() if not value: raise _MissingInformation("object name is absent") return value if category == "hposition": return _horizontal_position(obj, world) if category == "vposition": return _vertical_position(obj, world) candidates = _ATTRIBUTE_CLASSES.get(category) attributes = _attributes(obj) if candidates is None: if len(attributes) == 1: return attributes[0] raise GQASemanticError(f"query attribute class {category!r} is unsupported") matched = [attribute for attribute in attributes if attribute.casefold() in candidates] if len(matched) != 1: raise _InvalidReferent( f"query {category!r} requires one matching attribute, got {len(matched)}" ) return matched[0] def _horizontal_position(obj: Mapping[str, Any], world: World) -> str: width = _positive_number(world.get("width"), "world width") center = _number(obj.get("x"), "object x") + _number(obj.get("w"), "object w") / 2 if center < width / 3: return "left" if center > 2 * width / 3: return "right" return "center" def _vertical_position(obj: Mapping[str, Any], world: World) -> str: height = _positive_number(world.get("height"), "world height") center = _number(obj.get("y"), "object y") + _number(obj.get("h"), "object h") / 2 if center < height / 3: return "top" if center > 2 * height / 3: return "bottom" return "middle" def _number(value: Any, label: str) -> float: if isinstance(value, bool): raise GQASemanticError(f"{label} must be numeric") try: return float(value) except (TypeError, ValueError) as exc: raise GQASemanticError(f"{label} must be numeric") from exc def _positive_number(value: Any, label: str) -> float: number = _number(value, label) if number <= 0: raise GQASemanticError(f"{label} must be positive") return number def _comparison_spec(argument: str, qualifier: str) -> tuple[str, str]: tokens = [ token for token in re.split(r"[\s,|]+", f"{qualifier} {argument}".strip().casefold()) if token ] relation = next( ( token for token in tokens if token in {"same", "different", "more", "greater", "less", "fewer", "equal"} ), "same", ) category = next( ( token for token in tokens if token not in {"same", "different", "more", "greater", "less", "fewer", "equal", "than"} ), "name", ) return relation, category def _numeric_comparand(value: GQAValue) -> int: if isinstance(value, bool): return int(value) if isinstance(value, int): return value if isinstance(value, tuple): return len(value) raise GQASemanticError("numeric compare requires counts or object sets") def _comparison_property(value: GQAValue, category: str, world: World) -> str: objects = _as_object_set(value, "compare") if len(objects) != 1: raise _InvalidReferent(f"property compare requires one object, got {len(objects)}") return _property_value(_object(world, objects[0]), category, world) def _answer(value: GQAValue) -> AnswerValue: if isinstance(value, (str, int, bool)): return value raise GQASemanticError("final GQA semantic step did not produce a scalar answer") def _trace_value(value: GQAValue) -> str | int | bool: if isinstance(value, tuple): return "[" + ",".join(value) + "]" if isinstance(value, _Scene): return "scene" return value __all__ = [ "GQA_HIDDEN_OBJECTS_KEY", "GQA_WORLD_SCHEMA", "GQASemanticError", "GQASemanticExecutor", "GQASemanticProgram", "GQASemanticStep", "compile_gqa_program", ]