type-bridge-contract 2.3.2

Versioned binding-neutral contract primitives 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
//! Additive canonical read/write plans. V1/V2 representations remain frozen.

use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use super::*;
use crate::codec::from_canonical_json_with_limits;
use crate::id::TypeKind;
use crate::migration_assertion_wire::{FingerprintWire, RoleIdWire, TypeIdWire};
use crate::query_plan_wire::rebuild_pattern_v2;
use crate::query_plan_wire::{
    InputColumnWire, LocalFunctionWire, QueryBindingWire, QueryOperandWire, rebuild_output,
    rebuild_read_stage_v2,
};
use crate::schema::{
    AnnotationFactId, AnnotationKindId, AnnotationSubjectId, DeclaredSchema, OwnsFactId,
    PlaysFactId, RelatesFactId, SchemaFact, SchemaFactId,
};

/// Exact discriminator of the additive write-plan format.
pub const QUERY_PLAN_FORMAT_V3: &str = "typebridge.query-plan/v3";
/// Canonicalization version separating V3 fingerprints from frozen V2.
pub const QUERY_PLAN_CANONICALIZATION_V3: &str = "typebridge.query-plan-c14n/v3";

#[path = "query_plan_v3_expr.rs"]
mod expression;
pub use expression::{ArithOp, Builtin, Expr};
use expression::{ExprWire, operand_type};

#[path = "query_plan_v3_builder.rs"]
mod builder;
pub use builder::PlanBuilder;

/// A closed match pattern, including a fresh scalar expression assignment.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Pattern {
    /// A released closed read pattern.
    Read(QueryPattern),
    /// Assign a fresh value binding in source order.
    Let {
        /// Fresh declared scalar binding.
        binding: BindingId,
        /// Typed expression over present bindings, literals and inputs.
        expr: Expr,
    },
    /// Identify a thing binding, typed by a positive pattern of the same
    /// match, by its canonical provider IID. Root-match only.
    Iid {
        /// Entity or relation binding established by this match.
        binding: BindingId,
        /// Canonical TypeDB thing IID.
        iid: String,
    },
}
impl From<QueryPattern> for Pattern {
    fn from(pattern: QueryPattern) -> Self {
        Self::Read(pattern)
    }
}
impl Serialize for Pattern {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Read(pattern) => pattern.serialize(serializer),
            Self::Let { binding, expr } => {
                #[derive(Serialize)]
                struct View<'a> {
                    kind: &'static str,
                    binding: BindingId,
                    expr: &'a Expr,
                }
                View {
                    kind: "let",
                    binding: *binding,
                    expr,
                }
                .serialize(serializer)
            }
            Self::Iid { binding, iid } => {
                #[derive(Serialize)]
                struct View<'a> {
                    kind: &'static str,
                    binding: BindingId,
                    iid: &'a str,
                }
                View {
                    kind: "iid",
                    binding: *binding,
                    iid,
                }
                .serialize(serializer)
            }
        }
    }
}

/// The terminal operation is part of V3 plan identity.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Operation {
    /// Project read rows.
    Rows,
    /// Count matched read rows.
    Count,
    /// Whether any read row matched.
    Exists,
    /// Execute at least one write stage.
    Write {
        /// Resolve a match count or the same pipeline's projection.
        returns: WriteReturns,
    },
}

/// A write plan's result category.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WriteReturns {
    /// Number of rows matched by the write pipeline.
    Matched,
    /// Project rows after the writes, in the same pipeline.
    Rows,
}

/// Every capability derivable from closed V3 syntax that a staged
/// endpoint advertises.
///
/// `query.fetch.thing` (a [`Stage::Fetch`]) is derived but not advertised
/// yet: proxies refuse fetch plans at capability admission until they are
/// served remotely.
#[must_use]
pub fn query_plan_v3_capability_vocabulary() -> CapabilitySet {
    query_plan_v2_capability_vocabulary()
        .into_iter()
        .chain(
            [
                "query.plan.v3",
                "query.write.insert",
                "query.write.update",
                "query.write.delete",
                "query.write.put",
                "query.let",
                "query.expr.add",
                "query.expr.sub",
                "query.expr.mul",
                "query.expr.div",
                "query.expr.mod",
                "query.expr.pow",
                "query.expr.abs",
                "query.expr.ceil",
                "query.expr.floor",
                "query.expr.round",
                "query.expr.min",
                "query.expr.max",
                "query.expr.length",
            ]
            .map(|name| CapabilityId::new(name).expect("static capability")),
        )
        .collect()
}

/// A thing created or matched by insert/put. Field and player order is retained.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct InsertThing {
    /// Fresh dense binding assigned by this stage.
    pub binding: BindingId,
    /// Concrete entity or relation type.
    pub type_id: TypeId,
    /// Declared ownerships and their scalar operands.
    pub fields: Vec<(OwnsFactId, QueryOperand)>,
    /// Declared roles and player bindings.
    pub players: Vec<(RoleId, BindingId)>,
}

/// One update assignment, evaluated inside the same pipeline.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Set {
    /// Replace an ownership value.
    Field {
        /// Bound owner.
        owner: BindingId,
        /// Declared ownership; key fields cannot be replaced.
        field: OwnsFactId,
        /// New scalar value.
        operand: QueryOperand,
    },
    /// Assign a player to a declared role.
    Link {
        /// Bound relation.
        relation: BindingId,
        /// Declared role.
        role: RoleId,
        /// Bound player.
        player: BindingId,
    },
}

/// One deletion within a pipeline.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum DeleteItem {
    /// Delete a thing and end its binding's lifetime.
    Thing {
        /// Thing to delete.
        binding: BindingId,
    },
    /// Delete an ownership without deleting the owner.
    Has {
        /// Bound owner.
        owner: BindingId,
        /// Declared ownership.
        field: OwnsFactId,
    },
    /// Remove one role player.
    Links {
        /// Bound relation.
        relation: BindingId,
        /// Declared role.
        role: RoleId,
        /// Bound player.
        player: BindingId,
    },
    /// Remove every player of one declared role, leaving the relation alive.
    Players {
        /// Bound relation.
        relation: BindingId,
        /// Declared role.
        role: RoleId,
    },
}

/// One addition to an already bound thing.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum AttachItem {
    /// Add one value of a non-key ownership; existing values stay.
    Has {
        /// Bound owner.
        owner: BindingId,
        /// Declared ownership; key fields cannot be attached.
        field: OwnsFactId,
        /// Value to add.
        operand: QueryOperand,
    },
    /// Add one player to a declared role; existing players stay.
    Links {
        /// Bound relation.
        relation: BindingId,
        /// Declared role.
        role: RoleId,
        /// Bound player.
        player: BindingId,
    },
}

/// One role whose players a thing document lists.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[non_exhaustive]
pub struct DocumentRole {
    /// Declared role.
    pub role: RoleId,
    /// Whether the role must be filled; an unfilled required role drops
    /// the row, an unfilled optional one omits its keys.
    pub required: bool,
}

impl DocumentRole {
    /// One listed role.
    #[must_use]
    pub const fn new(role: RoleId, required: bool) -> Self {
        Self { role, required }
    }
}

/// The hydration document of one thing: its IID, exact type label, every
/// owned attribute and, for a relation, the players of the listed roles.
///
/// The document keys are fixed: `_iid`, `_type`, `attributes`, and for the
/// role at position `N` of `roles`: `_role_N_iid`, `_role_N_type` and
/// `_role_N_attributes`. A role with several players yields one document per
/// player combination.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[non_exhaustive]
pub struct ThingDocument {
    /// Entity or relation binding to describe.
    pub thing: BindingId,
    /// Listed roles, in key order.
    pub roles: Vec<DocumentRole>,
}

impl ThingDocument {
    /// Describe one thing and the players of `roles`.
    #[must_use]
    pub const fn new(thing: BindingId, roles: Vec<DocumentRole>) -> Self {
        Self { thing, roles }
    }
}

/// Ordered V3 pipeline vocabulary. Read tails retain the V2 order.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Stage {
    /// Initial closed match conjunction.
    Match {
        /// Typed read patterns.
        patterns: Vec<Pattern>,
    },
    /// Create fresh things.
    Insert {
        /// Things created together, in source order.
        things: Vec<InsertThing>,
    },
    /// Replace fields or role players.
    Update {
        /// Assignments in source order.
        sets: Vec<Set>,
    },
    /// Delete things, ownerships or role players.
    Delete {
        /// Deletions in source order.
        items: Vec<DeleteItem>,
    },
    /// Add ownerships or role players to bound things, keeping existing
    /// ones (for multi-valued fields and roles, where `update` replaces).
    Attach {
        /// Additions in source order.
        items: Vec<AttachItem>,
    },
    /// Match or create things.
    Put {
        /// Things matched or created together.
        things: Vec<InsertThing>,
    },
    /// Restrict the visible row environment.
    Select {
        /// Strictly ascending binding set.
        bindings: Vec<BindingId>,
    },
    /// Require visible bindings.
    Require {
        /// Strictly ascending binding set.
        bindings: Vec<BindingId>,
    },
    /// Deduplicate visible rows.
    Distinct,
    /// Group and reduce rows.
    Reduce {
        /// Fresh reducer assignments.
        assignments: Vec<ReduceAssignment>,
        /// Strictly ascending group keys.
        groups: Vec<BindingId>,
    },
    /// Impose a total order.
    Sort {
        /// Ordered sort terms.
        terms: Vec<OrderTerm>,
    },
    /// Skip sorted rows.
    Offset {
        /// Number of rows to skip.
        rows: u64,
    },
    /// Limit sorted rows.
    Limit {
        /// Maximum number of rows.
        rows: u64,
    },
    /// Fetch one thing document per row. Terminal; the plan's output is then
    /// empty rows and its answer is the documents.
    Fetch(ThingDocument),
}

impl From<ReadStage> for Stage {
    fn from(stage: ReadStage) -> Self {
        match stage {
            ReadStage::Match { patterns } => Self::Match {
                patterns: patterns.into_iter().map(Pattern::Read).collect(),
            },
            ReadStage::Select { bindings } => Self::Select { bindings },
            ReadStage::Require { bindings } => Self::Require { bindings },
            ReadStage::Distinct => Self::Distinct,
            ReadStage::Reduce {
                assignments,
                groups,
            } => Self::Reduce {
                assignments,
                groups,
            },
            ReadStage::Sort { terms } => Self::Sort { terms },
            ReadStage::Offset { rows } => Self::Offset { rows },
            ReadStage::Limit { rows } => Self::Limit { rows },
        }
    }
}

impl Stage {
    /// Whether this stage mutates provider data.
    #[must_use]
    pub const fn is_write(&self) -> bool {
        matches!(
            self,
            Self::Insert { .. }
                | Self::Update { .. }
                | Self::Delete { .. }
                | Self::Put { .. }
                | Self::Attach { .. }
        )
    }

    fn read_stage(&self) -> Option<ReadStage> {
        Some(match self {
            Self::Match { patterns } => ReadStage::Match {
                patterns: patterns
                    .iter()
                    .filter_map(|pattern| match pattern {
                        Pattern::Read(pattern) => Some(pattern.clone()),
                        Pattern::Let { .. } | Pattern::Iid { .. } => None,
                    })
                    .collect(),
            },
            Self::Select { bindings } => ReadStage::Select {
                bindings: bindings.clone(),
            },
            Self::Require { bindings } => ReadStage::Require {
                bindings: bindings.clone(),
            },
            Self::Distinct => ReadStage::Distinct,
            Self::Reduce {
                assignments,
                groups,
            } => ReadStage::Reduce {
                assignments: assignments.clone(),
                groups: groups.clone(),
            },
            Self::Sort { terms } => ReadStage::Sort {
                terms: terms.clone(),
            },
            Self::Offset { rows } => ReadStage::Offset { rows: *rows },
            Self::Limit { rows } => ReadStage::Limit { rows: *rows },
            _ => return None,
        })
    }
}

/// Untrusted constructor inputs; QueryPlanV3 validates them against authority.
#[derive(Clone, Debug)]
pub struct PlanSpec {
    /// Dense ordered binding declarations.
    pub bindings: Vec<AssertionBinding>,
    /// Typed invocation columns.
    pub inputs: Vec<InputColumn>,
    /// Bound rows, or None for an invocation-free reusable template.
    pub given_rows: Option<Vec<InputRow>>,
    /// Terminal read or write operation.
    pub operation: Operation,
    /// Ordered read/write pipeline.
    pub pipeline: Vec<Stage>,
    /// Final projection. A write without a projection uses empty row columns.
    pub output: QueryOutput,
    /// Expected managed schema semantics.
    pub managed_semantics: ManagedSemanticSchemaFingerprint,
    /// Retained V2 read semantics when lifting a model-query plan.
    pub compatibility: Option<QueryPlanV2Compatibility>,
    /// Plan-local read functions.
    pub functions: Vec<LocalFunction>,
}

/// A trusted canonical V3 plan. Decoding always rebuilds through validation.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct QueryPlanV3 {
    bindings: Vec<AssertionBinding>,
    #[serde(skip_serializing_if = "Option::is_none")]
    compatibility: Option<QueryPlanV2Compatibility>,
    format: String,
    functions: Vec<LocalFunction>,
    inputs: Vec<InputColumn>,
    #[serde(skip_serializing_if = "Option::is_none")]
    given_rows: Option<Vec<InputRow>>,
    operation: Operation,
    #[serde(skip)]
    limits: QueryLimits,
    managed_semantics: ManagedSemanticSchemaFingerprint,
    output: QueryOutput,
    pipeline: Vec<Stage>,
    required_capabilities: CapabilitySet,
}

impl QueryPlanV3 {
    /// Validate one program against declared schema authority and fixed limits.
    pub fn new(spec: PlanSpec, schema: &DeclaredSchema) -> Result<Self, Diagnostic> {
        Self::new_with_limits(spec, schema, QueryLimits::CANONICAL)
    }

    /// Validate with caller-selected limits, which never enter canonical bytes.
    pub fn new_with_limits(
        spec: PlanSpec,
        schema: &DeclaredSchema,
        limits: QueryLimits,
    ) -> Result<Self, Diagnostic> {
        limits.validate().map_err(|_| {
            failure(
                DiagnosticCategory::ResourceLimit,
                "query_plan_invalid_limits",
                "plan limits are outside the supported protocol range",
            )
        })?;
        Self::build(spec, schema, limits).map_err(|diagnostic| limits.annotate(diagnostic))
    }

    fn build(
        spec: PlanSpec,
        schema: &DeclaredSchema,
        limits: QueryLimits,
    ) -> Result<Self, Diagnostic> {
        validate_declarations(&spec.bindings, &spec.inputs, limits.structural)?;
        validate_operation(&spec)?;
        if let Some(rows) = &spec.given_rows {
            if spec.inputs.is_empty() {
                return Err(invalid(
                    "query_invocation_unexpected_inputs",
                    "given rows require declared input columns",
                ));
            }
            validate_input_rows(&spec.inputs, rows, limits.structural)?;
        }
        let mut nodes = 0;
        validate_local_functions(&spec.functions, limits.structural, &mut nodes)?;
        validate_stages(&spec, schema, limits, &mut nodes)?;
        if let Some(compatibility) = &spec.compatibility {
            compatibility.validate(spec.bindings.len(), limits)?;
        }
        let reads: Vec<_> = spec.pipeline.iter().filter_map(Stage::read_stage).collect();
        let mut required_capabilities = derive_capabilities(
            &reads,
            &spec.functions,
            &spec.inputs,
            &spec.output,
            spec.compatibility.as_ref(),
        )?;
        insert_capability(&mut required_capabilities, "query.plan.v3")?;
        add_read_given_capability(
            &spec.pipeline,
            &spec.functions,
            &spec.inputs,
            &mut required_capabilities,
        )?;
        for stage in &spec.pipeline {
            if let Stage::Match { patterns } = stage {
                for pattern in patterns {
                    match pattern {
                        Pattern::Let { expr, .. } => {
                            insert_capability(&mut required_capabilities, "query.let")?;
                            expr.capabilities(&mut required_capabilities)?;
                        }
                        Pattern::Iid { .. } => {
                            insert_capability(&mut required_capabilities, v2::CAP_IID)?;
                        }
                        Pattern::Read(_) => {}
                    }
                }
            }
            let operands: Vec<&QueryOperand> = match stage {
                Stage::Insert { things } | Stage::Put { things } => things
                    .iter()
                    .flat_map(|thing| thing.fields.iter().map(|(_, operand)| operand))
                    .collect(),
                Stage::Update { sets } => sets
                    .iter()
                    .filter_map(|set| match set {
                        Set::Field { operand, .. } => Some(operand),
                        _ => None,
                    })
                    .collect(),
                Stage::Attach { items } => items
                    .iter()
                    .filter_map(|item| match item {
                        AttachItem::Has { operand, .. } => Some(operand),
                        AttachItem::Links { .. } => None,
                    })
                    .collect(),
                _ => vec![],
            };
            if operands.iter().any(|operand| {
                matches!(
                    operand,
                    QueryOperand::Literal { .. } | QueryOperand::Input { .. }
                )
            }) {
                insert_capability(&mut required_capabilities, "query.input.given-rows")?;
            }
        }
        for stage in &spec.pipeline {
            let capability = match stage {
                Stage::Insert { .. } => "query.write.insert",
                Stage::Update { .. } => "query.write.update",
                Stage::Delete { .. } => "query.write.delete",
                Stage::Put { .. } => "query.write.put",
                Stage::Fetch(_) => "query.fetch.thing",
                Stage::Attach { .. } => "query.write.attach",
                _ => continue,
            };
            insert_capability(&mut required_capabilities, capability)?;
        }
        let plan = Self {
            bindings: spec.bindings,
            compatibility: spec.compatibility,
            format: QUERY_PLAN_FORMAT_V3.into(),
            functions: spec.functions,
            inputs: spec.inputs,
            given_rows: spec.given_rows,
            operation: spec.operation,
            limits,
            managed_semantics: spec.managed_semantics,
            output: spec.output,
            pipeline: spec.pipeline,
            required_capabilities,
        };
        plan.canonical_bytes()?;
        Ok(plan)
    }

    pub(super) fn from_read_plan(
        plan: &QueryPlan,
        schema: &DeclaredSchema,
    ) -> Result<Self, Diagnostic> {
        Self::new_with_limits(
            PlanSpec {
                bindings: plan.bindings.clone(),
                compatibility: plan.compatibility.clone(),
                functions: plan.functions.clone(),
                inputs: plan.inputs.clone(),
                given_rows: None,
                operation: Operation::Rows,
                managed_semantics: plan.managed_semantics.clone(),
                output: plan.output.clone(),
                pipeline: plan.pipeline.iter().cloned().map(Stage::from).collect(),
            },
            schema,
            plan.limits,
        )
    }

    /// Exact format discriminator.
    #[must_use]
    pub fn format(&self) -> &str {
        &self.format
    }
    /// Receiver-owned limits retained during trusted construction.
    #[must_use]
    pub const fn limits(&self) -> QueryLimits {
        self.limits
    }
    /// Dense binding declarations.
    #[must_use]
    pub fn bindings(&self) -> &[AssertionBinding] {
        &self.bindings
    }
    /// Typed invocation columns.
    #[must_use]
    pub fn inputs(&self) -> &[InputColumn] {
        &self.inputs
    }
    /// Ordered pipeline.
    #[must_use]
    pub fn pipeline(&self) -> &[Stage] {
        &self.pipeline
    }
    /// Plan-local read functions.
    #[must_use]
    pub fn functions(&self) -> &[LocalFunction] {
        &self.functions
    }
    /// Frozen V2 model-query evidence retained by a lifted plan.
    #[must_use]
    pub fn compatibility(&self) -> Option<&QueryPlanV2Compatibility> {
        self.compatibility.as_ref()
    }
    /// Bound given rows, absent for a reusable template.
    #[must_use]
    pub fn given_rows(&self) -> Option<&[InputRow]> {
        self.given_rows.as_deref()
    }
    /// Terminal operation.
    #[must_use]
    pub const fn operation(&self) -> Operation {
        self.operation
    }
    /// Whether the plan writes, and therefore needs a write transaction.
    #[must_use]
    pub const fn writes(&self) -> bool {
        matches!(self.operation, Operation::Write { .. })
    }
    /// Bind values to a reusable plan; rows participate in its V3 fingerprint.
    pub fn with_given_rows(
        &self,
        rows: Vec<InputRow>,
        schema: &DeclaredSchema,
    ) -> Result<Self, Diagnostic> {
        let mut spec = self.spec();
        spec.given_rows = Some(rows);
        Self::new_with_limits(spec, schema, self.limits)
    }
    /// Select an operation when lifting an invocation from V2.
    pub fn with_operation(
        &self,
        operation: Operation,
        schema: &DeclaredSchema,
    ) -> Result<Self, Diagnostic> {
        let mut spec = self.spec();
        spec.operation = operation;
        Self::new_with_limits(spec, schema, self.limits)
    }
    fn spec(&self) -> PlanSpec {
        PlanSpec {
            bindings: self.bindings.clone(),
            inputs: self.inputs.clone(),
            given_rows: self.given_rows.clone(),
            operation: self.operation,
            pipeline: self.pipeline.clone(),
            output: self.output.clone(),
            managed_semantics: self.managed_semantics.clone(),
            compatibility: self.compatibility.clone(),
            functions: self.functions.clone(),
        }
    }
    /// Final projection.
    #[must_use]
    pub const fn output(&self) -> &QueryOutput {
        &self.output
    }
    /// Managed schema semantics.
    #[must_use]
    pub const fn managed_semantics(&self) -> &ManagedSemanticSchemaFingerprint {
        &self.managed_semantics
    }
    /// Capabilities derived exclusively from syntax.
    #[must_use]
    pub const fn required_capabilities(&self) -> &CapabilitySet {
        &self.required_capabilities
    }
    /// Encode with the bounded common canonical JSON codec.
    pub fn canonical_bytes(&self) -> Result<Vec<u8>, Diagnostic> {
        to_canonical_json_with_limits(self, self.limits.codec)
    }
    /// Fingerprint under the V3 canonicalization version and common plan domain.
    pub fn fingerprint(&self) -> Result<QueryPlanFingerprint, Diagnostic> {
        Ok(QueryPlanFingerprint(Fingerprint::compute(
            FingerprintDomain::new(QUERY_PLAN_FINGERPRINT_DOMAIN)?,
            CanonicalizationVersion::new(QUERY_PLAN_CANONICALIZATION_V3)?,
            None,
            &self.canonical_bytes()?,
        )))
    }
}

fn invalid(code: &'static str, message: &'static str) -> Diagnostic {
    failure(DiagnosticCategory::InvalidContract, code, message)
}

fn validate_stages(
    spec: &PlanSpec,
    schema: &DeclaredSchema,
    limits: QueryLimits,
    nodes: &mut usize,
) -> Result<(), Diagnostic> {
    let Some(first) = spec.pipeline.first() else {
        return Err(invalid(
            "query_plan_empty_pipeline",
            "a plan requires at least one stage",
        ));
    };
    let index = SchemaIndex::new(schema);
    let mut mandatory = BTreeSet::new();
    let mut optional = BTreeSet::new();
    let mut referenced = BTreeSet::new();
    let mut types = BTreeMap::<BindingId, BTreeSet<TypeId>>::new();
    let mut scalar_types = BTreeMap::new();
    let mut read_tail = Vec::new();
    let mut reading = false;
    let mut fetched: Option<&ThingDocument> = None;
    if !matches!(
        first,
        Stage::Match { .. } | Stage::Insert { .. } | Stage::Put { .. }
    ) {
        return Err(invalid(
            "query_plan_match_not_first",
            "a plan starts with match, insert or put",
        ));
    }
    for (stage_index, stage) in spec.pipeline.iter().enumerate() {
        *nodes += 1;
        if *nodes > limits.structural.predicate_nodes {
            return Err(failure(
                DiagnosticCategory::ResourceLimit,
                "query_plan_stage_limit",
                "plan stages exceed the structural ceiling",
            ));
        }
        match stage {
            Stage::Match { patterns } => {
                if stage_index != 0 {
                    return Err(invalid(
                        "query_plan_stage_order",
                        "match occurs only at the start",
                    ));
                }
                nonempty(patterns.len(), limits, nodes)?;
                let reads: Vec<_> = patterns
                    .iter()
                    .filter_map(|pattern| match pattern {
                        Pattern::Read(pattern) => Some(pattern.clone()),
                        _ => None,
                    })
                    .collect();
                *nodes -= reads.len();
                if !reads.is_empty() {
                    (mandatory, optional, _) = validate_pipeline(
                        &[ReadStage::Match {
                            patterns: reads.clone(),
                        }],
                        spec.bindings.len(),
                        spec.inputs.len(),
                        limits.structural,
                        nodes,
                    )?;
                }
                for pattern in &reads {
                    collect_pattern_bindings(pattern, &mut referenced);
                    index.pattern_types(pattern, &mut types)?;
                }
                for (binding, domains) in &types {
                    if mandatory.contains(binding)
                        && let Some(domain) = index.scalar_domain(domains)
                    {
                        scalar_types.insert(*binding, domain);
                    }
                }
                index.function_values(&reads, &spec.functions, &mandatory, &mut scalar_types)?;
                let mut produced = BTreeSet::new();
                for pattern in &reads {
                    collect_produced_bindings(pattern, &mut produced);
                }
                for pattern in patterns {
                    if let Pattern::Let { binding, expr } = pattern {
                        check_binding(*binding, spec.bindings.len())?;
                        if produced.contains(binding)
                            || mandatory.contains(binding)
                            || optional.contains(binding)
                        {
                            return Err(invalid(
                                "query_plan_let_binding_not_fresh",
                                "let requires a fresh value binding",
                            ));
                        }
                        let domain = expr.infer(&scalar_types, &spec.inputs, limits, 1, nodes)?;
                        mandatory.insert(*binding);
                        referenced.insert(*binding);
                        scalar_types.insert(*binding, domain);
                    }
                }
                refuse_duration_ranges(&reads, &scalar_types, &spec.inputs)?;
                for pattern in patterns {
                    if let Pattern::Iid { binding, iid } = pattern {
                        check_binding(*binding, spec.bindings.len())?;
                        if !crate::id::is_canonical_thing_iid(iid) {
                            return Err(invalid(
                                "query_plan_invalid_iid",
                                "IID patterns require a canonical TypeDB thing IID",
                            ));
                        }
                        let thing = mandatory.contains(binding)
                            && types.get(binding).is_some_and(|types| {
                                !types.is_empty()
                                    && types.iter().all(|type_id| {
                                        matches!(
                                            type_id.kind(),
                                            TypeKind::Entity | TypeKind::Relation
                                        )
                                    })
                            });
                        if !thing {
                            return Err(invalid(
                                "query_plan_iid_untyped_thing",
                                "IID patterns require a positively typed thing binding",
                            ));
                        }
                    }
                }
            }
            Stage::Insert { things } | Stage::Put { things } => {
                if reading {
                    return Err(invalid(
                        "query_plan_stage_order",
                        "write stages precede the read tail",
                    ));
                }
                nonempty(things.len(), limits, nodes)?;
                for thing in things {
                    check_binding(thing.binding, spec.bindings.len())?;
                    if !mandatory.insert(thing.binding)
                        || optional.contains(&thing.binding)
                        || referenced.contains(&thing.binding)
                    {
                        return Err(invalid(
                            "query_plan_write_binding_not_fresh",
                            "insert and put assign fresh declared bindings",
                        ));
                    }
                    if thing.type_id.kind() == TypeKind::Attribute {
                        return Err(invalid(
                            "query_plan_insert_attribute_type",
                            "insert and put require an entity or relation type",
                        ));
                    }
                    if thing.type_id.kind() == TypeKind::Relation && thing.players.is_empty() {
                        return Err(invalid(
                            "query_plan_insert_relation_players",
                            "relation insert and put require at least one player",
                        ));
                    }
                    index.concrete(&thing.type_id)?;
                    types.insert(thing.binding, BTreeSet::from([thing.type_id.clone()]));
                    referenced.insert(thing.binding);
                }
                for thing in things {
                    for (field, operand) in &thing.fields {
                        index.ownership(thing.binding, field, &types, false)?;
                        validate_operand(operand, &mandatory, &optional, spec.inputs.len())?;
                        index.field_value(field, operand, &scalar_types, &spec.inputs)?;
                    }
                    for (role, player) in &thing.players {
                        bound(*player, &mandatory)?;
                        index.role(thing.binding, role, *player, &types)?;
                    }
                    nonempty(thing.fields.len() + thing.players.len() + 1, limits, nodes)?;
                }
            }
            Stage::Update { sets } => {
                if reading {
                    return Err(invalid(
                        "query_plan_stage_order",
                        "write stages precede the read tail",
                    ));
                }
                nonempty(sets.len(), limits, nodes)?;
                for set in sets {
                    match set {
                        Set::Field {
                            owner,
                            field,
                            operand,
                        } => {
                            bound(*owner, &mandatory)?;
                            index.ownership(*owner, field, &types, true)?;
                            validate_operand(operand, &mandatory, &optional, spec.inputs.len())?;
                            index.field_value(field, operand, &scalar_types, &spec.inputs)?;
                        }
                        Set::Link {
                            relation,
                            role,
                            player,
                        } => {
                            bound(*relation, &mandatory)?;
                            bound(*player, &mandatory)?;
                            index.role(*relation, role, *player, &types)?;
                        }
                    }
                }
            }
            Stage::Attach { items } => {
                if reading {
                    return Err(invalid(
                        "query_plan_stage_order",
                        "write stages precede the read tail",
                    ));
                }
                nonempty(items.len(), limits, nodes)?;
                for item in items {
                    match item {
                        AttachItem::Has {
                            owner,
                            field,
                            operand,
                        } => {
                            bound(*owner, &mandatory)?;
                            // A key is fixed at creation, as for update.
                            index.ownership(*owner, field, &types, true)?;
                            validate_operand(operand, &mandatory, &optional, spec.inputs.len())?;
                            index.field_value(field, operand, &scalar_types, &spec.inputs)?;
                        }
                        AttachItem::Links {
                            relation,
                            role,
                            player,
                        } => {
                            bound(*relation, &mandatory)?;
                            bound(*player, &mandatory)?;
                            index.role(*relation, role, *player, &types)?;
                        }
                    }
                }
            }
            Stage::Delete { items } => {
                if reading {
                    return Err(invalid(
                        "query_plan_stage_order",
                        "write stages precede the read tail",
                    ));
                }
                nonempty(items.len(), limits, nodes)?;
                // Every deletion reads the incoming environment. Lifetimes end
                // together at this stage's boundary, not by item list order.
                for item in items {
                    match item {
                        DeleteItem::Thing { binding } => {
                            bound(*binding, &mandatory)?;
                            if !types.contains_key(binding) {
                                return Err(invalid(
                                    "query_plan_delete_untyped_thing",
                                    "thing deletion requires a typed thing binding",
                                ));
                            }
                        }
                        DeleteItem::Has { owner, field } => {
                            bound(*owner, &mandatory)?;
                            index.ownership(*owner, field, &types, false)?;
                        }
                        DeleteItem::Links {
                            relation,
                            role,
                            player,
                        } => {
                            bound(*relation, &mandatory)?;
                            bound(*player, &mandatory)?;
                            index.role(*relation, role, *player, &types)?;
                        }
                        DeleteItem::Players { relation, role } => {
                            bound(*relation, &mandatory)?;
                            index.relation_role(*relation, role, &types)?;
                        }
                    }
                }
                for item in items {
                    if let DeleteItem::Thing { binding } = item {
                        mandatory.remove(binding);
                    }
                }
            }
            Stage::Fetch(document) => {
                if stage_index + 1 != spec.pipeline.len() {
                    return Err(invalid(
                        "query_plan_fetch_not_last",
                        "a thing fetch is the last stage",
                    ));
                }
                if !matches!(
                    spec.operation,
                    Operation::Rows
                        | Operation::Write {
                            returns: WriteReturns::Rows
                        }
                ) || !matches!(&spec.output, QueryOutput::Rows { columns } if columns.is_empty())
                {
                    return Err(invalid(
                        "query_plan_fetch_output",
                        "a thing fetch answers rows with an empty declared output",
                    ));
                }
                check_binding(document.thing, spec.bindings.len())?;
                nonempty(document.roles.len() + 1, limits, nodes)?;
                for (index, role) in document.roles.iter().enumerate() {
                    if document.roles[..index]
                        .iter()
                        .any(|earlier| earlier.role == role.role)
                    {
                        return Err(invalid(
                            "query_plan_fetch_duplicate_role",
                            "a thing fetch lists each role once",
                        ));
                    }
                }
                fetched = Some(document);
            }
            _ => {
                reading = true;
                read_tail.push(stage.read_stage().expect("read stage"));
            }
        }
    }
    let (mandatory, optional, has_sort) = validate_read_stages(
        &read_tail,
        mandatory,
        optional,
        &referenced,
        spec.bindings.len(),
        limits.structural,
    )?;
    for stage in &read_tail {
        if let ReadStage::Sort { terms } = stage
            && terms
                .iter()
                .any(|term| scalar_types.get(&term.binding()) == Some(&ValueTypeTag::Duration))
        {
            return Err(invalid(
                "query_plan_sort_unordered_value",
                "sort requires an ordered value type; durations have no total order",
            ));
        }
    }
    if !has_sort
        && read_tail
            .iter()
            .any(|stage| matches!(stage, ReadStage::Offset { .. } | ReadStage::Limit { .. }))
    {
        return Err(invalid(
            "query_plan_unordered_truncation",
            "offset and limit require explicit sort",
        ));
    }
    if let Some(document) = fetched {
        index.thing_document(document, &mandatory, &optional, &types)?;
    } else if !matches!(&spec.output, QueryOutput::Rows { columns } if columns.is_empty() && matches!(spec.operation,Operation::Count|Operation::Exists|Operation::Write{returns:WriteReturns::Matched}))
    {
        validate_output(&spec.output, &mandatory, &optional, limits.structural)?;
    }
    Ok(())
}

/// TypeDB 3.14 refuses range comparisons of durations (3.13 accepted them);
/// refuse them at build time on every profile so a plan fails the same way
/// before reaching any server. Operands whose domain is unknown here
/// (branch-local bindings) are left to the server.
fn refuse_duration_ranges(
    patterns: &[QueryPattern],
    scalar_types: &BTreeMap<BindingId, ValueTypeTag>,
    inputs: &[InputColumn],
) -> Result<(), Diagnostic> {
    use crate::migration_assertion::ValueComparator;
    let duration = |operand: &QueryOperand| match operand {
        QueryOperand::Literal { value } => value.value_type() == ValueTypeTag::Duration,
        QueryOperand::Binding { binding } => {
            scalar_types.get(binding) == Some(&ValueTypeTag::Duration)
        }
        QueryOperand::Input { column } => inputs
            .get(usize::from(column.get()))
            .is_some_and(|input| input.value_type() == ValueTypeTag::Duration),
    };
    for pattern in patterns {
        match pattern {
            QueryPattern::Value {
                comparator,
                left,
                right,
            } if matches!(
                comparator,
                ValueComparator::Less
                    | ValueComparator::LessOrEqual
                    | ValueComparator::Greater
                    | ValueComparator::GreaterOrEqual
            ) && (duration(left) || duration(right)) =>
            {
                return Err(invalid(
                    "query_plan_duration_range",
                    "durations admit only equality comparison",
                ));
            }
            QueryPattern::Or { branches } => {
                for branch in branches {
                    refuse_duration_ranges(branch, scalar_types, inputs)?;
                }
            }
            QueryPattern::Not { patterns } | QueryPattern::Try { patterns } => {
                refuse_duration_ranges(patterns, scalar_types, inputs)?;
            }
            _ => {}
        }
    }
    Ok(())
}

fn nonempty(count: usize, limits: QueryLimits, nodes: &mut usize) -> Result<(), Diagnostic> {
    if count == 0 {
        return Err(invalid(
            "query_plan_write_empty",
            "a write stage requires at least one term",
        ));
    }
    *nodes = nodes.saturating_add(count);
    if count > limits.structural.boolean_terms || *nodes > limits.structural.predicate_nodes {
        return Err(failure(
            DiagnosticCategory::ResourceLimit,
            "query_plan_write_term_limit",
            "write terms exceed the structural ceiling",
        ));
    }
    Ok(())
}

fn bound(binding: BindingId, visible: &BTreeSet<BindingId>) -> Result<(), Diagnostic> {
    if visible.contains(&binding) {
        Ok(())
    } else {
        Err(invalid(
            "query_plan_write_unbound_target",
            "write references an unbound or deleted binding",
        ))
    }
}

fn validate_operand(
    operand: &QueryOperand,
    mandatory: &BTreeSet<BindingId>,
    optional: &BTreeSet<BindingId>,
    inputs: usize,
) -> Result<(), Diagnostic> {
    match operand {
        QueryOperand::Binding { binding } => {
            bound(*binding, mandatory)?;
            if optional.contains(binding) {
                return Err(invalid(
                    "query_plan_write_optional_operand",
                    "write operands require present values",
                ));
            }
        }
        QueryOperand::Input { column } if usize::from(column.get()) >= inputs => {
            return Err(invalid(
                "query_plan_unknown_input",
                "write references an undeclared input",
            ));
        }
        _ => {}
    }
    Ok(())
}

struct SchemaIndex<'a> {
    schema: &'a DeclaredSchema,
    parents: BTreeMap<TypeId, TypeId>,
}

impl<'a> SchemaIndex<'a> {
    fn new(schema: &'a DeclaredSchema) -> Self {
        Self {
            schema,
            parents: schema
                .facts()
                .filter_map(|fact| match fact {
                    SchemaFact::Sub(fact) => {
                        Some((fact.id().subtype().clone(), fact.id().supertype().clone()))
                    }
                    _ => None,
                })
                .collect(),
        }
    }
    fn ancestors(&self, type_id: &TypeId) -> Vec<TypeId> {
        let mut result = Vec::new();
        let mut seen = BTreeSet::new();
        let mut current = Some(type_id);
        while let Some(id) = current {
            if !seen.insert(id.clone()) {
                break;
            }
            result.push(id.clone());
            current = self.parents.get(id);
        }
        result
    }
    fn exists(&self, type_id: &TypeId) -> Result<(), Diagnostic> {
        if self
            .schema
            .fact(&SchemaFactId::Type(type_id.clone()))
            .is_none()
        {
            return Err(invalid(
                "query_plan_unknown_type",
                "plan references an undeclared schema type",
            ));
        }
        Ok(())
    }
    fn annotation(&self, subject: AnnotationSubjectId, kind: AnnotationKindId) -> bool {
        self.schema
            .fact(&SchemaFactId::Annotation(AnnotationFactId::new(
                subject, kind,
            )))
            .is_some()
    }
    fn concrete(&self, type_id: &TypeId) -> Result<(), Diagnostic> {
        self.exists(type_id)?;
        if self.annotation(
            AnnotationSubjectId::Type(type_id.clone()),
            AnnotationKindId::Abstract,
        ) {
            return Err(invalid(
                "query_plan_abstract_insert",
                "insert and put require concrete types",
            ));
        }
        Ok(())
    }
    fn pattern_types(
        &self,
        pattern: &QueryPattern,
        types: &mut BTreeMap<BindingId, BTreeSet<TypeId>>,
    ) -> Result<(), Diagnostic> {
        match pattern {
            QueryPattern::Isa {
                binding,
                type_id,
                include_subtypes,
            } => {
                self.exists(type_id)?;
                let candidates = types.entry(*binding).or_default();
                candidates.insert(type_id.clone());
                if *include_subtypes {
                    for fact in self.schema.facts() {
                        if let SchemaFact::Type(fact) = fact
                            && self.ancestors(fact.id()).contains(type_id)
                        {
                            candidates.insert(fact.id().clone());
                        }
                    }
                }
            }
            QueryPattern::Has {
                attribute,
                attribute_id,
                ..
            } => {
                let id = TypeId::new(TypeKind::Attribute, attribute_id.label().as_str())?;
                self.exists(&id)?;
                types.entry(*attribute).or_default().insert(id);
            }
            QueryPattern::Links {
                relation,
                relation_id,
                ..
            } => {
                self.exists(relation_id)?;
                types
                    .entry(*relation)
                    .or_default()
                    .insert(relation_id.clone());
            }
            QueryPattern::Or { branches } => {
                for branch in branches {
                    for pattern in branch {
                        self.pattern_types(pattern, types)?;
                    }
                }
            }
            QueryPattern::Try { patterns } => {
                for pattern in patterns {
                    self.pattern_types(pattern, types)?;
                }
            }
            _ => {}
        }
        Ok(())
    }
    fn ownership(
        &self,
        owner: BindingId,
        field: &OwnsFactId,
        types: &BTreeMap<BindingId, BTreeSet<TypeId>>,
        update: bool,
    ) -> Result<(), Diagnostic> {
        if self
            .schema
            .fact(&SchemaFactId::Owns(field.clone()))
            .is_none()
        {
            return Err(invalid(
                "query_plan_undeclared_owns",
                "write ownership is not declared",
            ));
        }
        let candidates = types.get(&owner).ok_or_else(|| {
            invalid(
                "query_plan_write_untyped_target",
                "write target has no schema type",
            )
        })?;
        for type_id in candidates {
            let ancestors = self.ancestors(type_id);
            if !ancestors.contains(field.owner()) {
                return Err(invalid(
                    "query_plan_wrong_owns_owner",
                    "ownership does not belong to the bound owner type",
                ));
            }
            if update
                && ancestors.iter().any(|owner| {
                    OwnsFactId::new(owner.clone(), field.attribute().clone())
                        .ok()
                        .is_some_and(|id| {
                            self.annotation(AnnotationSubjectId::Owns(id), AnnotationKindId::Key)
                        })
                })
            {
                return Err(invalid(
                    "query_plan_key_update",
                    "key ownerships cannot be updated",
                ));
            }
        }
        Ok(())
    }
    /// The fetched thing is a present entity or relation; every listed role
    /// is declared by a relation type the thing can be.
    fn thing_document(
        &self,
        document: &ThingDocument,
        mandatory: &BTreeSet<BindingId>,
        optional: &BTreeSet<BindingId>,
        types: &BTreeMap<BindingId, BTreeSet<TypeId>>,
    ) -> Result<(), Diagnostic> {
        let candidates = types
            .get(&document.thing)
            .filter(|candidates| {
                mandatory.contains(&document.thing)
                    && !optional.contains(&document.thing)
                    && !candidates.is_empty()
                    && candidates.iter().all(|type_id| {
                        matches!(type_id.kind(), TypeKind::Entity | TypeKind::Relation)
                    })
            })
            .ok_or_else(|| {
                invalid(
                    "query_plan_fetch_untyped_thing",
                    "a thing fetch requires a present entity or relation binding",
                )
            })?;
        for listed in &document.roles {
            let owner = TypeId::new(
                TypeKind::Relation,
                listed.role.declaring_relation().as_str(),
            )?;
            let relates = RelatesFactId::new(owner.clone(), listed.role.clone())?;
            if self.schema.fact(&SchemaFactId::Relates(relates)).is_none() {
                return Err(invalid(
                    "query_plan_undeclared_relates",
                    "fetched role is not declared",
                ));
            }
            if candidates
                .iter()
                .any(|id| !self.ancestors(id).contains(&owner))
            {
                return Err(invalid(
                    "query_plan_wrong_role_owner",
                    "role does not belong to the relation type",
                ));
            }
        }
        Ok(())
    }

    /// The role is declared by a relation type the bound relation can be.
    fn relation_role(
        &self,
        relation: BindingId,
        role: &RoleId,
        types: &BTreeMap<BindingId, BTreeSet<TypeId>>,
    ) -> Result<(), Diagnostic> {
        let owner = TypeId::new(TypeKind::Relation, role.declaring_relation().as_str())?;
        let relates = RelatesFactId::new(owner.clone(), role.clone())?;
        if self.schema.fact(&SchemaFactId::Relates(relates)).is_none() {
            return Err(invalid(
                "query_plan_undeclared_relates",
                "write role is not declared",
            ));
        }
        let relations = types.get(&relation).ok_or_else(|| {
            invalid(
                "query_plan_write_untyped_target",
                "relation has no schema type",
            )
        })?;
        if relations
            .iter()
            .any(|id| !self.ancestors(id).contains(&owner))
        {
            return Err(invalid(
                "query_plan_wrong_role_owner",
                "role does not belong to the relation type",
            ));
        }
        Ok(())
    }

    fn role(
        &self,
        relation: BindingId,
        role: &RoleId,
        player: BindingId,
        types: &BTreeMap<BindingId, BTreeSet<TypeId>>,
    ) -> Result<(), Diagnostic> {
        let owner = TypeId::new(TypeKind::Relation, role.declaring_relation().as_str())?;
        let relates = RelatesFactId::new(owner.clone(), role.clone())?;
        if self.schema.fact(&SchemaFactId::Relates(relates)).is_none() {
            return Err(invalid(
                "query_plan_undeclared_relates",
                "write role is not declared",
            ));
        }
        let relations = types.get(&relation).ok_or_else(|| {
            invalid(
                "query_plan_write_untyped_target",
                "relation has no schema type",
            )
        })?;
        if relations
            .iter()
            .any(|id| !self.ancestors(id).contains(&owner))
        {
            return Err(invalid(
                "query_plan_wrong_role_owner",
                "role does not belong to the relation type",
            ));
        }
        let players = types.get(&player).ok_or_else(|| {
            invalid(
                "query_plan_write_untyped_target",
                "player has no schema type",
            )
        })?;
        for player in players {
            let plays = self.ancestors(player).iter().any(|id| {
                PlaysFactId::new(id.clone(), role.clone())
                    .ok()
                    .is_some_and(|id| self.schema.fact(&SchemaFactId::Plays(id)).is_some())
            });
            if !plays {
                return Err(invalid(
                    "query_plan_undeclared_plays",
                    "player type does not declare the written role",
                ));
            }
        }
        Ok(())
    }
}

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct PlanWire {
    bindings: Vec<QueryBindingWire>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    compatibility: Option<QueryPlanV2Compatibility>,
    format: String,
    functions: Vec<LocalFunctionWire>,
    inputs: Vec<InputColumnWire>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    given_rows: Option<Vec<Vec<Option<CanonicalValue>>>>,
    operation: Operation,
    managed_semantics: FingerprintWire,
    output: serde_json::Value,
    pipeline: Vec<serde_json::Value>,
    required_capabilities: CapabilitySet,
}

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct OwnsWire {
    owner: TypeIdWire,
    attribute: String,
}
impl OwnsWire {
    fn rebuild(self) -> Result<OwnsFactId, Diagnostic> {
        OwnsFactId::new(self.owner.rebuild()?, AttributeId::new(self.attribute)?)
    }
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct ThingWire {
    binding: u16,
    type_id: TypeIdWire,
    fields: Vec<(OwnsWire, QueryOperandWire)>,
    players: Vec<(RoleIdWire, u16)>,
}
impl ThingWire {
    fn rebuild(self) -> Result<InsertThing, Diagnostic> {
        Ok(InsertThing {
            binding: BindingId::new(self.binding)?,
            type_id: self.type_id.rebuild()?,
            fields: self
                .fields
                .into_iter()
                .map(|(field, value)| Ok((field.rebuild()?, value.rebuild()?)))
                .collect::<Result<_, Diagnostic>>()?,
            players: self
                .players
                .into_iter()
                .map(|(role, player)| Ok((role.rebuild()?, BindingId::new(player)?)))
                .collect::<Result<_, Diagnostic>>()?,
        })
    }
}
#[derive(Deserialize, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
enum SetWire {
    Field {
        owner: u16,
        field: OwnsWire,
        operand: QueryOperandWire,
    },
    Link {
        relation: u16,
        role: RoleIdWire,
        player: u16,
    },
}
impl SetWire {
    fn rebuild(self) -> Result<Set, Diagnostic> {
        Ok(match self {
            Self::Field {
                owner,
                field,
                operand,
            } => Set::Field {
                owner: BindingId::new(owner)?,
                field: field.rebuild()?,
                operand: operand.rebuild()?,
            },
            Self::Link {
                relation,
                role,
                player,
            } => Set::Link {
                relation: BindingId::new(relation)?,
                role: role.rebuild()?,
                player: BindingId::new(player)?,
            },
        })
    }
}
#[derive(Deserialize, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
enum DeleteWire {
    Thing {
        binding: u16,
    },
    Has {
        owner: u16,
        field: OwnsWire,
    },
    Links {
        relation: u16,
        role: RoleIdWire,
        player: u16,
    },
    Players {
        relation: u16,
        role: RoleIdWire,
    },
}
impl DeleteWire {
    fn rebuild(self) -> Result<DeleteItem, Diagnostic> {
        Ok(match self {
            Self::Thing { binding } => DeleteItem::Thing {
                binding: BindingId::new(binding)?,
            },
            Self::Has { owner, field } => DeleteItem::Has {
                owner: BindingId::new(owner)?,
                field: field.rebuild()?,
            },
            Self::Links {
                relation,
                role,
                player,
            } => DeleteItem::Links {
                relation: BindingId::new(relation)?,
                role: role.rebuild()?,
                player: BindingId::new(player)?,
            },
            Self::Players { relation, role } => DeleteItem::Players {
                relation: BindingId::new(relation)?,
                role: role.rebuild()?,
            },
        })
    }
}
#[derive(Deserialize, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
enum AttachWire {
    Has {
        owner: u16,
        field: OwnsWire,
        operand: QueryOperandWire,
    },
    Links {
        relation: u16,
        role: RoleIdWire,
        player: u16,
    },
}
impl AttachWire {
    fn rebuild(self) -> Result<AttachItem, Diagnostic> {
        Ok(match self {
            Self::Has {
                owner,
                field,
                operand,
            } => AttachItem::Has {
                owner: BindingId::new(owner)?,
                field: field.rebuild()?,
                operand: operand.rebuild()?,
            },
            Self::Links {
                relation,
                role,
                player,
            } => AttachItem::Links {
                relation: BindingId::new(relation)?,
                role: role.rebuild()?,
                player: BindingId::new(player)?,
            },
        })
    }
}
#[derive(Deserialize, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
enum WriteWire {
    Attach { items: Vec<AttachWire> },
    Insert { things: Vec<ThingWire> },
    Update { sets: Vec<SetWire> },
    Delete { items: Vec<DeleteWire> },
    Put { things: Vec<ThingWire> },
}
impl WriteWire {
    fn rebuild(self) -> Result<Stage, Diagnostic> {
        Ok(match self {
            Self::Attach { items } => Stage::Attach {
                items: items
                    .into_iter()
                    .map(AttachWire::rebuild)
                    .collect::<Result<_, _>>()?,
            },
            Self::Insert { things } => Stage::Insert {
                things: things
                    .into_iter()
                    .map(ThingWire::rebuild)
                    .collect::<Result<_, _>>()?,
            },
            Self::Put { things } => Stage::Put {
                things: things
                    .into_iter()
                    .map(ThingWire::rebuild)
                    .collect::<Result<_, _>>()?,
            },
            Self::Update { sets } => Stage::Update {
                sets: sets
                    .into_iter()
                    .map(SetWire::rebuild)
                    .collect::<Result<_, _>>()?,
            },
            Self::Delete { items } => Stage::Delete {
                items: items
                    .into_iter()
                    .map(DeleteWire::rebuild)
                    .collect::<Result<_, _>>()?,
            },
        })
    }
}
fn decode_stage(value: serde_json::Value) -> Result<Stage, Diagnostic> {
    if value.get("kind").and_then(serde_json::Value::as_str) == Some("match") {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct MatchWire {
            kind: String,
            patterns: Vec<serde_json::Value>,
        }
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct LetWire {
            kind: String,
            binding: u16,
            expr: ExprWire,
        }
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct IidWire {
            kind: String,
            binding: u16,
            iid: String,
        }
        let wire: MatchWire = serde_json::from_value(value)
            .map_err(|_| invalid("invalid_canonical_value", "invalid match stage"))?;
        debug_assert_eq!(wire.kind, "match");
        return Ok(Stage::Match {
            patterns: wire
                .patterns
                .into_iter()
                .map(|value| {
                    if value.get("kind").and_then(serde_json::Value::as_str) == Some("let") {
                        let wire: LetWire = serde_json::from_value(value).map_err(|_| {
                            invalid("invalid_canonical_value", "invalid let pattern")
                        })?;
                        debug_assert_eq!(wire.kind, "let");
                        Ok(Pattern::Let {
                            binding: BindingId::new(wire.binding)?,
                            expr: wire.expr.rebuild()?,
                        })
                    } else if value.get("kind").and_then(serde_json::Value::as_str) == Some("iid") {
                        let wire: IidWire = serde_json::from_value(value).map_err(|_| {
                            invalid("invalid_canonical_value", "invalid iid pattern")
                        })?;
                        debug_assert_eq!(wire.kind, "iid");
                        Ok(Pattern::Iid {
                            binding: BindingId::new(wire.binding)?,
                            iid: wire.iid,
                        })
                    } else {
                        Ok(Pattern::Read(rebuild_pattern_v2(value)?))
                    }
                })
                .collect::<Result<_, Diagnostic>>()?,
        });
    }

    if value.get("kind").and_then(serde_json::Value::as_str) == Some("fetch") {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct RoleWire {
            required: bool,
            role: RoleIdWire,
        }
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct FetchWire {
            kind: String,
            roles: Vec<RoleWire>,
            thing: u16,
        }
        let wire: FetchWire = serde_json::from_value(value)
            .map_err(|_| invalid("invalid_canonical_value", "invalid fetch stage"))?;
        debug_assert_eq!(wire.kind, "fetch");
        return Ok(Stage::Fetch(ThingDocument::new(
            BindingId::new(wire.thing)?,
            wire.roles
                .into_iter()
                .map(|role| Ok(DocumentRole::new(role.role.rebuild()?, role.required)))
                .collect::<Result<_, Diagnostic>>()?,
        )));
    }
    if matches!(
        value.get("kind").and_then(serde_json::Value::as_str),
        Some("insert" | "update" | "delete" | "put" | "attach")
    ) {
        serde_json::from_value::<WriteWire>(value)
            .map_err(|_| invalid("invalid_canonical_value", "invalid write stage"))?
            .rebuild()
    } else {
        Ok(rebuild_read_stage_v2(value)?.into())
    }
}

/// Decode exact canonical V3 bytes using local schema authority.
pub fn decode_query_plan_v3(
    bytes: &[u8],
    schema: &DeclaredSchema,
) -> Result<QueryPlanV3, Diagnostic> {
    decode_query_plan_v3_with_limits(bytes, schema, QueryLimits::CANONICAL)
}

/// Decode under caller-selected codec and structural ceilings.
pub fn decode_query_plan_v3_with_limits(
    bytes: &[u8],
    schema: &DeclaredSchema,
    limits: QueryLimits,
) -> Result<QueryPlanV3, Diagnostic> {
    let wire: PlanWire = from_canonical_json_with_limits(bytes, limits.codec)?;
    if wire.format != QUERY_PLAN_FORMAT_V3 {
        return Err(invalid(
            "query_plan_format_unsupported",
            "V3 decoding requires the exact V3 discriminator",
        ));
    }
    let claims = wire.required_capabilities;
    let plan = QueryPlanV3::new_with_limits(
        PlanSpec {
            bindings: wire
                .bindings
                .into_iter()
                .map(QueryBindingWire::rebuild)
                .collect::<Result<_, _>>()?,
            given_rows: wire
                .given_rows
                .map(|rows| rows.into_iter().map(InputRow::new).collect()),
            operation: wire.operation,
            inputs: wire
                .inputs
                .into_iter()
                .map(InputColumnWire::rebuild)
                .collect::<Result<_, _>>()?,
            pipeline: wire
                .pipeline
                .into_iter()
                .map(decode_stage)
                .collect::<Result<_, _>>()?,
            output: rebuild_output(wire.output)?,
            managed_semantics: ManagedSemanticSchemaFingerprint::from_wire(
                wire.managed_semantics.rebuild()?,
            )?,
            compatibility: wire.compatibility,
            functions: wire
                .functions
                .into_iter()
                .map(LocalFunctionWire::rebuild)
                .collect::<Result<_, _>>()?,
        },
        schema,
        limits,
    )?;
    if claims != plan.required_capabilities {
        return Err(invalid(
            "query_plan_capability_claim_mismatch",
            "V3 capabilities must be syntax-derived",
        ));
    }
    if plan.canonical_bytes()? != bytes {
        return Err(invalid(
            "query_plan_wire_mismatch",
            "V3 reconstruction changes canonical bytes",
        ));
    }
    Ok(plan)
}

fn validate_operation(spec: &PlanSpec) -> Result<(), Diagnostic> {
    let writes = spec.pipeline.iter().any(Stage::is_write);
    if writes != matches!(spec.operation, Operation::Write { .. }) {
        return Err(invalid(
            "query_plan_operation_write_mismatch",
            "read operations require read stages; write requires a write stage",
        ));
    }
    if matches!(
        spec.operation,
        Operation::Write {
            returns: WriteReturns::Matched
        }
    ) && !matches!(&spec.output,QueryOutput::Rows{columns} if columns.is_empty())
    {
        return Err(invalid(
            "query_plan_matched_projection",
            "matched writes have no projected output",
        ));
    }
    Ok(())
}

fn read_uses_given(pattern: &QueryPattern) -> bool {
    match pattern {
        QueryPattern::Value { left, right, .. } => [left, right].iter().any(|operand| {
            matches!(
                operand,
                QueryOperand::Literal { .. } | QueryOperand::Input { .. }
            )
        }),
        QueryPattern::FunctionCall { .. } => true,
        QueryPattern::Or { branches } => branches.iter().flatten().any(read_uses_given),
        QueryPattern::Not { patterns } | QueryPattern::Try { patterns } => {
            patterns.iter().any(read_uses_given)
        }
        _ => false,
    }
}
fn add_read_given_capability(
    pipeline: &[Stage],
    functions: &[LocalFunction],
    inputs: &[InputColumn],
    capabilities: &mut CapabilitySet,
) -> Result<(), Diagnostic> {
    if !inputs.is_empty() || pipeline.iter().any(|stage|matches!(stage,Stage::Match{patterns} if patterns.iter().any(|pattern|matches!(pattern,Pattern::Read(pattern) if read_uses_given(pattern))))) || functions.iter().any(|function|function.body().iter().any(read_uses_given)) {
        insert_capability(capabilities,"query.input.given-rows")?;
    }
    Ok(())
}

impl SchemaIndex<'_> {
    fn attribute_domain(&self, attribute: &AttributeId) -> Option<ValueTypeTag> {
        let type_id = TypeId::new(TypeKind::Attribute, attribute.label().as_str()).ok()?;
        self.ancestors(&type_id).iter().find_map(|id| {
            let attribute = AttributeId::new(id.label().as_str()).ok()?;
            match self
                .schema
                .fact(&SchemaFactId::Value(crate::schema::ValueFactId::new(
                    attribute,
                ))) {
                Some(SchemaFact::Value(fact)) => Some(fact.value_type()),
                _ => None,
            }
        })
    }
    fn scalar_domain(&self, types: &BTreeSet<TypeId>) -> Option<ValueTypeTag> {
        let mut domain = None;
        for type_id in types {
            if type_id.kind() != TypeKind::Attribute {
                return None;
            }
            let found = self.attribute_domain(&AttributeId::new(type_id.label().as_str()).ok()?)?;
            if domain.is_some_and(|domain| domain != found) {
                return None;
            }
            domain = Some(found);
        }
        domain
    }
    fn field_value(
        &self,
        field: &OwnsFactId,
        operand: &QueryOperand,
        bindings: &BTreeMap<BindingId, ValueTypeTag>,
        inputs: &[InputColumn],
    ) -> Result<(), Diagnostic> {
        let expected = self.attribute_domain(field.attribute()).ok_or_else(|| {
            invalid(
                "query_plan_write_value_type",
                "ownership has no unique scalar domain",
            )
        })?;
        let actual = operand_type(operand, bindings, inputs)?;
        if actual != expected {
            return Err(invalid(
                "query_plan_write_value_type",
                "write operand differs from the ownership scalar domain",
            ));
        }
        Ok(())
    }
    fn function_values(
        &self,
        patterns: &[QueryPattern],
        functions: &[LocalFunction],
        mandatory: &BTreeSet<BindingId>,
        values: &mut BTreeMap<BindingId, ValueTypeTag>,
    ) -> Result<(), Diagnostic> {
        use crate::schema::{FunctionReturnMode, TypeReference};
        for pattern in patterns {
            match pattern {
                QueryPattern::FunctionCall {
                    assigned, function, ..
                } if mandatory.contains(assigned) => {
                    let domain = if let Some(local) =
                        functions.iter().find(|local| local.name() == function)
                    {
                        Some(local.returns().value_type())
                    } else if let Some(SchemaFact::Function(function)) =
                        self.schema.fact(&SchemaFactId::Function(function.clone()))
                    {
                        match function.signature().returns() {
                            FunctionReturnMode::Scalar(element) if !element.optional() => {
                                match element.type_ref() {
                                    TypeReference::Value(domain) => Some(*domain),
                                    TypeReference::Schema(label) => {
                                        self.attribute_domain(&AttributeId::new(label.as_str())?)
                                    }
                                }
                            }
                            _ => None,
                        }
                    } else {
                        return Err(invalid(
                            "query_plan_unknown_function",
                            "expression references an undeclared function",
                        ));
                    };
                    if let Some(domain) = domain
                        && values
                            .insert(*assigned, domain)
                            .is_some_and(|previous| previous != domain)
                    {
                        return Err(invalid(
                            "query_plan_expression_binding",
                            "function binding has inconsistent scalar domains",
                        ));
                    }
                }
                QueryPattern::Or { branches } => {
                    for branch in branches {
                        self.function_values(branch, functions, mandatory, values)?;
                    }
                }
                QueryPattern::Try { patterns } => {
                    self.function_values(patterns, functions, mandatory, values)?
                }
                _ => {}
            }
        }
        Ok(())
    }
}

fn collect_produced_bindings(pattern: &QueryPattern, bindings: &mut BTreeSet<BindingId>) {
    match pattern {
        QueryPattern::Or { branches } => {
            for branch in branches {
                for pattern in branch {
                    collect_produced_bindings(pattern, bindings);
                }
            }
        }
        QueryPattern::Not { patterns } | QueryPattern::Try { patterns } => {
            for pattern in patterns {
                collect_produced_bindings(pattern, bindings);
            }
        }
        _ => collect_direct_positive_bindings(pattern, bindings),
    }
}