type-bridge-schema-codegen 2.2.4

Deterministic projection-only schema emitters for type-bridge
Documentation
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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
"""Projection-owned query references emitted with a generated Python package."""

from __future__ import annotations

import asyncio
import json
from collections.abc import Awaitable, Callable, Iterable, Iterator, Sequence
from dataclasses import fields, is_dataclass
from datetime import date, datetime, timedelta
from decimal import Decimal
from typing import Literal, Protocol, TypeGuard, get_args, get_origin, get_type_hints, overload

from type_bridge_core import (
    DynamicValue,
    MatchBindingHandle,
    MatchFieldHandle,
    MatchFunctionArgumentHandle,
    MatchFunctionCallHandle,
    MatchFunctionValueHandle,
    MatchOrderHandle,
    MatchPredicateHandle,
    MatchQueryHandle,
    MatchRoleHandle,
    MatchSelectionHandle,
    MatchSessionHandle,
    PendingRemoteModelQuery,
    PyRuntimeProjection,
    QueryCancellation,
    QueryExecutionResourceLimits,
    RemoteModelQueryContext,
    ValidatedMatchResultHandle,
    ValidatedMatchRowHandle,
    query_v2_authority_from_schema_authority,
    query_v2_prepare_remote_model_count,
    query_v2_prepare_remote_model_exists,
    query_v2_prepare_remote_model_page,
    query_v2_prepare_remote_model_reduce,
    query_v2_prepare_remote_model_reduce_by_field,
    query_v2_prepare_remote_model_reduce_by_fields,
    query_v2_prepare_remote_model_rows,
    query_v2_remote_model_context,
    query_v2_remote_model_context_with_resources,
)
from type_bridge_core import (
    QueryV2Authority as _QueryV2Authority,
)

from type_bridge._rust_runtime import rust_database_for, rust_transaction_for
from type_bridge.session import Database, TransactionContext

from ._authority import SCHEMA_AUTHORITY_BYTES
from ._runtime import (
    AttributeBase,
    EntityBase,
    FieldToken,
    FunctionRef,
    ModelBase,
    RelationBase,
    RoleToken,
    attribute_model_for_query_label,
    function_identity_for_query,
)
from ._schema import SEMANTIC_SCHEMA_FINGERPRINT_JSON


def _model_label(model: type[ModelBase]) -> str:
    identity: object = json.loads(model.__type_id__)
    if not _is_object_dict(identity):
        raise TypeError("generated model identity must be an object")
    label = identity.get("label")
    if not isinstance(label, str):
        raise TypeError("generated model identity has no string label")
    return label


def _exact_projection(model: type[ModelBase]) -> PyRuntimeProjection:
    projection = model.__dict__.get("__runtime_projection__")
    if not isinstance(projection, PyRuntimeProjection):
        raise TypeError("generated query requires an exact installed generated model class")
    return projection


_package_projection: PyRuntimeProjection | None = None
_package_query_authority: _QueryV2Authority = query_v2_authority_from_schema_authority(
    SCHEMA_AUTHORITY_BYTES,
    SEMANTIC_SCHEMA_FINGERPRINT_JSON.encode("utf-8"),
)


def install_projection(projection: PyRuntimeProjection) -> None:
    global _package_projection
    if _package_projection is not None:
        raise RuntimeError("generated query projection is already installed")
    _package_projection = projection


def _installed_projection() -> PyRuntimeProjection:
    if _package_projection is None:
        raise RuntimeError("generated package runtime projection is not installed")
    return _package_projection


def _installed_query_authority() -> _QueryV2Authority:
    return _package_query_authority


def _attribute_model(label: str) -> type[AttributeBase]:
    return attribute_model_for_query_label(label)


class _Frozen:
    __slots__ = ()

    def __setattr__(self, name: str, value: object) -> None:
        del name, value
        raise AttributeError(f"{type(self).__name__} values are immutable")


class Predicate(_Frozen):
    __slots__ = ("__handle", "__projection")
    __handle: MatchPredicateHandle
    __projection: PyRuntimeProjection

    def __init__(self, handle: MatchPredicateHandle, projection: PyRuntimeProjection) -> None:
        object.__setattr__(self, "_Predicate__handle", handle)
        object.__setattr__(self, "_Predicate__projection", projection)

    def and_(self, other: Predicate) -> Predicate:
        _require_projection(other.projection_identity(), self.__projection, "predicate")
        return Predicate(self.__handle.and_(other.native_handle()), self.__projection)

    def or_(self, other: Predicate) -> Predicate:
        _require_projection(other.projection_identity(), self.__projection, "predicate")
        return Predicate(self.__handle.or_(other.native_handle()), self.__projection)

    def not_(self) -> Predicate:
        return Predicate(self.__handle.not_(), self.__projection)

    def __and__(self, other: Predicate) -> Predicate:
        return self.and_(other)

    def __or__(self, other: Predicate) -> Predicate:
        return self.or_(other)

    def __invert__(self) -> Predicate:
        return self.not_()

    def native_handle(self) -> MatchPredicateHandle:
        return self.__handle

    def projection_identity(self) -> PyRuntimeProjection:
        return self.__projection


class FunctionInput[DomainT](_Frozen):
    """One exact session/projection-branded scalar schema-function input."""

    __slots__ = ("__handle", "__projection")
    __handle: MatchFunctionValueHandle
    __projection: PyRuntimeProjection

    def __init__(
        self,
        handle: MatchFunctionValueHandle,
        projection: PyRuntimeProjection,
    ) -> None:
        object.__setattr__(self, "_FunctionInput__handle", handle)
        object.__setattr__(self, "_FunctionInput__projection", projection)

    def native_argument(self) -> MatchFunctionArgumentHandle:
        return self.__handle.function_argument()

    def native_handle(self) -> MatchFunctionValueHandle:
        return self.__handle

    def projection_identity(self) -> PyRuntimeProjection:
        return self.__projection


class FunctionCall[DomainT](_Frozen):
    """One immutable scalar schema-function call."""

    __slots__ = ("__handle", "__projection")
    __handle: MatchFunctionCallHandle
    __projection: PyRuntimeProjection

    def __init__(
        self,
        handle: MatchFunctionCallHandle,
        projection: PyRuntimeProjection,
    ) -> None:
        object.__setattr__(self, "_FunctionCall__handle", handle)
        object.__setattr__(self, "_FunctionCall__projection", projection)

    def eq_field(self, field: BoundField) -> Predicate:
        return self.__compare_field("equal", field)

    def neq_field(self, field: BoundField) -> Predicate:
        return self.__compare_field("not_equal", field)

    def lt_field(self, field: BoundField) -> Predicate:
        return self.__compare_field("less_than", field)

    def lte_field(self, field: BoundField) -> Predicate:
        return self.__compare_field("less_than_or_equal", field)

    def gt_field(self, field: BoundField) -> Predicate:
        return self.__compare_field("greater_than", field)

    def gte_field(self, field: BoundField) -> Predicate:
        return self.__compare_field("greater_than_or_equal", field)

    def eq_value(self, value: FunctionInput[DomainT]) -> Predicate:
        return self.__compare_value("equal", value)

    def neq_value(self, value: FunctionInput[DomainT]) -> Predicate:
        return self.__compare_value("not_equal", value)

    def lt_value(self, value: FunctionInput[DomainT]) -> Predicate:
        return self.__compare_value("less_than", value)

    def lte_value(self, value: FunctionInput[DomainT]) -> Predicate:
        return self.__compare_value("less_than_or_equal", value)

    def gt_value(self, value: FunctionInput[DomainT]) -> Predicate:
        return self.__compare_value("greater_than", value)

    def gte_value(self, value: FunctionInput[DomainT]) -> Predicate:
        return self.__compare_value("greater_than_or_equal", value)

    def eq_call(self, other: FunctionCall[DomainT]) -> Predicate:
        return self.__compare_call("equal", other)

    def neq_call(self, other: FunctionCall[DomainT]) -> Predicate:
        return self.__compare_call("not_equal", other)

    def lt_call(self, other: FunctionCall[DomainT]) -> Predicate:
        return self.__compare_call("less_than", other)

    def lte_call(self, other: FunctionCall[DomainT]) -> Predicate:
        return self.__compare_call("less_than_or_equal", other)

    def gt_call(self, other: FunctionCall[DomainT]) -> Predicate:
        return self.__compare_call("greater_than", other)

    def gte_call(self, other: FunctionCall[DomainT]) -> Predicate:
        return self.__compare_call("greater_than_or_equal", other)

    def native_argument(self) -> MatchFunctionArgumentHandle:
        return self.__handle.function_argument()

    def native_handle(self) -> MatchFunctionCallHandle:
        return self.__handle

    def projection_identity(self) -> PyRuntimeProjection:
        return self.__projection

    def __compare_field(self, operator: str, field: object) -> Predicate:
        if not isinstance(field, BoundField):
            raise TypeError("schema-function field comparison requires a BoundField")
        _require_projection(field.projection_identity(), self.__projection, "function field")
        return Predicate(
            self.__handle.compare_field(operator, field.native_handle()),
            self.__projection,
        )

    def __compare_value(self, operator: str, value: FunctionInput[DomainT]) -> Predicate:
        if type(value) is not FunctionInput:
            raise TypeError("schema-function value comparison requires a FunctionInput")
        _require_projection(value.projection_identity(), self.__projection, "function value")
        return Predicate(
            self.__handle.compare_value(operator, value.native_handle()),
            self.__projection,
        )

    def __compare_call(self, operator: str, other: FunctionCall[DomainT]) -> Predicate:
        if type(other) is not FunctionCall:
            raise TypeError("schema-function call comparison requires a FunctionCall")
        _require_projection(other.projection_identity(), self.__projection, "function call")
        return Predicate(
            self.__handle.compare_call(operator, other.native_handle()),
            self.__projection,
        )


class QueryOrder(_Frozen):
    __slots__ = ("__handle", "__projection")
    __handle: MatchOrderHandle
    __projection: PyRuntimeProjection

    def __init__(self, handle: MatchOrderHandle, projection: PyRuntimeProjection) -> None:
        object.__setattr__(self, "_QueryOrder__handle", handle)
        object.__setattr__(self, "_QueryOrder__projection", projection)

    def native_handle(self) -> MatchOrderHandle:
        return self.__handle

    def projection_identity(self) -> PyRuntimeProjection:
        return self.__projection


_AGGREGATE_TOKEN = object()
type _Reducer = Literal["count", "sum", "min", "max", "mean", "median", "std"]


class Aggregate(_Frozen):
    __slots__ = ("__input", "__projection", "__reducer")
    __input: MatchFieldHandle | None
    __projection: PyRuntimeProjection | None
    __reducer: _Reducer

    def __init__(
        self,
        reducer: _Reducer,
        input_: MatchFieldHandle | None,
        projection: PyRuntimeProjection | None,
        token: object,
    ) -> None:
        if token is not _AGGREGATE_TOKEN:
            raise TypeError("generated aggregate terms must come from aggregate constructors")
        object.__setattr__(self, "_Aggregate__reducer", reducer)
        object.__setattr__(self, "_Aggregate__input", input_)
        object.__setattr__(self, "_Aggregate__projection", projection)

    def native_reducer(self) -> _Reducer:
        return self.__reducer

    def native_input(self) -> MatchFieldHandle | None:
        return self.__input

    def projection_identity(self) -> PyRuntimeProjection | None:
        return self.__projection


class Page(_Frozen, Sequence[object]):
    __slots__ = ("__items", "__limit", "__offset", "__total")
    __items: tuple[object, ...]
    __limit: int
    __offset: int
    __total: int | None

    def __init__(
        self,
        items: Iterable[object],
        *,
        offset: int,
        limit: int,
        total: int | None,
    ) -> None:
        object.__setattr__(self, "_Page__items", tuple(items))
        object.__setattr__(self, "_Page__offset", offset)
        object.__setattr__(self, "_Page__limit", limit)
        object.__setattr__(self, "_Page__total", total)

    @property
    def items(self) -> tuple[object, ...]:
        return self.__items

    @property
    def offset(self) -> int:
        return self.__offset

    @property
    def limit(self) -> int:
        return self.__limit

    @property
    def total(self) -> int | None:
        return self.__total

    def __len__(self) -> int:
        return len(self.__items)

    @overload
    def __getitem__(self, index: int) -> object: ...

    @overload
    def __getitem__(self, index: slice) -> Sequence[object]: ...

    def __getitem__(self, index: int | slice) -> object | Sequence[object]:
        return self.__items[index]

    def __iter__(self) -> Iterator[object]:
        return iter(self.__items)


class BoundField(_Frozen):
    __slots__ = ("__attribute_label", "__attribute_model", "__handle", "__projection")
    __attribute_label: str
    __handle: MatchFieldHandle
    __projection: PyRuntimeProjection

    def __init__(
        self,
        handle: MatchFieldHandle,
        projection: PyRuntimeProjection,
        attribute_label: str,
        attribute_model: type[AttributeBase],
    ) -> None:
        object.__setattr__(self, "_BoundField__attribute_label", attribute_label)
        object.__setattr__(self, "_BoundField__attribute_model", attribute_model)
        object.__setattr__(self, "_BoundField__handle", handle)
        object.__setattr__(self, "_BoundField__projection", projection)

    def eq(self, value: AttributeBase | BoundField) -> Predicate:
        return self.__compare("equal", value)

    def eq_field(self, field: BoundField) -> Predicate:
        return self.__compare_field("equal", field)

    def neq(self, value: AttributeBase | BoundField) -> Predicate:
        return self.__compare("not_equal", value)

    def neq_field(self, field: BoundField) -> Predicate:
        return self.__compare_field("not_equal", field)

    def lt(self, value: AttributeBase | BoundField) -> Predicate:
        return self.__compare("less_than", value)

    def lt_field(self, field: BoundField) -> Predicate:
        return self.__compare_field("less_than", field)

    def lte(self, value: AttributeBase | BoundField) -> Predicate:
        return self.__compare("less_than_or_equal", value)

    def lte_field(self, field: BoundField) -> Predicate:
        return self.__compare_field("less_than_or_equal", field)

    def gt(self, value: AttributeBase | BoundField) -> Predicate:
        return self.__compare("greater_than", value)

    def gt_field(self, field: BoundField) -> Predicate:
        return self.__compare_field("greater_than", field)

    def gte(self, value: AttributeBase | BoundField) -> Predicate:
        return self.__compare("greater_than_or_equal", value)

    def gte_field(self, field: BoundField) -> Predicate:
        return self.__compare_field("greater_than_or_equal", field)

    def contains(self, value: AttributeBase) -> Predicate:
        return self.__compare("contains", value)

    def starts_with(self, value: AttributeBase) -> Predicate:
        return self.__compare("starts_with", value)

    def ends_with(self, value: AttributeBase) -> Predicate:
        return self.__compare("ends_with", value)

    def regex(self, value: AttributeBase) -> Predicate:
        return self.__compare("regex", value)

    def is_present(self) -> Predicate:
        return Predicate(self.__handle.presence(True), self.__projection)

    def is_missing(self) -> Predicate:
        return Predicate(self.__handle.presence(False), self.__projection)

    def asc(self, *, missing: str = "reject") -> QueryOrder:
        return QueryOrder(self.__handle.order("ascending", missing), self.__projection)

    def desc(self, *, missing: str = "reject") -> QueryOrder:
        return QueryOrder(self.__handle.order("descending", missing), self.__projection)

    def __compare(self, operator: str, value: AttributeBase | BoundField) -> Predicate:
        if isinstance(value, BoundField):
            if value.attribute_label() != self.__attribute_label:
                raise TypeError(
                    "cross-attribute field comparisons require the explicit *_field method"
                )
            return self.__compare_field(operator, value)
        else:
            _require_projection(_exact_projection(type(value)), self.__projection, "attribute")
            if _model_label(type(value)) != self.__attribute_label:
                raise TypeError("generated field comparison requires its exact attribute wrapper")
            handle = self.__handle.compare_value(operator, _dynamic_value(value))
        return Predicate(handle, self.__projection)

    def __compare_field(self, operator: str, field: BoundField) -> Predicate:
        _require_projection(field.projection_identity(), self.__projection, "bound field")
        return Predicate(
            self.__handle.compare_field(operator, field.native_handle()),
            self.__projection,
        )

    def attribute_label(self) -> str:
        return self.__attribute_label

    def native_handle(self) -> MatchFieldHandle:
        return self.__handle

    def attribute_model(self) -> type[AttributeBase]:
        return self.__attribute_model

    def projection_identity(self) -> PyRuntimeProjection:
        return self.__projection


class _AggregateFactory(_Frozen):
    __slots__ = ()

    def count(self) -> Aggregate:
        return Aggregate("count", None, None, _AGGREGATE_TOKEN)

    def sum(self, field: BoundField) -> Aggregate:
        return self.__field("sum", field)

    def min(self, field: BoundField) -> Aggregate:
        return self.__field("min", field)

    def max(self, field: BoundField) -> Aggregate:
        return self.__field("max", field)

    def mean(self, field: BoundField) -> Aggregate:
        return self.__field("mean", field)

    def median(self, field: BoundField) -> Aggregate:
        return self.__field("median", field)

    def std(self, field: BoundField) -> Aggregate:
        return self.__field("std", field)

    def __field(
        self,
        reducer: Literal["sum", "min", "max", "mean", "median", "std"],
        field: BoundField,
    ) -> Aggregate:
        if type(field) is not BoundField:
            raise TypeError("generated reductions require an exact BoundField")
        return Aggregate(
            reducer,
            field.native_handle(),
            field.projection_identity(),
            _AGGREGATE_TOKEN,
        )


aggregate = _AggregateFactory()


class BoundRole(_Frozen):
    __slots__ = ("__accepted", "__handle", "__projection")
    __accepted: frozenset[str]
    __handle: MatchRoleHandle
    __projection: PyRuntimeProjection

    def __init__(
        self,
        handle: MatchRoleHandle,
        projection: PyRuntimeProjection,
        accepted: frozenset[str],
    ) -> None:
        object.__setattr__(self, "_BoundRole__accepted", accepted)
        object.__setattr__(self, "_BoundRole__handle", handle)
        object.__setattr__(self, "_BoundRole__projection", projection)

    def connects(self, player: BoundVar) -> Predicate:
        _require_projection(player.projection_identity(), self.__projection, "role player")
        if self.__accepted.isdisjoint(player.model_domain_labels()):
            raise TypeError("generated role does not accept this projected player type")
        return Predicate(self.__handle.connects(player.native_handle()), self.__projection)

    def is_(self, player: BoundVar) -> Predicate:
        return self.connects(player)


class BoundVar(_Frozen):
    __slots__ = ("__handle", "__model", "__projection", "__subtypes")
    __handle: MatchBindingHandle
    __model: type[ModelBase]
    __projection: PyRuntimeProjection

    def __init__(
        self,
        handle: MatchBindingHandle,
        model: type[ModelBase],
        projection: PyRuntimeProjection,
        *,
        subtypes: bool,
    ) -> None:
        object.__setattr__(self, "_BoundVar__handle", handle)
        object.__setattr__(self, "_BoundVar__model", model)
        object.__setattr__(self, "_BoundVar__projection", projection)
        object.__setattr__(self, "_BoundVar__subtypes", subtypes)

    @property
    def model(self) -> type[ModelBase]:
        return self.__model

    def field[OwnerT: ModelBase](self, token: FieldToken[OwnerT, AttributeBase]) -> BoundField:
        _require_projection(_exact_projection(token.owner), self.__projection, "field token")
        if token.owner is not self.__model:
            raise TypeError("generated field token owner does not match the bound model")
        identity = token.fact["id"]
        if not _is_object_dict(identity):
            raise TypeError("generated field token identity is invalid")
        owner = identity.get("owner")
        attribute = identity.get("attribute")
        if not _is_object_dict(owner) or not isinstance(attribute, str):
            raise TypeError("generated field token identity is invalid")
        owner_label = owner.get("label")
        if not isinstance(owner_label, str):
            raise TypeError("generated field token owner is invalid")
        return BoundField(
            self.__handle.field_owned_by(owner_label, attribute),
            self.__projection,
            attribute,
            _attribute_model(attribute),
        )

    def role[OwnerT: ModelBase, PlayerT: ModelBase](
        self,
        token: RoleToken[OwnerT, PlayerT, BoundVar],
    ) -> BoundRole:
        _require_projection(_exact_projection(token.owner), self.__projection, "role token")
        if token.owner is not self.__model:
            raise TypeError("generated role token owner does not match the bound model")
        role = token.fact["role"]
        if not _is_object_dict(role):
            raise TypeError("generated role token identity is invalid")
        owner_label = role.get("declaring_relation")
        role_label = role.get("label")
        if not isinstance(owner_label, str) or not isinstance(role_label, str):
            raise TypeError("generated role token identity is invalid")
        accepted_players = token.fact.get("accepted_players")
        if not _is_object_list(accepted_players):
            raise TypeError("generated role token player contract is invalid")
        accepted = frozenset(_type_id_label(player) for player in accepted_players)
        return BoundRole(
            self.__handle.role_owned_by(owner_label, role_label),
            self.__projection,
            accepted,
        )

    def iid(self, iid: str) -> Predicate:
        return Predicate(self.__handle.iid(iid), self.__projection)

    def iid_in(self, iids: Iterable[str]) -> Predicate:
        return Predicate(self.__handle.iid_in(list(iids)), self.__projection)

    def collect(self) -> Collected:
        return Collected(self.__handle.collect(), self.__model, self.__projection)

    def selection_handle(self) -> MatchSelectionHandle:
        return self.__handle.one()

    def native_handle(self) -> MatchBindingHandle:
        return self.__handle

    def projection_identity(self) -> PyRuntimeProjection:
        return self.__projection

    def model_domain_labels(self) -> frozenset[str]:
        if not self.__subtypes:
            return frozenset((_model_label(self.__model),))
        pending = [self.__model]
        labels: set[str] = set()
        while pending:
            candidate = pending.pop()
            if _exact_projection(candidate) is self.__projection:
                labels.add(_model_label(candidate))
            pending.extend(candidate.__subclasses__())
        return frozenset(labels)

    def selected_model(self) -> type[ModelBase]:
        return self.__model

    def is_collection(self) -> bool:
        return False


class SubtypeBoundVar(BoundVar):
    __slots__ = ()


def _require_aggregate_groups(
    candidates: tuple[object, ...],
    projection: PyRuntimeProjection,
    context: str,
) -> BoundVar | BoundField | tuple[BoundField, ...]:
    if not candidates:
        raise TypeError("aggregate grouping requires at least one generated group")
    if len(candidates) > 16:
        raise ValueError("aggregate grouping supports at most sixteen fields")
    if len(candidates) == 1 and isinstance(candidates[0], BoundVar):
        candidate = candidates[0]
        _require_projection(candidate.projection_identity(), projection, context)
        return candidate
    fields: list[BoundField] = []
    for candidate in candidates:
        if not isinstance(candidate, BoundField):
            raise TypeError(
                "aggregate grouping requires one BoundVar or one or more generated BoundFields"
            )
        _require_projection(candidate.projection_identity(), projection, f"{context} field")
        fields.append(candidate)
    if len(fields) == 1:
        return fields[0]
    return tuple(fields)


class Collected(_Frozen):
    __slots__ = ("__handle", "__model", "__projection")
    __handle: MatchSelectionHandle
    __model: type[ModelBase]
    __projection: PyRuntimeProjection

    def __init__(
        self,
        handle: MatchSelectionHandle,
        model: type[ModelBase],
        projection: PyRuntimeProjection,
    ) -> None:
        object.__setattr__(self, "_Collected__handle", handle)
        object.__setattr__(self, "_Collected__model", model)
        object.__setattr__(self, "_Collected__projection", projection)

    def distinct(self, enabled: bool = True) -> Collected:
        return Collected(self.__handle.distinct(enabled), self.__model, self.__projection)

    def order_by(self, order: QueryOrder) -> Collected:
        _require_projection(order.projection_identity(), self.__projection, "selection order")
        return Collected(
            self.__handle.order_by(order.native_handle()),
            self.__model,
            self.__projection,
        )

    def selection_handle(self) -> MatchSelectionHandle:
        return self.__handle

    def projection_identity(self) -> PyRuntimeProjection:
        return self.__projection

    def selected_model(self) -> type[ModelBase]:
        return self.__model

    def is_collection(self) -> bool:
        return True


class Query(_Frozen):
    __slots__ = (
        "__collected",
        "__connection",
        "__declaration",
        "__handle",
        "__names",
        "__projection",
    )
    __collected: tuple[bool, ...]
    __connection: Database | TransactionContext | None
    __declaration: type[object] | None
    __handle: MatchQueryHandle
    __names: tuple[str, ...] | None
    __projection: PyRuntimeProjection

    def __init__(
        self,
        handle: MatchQueryHandle,
        projection: PyRuntimeProjection,
        connection: Database | TransactionContext | None,
        collected: tuple[bool, ...],
        names: tuple[str, ...] | None = None,
        declaration: type[object] | None = None,
    ) -> None:
        object.__setattr__(self, "_Query__handle", handle)
        object.__setattr__(self, "_Query__projection", projection)
        object.__setattr__(self, "_Query__connection", connection)
        object.__setattr__(self, "_Query__collected", collected)
        object.__setattr__(self, "_Query__names", names)
        object.__setattr__(self, "_Query__declaration", declaration)

    def close(self) -> None:
        """Close only this query; persistent ancestors and descendants stay usable."""
        self.__handle.close()

    @property
    def is_closed(self) -> bool:
        return self.__handle.is_closed

    def clone(self) -> Query:
        """Return an independently closable value-equivalent query."""
        return self.__clone(self.__handle.fork())

    def match(self, *bindings: object) -> Query:
        if not bindings:
            raise TypeError("Query.match requires at least one generated binding")
        handle = self.__handle
        for binding in bindings:
            if not isinstance(binding, BoundVar):
                raise TypeError("Query.match requires generated BoundVar values")
            _require_projection(binding.projection_identity(), self.__projection, "query binding")
            handle = handle.add_hidden(binding.native_handle())
        return self.__clone(handle)

    def where(self, *predicates: Predicate) -> Query:
        if not predicates:
            raise TypeError("Query.where requires at least one generated predicate")
        handle = self.__handle
        for predicate in predicates:
            _require_projection(
                predicate.projection_identity(), self.__projection, "query predicate"
            )
            handle = handle.where_predicate(predicate.native_handle())
        return self.__clone(handle)

    def allow_cross_join(
        self,
        left: BoundVar,
        right: BoundVar,
    ) -> Query:
        _require_projection(left.projection_identity(), self.__projection, "cross-join binding")
        _require_projection(right.projection_identity(), self.__projection, "cross-join binding")
        return self.__clone(
            self.__handle.allow_cross_join(left.native_handle(), right.native_handle())
        )

    def one(self) -> object:
        result = self.__fetch(0, 1, "exactly_one", ())
        return self.__materialize_row(result.row(0))

    def first(self, *, order_by: Iterable[QueryOrder] = ()) -> object | None:
        result = self.__fetch(0, 1, "bounded_many", order_by)
        if result.row_count() == 0:
            return None
        return self.__materialize_row(result.row(0))

    def rows(
        self,
        *,
        limit: int,
        offset: int = 0,
        order_by: Iterable[QueryOrder] = (),
    ) -> list[object]:
        result = self.__fetch(offset, limit, "bounded_many", order_by)
        return [self.__materialize_row(result.row(index)) for index in range(result.row_count())]

    def page_by(
        self,
        root: BoundVar,
        *,
        limit: int,
        offset: int = 0,
        order_by: Iterable[QueryOrder] = (),
        include_total: bool = False,
    ) -> Page:
        _require_projection(root.projection_identity(), self.__projection, "query root")
        if type(include_total) is not bool:
            raise TypeError("include_total must be an exact bool")
        offset, limit = _window(offset, limit)
        handles = self.__order_handles(order_by)
        transaction = rust_transaction_for(self.__direct_connection())
        if transaction is not None:
            result = self.__handle.execute_page_by_borrowed(
                transaction,
                root.native_handle(),
                handles,
                offset,
                limit,
                include_total,
            )
        else:
            result = self.__handle.execute_page_by_owned(
                rust_database_for(self.__direct_connection()),
                root.native_handle(),
                handles,
                offset,
                limit,
                include_total,
            )
        return self.__materialize_page(result)

    def count_by(self, root: BoundVar) -> int:
        result = self.__root_result(root, count=True)
        return result.count_value()

    def exists_by(self, root: BoundVar) -> bool:
        result = self.__root_result(root, count=False)
        return result.exists_value()

    def aggregate(self, root: BoundVar, *terms: Aggregate) -> tuple[object, ...]:
        result = self.reduction_result(root, None, terms)
        materialized = self.__materialize_reduction(result, len(terms), group=None)
        if not _is_object_tuple(materialized):
            raise RuntimeError("validated aggregate returned an invalid result")
        return materialized

    def group_by(self, root: BoundVar, *groups: BoundVar | BoundField) -> GroupedQuery:
        self.__require_root(root, "aggregate root")
        return GroupedQuery(
            self.clone(),
            root,
            _require_aggregate_groups(groups, self.__projection, "aggregate group"),
        )

    def __root_result(
        self,
        root: BoundVar,
        *,
        count: bool,
    ) -> ValidatedMatchResultHandle:
        _require_projection(root.projection_identity(), self.__projection, "query root")
        connection = self.__direct_connection()
        transaction = rust_transaction_for(connection)
        if count:
            if transaction is not None:
                return self.__handle.execute_count_by_borrowed(transaction, root.native_handle())
            return self.__handle.execute_count_by_owned(
                rust_database_for(connection), root.native_handle()
            )
        if transaction is not None:
            return self.__handle.execute_exists_by_borrowed(transaction, root.native_handle())
        return self.__handle.execute_exists_by_owned(
            rust_database_for(connection), root.native_handle()
        )

    def reduction_result(
        self,
        root: BoundVar,
        group: BoundVar | BoundField | tuple[BoundField, ...] | None,
        terms: tuple[Aggregate, ...],
    ) -> ValidatedMatchResultHandle:
        self.__require_root(root, "aggregate root")
        if isinstance(group, BoundVar):
            self.__require_root(group, "aggregate group")
        elif isinstance(group, BoundField):
            _require_projection(
                group.projection_identity(), self.__projection, "aggregate group field"
            )
        elif isinstance(group, tuple):
            for field in group:
                _require_projection(
                    field.projection_identity(), self.__projection, "aggregate group field"
                )
        reducers, inputs = _prepare_aggregate_terms(terms, self.__projection)
        connection = self.__direct_connection()
        transaction = rust_transaction_for(connection)
        if isinstance(group, tuple):
            handles = [field.native_handle() for field in group]
            if transaction is not None:
                return self.__handle.execute_reduce_by_fields_borrowed(
                    transaction,
                    root.native_handle(),
                    handles,
                    reducers,
                    inputs,
                )
            return self.__handle.execute_reduce_by_fields_owned(
                rust_database_for(connection),
                root.native_handle(),
                handles,
                reducers,
                inputs,
            )
        if isinstance(group, BoundField):
            if transaction is not None:
                return self.__handle.execute_reduce_by_field_borrowed(
                    transaction,
                    root.native_handle(),
                    group.native_handle(),
                    reducers,
                    inputs,
                )
            return self.__handle.execute_reduce_by_field_owned(
                rust_database_for(connection),
                root.native_handle(),
                group.native_handle(),
                reducers,
                inputs,
            )
        if transaction is not None:
            return self.__handle.execute_reduce_by_borrowed(
                transaction,
                root.native_handle(),
                None if group is None else group.native_handle(),
                reducers,
                inputs,
            )
        return self.__handle.execute_reduce_by_owned(
            rust_database_for(connection),
            root.native_handle(),
            None if group is None else group.native_handle(),
            reducers,
            inputs,
        )

    def __materialize_reduction(
        self,
        result: ValidatedMatchResultHandle,
        term_count: int,
        *,
        group: BoundVar | BoundField | tuple[BoundField, ...] | None,
    ) -> object:
        rows: list[object] = []
        for row_index in range(result.reduction_row_count()):
            if result.reduction_value_count(row_index) != term_count:
                raise RuntimeError("validated aggregate result changed its term count")
            values = tuple(
                result.reduction_value(row_index, value_index) for value_index in range(term_count)
            )
            if isinstance(group, BoundVar):
                rows.append(
                    (
                        self.__projection.hydrate_thing(result.reduction_group(row_index)),
                        values,
                    )
                )
            elif isinstance(group, BoundField):
                rows.append(
                    (
                        group.attribute_model()._from_validated_query_value(
                            result.reduction_group_value(row_index)
                        ),
                        values,
                    )
                )
            elif isinstance(group, tuple):
                group_values = result.reduction_group_values(row_index)
                if len(group_values) != len(group):
                    raise RuntimeError("validated aggregate result changed its group arity")
                rows.append(
                    (
                        tuple(
                            field.attribute_model()._from_validated_query_value(value)
                            for field, value in zip(group, group_values, strict=True)
                        ),
                        values,
                    )
                )
            else:
                rows.append(values)
        if group is not None:
            return tuple(rows)
        if len(rows) != 1:
            raise RuntimeError("validated ungrouped aggregate did not return exactly one row")
        return rows[0]

    def __require_root(self, root: BoundVar, context: str) -> None:
        _require_projection(root.projection_identity(), self.__projection, context)

    def __fetch(
        self,
        offset: int,
        limit: int,
        cardinality: str,
        order_by: Iterable[QueryOrder],
    ) -> ValidatedMatchResultHandle:
        offset, limit = _window(offset, limit)
        handles = self.__order_handles(order_by)
        connection = self.__direct_connection()
        transaction = rust_transaction_for(connection)
        if transaction is not None:
            return self.__handle.execute_fetch_rows_borrowed(
                transaction,
                handles,
                offset,
                limit,
                cardinality,
            )
        return self.__handle.execute_fetch_rows_owned(
            rust_database_for(connection),
            handles,
            offset,
            limit,
            cardinality,
        )

    def __materialize_row(self, row: ValidatedMatchRowHandle) -> object:
        if row.slot_count() != len(self.__collected):
            raise RuntimeError("validated query result shape differs from its generated selection")
        values: list[object] = []
        for index, collected in enumerate(self.__collected):
            slot = row.slot(index)
            if slot.is_collection() is not collected:
                raise RuntimeError(
                    "validated query slot collection shape differs from its selection"
                )
            if collected:
                values.append(
                    tuple(
                        self.__projection.hydrate_thing(slot.thing(item))
                        for item in range(slot.thing_count())
                    )
                )
            else:
                if slot.thing_count() != 1:
                    raise RuntimeError("validated singular query slot has invalid cardinality")
                values.append(self.__projection.hydrate_thing(slot.thing(0)))
        if self.__declaration is None:
            if self.__names is not None or any(
                row.slot(index).name() is not None for index in range(row.slot_count())
            ):
                raise RuntimeError("positional generated query received named result slots")
            return values[0] if len(values) == 1 else tuple(values)
        if self.__names is None:
            raise RuntimeError("generated named query lost its declared field names")
        actual_names = tuple(row.slot(index).name() for index in range(row.slot_count()))
        if actual_names != self.__names:
            raise RuntimeError("generated named result differs from its declaration")
        try:
            result = self.__declaration(**dict(zip(self.__names, values, strict=True)))
        except Exception as error:
            raise RuntimeError("failed to construct generated named query row") from error
        if type(result) is not self.__declaration:
            raise RuntimeError("generated named query constructor substituted its row type")
        return result

    def __materialize_page(self, result: ValidatedMatchResultHandle) -> Page:
        return Page(
            (
                self.__materialize_row(result.page_entry(index))
                for index in range(result.page_entry_count())
            ),
            offset=result.page_offset(),
            limit=result.page_limit(),
            total=result.page_total(),
        )

    def __order_handles(self, order_by: Iterable[object]) -> list[MatchOrderHandle]:
        handles: list[MatchOrderHandle] = []
        for order in order_by:
            if not isinstance(order, QueryOrder):
                raise TypeError("order_by entries must be generated QueryOrder values")
            _require_projection(order.projection_identity(), self.__projection, "query order")
            handles.append(order.native_handle())
        return handles

    def __direct_connection(self) -> Database | TransactionContext:
        if self.__connection is None:
            raise RuntimeError("direct generated query requires a Database or TransactionContext")
        return self.__connection

    def __clone(self, handle: MatchQueryHandle) -> Query:
        return Query(
            handle,
            self.__projection,
            self.__connection,
            self.__collected,
            self.__names,
            self.__declaration,
        )

    def native_handle(self) -> MatchQueryHandle:
        return self.__handle

    def projection_identity(self) -> PyRuntimeProjection:
        return self.__projection

    def materialize_row(self, row: ValidatedMatchRowHandle) -> object:
        return self.__materialize_row(row)

    def materialize_page(self, result: ValidatedMatchResultHandle) -> Page:
        return self.__materialize_page(result)

    def materialize_reduction(
        self,
        result: ValidatedMatchResultHandle,
        term_count: int,
        *,
        group: BoundVar | BoundField | tuple[BoundField, ...] | None,
    ) -> object:
        return self.__materialize_reduction(result, term_count, group=group)

    def order_handles(self, order_by: Iterable[object]) -> list[MatchOrderHandle]:
        return self.__order_handles(order_by)


class GroupedQuery(_Frozen):
    __slots__ = ("__group", "__query", "__root")
    __group: BoundVar | BoundField | tuple[BoundField, ...]
    __query: Query
    __root: BoundVar

    def __init__(
        self,
        query: Query,
        root: BoundVar,
        group: BoundVar | BoundField | tuple[BoundField, ...],
    ) -> None:
        object.__setattr__(self, "_GroupedQuery__query", query)
        object.__setattr__(self, "_GroupedQuery__root", root)
        object.__setattr__(self, "_GroupedQuery__group", group)

    def close(self) -> None:
        self.__query.close()

    @property
    def is_closed(self) -> bool:
        return self.__query.is_closed

    def match(self, *bindings: BoundVar) -> GroupedQuery:
        return GroupedQuery(self.__query.match(*bindings), self.__root, self.__group)

    def where(self, *predicates: Predicate) -> GroupedQuery:
        return GroupedQuery(self.__query.where(*predicates), self.__root, self.__group)

    def allow_cross_join(self, left: BoundVar, right: BoundVar) -> GroupedQuery:
        return GroupedQuery(
            self.__query.allow_cross_join(left, right),
            self.__root,
            self.__group,
        )

    def aggregate(self, *terms: Aggregate) -> tuple[tuple[object, tuple[object, ...]], ...]:
        result = self.__query.reduction_result(self.__root, self.__group, terms)
        materialized = self.__query.materialize_reduction(result, len(terms), group=self.__group)
        if not _is_grouped_reduction(materialized):
            raise RuntimeError("validated grouped aggregate returned an invalid result")
        return materialized


class _Selection(Protocol):
    def selection_handle(self) -> MatchSelectionHandle: ...
    def projection_identity(self) -> PyRuntimeProjection: ...
    def selected_model(self) -> type[ModelBase]: ...
    def is_collection(self) -> bool: ...


class QuerySession(_Frozen):
    __slots__ = ("__connection", "__handle", "__projection")
    __connection: Database | TransactionContext | None
    __handle: MatchSessionHandle
    __projection: PyRuntimeProjection

    def __init__(
        self,
        projection: PyRuntimeProjection,
        connection: Database | TransactionContext,
        *,
        resources: QueryExecutionResourceLimits | None = None,
        cancellation: QueryCancellation | None = None,
    ) -> None:
        if not _is_connection(connection):
            raise TypeError("generated QuerySession requires a Database or TransactionContext")
        use_legacy_defaults = resources is None and cancellation is None
        effective_resources = QueryExecutionResourceLimits() if resources is None else resources
        effective_cancellation = QueryCancellation() if cancellation is None else cancellation
        if type(effective_resources) is not QueryExecutionResourceLimits:
            raise TypeError("generated query resources must be QueryExecutionResourceLimits")
        if type(effective_cancellation) is not QueryCancellation:
            raise TypeError("generated query cancellation must be QueryCancellation")
        object.__setattr__(self, "_QuerySession__projection", projection)
        object.__setattr__(self, "_QuerySession__connection", connection)
        handle = (
            projection.match_session()
            if use_legacy_defaults
            else projection.match_session_with_resources(
                effective_resources, effective_cancellation
            )
        )
        object.__setattr__(self, "_QuerySession__handle", handle)

    def close(self) -> None:
        """Close this authoring session and invalidate its descendant terminals."""
        self.__handle.close()

    @property
    def is_closed(self) -> bool:
        return self.__handle.is_closed

    @classmethod
    def remote_factory(
        cls,
        projection: PyRuntimeProjection,
        resources: QueryExecutionResourceLimits | None = None,
        cancellation: QueryCancellation | None = None,
    ) -> QuerySession:
        session = cls.__new__(cls)
        object.__setattr__(session, "_QuerySession__projection", projection)
        object.__setattr__(session, "_QuerySession__connection", None)
        use_legacy_defaults = resources is None and cancellation is None
        effective_resources = QueryExecutionResourceLimits() if resources is None else resources
        effective_cancellation = QueryCancellation() if cancellation is None else cancellation
        handle = (
            projection.match_session()
            if use_legacy_defaults
            else (
                projection.match_session_with_resources(effective_resources, effective_cancellation)
            )
        )
        object.__setattr__(session, "_QuerySession__handle", handle)
        return session

    def var(self, model: type[ModelBase], *, subtypes: bool = False) -> BoundVar:
        if type(subtypes) is not bool:
            raise TypeError("subtypes must be an exact bool")
        return self.__bind(model, subtypes=subtypes)

    def exact(self, model: type[ModelBase]) -> BoundVar:
        return self.var(model)

    def subtypes(self, model: type[ModelBase]) -> BoundVar:
        return self.var(model, subtypes=True)

    def _function_input[DomainT](
        self, value: object, domain: type[DomainT]
    ) -> FunctionInput[DomainT]:
        if not isinstance(value, AttributeBase):
            raise TypeError("schema-function inputs require projected attribute values")
        del domain
        _require_projection(_exact_projection(type(value)), self.__projection, "function input")
        return FunctionInput(
            self.__handle.function_value(type(value).__type_id__, _dynamic_value(value)),
            self.__projection,
        )

    def _call_function[DomainT](
        self,
        function: FunctionRef[..., object],
        arguments: tuple[object, ...],
        domain: type[DomainT],
    ) -> FunctionCall[DomainT]:
        del domain
        function_id, _signature = function_identity_for_query(function)
        native_arguments: list[MatchFunctionArgumentHandle] = []
        for argument in arguments:
            if isinstance(argument, BoundVar):
                _require_projection(
                    argument.projection_identity(), self.__projection, "function binding"
                )
                native_arguments.append(argument.native_handle().function_argument())
            elif type(argument) is FunctionInput:
                _require_projection(
                    argument.projection_identity(), self.__projection, "function input"
                )
                native_arguments.append(argument.native_argument())
            elif type(argument) is FunctionCall:
                _require_projection(
                    argument.projection_identity(), self.__projection, "function call"
                )
                native_arguments.append(argument.native_argument())
            else:
                raise TypeError("invalid generated schema-function argument")
        handle = self.__handle.function_by_id(function_id).call(native_arguments)
        return FunctionCall(handle, self.__projection)

    def reachable(
        self,
        source: object,
        target: object,
        relation: object,
        role_from: object,
        role_to: object,
        *,
        min_depth: int,
        max_depth: int,
    ) -> Predicate:
        if not isinstance(source, BoundVar) or not isinstance(target, BoundVar):
            raise TypeError("generated reachable endpoints must be BoundVar values")
        if not isinstance(relation, type) or not issubclass(relation, RelationBase):
            raise TypeError("generated reachable relation must be a relation model")
        _require_projection(source.projection_identity(), self.__projection, "reachable source")
        _require_projection(target.projection_identity(), self.__projection, "reachable target")
        _require_projection(_exact_projection(relation), self.__projection, "reachable relation")
        from_role = _reachable_role(
            role_from,
            relation,
            source,
            self.__projection,
            "role_from",
        )
        to_role = _reachable_role(
            role_to,
            relation,
            target,
            self.__projection,
            "role_to",
        )
        return Predicate(
            self.__handle.reachable(
                _model_label(relation),
                from_role,
                to_role,
                source.native_handle(),
                target.native_handle(),
                _depth(min_depth, "min_depth"),
                _depth(max_depth, "max_depth"),
            ),
            self.__projection,
        )

    def query(self, *selections: _Selection) -> Query:
        if not selections:
            raise TypeError("QuerySession.query requires at least one generated selection")
        if len(selections) > 16:
            raise ValueError("QuerySession.query supports at most sixteen generated selections")
        handles: list[MatchSelectionHandle] = []
        collected: list[bool] = []
        for selection in selections:
            if not isinstance(selection, (BoundVar, Collected)):
                raise TypeError("generated selections must be BoundVar or Collected values")
            _require_projection(
                selection.projection_identity(), self.__projection, "query selection"
            )
            handles.append(selection.selection_handle())
            collected.append(isinstance(selection, Collected))
        shape = self.__handle.positional(handles)
        return Query(
            self.__handle.query(shape),
            self.__projection,
            self.__connection,
            tuple(collected),
        )

    def query_as(
        self,
        declaration: type[object],
        /,
        **selections: _Selection,
    ) -> Query:
        declared = _named_declaration(declaration, self.__projection)
        names = tuple(name for name, _, _ in declared)
        if tuple(selections) != names:
            raise TypeError("query_as selections must exactly match declaration fields")
        handles: list[MatchSelectionHandle] = []
        collected: list[bool] = []
        native_declarations: list[tuple[str, str, bool]] = []
        for (name, model, is_collection), selection in zip(
            declared,
            selections.values(),
            strict=True,
        ):
            if not isinstance(selection, (BoundVar, Collected)):
                raise TypeError("query_as values must be generated selections")
            _require_projection(
                selection.projection_identity(),
                self.__projection,
                "named query selection",
            )
            if selection.is_collection() is not is_collection:
                raise TypeError(f"query_as field {name!r} collection shape differs")
            if selection.selected_model() is not model:
                raise TypeError(f"query_as field {name!r} model type differs")
            handles.append(selection.selection_handle())
            collected.append(is_collection)
            native_declarations.append((name, _model_label(model), is_collection))
        shape = self.__handle.named_checked(native_declarations, list(names), handles)
        return Query(
            self.__handle.query(shape),
            self.__projection,
            self.__connection,
            tuple(collected),
            names,
            declaration,
        )

    def __bind(
        self,
        model: type[ModelBase],
        *,
        subtypes: bool,
    ) -> BoundVar:
        _require_projection(_exact_projection(model), self.__projection, "query model")
        if not issubclass(model, (EntityBase, RelationBase)):
            raise TypeError("generated query variables require an entity or relation model")
        label = _model_label(model)
        handle = self.__handle.subtypes(label) if subtypes else self.__handle.exact(label)
        binding = SubtypeBoundVar if subtypes else BoundVar
        return binding(handle, model, self.__projection, subtypes=subtypes)


class RemoteQueryLimits(_Frozen):
    __slots__ = (
        "__deadline_ms",
        "__max_attribute_values",
        "__max_bytes",
        "__max_collection_members",
        "__max_graph_nodes",
        "__max_items",
        "__max_role_players",
    )

    def __init__(
        self,
        *,
        max_items: int,
        max_bytes: int,
        max_collection_members: int,
        max_graph_nodes: int,
        max_attribute_values: int,
        max_role_players: int,
        deadline_ms: int | None = None,
    ) -> None:
        object.__setattr__(self, "_RemoteQueryLimits__max_items", max_items)
        object.__setattr__(self, "_RemoteQueryLimits__max_bytes", max_bytes)
        object.__setattr__(
            self,
            "_RemoteQueryLimits__max_collection_members",
            max_collection_members,
        )
        object.__setattr__(self, "_RemoteQueryLimits__max_graph_nodes", max_graph_nodes)
        object.__setattr__(
            self,
            "_RemoteQueryLimits__max_attribute_values",
            max_attribute_values,
        )
        object.__setattr__(self, "_RemoteQueryLimits__max_role_players", max_role_players)
        object.__setattr__(self, "_RemoteQueryLimits__deadline_ms", deadline_ms)

    @property
    def max_items(self) -> int:
        return self.__max_items

    @property
    def max_bytes(self) -> int:
        return self.__max_bytes

    @property
    def max_collection_members(self) -> int:
        return self.__max_collection_members

    @property
    def max_graph_nodes(self) -> int:
        return self.__max_graph_nodes

    @property
    def max_attribute_values(self) -> int:
        return self.__max_attribute_values

    @property
    def max_role_players(self) -> int:
        return self.__max_role_players

    @property
    def deadline_ms(self) -> int | None:
        return self.__deadline_ms


class RemoteQuery(_Frozen):
    __slots__ = ("__cancellation", "__context", "__exchange", "__query")
    __cancellation: QueryCancellation
    __context: RemoteModelQueryContext
    __exchange: Callable[[bytes], Awaitable[bytes]]
    __query: Query

    def __init__(
        self,
        query: Query,
        context: RemoteModelQueryContext,
        exchange: Callable[[bytes], Awaitable[bytes]],
        cancellation: QueryCancellation,
    ) -> None:
        object.__setattr__(self, "_RemoteQuery__query", query)
        object.__setattr__(self, "_RemoteQuery__context", context)
        object.__setattr__(self, "_RemoteQuery__exchange", exchange)
        object.__setattr__(self, "_RemoteQuery__cancellation", cancellation)

    def close(self) -> None:
        self.__query.close()

    @property
    def is_closed(self) -> bool:
        return self.__query.is_closed

    def clone(self) -> RemoteQuery:
        return RemoteQuery(
            self.__query.clone(),
            self.__context,
            self.__exchange,
            self.__cancellation,
        )

    def match(self, *bindings: BoundVar) -> RemoteQuery:
        return RemoteQuery(
            self.__query.match(*bindings),
            self.__context,
            self.__exchange,
            self.__cancellation,
        )

    def where(self, *predicates: Predicate) -> RemoteQuery:
        return RemoteQuery(
            self.__query.where(*predicates),
            self.__context,
            self.__exchange,
            self.__cancellation,
        )

    def allow_cross_join(self, left: BoundVar, right: BoundVar) -> RemoteQuery:
        return RemoteQuery(
            self.__query.allow_cross_join(left, right),
            self.__context,
            self.__exchange,
            self.__cancellation,
        )

    async def one(self) -> object:
        pending = query_v2_prepare_remote_model_rows(
            self.__query.native_handle(),
            self.__context,
            [],
            0,
            1,
            "exactly_one",
        )
        result = await self.__execute(pending)
        if result.row_count() != 1:
            raise RuntimeError("validated remote exactly-one result did not contain one row")
        return self.__query.materialize_row(result.row(0))

    async def first(self, *, order_by: Iterable[QueryOrder] = ()) -> object | None:
        pending = query_v2_prepare_remote_model_rows(
            self.__query.native_handle(),
            self.__context,
            self.__query.order_handles(order_by),
            0,
            1,
            "bounded_many",
        )
        result = await self.__execute(pending)
        if result.row_count() == 0:
            return None
        return self.__query.materialize_row(result.row(0))

    async def rows(
        self,
        *,
        limit: int,
        offset: int = 0,
        order_by: Iterable[QueryOrder] = (),
    ) -> list[object]:
        offset, limit = _window(offset, limit)
        pending = query_v2_prepare_remote_model_rows(
            self.__query.native_handle(),
            self.__context,
            self.__query.order_handles(order_by),
            offset,
            limit,
            "bounded_many",
        )
        result = await self.__execute(pending)
        return [
            self.__query.materialize_row(result.row(index)) for index in range(result.row_count())
        ]

    async def page_by(
        self,
        root: BoundVar,
        *,
        limit: int,
        offset: int = 0,
        order_by: Iterable[QueryOrder] = (),
        include_total: bool = False,
    ) -> Page:
        _require_projection(
            root.projection_identity(),
            self.__query.projection_identity(),
            "remote query root",
        )
        if type(include_total) is not bool:
            raise TypeError("include_total must be an exact bool")
        offset, limit = _window(offset, limit)
        pending = query_v2_prepare_remote_model_page(
            self.__query.native_handle(),
            self.__context,
            root.native_handle(),
            self.__query.order_handles(order_by),
            offset,
            limit,
            include_total,
        )
        return self.__query.materialize_page(await self.__execute(pending))

    async def count_by(self, root: BoundVar) -> int:
        self.__require_root(root)
        pending = query_v2_prepare_remote_model_count(
            self.__query.native_handle(),
            self.__context,
            root.native_handle(),
        )
        return (await self.__execute(pending)).count_value()

    async def exists_by(self, root: BoundVar) -> bool:
        self.__require_root(root)
        pending = query_v2_prepare_remote_model_exists(
            self.__query.native_handle(),
            self.__context,
            root.native_handle(),
        )
        return (await self.__execute(pending)).exists_value()

    async def aggregate(self, root: BoundVar, *terms: Aggregate) -> tuple[object, ...]:
        result = await self.reduction_result(root, None, terms)
        materialized = self.__query.materialize_reduction(result, len(terms), group=None)
        if not _is_object_tuple(materialized):
            raise RuntimeError("validated remote aggregate returned an invalid result")
        return materialized

    def group_by(self, root: BoundVar, *groups: BoundVar | BoundField) -> RemoteGroupedQuery:
        self.__require_root(root, "remote aggregate root")
        return RemoteGroupedQuery(
            self.clone(),
            root,
            _require_aggregate_groups(
                groups,
                self.__query.projection_identity(),
                "remote aggregate group",
            ),
        )

    def __require_root(self, root: BoundVar, context: str = "remote query root") -> None:
        _require_projection(
            root.projection_identity(),
            self.__query.projection_identity(),
            context,
        )

    async def reduction_result(
        self,
        root: BoundVar,
        group: BoundVar | BoundField | tuple[BoundField, ...] | None,
        terms: tuple[Aggregate, ...],
    ) -> ValidatedMatchResultHandle:
        self.__require_root(root, "remote aggregate root")
        if isinstance(group, BoundVar):
            self.__require_root(group, "remote aggregate group")
        elif isinstance(group, BoundField):
            _require_projection(
                group.projection_identity(),
                self.__query.projection_identity(),
                "remote aggregate group field",
            )
        elif isinstance(group, tuple):
            for field in group:
                _require_projection(
                    field.projection_identity(),
                    self.__query.projection_identity(),
                    "remote aggregate group field",
                )
        reducers, inputs = _prepare_aggregate_terms(
            terms,
            self.__query.projection_identity(),
        )
        if isinstance(group, tuple):
            pending = query_v2_prepare_remote_model_reduce_by_fields(
                self.__query.native_handle(),
                self.__context,
                root.native_handle(),
                [field.native_handle() for field in group],
                reducers,
                inputs,
            )
        elif isinstance(group, BoundField):
            pending = query_v2_prepare_remote_model_reduce_by_field(
                self.__query.native_handle(),
                self.__context,
                root.native_handle(),
                group.native_handle(),
                reducers,
                inputs,
            )
        else:
            pending = query_v2_prepare_remote_model_reduce(
                self.__query.native_handle(),
                self.__context,
                root.native_handle(),
                None if group is None else group.native_handle(),
                reducers,
                inputs,
            )
        return await self.__execute(pending)

    def materialize_reduction(
        self,
        result: ValidatedMatchResultHandle,
        term_count: int,
        *,
        group: BoundVar | BoundField | tuple[BoundField, ...] | None,
    ) -> object:
        return self.__query.materialize_reduction(result, term_count, group=group)

    async def __execute(
        self,
        pending: PendingRemoteModelQuery,
    ) -> ValidatedMatchResultHandle:
        request = pending.request_bytes()
        if self.__cancellation.is_cancelled:
            # Claim through the neutral one-shot authority after cancellation
            # so the canonical diagnostic wins and this request is consumed.
            return pending.decode_reply(b"")

        exchange_task = asyncio.ensure_future(self.__exchange(request))
        cancellation_task = asyncio.create_task(_wait_for_query_cancellation(self.__cancellation))
        await asyncio.wait(
            (exchange_task, cancellation_task),
            return_when=asyncio.FIRST_COMPLETED,
        )
        if self.__cancellation.is_cancelled:
            exchange_task.cancel()
            exchange_task.add_done_callback(_consume_remote_exchange_task)
            return pending.decode_reply(b"")

        cancellation_task.cancel()
        cancellation_task.add_done_callback(_consume_remote_exchange_task)
        response = await exchange_task
        if type(response) is not bytes:
            raise TypeError("generated remote query exchange must return exact bytes")
        return pending.decode_reply(response)


class RemoteGroupedQuery(_Frozen):
    __slots__ = ("__group", "__query", "__root")
    __group: BoundVar | BoundField | tuple[BoundField, ...]
    __query: RemoteQuery
    __root: BoundVar

    def __init__(
        self,
        query: RemoteQuery,
        root: BoundVar,
        group: BoundVar | BoundField | tuple[BoundField, ...],
    ) -> None:
        object.__setattr__(self, "_RemoteGroupedQuery__query", query)
        object.__setattr__(self, "_RemoteGroupedQuery__root", root)
        object.__setattr__(self, "_RemoteGroupedQuery__group", group)

    def close(self) -> None:
        self.__query.close()

    @property
    def is_closed(self) -> bool:
        return self.__query.is_closed

    def match(self, *bindings: BoundVar) -> RemoteGroupedQuery:
        return RemoteGroupedQuery(self.__query.match(*bindings), self.__root, self.__group)

    def where(self, *predicates: Predicate) -> RemoteGroupedQuery:
        return RemoteGroupedQuery(self.__query.where(*predicates), self.__root, self.__group)

    def allow_cross_join(self, left: BoundVar, right: BoundVar) -> RemoteGroupedQuery:
        return RemoteGroupedQuery(
            self.__query.allow_cross_join(left, right),
            self.__root,
            self.__group,
        )

    async def aggregate(
        self,
        *terms: Aggregate,
    ) -> tuple[tuple[object, tuple[object, ...]], ...]:
        result = await self.__query.reduction_result(self.__root, self.__group, terms)
        materialized = self.__query.materialize_reduction(
            result,
            len(terms),
            group=self.__group,
        )
        if not _is_grouped_reduction(materialized):
            raise RuntimeError("validated remote grouped aggregate returned an invalid result")
        return materialized


class RemoteQuerySession(_Frozen):
    __slots__ = ("__cancellation", "__context", "__direct", "__exchange")
    __cancellation: QueryCancellation
    __context: RemoteModelQueryContext
    __direct: QuerySession
    __exchange: Callable[[bytes], Awaitable[bytes]]

    def __init__(
        self,
        advertisement: object,
        exchange: object,
        limits: object,
        *,
        cancellation: QueryCancellation | None = None,
    ) -> None:
        if type(advertisement) is not bytes:
            raise TypeError("generated remote advertisement must be exact bytes")
        if not _is_exchange(exchange):
            raise TypeError("generated remote exchange must be callable")
        legacy_limits = (
            limits
            if isinstance(limits, RemoteQueryLimits) and type(limits) is RemoteQueryLimits
            else None
        )
        use_legacy_defaults = legacy_limits is not None and cancellation is None
        if cancellation is None:
            cancellation = QueryCancellation()
        if type(cancellation) is not QueryCancellation:
            raise TypeError("generated query cancellation must be QueryCancellation")
        if legacy_limits is not None:
            resources = QueryExecutionResourceLimits(
                timeout_milliseconds=(
                    30_000 if legacy_limits.deadline_ms is None else legacy_limits.deadline_ms
                ),
                items=legacy_limits.max_items,
                bytes=legacy_limits.max_bytes,
                graph_nodes=legacy_limits.max_graph_nodes,
                attribute_values=legacy_limits.max_attribute_values,
                collection_members=legacy_limits.max_collection_members,
                role_players=legacy_limits.max_role_players,
            )
        elif (
            isinstance(limits, QueryExecutionResourceLimits)
            and type(limits) is QueryExecutionResourceLimits
        ):
            resources = limits
        else:
            raise TypeError(
                "generated remote limits must be RemoteQueryLimits or QueryExecutionResourceLimits"
            )
        if use_legacy_defaults:
            if legacy_limits is None:
                raise RuntimeError("legacy remote limit state is inconsistent")
            context = query_v2_remote_model_context(
                _installed_query_authority(),
                advertisement,
                legacy_limits.max_items,
                legacy_limits.max_bytes,
                legacy_limits.max_collection_members,
                legacy_limits.max_graph_nodes,
                legacy_limits.max_attribute_values,
                legacy_limits.max_role_players,
                legacy_limits.deadline_ms,
            )
        else:
            context = query_v2_remote_model_context_with_resources(
                _installed_query_authority(), advertisement, resources, cancellation
            )
        object.__setattr__(self, "_RemoteQuerySession__context", context)
        object.__setattr__(self, "_RemoteQuerySession__exchange", exchange)
        object.__setattr__(self, "_RemoteQuerySession__cancellation", cancellation)
        object.__setattr__(
            self,
            "_RemoteQuerySession__direct",
            QuerySession.remote_factory(
                _installed_projection(),
                None if use_legacy_defaults else resources,
                None if use_legacy_defaults else cancellation,
            ),
        )

    def close(self) -> None:
        self.__direct.close()

    @property
    def is_closed(self) -> bool:
        return self.__direct.is_closed

    def var(self, model: type[ModelBase], *, subtypes: bool = False) -> BoundVar:
        return self.__direct.var(model, subtypes=subtypes)

    def exact(self, model: type[ModelBase]) -> BoundVar:
        return self.__direct.exact(model)

    def subtypes(self, model: type[ModelBase]) -> BoundVar:
        return self.__direct.subtypes(model)

    def _function_input[DomainT](
        self, value: object, domain: type[DomainT]
    ) -> FunctionInput[DomainT]:
        return self.__direct._function_input(  # pyright: ignore[reportPrivateUsage]
            value, domain
        )

    def _call_function[DomainT](
        self,
        function: FunctionRef[..., object],
        arguments: tuple[object, ...],
        domain: type[DomainT],
    ) -> FunctionCall[DomainT]:
        return self.__direct._call_function(  # pyright: ignore[reportPrivateUsage]
            function, arguments, domain
        )

    def reachable(
        self,
        source: object,
        target: object,
        relation: object,
        role_from: object,
        role_to: object,
        *,
        min_depth: int,
        max_depth: int,
    ) -> Predicate:
        return self.__direct.reachable(
            source,
            target,
            relation,
            role_from,
            role_to,
            min_depth=min_depth,
            max_depth=max_depth,
        )

    def query(self, *selections: _Selection) -> RemoteQuery:
        return RemoteQuery(
            self.__direct.query(*selections),
            self.__context,
            self.__exchange,
            self.__cancellation,
        )

    def query_as(
        self,
        declaration: type[object],
        /,
        **selections: _Selection,
    ) -> RemoteQuery:
        return RemoteQuery(
            self.__direct.query_as(declaration, **selections),
            self.__context,
            self.__exchange,
            self.__cancellation,
        )


def _require_projection(
    actual: PyRuntimeProjection,
    expected: PyRuntimeProjection,
    kind: str,
) -> None:
    if actual is not expected:
        raise TypeError(f"generated {kind} must belong to the same installed package")


def _depth(value: int, name: str) -> int:
    if type(value) is not int:
        raise TypeError(f"{name} must be an exact int")
    if not 0 <= value <= 255:
        raise ValueError(f"{name} must be between zero and 255")
    return value


def _reachable_role(
    token: object,
    relation: type[RelationBase],
    endpoint: BoundVar,
    projection: PyRuntimeProjection,
    name: str,
) -> str:
    if not _is_role_token(token) or token.owner is not relation:
        raise TypeError(f"generated reachable {name} must belong to the relation")
    _require_projection(_exact_projection(token.owner), projection, f"reachable {name}")
    role = token.fact.get("role")
    accepted_players = token.fact.get("accepted_players")
    if not _is_object_dict(role) or not _is_object_list(accepted_players):
        raise TypeError(f"generated reachable {name} contract is invalid")
    accepted = frozenset(_type_id_label(player) for player in accepted_players)
    if accepted.isdisjoint(endpoint.model_domain_labels()):
        raise TypeError(f"generated reachable {name} does not accept its endpoint")
    role_label = role.get("label")
    if not isinstance(role_label, str):
        raise TypeError(f"generated reachable {name} identity is invalid")
    return role_label


def _named_declaration(
    declaration: type[object],
    projection: PyRuntimeProjection,
) -> tuple[tuple[str, type[ModelBase], bool], ...]:
    names = _declaration_names(declaration, require_frozen=True)
    try:
        raw_annotations: object = get_type_hints(declaration, include_extras=True)
    except (NameError, TypeError) as error:
        raise TypeError("query_as annotations must resolve exactly") from error
    if not _is_object_dict(raw_annotations) or tuple(raw_annotations) != names:
        raise TypeError("query_as requires one exact annotation per field")
    normalized: list[tuple[str, type[ModelBase], bool]] = []
    for name in names:
        annotation = raw_annotations[name]
        if get_origin(annotation) is tuple:
            raw_arguments: object = get_args(annotation)
            if (
                not _is_object_tuple(raw_arguments)
                or len(raw_arguments) != 2
                or raw_arguments[1] is not Ellipsis
            ):
                raise TypeError(f"query_as field {name!r} has invalid collection type")
            model = raw_arguments[0]
            collection = True
        else:
            model = annotation
            collection = False
        if not isinstance(model, type) or not issubclass(model, (EntityBase, RelationBase)):
            raise TypeError(f"query_as field {name!r} is not a generated model")
        _require_projection(_exact_projection(model), projection, f"query_as field {name!r}")
        normalized.append((name, model, collection))
    return tuple(normalized)


def _declaration_names(
    declaration: type[object],
    *,
    require_frozen: bool,
) -> tuple[str, ...]:
    if is_dataclass(declaration):
        parameters: object = getattr(declaration, "__dataclass_params__", None)
        frozen: object = getattr(parameters, "frozen", None)
        if require_frozen and frozen is not True:
            raise TypeError("query_as dataclasses must be frozen")
        return tuple(field.name for field in fields(declaration))
    raw_names: object = getattr(declaration, "_fields", None)
    if issubclass(declaration, tuple) and _is_string_tuple(raw_names):
        return raw_names
    raise TypeError("query_as requires a frozen dataclass or NamedTuple class")


def _dynamic_value(value: AttributeBase) -> DynamicValue:
    declaration = value.__projection__["declaration"]
    if not _is_object_dict(declaration):
        raise TypeError("generated attribute declaration is invalid")
    value_type = declaration.get("value_type")
    if not isinstance(value_type, str):
        raise TypeError("generated attribute value type is invalid")
    kind = value_type
    scalar = value.value
    if kind == "string" and isinstance(scalar, str):
        return DynamicValue.string(scalar)
    if kind == "long" and type(scalar) is int:
        return DynamicValue.long(scalar)
    if kind == "double" and type(scalar) is float:
        return DynamicValue.double(scalar)
    if kind == "boolean" and type(scalar) is bool:
        return DynamicValue.boolean(scalar)
    if kind == "date" and type(scalar) is date:
        return DynamicValue.date(scalar.isoformat())
    if kind == "datetime" and type(scalar) is datetime and scalar.tzinfo is None:
        return DynamicValue.datetime(scalar.isoformat())
    if kind == "datetime_tz" and type(scalar) is datetime and scalar.tzinfo is not None:
        return DynamicValue.datetime_tz(scalar.isoformat())
    if kind == "decimal" and type(scalar) is Decimal:
        return DynamicValue.decimal(str(scalar))
    if kind == "duration" and type(scalar) is timedelta:
        return DynamicValue.duration(_duration_isoformat(scalar))
    raise TypeError("generated attribute value does not match its projected scalar type")


def _is_object_dict(value: object) -> TypeGuard[dict[str, object]]:
    if not _is_untyped_dict(value):
        return False
    return all(isinstance(key, str) for key in value)


def _is_object_list(value: object) -> TypeGuard[list[object]]:
    return isinstance(value, list)


def _is_object_tuple(value: object) -> TypeGuard[tuple[object, ...]]:
    return isinstance(value, tuple)


def _is_string_tuple(value: object) -> TypeGuard[tuple[str, ...]]:
    return _is_object_tuple(value) and all(isinstance(item, str) for item in value)


def _is_role_token(value: object) -> TypeGuard[RoleToken[ModelBase, ModelBase, BoundVar]]:
    return isinstance(value, RoleToken)


def _is_exchange(
    value: object,
) -> TypeGuard[Callable[[bytes], Awaitable[bytes]]]:
    return callable(value)


async def _wait_for_query_cancellation(cancellation: QueryCancellation) -> None:
    """Yield cooperatively until the shared native cancellation is observed."""
    while not cancellation.is_cancelled:
        await asyncio.sleep(0)


def _consume_remote_exchange_task[ResultT](task: asyncio.Future[ResultT]) -> None:
    """Observe a losing task so cancellation never leaks an event-loop warning."""
    if task.cancelled():
        return
    task.exception()


def _type_id_label(value: object) -> str:
    if not _is_object_dict(value):
        raise TypeError("generated model identity must be an object")
    label = value.get("label")
    if not isinstance(label, str):
        raise TypeError("generated model identity has no string label")
    return label


def _is_untyped_dict(value: object) -> TypeGuard[dict[object, object]]:
    return isinstance(value, dict)


def _is_connection(value: object) -> TypeGuard[Database | TransactionContext]:
    return isinstance(value, (Database, TransactionContext))


def _duration_isoformat(value: timedelta) -> str:
    total_microseconds = (
        value.days * 86_400_000_000 + value.seconds * 1_000_000 + value.microseconds
    )
    sign = "-" if total_microseconds < 0 else ""
    remaining = abs(total_microseconds)
    days, remaining = divmod(remaining, 86_400_000_000)
    hours, remaining = divmod(remaining, 3_600_000_000)
    minutes, remaining = divmod(remaining, 60_000_000)
    seconds, microseconds = divmod(remaining, 1_000_000)
    second_text = str(seconds)
    if microseconds:
        second_text += f".{microseconds:06d}".rstrip("0")
    return f"{sign}P{days}DT{hours}H{minutes}M{second_text}S"


def _window(offset: int, limit: int) -> tuple[int, int]:
    if type(offset) is not int or offset < 0:
        raise ValueError("generated query offset must be a non-negative integer")
    if type(limit) is not int or limit < 1:
        raise ValueError("generated query limit must be a positive integer")
    return offset, limit


def _prepare_aggregate_terms(
    terms: tuple[Aggregate, ...],
    projection: PyRuntimeProjection,
) -> tuple[list[_Reducer], list[MatchFieldHandle | None]]:
    if not 1 <= len(terms) <= 16:
        raise ValueError("generated aggregate requires between one and sixteen terms")
    reducers: list[_Reducer] = []
    inputs: list[MatchFieldHandle | None] = []
    for term in terms:
        if type(term) is not Aggregate:
            raise TypeError("generated aggregate terms must come from aggregate constructors")
        term_projection = term.projection_identity()
        if term_projection is not None:
            _require_projection(term_projection, projection, "aggregate field")
        reducers.append(term.native_reducer())
        inputs.append(term.native_input())
    return reducers, inputs


def _is_grouped_reduction(
    value: object,
) -> TypeGuard[tuple[tuple[object, tuple[object, ...]], ...]]:
    if not _is_object_tuple(value):
        return False
    for row in value:
        if not _is_object_tuple(row) or len(row) != 2 or not _is_object_tuple(row[1]):
            return False
    return True


__all__ = [
    "Aggregate",
    "BoundField",
    "BoundRole",
    "BoundVar",
    "Collected",
    "FunctionCall",
    "FunctionInput",
    "Predicate",
    "Query",
    "QueryOrder",
    "QueryCancellation",
    "QueryExecutionResourceLimits",
    "QuerySession",
    "GroupedQuery",
    "Page",
    "RemoteGroupedQuery",
    "RemoteQuery",
    "RemoteQueryLimits",
    "RemoteQuerySession",
    "SubtypeBoundVar",
    "aggregate",
]