distributed 4.2.0

CQRS/ES framework for Rust using Plain Old Rust Structs — append-only events, replay, snapshots, outbox, service bus, and pluggable infrastructure
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
//! Typed projection authoring metadata and authoritative ORM lowering.
//!
//! Portable declarations resolve through [`super::ProjectionPlanTemplate`].
//! This module then maps their logical field names through the existing
//! [`crate::RelationalReadModel`] schema and stages the same
//! [`crate::read_model::ReadModelWritePlanBuilder`] used by hand-written server code.

use std::collections::BTreeMap;
use std::fmt;
use std::marker::PhantomData;
use std::sync::{OnceLock, RwLock};

use super::ResolvedProjectionField;
use crate::read_model::{ReadModelWritePlanBuilder, RelationalReadModel};
use crate::table::validate_row_values;
use crate::{
    ColumnType, DomainEvent, DomainEventOccurrence, DomainState, ExpectedVersion, PatchMode,
    ProjectionArm, ProjectionAssignment, ProjectionEventSelector, ProjectionEventSet,
    ProjectionExpression, ProjectionField, ProjectionInvalidation, ProjectionKeyField,
    ProjectionMutationKind, ProjectionOperation, ProjectionPartition, ProjectionPlanTemplate,
    ProjectionProgram, ProjectionProgramError, ProjectionProgramId, ProjectionRelationship,
    ProjectionRelationshipEffect, ProjectionTarget, ProjectionValue, ProjectionValueRef,
    ProjectionValueType, ResolvedProjectionKey, ResolvedProjectionMutation, ResolvedProjectionPlan,
    ResolvedProjectionValue, RowKey, RowPatch, RowValue, RowValues, RowWriteMode,
    TableAdapterCapabilities, TableSchema, TableStoreError, TableWritePlan,
};

/// Flat portable Rust field category emitted by the domain-state/event derives.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProjectionPortableType {
    /// Boolean scalar.
    Boolean,
    /// Signed integer scalar.
    I64,
    /// Unsigned integer scalar.
    U64,
    /// Floating-point scalar.
    F64,
    /// UTF-8 string.
    String,
    /// Byte sequence.
    Bytes,
    /// Structured JSON value.
    Json,
    /// A user type whose exact Rust identity must match.
    Custom,
}

/// Hidden compile-time field metadata for a domain-event body.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ProjectionBodyFieldMetadata {
    /// Rust source-field name.
    pub rust_name: &'static str,
    /// Serialized body-field name.
    pub wire_name: &'static str,
    /// Canonical inner Rust type identity (without `Option`).
    pub rust_type: &'static str,
    /// Flat portable category.
    pub portable_type: ProjectionPortableType,
    /// Whether the serialized value may be null.
    pub nullable: bool,
    /// Whether this field is present in the serialized body.
    pub present: bool,
    /// Whether serialization always includes the field rather than applying a
    /// conditional omission rule.
    pub always_present: bool,
}

/// Hidden compile-time portable-body metadata emitted by `DomainState` and
/// `DomainEvent`.
#[doc(hidden)]
pub trait ProjectionBodyMetadata {
    /// Canonical flat body fields in declaration order.
    const PROJECTION_FIELDS: &'static [ProjectionBodyFieldMetadata];
    /// Independent fingerprint of the portable field inventory.
    const PROJECTION_SCHEMA_FINGERPRINT: &'static str;
}

/// Hidden compile-time field metadata for a relational read model.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ProjectionModelFieldMetadata {
    /// Rust model-field name used by projection declarations.
    pub field_name: &'static str,
    /// Physical column name owned by the existing ORM.
    pub column_name: &'static str,
    /// Canonical inner Rust type identity (without `Option`).
    pub rust_type: &'static str,
    /// Flat portable category.
    pub portable_type: ProjectionPortableType,
    /// Whether the mapped field may be null.
    pub nullable: bool,
    /// Whether a complete write requires an explicit value.
    pub required: bool,
    /// Whether this field is part of the complete primary key.
    pub primary_key: bool,
}

/// Hidden compile-time portable read-model metadata emitted by `ReadModel`.
#[doc(hidden)]
pub trait ProjectionReadModelMetadata: RelationalReadModel {
    /// Canonical mapped fields in declaration order.
    const PROJECTION_FIELDS: &'static [ProjectionModelFieldMetadata];
    /// Independent fingerprint of fields, keys, storage and relationships.
    const PROJECTION_SCHEMA_FINGERPRINT: &'static str;
}

/// Hidden relationship marker implemented on the marker types emitted by
/// `ReadModel`.
#[doc(hidden)]
pub trait ProjectionRelationshipMetadata {
    /// Relationship source read model.
    type Source: ProjectionReadModelMetadata;
    /// Relationship target read model.
    type Target: ProjectionReadModelMetadata;
    /// Stable relationship field.
    const FIELD: &'static str;
}

/// Hidden exact deletion-body descriptor emitted for a sourced aggregate
/// identity used by `domain = deleted`.
#[doc(hidden)]
pub trait ProjectionDeletionMetadata {
    /// Stable `DomainDeletion<Identity>` body type name.
    const BODY_TYPE_NAME: &'static str;
    /// Independently versioned canonical deletion body schema.
    const BODY_SCHEMA: &'static str;
    /// Canonical SHA-256 body-schema fingerprint.
    const BODY_FINGERPRINT: &'static str;
}

/// Compile-time proof that the common state-upsert shorthand has exact flat
/// coverage.
///
/// Renamed, missing, extra, omitted, nested, type-incompatible, or
/// nullability-incompatible fields intentionally fail constant evaluation.
#[doc(hidden)]
pub const fn assert_state_upsert_compatible(
    state: &[ProjectionBodyFieldMetadata],
    model: &[ProjectionModelFieldMetadata],
) {
    let mut state_index = 0;
    while state_index < state.len() {
        if !state[state_index].present || !state[state_index].always_present {
            panic!("projection state-upsert rejects omitted state fields");
        }
        state_index += 1;
    }
    if state.len() != model.len() {
        panic!("projection state-upsert requires exact field coverage");
    }

    let mut model_index = 0;
    while model_index < model.len() {
        let model_field = &model[model_index];
        let mut found = false;
        let mut candidate_index = 0;
        while candidate_index < state.len() {
            let candidate = &state[candidate_index];
            if candidate.present && const_str_eq(candidate.wire_name, model_field.field_name) {
                if !const_str_eq(candidate.rust_name, candidate.wire_name) {
                    panic!("projection state-upsert rejects renamed state fields");
                }
                if !const_str_eq(candidate.rust_type, model_field.rust_type)
                    || !portable_type_eq(candidate.portable_type, model_field.portable_type)
                {
                    panic!("projection state-upsert field type mismatch");
                }
                if candidate.nullable != model_field.nullable {
                    panic!("projection state-upsert field nullability mismatch");
                }
                if matches!(
                    candidate.portable_type,
                    ProjectionPortableType::Json | ProjectionPortableType::Bytes
                ) {
                    panic!(
                        "projection state-upsert nested/collection fields require an explicit block"
                    );
                }
                found = true;
                break;
            }
            candidate_index += 1;
        }
        if !found {
            panic!("projection state-upsert field is missing or renamed");
        }
        model_index += 1;
    }
}

/// Compile-time proof for one explicit direct body-field mapping.
#[doc(hidden)]
pub const fn assert_explicit_field_compatible(
    body: &[ProjectionBodyFieldMetadata],
    source: &str,
    model: &[ProjectionModelFieldMetadata],
    target: &str,
) {
    let mut source_index = 0;
    while source_index < body.len() && !const_str_eq(body[source_index].rust_name, source) {
        source_index += 1;
    }
    if source_index == body.len() || !body[source_index].present {
        panic!("projection body field does not exist");
    }
    let mut target_index = 0;
    while target_index < model.len() && !const_str_eq(model[target_index].field_name, target) {
        target_index += 1;
    }
    if target_index == model.len() {
        panic!("projection read-model field does not exist");
    }
    let source_field = &body[source_index];
    let target_field = &model[target_index];
    if !const_str_eq(source_field.rust_type, target_field.rust_type)
        || !portable_type_eq(source_field.portable_type, target_field.portable_type)
    {
        panic!("projection explicit field type mismatch");
    }
    if source_field.nullable && !target_field.nullable {
        panic!("projection nullable body field cannot target a non-null read-model field");
    }
}

const fn portable_type_eq(left: ProjectionPortableType, right: ProjectionPortableType) -> bool {
    left as u8 == right as u8
}

const fn const_str_eq(left: &str, right: &str) -> bool {
    let left = left.as_bytes();
    let right = right.as_bytes();
    if left.len() != right.len() {
        return false;
    }
    let mut index = 0;
    while index < left.len() {
        if left[index] != right[index] {
            return false;
        }
        index += 1;
    }
    true
}

/// Generated candidate for direct placement.
///
/// The macro emits this marker only for the exact full-state upsert shorthand.
/// It is a syntactic capability, not the final direct-placement proof:
/// `.direct()` revalidates the materialized program, schemas, and placement
/// constraints before a catalog binding can be constructed.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DirectCandidate;

/// Marker for a program that must use eventual execution until a stronger
/// direct evidence protocol exists.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EventualOnly;

/// One model in a projection's generated output inventory.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProjectionOutputModel {
    /// Logical model name.
    pub model: String,
    /// Physical storage identity.
    pub storage: String,
    /// Fingerprint emitted by the model derive.
    pub schema_fingerprint: String,
    /// Exact validated schema used by the authoritative ORM lowerer.
    pub schema: TableSchema,
}

impl ProjectionOutputModel {
    /// Construct an inventory entry from the authoritative ORM model metadata.
    ///
    /// # Errors
    ///
    /// Returns a schema validation error before any storage operation.
    pub fn of<M>() -> Result<Self, TableStoreError>
    where
        M: ProjectionReadModelMetadata,
    {
        let schema = ReadModelWritePlanBuilder::projection_validated_schema::<M>()?;
        Ok(Self {
            model: schema.model_name.clone(),
            storage: schema.table_name.clone(),
            schema_fingerprint: M::PROJECTION_SCHEMA_FINGERPRINT.to_owned(),
            schema: schema.clone(),
        })
    }
}

/// Canonical model and relationship inventory generated by one declaration.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ProjectionOutputInventory {
    /// Sorted, duplicate-free output models.
    pub models: Vec<ProjectionOutputModel>,
    /// Sorted, duplicate-free logical relationships.
    pub relationships: Vec<ProjectionRelationship>,
}

impl ProjectionOutputInventory {
    /// Canonicalize a generated inventory.
    pub fn new(
        mut models: Vec<ProjectionOutputModel>,
        mut relationships: Vec<ProjectionRelationship>,
    ) -> Self {
        models.sort_by(|left, right| {
            (&left.model, &left.storage, &left.schema_fingerprint).cmp(&(
                &right.model,
                &right.storage,
                &right.schema_fingerprint,
            ))
        });
        models.dedup();
        relationships.sort();
        relationships.dedup();
        Self {
            models,
            relationships,
        }
    }
}

/// Generated program factory function.
#[doc(hidden)]
pub type ProjectionProgramFactory = fn() -> Result<ProjectionProgram, ProjectionProgramError>;
/// Generated exact occurrence resolver function.
#[doc(hidden)]
pub type ProjectionResolver =
    fn(&DomainEventOccurrence) -> Result<ResolvedProjectionPlan, ProjectionProgramError>;
/// Generated authoritative ORM lowerer function.
#[doc(hidden)]
pub type ProjectionLowerer =
    fn(&ResolvedProjectionPlan) -> Result<LoweredProjectionPlan, ProjectionLoweringError>;
/// Generated output inventory factory function.
#[doc(hidden)]
pub type ProjectionInventoryFactory =
    fn() -> Result<ProjectionOutputInventory, ProjectionLoweringError>;

/// Const descriptor generated by `projection!`.
///
/// `D` is a compiler-generated placement-candidate classification. Every
/// projection may be mounted eventually; only [`DirectCandidate`] descriptors
/// may attempt the direct-placement extension, which revalidates the generated
/// candidate before constructing a binding.
#[derive(Clone, Copy)]
pub struct ProjectionDescriptor<D = EventualOnly> {
    name: &'static str,
    version: u64,
    epoch: &'static str,
    program: ProjectionProgramFactory,
    resolve: ProjectionResolver,
    lower: ProjectionLowerer,
    inventory: ProjectionInventoryFactory,
    marker: PhantomData<fn() -> D>,
}

impl<D> fmt::Debug for ProjectionDescriptor<D> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ProjectionDescriptor")
            .field("name", &self.name)
            .field("version", &self.version)
            .field("epoch", &self.epoch)
            .finish_non_exhaustive()
    }
}

impl<D> ProjectionDescriptor<D> {
    /// Construct a generated descriptor from closed function items.
    #[doc(hidden)]
    pub const fn __generated(
        name: &'static str,
        version: u64,
        epoch: &'static str,
        program: ProjectionProgramFactory,
        resolve: ProjectionResolver,
        lower: ProjectionLowerer,
        inventory: ProjectionInventoryFactory,
    ) -> Self {
        Self {
            name,
            version,
            epoch,
            program,
            resolve,
            lower,
            inventory,
            marker: PhantomData,
        }
    }

    /// Return the stable projection name.
    pub fn name(&self) -> &'static str {
        self.name
    }

    /// Return the independently evolving declaration version.
    pub fn version(&self) -> u64 {
        self.version
    }

    /// Return the rebuild/ownership incarnation.
    ///
    /// Epoch is binding metadata and is intentionally excluded from
    /// [`ProjectionProgramId`].
    pub fn epoch(&self) -> &'static str {
        self.epoch
    }

    /// Build the canonical task-7 portable program.
    ///
    /// # Errors
    ///
    /// Returns declaration or ORM metadata validation failures.
    pub fn program(&self) -> Result<ProjectionProgram, ProjectionProgramError> {
        (self.program)()
    }

    /// Compute the canonical task-7 program digest.
    ///
    /// # Errors
    ///
    /// Returns declaration or canonical encoding failures.
    pub fn program_id(&self) -> Result<ProjectionProgramId, ProjectionProgramError> {
        self.program()?.id()
    }

    /// Resolve one exact domain-event occurrence.
    ///
    /// # Errors
    ///
    /// Returns exact-selector, expression, or logical-plan failures.
    pub fn resolve(
        &self,
        occurrence: &DomainEventOccurrence,
    ) -> Result<ResolvedProjectionPlan, ProjectionProgramError> {
        (self.resolve)(occurrence)
    }

    /// Lower a resolved logical plan through the existing relational ORM.
    ///
    /// # Errors
    ///
    /// Returns unknown generated operations, metadata, completeness, key,
    /// relationship, or adapter-capability failures before I/O.
    pub fn lower(
        &self,
        plan: &ResolvedProjectionPlan,
    ) -> Result<LoweredProjectionPlan, ProjectionLoweringError> {
        (self.lower)(plan)
    }

    /// Return canonical generated output inventory.
    ///
    /// # Errors
    ///
    /// Returns invalid ORM metadata.
    pub fn output_inventory(&self) -> Result<ProjectionOutputInventory, ProjectionLoweringError> {
        (self.inventory)()
    }

    /// Return the generated server executor descriptor.
    ///
    /// # Errors
    ///
    /// Returns program or inventory construction failures.
    pub fn server_executor(
        &self,
    ) -> Result<ProjectionServerExecutorDescriptor, ProjectionLoweringError> {
        let program = self.program()?;
        Ok(ProjectionServerExecutorDescriptor {
            name: self.name,
            version: self.version,
            epoch: self.epoch,
            program_id: program.id()?,
            outputs: self.output_inventory()?,
            selectors: program
                .arms()
                .iter()
                .map(|arm| arm.selector().clone())
                .collect(),
            unit_partition: matches!(program.partition(), ProjectionPartition::Unit),
            resolve: self.resolve,
            lower: self.lower,
        })
    }
}

/// Store-free generated server executor metadata.
#[derive(Clone)]
pub struct ProjectionServerExecutorDescriptor {
    /// Stable program name.
    pub name: &'static str,
    /// Declaration version.
    pub version: u64,
    /// Rebuild/ownership epoch.
    pub epoch: &'static str,
    /// Canonical portable program identity.
    pub program_id: ProjectionProgramId,
    /// Canonical output inventory.
    pub outputs: ProjectionOutputInventory,
    selectors: Vec<ProjectionEventSelector>,
    #[cfg_attr(not(feature = "graphql"), allow(dead_code))]
    unit_partition: bool,
    resolve: ProjectionResolver,
    lower: ProjectionLowerer,
}

impl ProjectionServerExecutorDescriptor {
    pub(crate) fn matches(&self, occurrence: &DomainEventOccurrence) -> bool {
        self.selectors
            .iter()
            .any(|selector| selector.matches(occurrence))
    }

    #[cfg(feature = "graphql")]
    pub(crate) fn has_unit_partition(&self) -> bool {
        self.unit_partition
    }

    /// Resolve and physically lower an exact occurrence without performing I/O.
    ///
    /// # Errors
    ///
    /// Returns portable resolution or authoritative ORM validation failures.
    pub fn plan(
        &self,
        occurrence: &DomainEventOccurrence,
    ) -> Result<LoweredProjectionPlan, ProjectionLoweringError> {
        let resolved = (self.resolve)(occurrence)?;
        (self.lower)(&resolved)
    }
}

/// Process-wide registry of placement-selected direct projection executors.
///
/// Service construction registers each direct modeled owner by output model
/// name. Command handlers then call `commit()?.atomic()` without naming a
/// projection selector; the runtime looks up the executor by returned model.
static PLACEMENT_SELECTED_DIRECT: OnceLock<
    RwLock<BTreeMap<String, ProjectionServerExecutorDescriptor>>,
> = OnceLock::new();

fn placement_selected_direct_registry(
) -> &'static RwLock<BTreeMap<String, ProjectionServerExecutorDescriptor>> {
    PLACEMENT_SELECTED_DIRECT.get_or_init(|| RwLock::new(BTreeMap::new()))
}

/// Register the placement-selected direct executor for one output model.
///
/// Called from service/projection registration. Replacing an existing model
/// entry is allowed so tests can rebuild services.
pub fn register_placement_selected_direct(
    model: impl Into<String>,
    executor: ProjectionServerExecutorDescriptor,
) {
    let model = model.into();
    if let Ok(mut guard) = placement_selected_direct_registry().write() {
        guard.insert(model, executor);
    }
}

/// Look up the placement-selected direct executor for a returned model.
pub fn placement_selected_direct_for_model(
    model: &str,
) -> Option<ProjectionServerExecutorDescriptor> {
    placement_selected_direct_registry()
        .read()
        .ok()
        .and_then(|guard| guard.get(model).cloned())
}

/// Register every single-model output of a direct descriptor for placement
/// selection. Multi-model descriptors are not eligible for `Atomic<M>`.
///
/// # Errors
///
/// Returns executor construction failures.
pub fn register_placement_selected_direct_descriptor(
    descriptor: &ProjectionDescriptor<DirectCandidate>,
) -> Result<(), ProjectionLoweringError> {
    let executor = descriptor.server_executor()?;
    if executor.outputs.models.len() == 1 {
        let model = executor.outputs.models[0].model.clone();
        register_placement_selected_direct(model, executor);
    }
    Ok(())
}

/// Physical ORM plan plus the canonical logical plan that produced it.
#[derive(Clone, Debug, PartialEq)]
pub struct LoweredProjectionPlan {
    /// Existing authoritative adapter write plan.
    pub write_plan: TableWritePlan,
    /// Resolved logical plan retaining occurrence and relationship provenance.
    pub resolved: ResolvedProjectionPlan,
}

impl LoweredProjectionPlan {
    /// Validate adapter support before executing any mutation.
    ///
    /// # Errors
    ///
    /// Returns an adapter-capability or row-shape error.
    pub fn validate_for(
        &self,
        capabilities: &TableAdapterCapabilities,
    ) -> Result<(), TableStoreError> {
        self.write_plan.validate_for(capabilities)
    }
}

/// Typed physical lowering failure.
#[derive(Debug)]
#[non_exhaustive]
pub enum ProjectionLoweringError {
    /// Portable program construction or resolution failed.
    Program(ProjectionProgramError),
    /// Existing ORM metadata or write-plan validation failed.
    Table(TableStoreError),
    /// Generated lowering did not recognize a resolved arm/operation.
    UnknownOperation {
        /// Selected arm.
        arm: String,
        /// Contributing operation IDs.
        operations: Vec<String>,
    },
    /// A related operation could not find its parent row mutation.
    MissingRelatedParent {
        /// Selected arm.
        arm: String,
        /// Parent operation ID.
        operation: String,
    },
}

impl fmt::Display for ProjectionLoweringError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Program(error) => error.fmt(formatter),
            Self::Table(error) => error.fmt(formatter),
            Self::UnknownOperation { arm, operations } => write!(
                formatter,
                "projection arm `{arm}` has no generated lowerer for operations {operations:?}"
            ),
            Self::MissingRelatedParent { arm, operation } => write!(
                formatter,
                "projection arm `{arm}` is missing related parent operation `{operation}`"
            ),
        }
    }
}

impl std::error::Error for ProjectionLoweringError {}

impl From<ProjectionProgramError> for ProjectionLoweringError {
    fn from(error: ProjectionProgramError) -> Self {
        Self::Program(error)
    }
}

impl From<TableStoreError> for ProjectionLoweringError {
    fn from(error: TableStoreError) -> Self {
        Self::Table(error)
    }
}

/// Hidden explicit field/expression pair generated by `projection!`.
#[doc(hidden)]
#[derive(Clone)]
pub struct ProjectionAuthoringField {
    field: String,
    assignment: ProjectionAssignment,
}

impl ProjectionAuthoringField {
    /// Construct a generated field assignment.
    pub fn set(field: impl Into<String>, expression: ProjectionExpression) -> Self {
        Self {
            field: field.into(),
            assignment: ProjectionAssignment::Set(expression),
        }
    }

    /// Construct a generated explicit-unset assignment.
    pub fn unset(field: impl Into<String>) -> Self {
        Self {
            field: field.into(),
            assignment: ProjectionAssignment::Unset,
        }
    }
}

/// Build a body path using derived flat portable field metadata.
///
/// # Errors
///
/// Rejects unknown or omitted fields.
#[doc(hidden)]
pub fn body_path<B>(field: &'static str) -> Result<ProjectionExpression, ProjectionProgramError>
where
    B: ProjectionBodyMetadata,
{
    let metadata = B::PROJECTION_FIELDS
        .iter()
        .find(|candidate| candidate.rust_name == field && candidate.present)
        .ok_or_else(|| ProjectionProgramError::RequiredValueAbsent {
            path: format!("body metadata field `{field}`"),
        })?;
    ProjectionExpression::body_path(
        projection_value_type(metadata.portable_type),
        [metadata.wire_name],
    )
}

/// Build an exact state-body event selector.
///
/// # Errors
///
/// Returns descriptor validation failures.
#[doc(hidden)]
pub fn state_selector<S>(
    name: &'static str,
    version: u64,
) -> Result<ProjectionEventSelector, ProjectionProgramError>
where
    S: DomainState,
{
    ProjectionEventSelector::try_from_descriptor(&crate::DomainEventDescriptor::state::<S>(
        name, version,
    ))
}

/// Build an exact typed domain-event selector.
///
/// # Errors
///
/// Returns descriptor validation failures.
#[doc(hidden)]
pub fn event_selector<E>() -> Result<ProjectionEventSelector, ProjectionProgramError>
where
    E: DomainEvent,
{
    ProjectionEventSelector::try_from_descriptor(&E::DESCRIPTOR)
}

/// Build an exact sourced deletion selector without a duplicate event DTO.
///
/// # Errors
///
/// Returns descriptor validation failures.
#[doc(hidden)]
pub fn deletion_selector<I>(
    name: &'static str,
    version: u64,
) -> Result<ProjectionEventSelector, ProjectionProgramError>
where
    I: ProjectionDeletionMetadata,
{
    ProjectionEventSelector::try_from_descriptor(&crate::DomainEventDescriptor {
        name: std::borrow::Cow::Borrowed(name),
        version,
        body: crate::DomainEventBodyDescriptor::distributed_json(
            crate::DomainEventBodyKind::Deletion,
            I::BODY_TYPE_NAME,
            1,
            I::BODY_SCHEMA,
            I::BODY_FINGERPRINT,
        ),
    })
}

/// Construct a model target from the existing ORM schema.
///
/// # Errors
///
/// Returns invalid schema metadata.
#[doc(hidden)]
pub fn projection_target<M>() -> Result<ProjectionTarget, ProjectionProgramError>
where
    M: ProjectionReadModelMetadata,
{
    let schema = projection_schema::<M>()?;
    ProjectionTarget::try_new(schema.model_name.clone(), schema.table_name.clone())
}

/// Construct the exact common full-state upsert operation.
///
/// # Errors
///
/// Returns invalid body/model metadata or task-7 operation validation failures.
#[doc(hidden)]
pub fn state_upsert_operation<S, M>(
    operation_id: &'static str,
    staging_ordinal: u32,
) -> Result<ProjectionOperation, ProjectionProgramError>
where
    S: DomainState + ProjectionBodyMetadata,
    M: ProjectionReadModelMetadata,
{
    let schema = projection_schema::<M>()?;
    let mut key = Vec::with_capacity(schema.primary_key.columns.len());
    for (ordinal, column) in schema.primary_key.columns.iter().enumerate() {
        let model_field = model_field_for_column::<M>(column)?;
        key.push(ProjectionKeyField::try_new(
            ordinal as u32,
            model_field.field_name,
            body_path_for_model_field::<S>(model_field)?,
        )?);
    }
    let mut fields = Vec::with_capacity(M::PROJECTION_FIELDS.len());
    for (ordinal, model_field) in M::PROJECTION_FIELDS.iter().enumerate() {
        fields.push(ProjectionField::try_new(
            ordinal as u32,
            model_field.field_name,
            ProjectionAssignment::Set(body_path_for_model_field::<S>(model_field)?),
        )?);
    }
    ProjectionOperation::try_new(
        operation_id,
        staging_ordinal,
        ProjectionMutationKind::Upsert,
        projection_target::<M>()?,
        key,
        fields,
        Vec::new(),
        Vec::new(),
    )
}

/// Construct one explicit model operation from closed expressions.
///
/// # Errors
///
/// Returns unknown fields, incomplete keys/rows, unsupported mutations, or
/// task-7 validation failures.
#[doc(hidden)]
pub fn model_operation<M>(
    operation_id: &'static str,
    staging_ordinal: u32,
    kind: ProjectionMutationKind,
    key: Vec<ProjectionAuthoringField>,
    fields: Vec<ProjectionAuthoringField>,
) -> Result<ProjectionOperation, ProjectionProgramError>
where
    M: ProjectionReadModelMetadata,
{
    build_model_operation::<M>(operation_id, staging_ordinal, kind, key, fields, Vec::new())
}

/// Construct a relationship-aware child operation using the existing ORM
/// relationship metadata and delegated foreign-key mapping.
///
/// # Errors
///
/// Returns invalid relationship metadata, caller attempts to author delegated
/// keys directly, incomplete keys/rows, or task-7 validation failures.
#[doc(hidden)]
pub fn related_operation<R>(
    operation_id: &'static str,
    staging_ordinal: u32,
    kind: ProjectionMutationKind,
    parent: &ProjectionOperation,
    key: Vec<ProjectionAuthoringField>,
    fields: Vec<ProjectionAuthoringField>,
) -> Result<ProjectionOperation, ProjectionProgramError>
where
    R: ProjectionRelationshipMetadata,
{
    let parent_schema = projection_schema::<R::Source>()?;
    let child_schema = projection_schema::<R::Target>()?;
    let relationship = ReadModelWritePlanBuilder::projection_relationship_for(
        parent_schema,
        R::FIELD,
        child_schema,
    )
    .map_err(program_metadata_error)?;
    let delegations = ReadModelWritePlanBuilder::projection_delegated_relationship_columns(
        parent_schema,
        relationship,
        child_schema,
    )
    .map_err(program_metadata_error)?;
    let mut key = key;
    let mut fields = fields;
    for (child_column, parent_column) in delegations {
        let child = model_field_for_column::<R::Target>(&child_column)?;
        if key.iter().any(|field| field.field == child.field_name)
            || fields.iter().any(|field| field.field == child.field_name)
        {
            return Err(ProjectionProgramError::InvalidOperation {
                operation: operation_id.to_owned(),
                reason: format!(
                    "delegated relationship field `{}` is owned by ORM metadata",
                    child.field_name
                ),
            });
        }
        let parent_expression =
            operation_expression_for_column(parent, parent_schema, &parent_column)?;
        if child.primary_key {
            key.push(ProjectionAuthoringField::set(
                child.field_name,
                parent_expression.clone(),
            ));
        } else if kind != ProjectionMutationKind::Delete {
            fields.push(ProjectionAuthoringField::set(
                child.field_name,
                parent_expression,
            ));
        }
    }
    let effect_kind = match kind {
        ProjectionMutationKind::InsertRelated | ProjectionMutationKind::UpsertRelated => {
            Some(crate::ProjectionRelationshipEffectKind::Link)
        }
        ProjectionMutationKind::Delete => Some(crate::ProjectionRelationshipEffectKind::Unlink),
        _ => None,
    }
    .ok_or_else(|| ProjectionProgramError::InvalidOperation {
        operation: operation_id.to_owned(),
        reason: "relationship authoring supports insert_related, upsert_related, or delete"
            .to_owned(),
    })?;

    let row_kind = match kind {
        ProjectionMutationKind::InsertRelated => ProjectionMutationKind::Insert,
        ProjectionMutationKind::UpsertRelated => ProjectionMutationKind::Upsert,
        other => other,
    };
    let built = build_model_operation::<R::Target>(
        operation_id,
        staging_ordinal,
        row_kind,
        key,
        fields,
        Vec::new(),
    )?;
    let relationship = ProjectionRelationship::try_new(
        parent_schema.model_name.clone(),
        R::FIELD,
        child_schema.model_name.clone(),
    )?;
    let effect = match effect_kind {
        crate::ProjectionRelationshipEffectKind::Link => ProjectionRelationshipEffect::link(
            0,
            relationship,
            parent.key().to_vec(),
            built.key().to_vec(),
        )?,
        crate::ProjectionRelationshipEffectKind::Unlink => ProjectionRelationshipEffect::unlink(
            0,
            relationship,
            parent.key().to_vec(),
            built.key().to_vec(),
        )?,
        crate::ProjectionRelationshipEffectKind::Invalidate => unreachable!(),
    };
    ProjectionOperation::try_new(
        built.operation_id().to_owned(),
        built.staging_ordinal(),
        kind,
        built.target().clone(),
        built.key().to_vec(),
        built.fields().to_vec(),
        vec![effect],
        Vec::new(),
    )
}

/// Lower one ordinary generated operation through its concrete read-model
/// schema.
///
/// # Errors
///
/// Returns target, key, row, patch, nullability, completeness or adapter
/// validation failures.
#[doc(hidden)]
pub fn lower_model_mutation<M>(
    builder: &mut ReadModelWritePlanBuilder,
    mutation: &ResolvedProjectionMutation,
) -> Result<(), ProjectionLoweringError>
where
    M: ProjectionReadModelMetadata,
{
    validate_target::<M>(mutation)?;
    let key = resolved_key::<M>(mutation.key())?;
    match mutation.kind() {
        ProjectionMutationKind::Insert => {
            let values = resolved_full_row::<M>(mutation.fields())?;
            builder.stage_projection_full_row::<M>(
                key,
                values,
                RowWriteMode::Insert,
                ExpectedVersion::NotExists,
            )?;
        }
        ProjectionMutationKind::Upsert | ProjectionMutationKind::Recreate => {
            let values = resolved_full_row::<M>(mutation.fields())?;
            builder.stage_projection_full_row::<M>(
                key,
                values,
                RowWriteMode::Upsert,
                ExpectedVersion::Any,
            )?;
        }
        ProjectionMutationKind::Patch => {
            builder.stage_projection_patch::<M>(
                key,
                resolved_patch::<M>(mutation.fields())?,
                PatchMode::UpdateExisting,
            )?;
        }
        ProjectionMutationKind::UpsertPatch => {
            let patch = resolved_patch::<M>(mutation.fields())?;
            validate_insert_missing_patch::<M>(&key, &patch)?;
            builder.stage_projection_patch::<M>(key, patch, PatchMode::InsertMissing)?;
        }
        ProjectionMutationKind::Delete => {
            builder.stage_projection_delete::<M>(key)?;
        }
        ProjectionMutationKind::InsertRelated | ProjectionMutationKind::UpsertRelated => {
            return Err(ProjectionLoweringError::Table(TableStoreError::Metadata(
                format!(
                    "related mutation for `{}` requires generated relationship lowering",
                    mutation.target().model()
                ),
            )));
        }
    }
    Ok(())
}

/// Lower one generated related child mutation through the existing
/// relationship mapper.
///
/// # Errors
///
/// Returns missing parent provenance, relationship, delegated-key, or row
/// validation failures.
#[doc(hidden)]
pub fn lower_related_mutation<R>(
    builder: &mut ReadModelWritePlanBuilder,
    plan: &ResolvedProjectionPlan,
    mutation: &ResolvedProjectionMutation,
    parent_operation_id: &'static str,
) -> Result<(), ProjectionLoweringError>
where
    R: ProjectionRelationshipMetadata,
{
    validate_target::<R::Target>(mutation)?;
    let parent = plan
        .mutations()
        .iter()
        .find(|candidate| {
            candidate.provenance().arm_id() == mutation.provenance().arm_id()
                && candidate
                    .provenance()
                    .operation_ids()
                    .iter()
                    .any(|operation| operation == parent_operation_id)
        })
        .ok_or_else(|| ProjectionLoweringError::MissingRelatedParent {
            arm: mutation.provenance().arm_id().to_owned(),
            operation: parent_operation_id.to_owned(),
        })?;
    validate_target::<R::Source>(parent)?;
    let parent_row = resolved_full_row::<R::Source>(parent.fields())?;
    match mutation.kind() {
        ProjectionMutationKind::InsertRelated | ProjectionMutationKind::UpsertRelated => {
            let child_row = resolved_full_row::<R::Target>(mutation.fields())?;
            let (mode, expected) = match mutation.kind() {
                ProjectionMutationKind::InsertRelated => {
                    (RowWriteMode::Insert, ExpectedVersion::NotExists)
                }
                ProjectionMutationKind::UpsertRelated => {
                    (RowWriteMode::Upsert, ExpectedVersion::Any)
                }
                _ => unreachable!(),
            };
            builder.stage_projection_related_row::<R::Source, R::Target>(
                R::FIELD,
                &parent_row,
                child_row,
                mode,
                expected,
            )?;
        }
        ProjectionMutationKind::Delete => {
            let key = resolved_key::<R::Target>(mutation.key())?;
            builder.stage_projection_delete::<R::Target>(key)?;
        }
        kind => {
            return Err(ProjectionLoweringError::Table(TableStoreError::Metadata(
                format!("unsupported related projection mutation `{kind:?}`"),
            )));
        }
    }
    Ok(())
}

/// Finish generated staging and retain the logical provenance.
///
/// # Errors
///
/// Returns canonical ORM validation failures.
#[doc(hidden)]
pub fn finish_lowering(
    builder: ReadModelWritePlanBuilder,
    resolved: &ResolvedProjectionPlan,
) -> Result<LoweredProjectionPlan, ProjectionLoweringError> {
    Ok(LoweredProjectionPlan {
        write_plan: builder.into_write_plan()?,
        resolved: resolved.clone(),
    })
}

fn projection_schema<M>() -> Result<&'static crate::TableSchema, ProjectionProgramError>
where
    M: ProjectionReadModelMetadata,
{
    ReadModelWritePlanBuilder::projection_validated_schema::<M>().map_err(program_metadata_error)
}

fn program_metadata_error(error: TableStoreError) -> ProjectionProgramError {
    ProjectionProgramError::InvalidOperation {
        operation: "read-model metadata".to_owned(),
        reason: error.to_string(),
    }
}

fn projection_value_type(kind: ProjectionPortableType) -> ProjectionValueType {
    match kind {
        ProjectionPortableType::Boolean => ProjectionValueType::Boolean,
        ProjectionPortableType::I64 => ProjectionValueType::I64,
        ProjectionPortableType::U64 => ProjectionValueType::U64,
        ProjectionPortableType::F64 => ProjectionValueType::F64,
        ProjectionPortableType::String => ProjectionValueType::String,
        ProjectionPortableType::Bytes
        | ProjectionPortableType::Json
        | ProjectionPortableType::Custom => ProjectionValueType::Json,
    }
}

fn model_field_for_column<M>(
    column: &str,
) -> Result<&'static ProjectionModelFieldMetadata, ProjectionProgramError>
where
    M: ProjectionReadModelMetadata,
{
    M::PROJECTION_FIELDS
        .iter()
        .find(|field| field.column_name == column)
        .ok_or_else(|| ProjectionProgramError::InvalidOperation {
            operation: "read-model metadata".to_owned(),
            reason: format!("column `{column}` has no portable field metadata"),
        })
}

fn body_path_for_model_field<B>(
    model: &ProjectionModelFieldMetadata,
) -> Result<ProjectionExpression, ProjectionProgramError>
where
    B: ProjectionBodyMetadata,
{
    let body = B::PROJECTION_FIELDS
        .iter()
        .find(|field| field.present && field.wire_name == model.field_name)
        .ok_or_else(|| ProjectionProgramError::RequiredValueAbsent {
            path: model.field_name.to_owned(),
        })?;
    ProjectionExpression::body_path(value_type_for_model(model), [body.wire_name])
}

fn value_type_for_model(model: &ProjectionModelFieldMetadata) -> ProjectionValueType {
    projection_value_type(model.portable_type)
}

fn build_model_operation<M>(
    operation_id: &'static str,
    staging_ordinal: u32,
    kind: ProjectionMutationKind,
    key: Vec<ProjectionAuthoringField>,
    fields: Vec<ProjectionAuthoringField>,
    invalidations: Vec<ProjectionInvalidation>,
) -> Result<ProjectionOperation, ProjectionProgramError>
where
    M: ProjectionReadModelMetadata,
{
    let schema = projection_schema::<M>()?;
    let mut key_by_name = unique_authoring_fields(operation_id, "key", key)?;
    let fields_by_name = unique_authoring_fields(operation_id, "set", fields)?;
    let mut projected_key = Vec::with_capacity(schema.primary_key.columns.len());
    for (ordinal, column) in schema.primary_key.columns.iter().enumerate() {
        let metadata = model_field_for_column::<M>(column)?;
        let field = key_by_name.remove(metadata.field_name).ok_or_else(|| {
            ProjectionProgramError::InvalidOperation {
                operation: operation_id.to_owned(),
                reason: format!("key is missing primary-key field `{}`", metadata.field_name),
            }
        })?;
        let ProjectionAssignment::Set(expression) = field.assignment else {
            return Err(ProjectionProgramError::UnsetNotAllowed {
                field: metadata.field_name.to_owned(),
            });
        };
        projected_key.push(ProjectionKeyField::try_new(
            ordinal as u32,
            metadata.field_name,
            expression,
        )?);
    }
    if let Some(extra) = key_by_name.keys().next() {
        return Err(ProjectionProgramError::InvalidOperation {
            operation: operation_id.to_owned(),
            reason: format!("key contains non-primary-key field `{extra}`"),
        });
    }

    let mut all_fields = fields_by_name;
    if kind.is_complete_write() {
        for key_field in &projected_key {
            if all_fields.contains_key(key_field.name()) {
                return Err(ProjectionProgramError::InvalidOperation {
                    operation: operation_id.to_owned(),
                    reason: format!("complete-row set repeats key field `{}`", key_field.name()),
                });
            }
            all_fields.insert(
                key_field.name().to_owned(),
                ProjectionAuthoringField::set(
                    key_field.name().to_owned(),
                    key_field.expression().clone(),
                ),
            );
        }
        for metadata in M::PROJECTION_FIELDS {
            if metadata.required && !all_fields.contains_key(metadata.field_name) {
                return Err(ProjectionProgramError::InvalidOperation {
                    operation: operation_id.to_owned(),
                    reason: format!(
                        "complete row is missing required field `{}`",
                        metadata.field_name
                    ),
                });
            }
        }
    }
    let mut projected_fields = Vec::new();
    for metadata in M::PROJECTION_FIELDS {
        if let Some(field) = all_fields.remove(metadata.field_name) {
            projected_fields.push(ProjectionField::try_new(
                projected_fields.len() as u32,
                metadata.field_name,
                field.assignment,
            )?);
        }
    }
    if let Some(extra) = all_fields.keys().next() {
        return Err(ProjectionProgramError::InvalidOperation {
            operation: operation_id.to_owned(),
            reason: format!("set references unknown read-model field `{extra}`"),
        });
    }

    ProjectionOperation::try_new(
        operation_id,
        staging_ordinal,
        kind,
        projection_target::<M>()?,
        projected_key,
        projected_fields,
        Vec::new(),
        invalidations,
    )
}

fn unique_authoring_fields(
    operation: &str,
    kind: &'static str,
    fields: Vec<ProjectionAuthoringField>,
) -> Result<BTreeMap<String, ProjectionAuthoringField>, ProjectionProgramError> {
    let mut result = BTreeMap::new();
    for field in fields {
        if result.insert(field.field.clone(), field).is_some() {
            return Err(ProjectionProgramError::InvalidOperation {
                operation: operation.to_owned(),
                reason: format!("duplicate {kind} field"),
            });
        }
    }
    Ok(result)
}

fn operation_expression_for_column(
    operation: &ProjectionOperation,
    schema: &crate::TableSchema,
    column: &str,
) -> Result<ProjectionExpression, ProjectionProgramError> {
    let logical_name = schema
        .columns
        .iter()
        .find(|candidate| candidate.column_name == column)
        .map(|candidate| candidate.field_name.as_str())
        .ok_or_else(|| ProjectionProgramError::InvalidOperation {
            operation: operation.operation_id().to_owned(),
            reason: format!("relationship source column `{column}` is not mapped"),
        })?;
    if let Some(key) = operation
        .key()
        .iter()
        .find(|field| field.name() == logical_name)
    {
        return Ok(key.expression().clone());
    }
    let assignment = operation
        .fields()
        .iter()
        .find(|field| field.name() == logical_name)
        .ok_or_else(|| ProjectionProgramError::InvalidOperation {
            operation: operation.operation_id().to_owned(),
            reason: format!(
                "parent operation does not provide delegated source field `{logical_name}`"
            ),
        })?
        .assignment();
    match assignment {
        ProjectionAssignment::Set(expression) => Ok(expression.clone()),
        ProjectionAssignment::Unset => Err(ProjectionProgramError::UnsetNotAllowed {
            field: logical_name.to_owned(),
        }),
    }
}

fn validate_target<M>(mutation: &ResolvedProjectionMutation) -> Result<(), ProjectionLoweringError>
where
    M: ProjectionReadModelMetadata,
{
    let schema = ReadModelWritePlanBuilder::projection_validated_schema::<M>()?;
    if mutation.target().model() != schema.model_name
        || mutation.target().storage() != schema.table_name
    {
        return Err(ProjectionLoweringError::Table(TableStoreError::Metadata(
            format!(
                "resolved target `{}/{}` does not match ORM model `{}/{}`",
                mutation.target().model(),
                mutation.target().storage(),
                schema.model_name,
                schema.table_name
            ),
        )));
    }
    Ok(())
}

fn resolved_key<M>(key: &ResolvedProjectionKey) -> Result<RowKey, ProjectionLoweringError>
where
    M: ProjectionReadModelMetadata,
{
    let schema = ReadModelWritePlanBuilder::projection_validated_schema::<M>()?;
    let mut result = RowKey::default();
    for field in key.fields() {
        let metadata = M::PROJECTION_FIELDS
            .iter()
            .find(|candidate| candidate.field_name == field.name())
            .ok_or_else(|| {
                TableStoreError::Metadata(format!(
                    "model `{}` has no projection key field `{}`",
                    schema.model_name,
                    field.name()
                ))
            })?;
        let column = schema
            .columns
            .iter()
            .find(|column| column.column_name == metadata.column_name)
            .ok_or_else(|| {
                TableStoreError::Metadata(format!(
                    "model `{}` is missing column `{}`",
                    schema.model_name, metadata.column_name
                ))
            })?;
        result.insert(
            metadata.column_name,
            projection_value_to_row(field.value(), &column.column_type)?,
        );
    }
    Ok(result)
}

fn resolved_full_row<M>(
    fields: &[ResolvedProjectionField],
) -> Result<RowValues, ProjectionLoweringError>
where
    M: ProjectionReadModelMetadata,
{
    let row = resolved_values::<M>(fields, false)?;
    validate_row_values(
        ReadModelWritePlanBuilder::projection_validated_schema::<M>()?,
        &row,
        true,
    )?;
    Ok(row)
}

fn resolved_patch<M>(
    fields: &[ResolvedProjectionField],
) -> Result<RowPatch, ProjectionLoweringError>
where
    M: ProjectionReadModelMetadata,
{
    let values = resolved_values::<M>(fields, true)?;
    let mut patch = RowPatch::new();
    for (column, value) in values {
        patch = patch.set(column, value);
    }
    Ok(patch)
}

fn resolved_values<M>(
    fields: &[ResolvedProjectionField],
    allow_absent: bool,
) -> Result<RowValues, ProjectionLoweringError>
where
    M: ProjectionReadModelMetadata,
{
    let schema = ReadModelWritePlanBuilder::projection_validated_schema::<M>()?;
    let mut values = RowValues::new();
    for field in fields {
        let metadata = M::PROJECTION_FIELDS
            .iter()
            .find(|candidate| candidate.field_name == field.name())
            .ok_or_else(|| {
                TableStoreError::Metadata(format!(
                    "model `{}` has no projection field `{}`",
                    schema.model_name,
                    field.name()
                ))
            })?;
        let column = schema
            .columns
            .iter()
            .find(|column| column.column_name == metadata.column_name)
            .ok_or_else(|| {
                TableStoreError::Metadata(format!(
                    "model `{}` is missing column `{}`",
                    schema.model_name, metadata.column_name
                ))
            })?;
        match field.value() {
            ResolvedProjectionValue::Value(value) => {
                values.insert(
                    metadata.column_name,
                    projection_value_to_row(value, &column.column_type)?,
                );
            }
            ResolvedProjectionValue::Absent if allow_absent => {}
            ResolvedProjectionValue::Absent => {
                return Err(ProjectionLoweringError::Program(
                    ProjectionProgramError::RequiredValueAbsent {
                        path: field.name().to_owned(),
                    },
                ));
            }
            ResolvedProjectionValue::Unset => {
                return Err(ProjectionLoweringError::Table(TableStoreError::Metadata(
                    format!(
                        "authoritative relational projection cannot unset field `{}`; use explicit null for nullable columns",
                        field.name()
                    ),
                )));
            }
        }
    }
    Ok(values)
}

fn validate_insert_missing_patch<M>(
    key: &RowKey,
    patch: &RowPatch,
) -> Result<(), ProjectionLoweringError>
where
    M: ProjectionReadModelMetadata,
{
    let schema = ReadModelWritePlanBuilder::projection_validated_schema::<M>()?;
    let mut candidate = RowValues::new();
    for (column, value) in key.iter() {
        candidate.insert(column, value.clone());
    }
    for (column, value) in patch.iter() {
        if let Some(key_value) = key.get(column) {
            if key_value != value {
                return Err(TableStoreError::Metadata(format!(
                    "model `{}` patch changes primary-key column `{column}`",
                    schema.model_name
                ))
                .into());
            }
        }
        candidate.insert(column, value.clone());
    }
    validate_row_values(schema, &candidate, true)?;
    Ok(())
}

fn projection_value_to_row(
    value: &ProjectionValue,
    column_type: &ColumnType,
) -> Result<RowValue, ProjectionLoweringError> {
    if value.is_null() {
        return Ok(RowValue::Null);
    }
    let invalid = || {
        ProjectionLoweringError::Table(TableStoreError::Metadata(format!(
            "portable projection value is incompatible with column type `{column_type:?}`"
        )))
    };
    match (column_type, value.as_ref()) {
        (ColumnType::Boolean, ProjectionValueRef::Boolean(value)) => Ok(RowValue::Bool(value)),
        (ColumnType::Integer, ProjectionValueRef::I64(value)) => value
            .parse::<i64>()
            .map(RowValue::I64)
            .map_err(|_| invalid()),
        (ColumnType::UnsignedInteger, ProjectionValueRef::U64(value)) => value
            .parse::<u64>()
            .map(|value| {
                i64::try_from(value)
                    .map(RowValue::I64)
                    .unwrap_or_else(|_| RowValue::U64(value))
            })
            .map_err(|_| invalid()),
        (ColumnType::Float, ProjectionValueRef::F64(value)) => value
            .parse::<f64>()
            .map(RowValue::F64)
            .map_err(|_| invalid()),
        (ColumnType::Text | ColumnType::Timestamp, ProjectionValueRef::String(value)) => {
            Ok(RowValue::String(value.to_owned()))
        }
        (ColumnType::Text | ColumnType::Timestamp, ProjectionValueRef::Enum { variant, .. }) => {
            Ok(RowValue::String(variant.to_owned()))
        }
        (ColumnType::Bytes, ProjectionValueRef::List(values)) => values
            .iter()
            .map(|value| match value.as_ref() {
                ProjectionValueRef::U64(value) => value.parse::<u8>().map_err(|_| invalid()),
                _ => Err(invalid()),
            })
            .collect::<Result<Vec<_>, _>>()
            .map(RowValue::Bytes),
        (ColumnType::Json, _) => Ok(RowValue::Json(projection_value_to_json(value)?)),
        (ColumnType::Unsupported(_), _) => Err(invalid()),
        _ => Err(invalid()),
    }
}

fn projection_value_to_json(
    value: &ProjectionValue,
) -> Result<serde_json::Value, ProjectionLoweringError> {
    Ok(match value.as_ref() {
        ProjectionValueRef::Null => serde_json::Value::Null,
        ProjectionValueRef::Boolean(value) => serde_json::Value::Bool(value),
        ProjectionValueRef::I64(value) => serde_json::Value::Number(
            value
                .parse::<i64>()
                .map_err(|_| {
                    TableStoreError::Metadata("invalid canonical i64 projection value".into())
                })?
                .into(),
        ),
        ProjectionValueRef::U64(value) => serde_json::Value::Number(
            value
                .parse::<u64>()
                .map_err(|_| {
                    TableStoreError::Metadata("invalid canonical u64 projection value".into())
                })?
                .into(),
        ),
        ProjectionValueRef::F64(value) => serde_json::Value::Number(
            serde_json::Number::from_f64(value.parse::<f64>().map_err(|_| {
                TableStoreError::Metadata("invalid canonical f64 projection value".into())
            })?)
            .ok_or_else(|| {
                TableStoreError::Metadata("non-finite canonical f64 projection value".into())
            })?,
        ),
        ProjectionValueRef::String(value) => serde_json::Value::String(value.to_owned()),
        ProjectionValueRef::Enum { variant, .. } => serde_json::Value::String(variant.to_owned()),
        ProjectionValueRef::List(values) => serde_json::Value::Array(
            values
                .iter()
                .map(projection_value_to_json)
                .collect::<Result<Vec<_>, _>>()?,
        ),
        ProjectionValueRef::Object(fields) => serde_json::Value::Object(
            fields
                .iter()
                .map(|field| {
                    Ok((
                        field.name().to_owned(),
                        projection_value_to_json(field.value())?,
                    ))
                })
                .collect::<Result<serde_json::Map<_, _>, ProjectionLoweringError>>()?,
        ),
    })
}

/// Construct a complete projection program from generated arms.
///
/// # Errors
///
/// Returns task-7 validation failures.
#[doc(hidden)]
pub fn projection_program(
    name: &'static str,
    version: u64,
    partition: ProjectionPartition,
    arms: Vec<ProjectionArm>,
) -> Result<ProjectionProgram, ProjectionProgramError> {
    ProjectionProgram::try_new(name, version, partition, arms)
}

/// Resolve through an exact generated event-set marker.
///
/// # Errors
///
/// Returns event-set, selector, expression, or logical-plan failures.
#[doc(hidden)]
pub fn resolve_typed<E>(
    program: ProjectionProgram,
    occurrence: &DomainEventOccurrence,
) -> Result<ResolvedProjectionPlan, ProjectionProgramError>
where
    E: ProjectionEventSet,
{
    ProjectionPlanTemplate::<E>::try_new(program)?.resolve(occurrence)
}

/// Build a canonical relationship output entry.
///
/// # Errors
///
/// Returns invalid ORM relationship metadata.
#[doc(hidden)]
pub fn output_relationship<R>() -> Result<ProjectionRelationship, ProjectionLoweringError>
where
    R: ProjectionRelationshipMetadata,
{
    let source = ReadModelWritePlanBuilder::projection_validated_schema::<R::Source>()?;
    let target = ReadModelWritePlanBuilder::projection_validated_schema::<R::Target>()?;
    ReadModelWritePlanBuilder::projection_relationship_for(source, R::FIELD, target)?;
    Ok(ProjectionRelationship::try_new(
        source.model_name.clone(),
        R::FIELD,
        target.model_name.clone(),
    )?)
}