File size: 30,439 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
"""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<name>.*?)(?:\s*\((?P<object_id>[^()]+)\))?\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",
]