hawdb-executor 0.29.0

An embedded Rust graph database for local data-plane workloads
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
// Copyright 2026 Nowledge
// SPDX-License-Identifier: Apache-2.0

//! Correlated MATCH execution with one optional boundary around the complete clause.

use crate::binding::{
    binding_memory_bytes, node_memory_bytes, relationship_memory_bytes, value_memory_bytes, Binding,
};
use crate::expression::{
    evaluate_conjunction_with_context, evaluate_predicate_with_context, node_value, path_value,
    relationship_value,
};
use crate::kernel::OperatorMemoryTracker;
use crate::pipeline::{
    runtime_checkpoint, AccountedBindingBatch, BatchControl, BatchExecutionContext, BindingBatch,
    BindingBatchSource,
};
use crate::predicate::{label_ids_for_pattern, node_matches_label_pattern};
use crate::store::{admit_graph_read, AdjacencyReadMemory, GraphExecutionRead, ScanControl};
use crate::traversal::shortest_path_bfs::{
    ShortestPathBfs, ShortestPathBfsOutcome, ShortestPathBfsSpec,
};
use crate::traversal::{
    projected_node_with_allocation, visit_bounded_expand_trails, visit_one_hop_adjacency_entries,
    visit_one_hop_relationship_records, visit_zero_hop_expand_target, BoundedTrailSpec,
    OneHopRecordSpec,
};
use crate::{ExecutionLimit, QueryMemoryAccount, QueryMemoryClass};
use hawdb_core::{HawDBError, RelTypeId, Result, Value};
use hawdb_plan_cypher::{
    GraphBindingImport, GraphEntityKind, GraphMatchNode, GraphMatchProgram, GraphMatchShortestPath,
    GraphMatchStep, PhysicalPlan, Predicate, ShortestPathSelection,
};
use hawdb_storage::read_view::{
    AdmittedNodeRead, AdmittedRelationshipRead, AdmittedVec, GraphReadAdmission,
    GraphReadAllocation,
};
use hawdb_storage::{adjacency::AdjacencyDirection, NodeId, NodeRecord, RelId};
use std::borrow::Cow;
use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet};

mod hash_join;
mod indexed_node;
mod membership;

const MAX_MATCH_STEPS: usize = 32;

/// WHERE conjuncts grouped by the number of steps completed before they run.
struct PlacedPredicate<'a> {
    early: Vec<Vec<&'a Predicate>>,
    last: Vec<&'a Predicate>,
    /// Conjuncts on the relationship that step `i` binds, evaluated on each
    /// relationship it reads before the target node is read. They belong to
    /// the group after step `i` and are not repeated there.
    edge: Vec<Vec<&'a Predicate>>,
}

impl<'a> PlacedPredicate<'a> {
    fn new(program: &'a GraphMatchProgram) -> Result<Self> {
        let end = program.steps.len();
        let mut early = vec![Vec::new(); end];
        let mut last = Vec::new();
        let mut edge = vec![Vec::new(); end];
        let invalid = || {
            HawDBError::Execution(
                "MATCH predicate placement does not match its conjuncts and steps".to_string(),
            )
        };
        if program.predicate_steps.is_empty() {
            if !program.edge_predicates.is_empty() {
                return Err(invalid());
            }
            last.extend(program.predicate.as_ref());
            return Ok(Self { early, last, edge });
        }
        let conjuncts = program.predicate_conjuncts();
        if conjuncts.len() != program.predicate_steps.len()
            || program.predicate_steps.iter().any(|step| *step > end)
            || program
                .edge_predicates
                .windows(2)
                .any(|pair| pair[0] >= pair[1])
        {
            return Err(invalid());
        }
        let mut edge_conjuncts = program.edge_predicates.iter().copied().peekable();
        for (position, (conjunct, step)) in
            conjuncts.iter().zip(&program.predicate_steps).enumerate()
        {
            if edge_conjuncts.next_if_eq(&position).is_some() {
                // Only a one-hop step that binds a relationship reads one.
                let expand = step.checked_sub(1).filter(|index| {
                    matches!(
                        program.steps.get(*index),
                        Some(GraphMatchStep::Expand {
                            relationship: Some(_),
                            min_hops: 1,
                            max_hops: 1,
                            ..
                        })
                    )
                });
                let Some(expand) = expand else {
                    return Err(invalid());
                };
                edge[expand].push(conjunct);
                continue;
            }
            match early.get_mut(*step) {
                Some(group) => group.push(conjunct),
                None => last.push(conjunct),
            }
        }
        if edge_conjuncts.next().is_some() {
            return Err(invalid());
        }
        Ok(Self { early, last, edge })
    }
}

/// Runs `visit` once per relationship type a one-hop step reads: with `None`
/// for an untyped step, else with each of `rel_type_ids` until one stops.
/// Types are disjoint, so no relationship is visited twice.
fn visit_step_types(
    rel_type_ids: Option<&[RelTypeId]>,
    visit: &mut dyn FnMut(Option<RelTypeId>) -> Result<ScanControl>,
) -> Result<ScanControl> {
    let Some(rel_type_ids) = rel_type_ids else {
        return visit(None);
    };
    for &rel_type_id in rel_type_ids {
        if visit(Some(rel_type_id))? == ScanControl::Stop {
            return Ok(ScanControl::Stop);
        }
    }
    Ok(ScanControl::Continue)
}

/// Retained bytes of one relationship id in the trail-uniqueness set.
const USED_RELATIONSHIP_BYTES: usize = 48;

/// Bytes one more graph slot adds to a bound row: the slot pair, both `Arc`
/// headers, the name `String` and slot-vector growth, as charged by
/// `binding_memory_bytes`.
fn graph_slot_entry_bytes(name: &str) -> usize {
    name.len()
        .saturating_add(16 * std::mem::size_of::<usize>())
        .saturating_add(std::mem::size_of::<NodeRecord>())
}

pub(crate) fn stream_graph_match(
    program: &GraphMatchProgram,
    input: Option<&PhysicalPlan>,
    source: &mut dyn BindingBatchSource,
    store: &dyn GraphExecutionRead,
    context: BatchExecutionContext<'_>,
    limit: ExecutionLimit,
    emit: &mut dyn FnMut(BindingBatch) -> Result<BatchControl>,
) -> Result<BatchControl> {
    // Validate before reading input so empty streams cannot bypass shape checks.
    validate_program(program)?;
    let placed = PlacedPredicate::new(program)?;
    if limit.is_reached(0) {
        return Ok(BatchControl::Stop);
    }
    // Seed scoring annotates every hop of a per-row match; it keeps the
    // per-row program, which the hash join's steps remain.
    if let (Some(join), Some(input)) = (&program.hash_join, input)
        && context.observer.seed_graph_scoring_input().is_none()
    {
        return hash_join::stream_graph_match_hash_join(
            program, join, input, source, store, context, limit, emit,
        );
    }
    let account = context.operator_account("GraphMatchExec state");
    let source_account = context.source_account_retaining("GraphMatchExec source", account.clone());
    let output_account = context.memory_ledger.account(
        QueryMemoryClass::PipelineBatch,
        "GraphMatchExec output",
        context.memory.batch_payload_bytes,
    );
    let mut output = AccountedBindingBatch::with_account(
        "GraphMatchExec",
        context.memory.batch_rows.get(),
        context.memory.batch_payload_bytes,
        output_account,
    );
    let runtime = MatchRuntime {
        program,
        placed,
        deferred: Cell::new(false),
        store,
        context: context.into(),
        account: &account,
        source_account: &source_account,
        indexed: indexed_node::IndexedNodeStats::default(),
        // Seed scoring reads the candidate's properties and annotates each
        // hop, so it keeps whole records and per-step row copies.
        scoring: context.observer.seed_graph_scoring_input().is_some(),
        candidate: None,
        memberships: membership::MembershipSets::default(),
    };
    let mut emitted = 0;
    // A visited match is restored after `append`, so it is copied; an owned
    // row moves into the output.
    let mut append = |binding: Cow<'_, Binding>| {
        let control = match binding {
            Cow::Borrowed(binding) => output.push_cloned(binding, emit)?,
            Cow::Owned(binding) => output.push(binding, emit)?,
        };
        if control == BatchControl::Stop {
            return Ok(ScanControl::Stop);
        }
        emitted += 1;
        if output.is_full() && output.emit(emit)? == BatchControl::Stop {
            return Ok(ScanControl::Stop);
        }
        Ok(if limit.is_reached(emitted) {
            ScanControl::Stop
        } else {
            ScanControl::Continue
        })
    };
    // Each input row is consumed: its working row moves rather than copies.
    let mut visit_input = |input: Binding| -> Result<BatchControl> {
        runtime_checkpoint(context.task_context)?;
        let (mut binding, _leases) = runtime.prepare(Cow::Owned(input))?;
        runtime.deferred.set(false);
        runtime.memberships.reset();
        let mut matched = false;
        // Steps extend this one row in place and restore it on return.
        let control = runtime.visit(0, &mut binding, &mut BTreeSet::new(), &mut |row| {
            matched = true;
            append(Cow::Borrowed(row))
        })?;
        if control == ScanControl::Stop {
            return Ok(BatchControl::Stop);
        }
        if !matched && program.optional {
            // The working row is not visited again, so the NULL-extended row
            // takes it instead of a copy (#1615). The reservation is unchanged.
            let _lease = account.reserve(
                binding_memory_bytes(&binding).saturating_add(
                    program
                        .introduced
                        .iter()
                        .map(|name| name.len() + 64)
                        .sum::<usize>(),
                ),
            )?;
            let mut row = binding;
            for name in &program.introduced {
                row.nodes.remove(name);
                row.relationships.remove(name);
                row.values.insert(name.clone(), Value::Null);
            }
            if context.observer.seed_graph_scoring_input().is_some() {
                crate::scoring::advance_seed_hop(&mut row, 0, false)?;
            }
            if append(Cow::Owned(row))? == ScanControl::Stop {
                return Ok(BatchControl::Stop);
            }
        }
        Ok(BatchControl::Continue)
    };
    let control = if let Some(input) = input {
        source.execute(input, ExecutionLimit::unlimited(), &mut |batch| {
            for row in batch {
                if visit_input(row)? == BatchControl::Stop {
                    return Ok(BatchControl::Stop);
                }
            }
            Ok(BatchControl::Continue)
        })?
    } else {
        visit_input(Binding::values(BTreeMap::new()))?
    };
    runtime.indexed.report(context.observer);
    if output.emit(emit)? == BatchControl::Stop {
        return Ok(BatchControl::Stop);
    }
    Ok(control)
}

/// What a correlated match reads besides its store and memory accounts.
#[derive(Clone, Copy)]
pub(crate) struct MatchContext<'a> {
    pub(crate) catalog: &'a hawdb_core::Catalog,
    pub(crate) observer: &'a dyn crate::observer::ExecutionObserver,
    pub(crate) task_context: Option<&'a hawdb_core::RuntimeTaskContext>,
    /// The budget of adjacency and record reads.
    pub(crate) query_memory_bytes: std::num::NonZeroUsize,
    /// The budget of shortest-path search state.
    pub(crate) blocking_operator_bytes: std::num::NonZeroUsize,
}

impl<'a> From<BatchExecutionContext<'a>> for MatchContext<'a> {
    fn from(context: BatchExecutionContext<'a>) -> Self {
        Self {
            catalog: context.catalog,
            observer: context.observer,
            task_context: context.task_context,
            query_memory_bytes: context.memory.query_memory_bytes,
            blocking_operator_bytes: context.memory.blocking_operator_bytes,
        }
    }
}

/// Runs `program` once over `input`, as one MATCH over one incoming row, and
/// calls `emit` with each complete match. The program must not be optional
/// and its predicate, if any, is evaluated without placement. State and the
/// records read are charged to `account`, and `candidate` is called for
/// every candidate node or partial match the program visits.
pub(crate) fn visit_correlated_matches(
    program: &GraphMatchProgram,
    store: &dyn GraphExecutionRead,
    context: MatchContext<'_>,
    account: &QueryMemoryAccount,
    input: &Binding,
    candidate: &dyn Fn() -> Result<()>,
    emit: &mut dyn FnMut(&Binding) -> Result<ScanControl>,
) -> Result<ScanControl> {
    validate_program(program)?;
    let runtime = MatchRuntime {
        program,
        placed: PlacedPredicate::new(program)?,
        deferred: Cell::new(false),
        store,
        context,
        account,
        source_account: account,
        indexed: indexed_node::IndexedNodeStats::default(),
        scoring: false,
        candidate: Some(candidate),
        memberships: membership::MembershipSets::default(),
    };
    let (mut binding, _leases) = runtime.prepare(Cow::Borrowed(input))?;
    runtime.visit(0, &mut binding, &mut BTreeSet::new(), emit)
}

fn validate_program(program: &GraphMatchProgram) -> Result<()> {
    if program.steps.len() > MAX_MATCH_STEPS {
        return Err(HawDBError::Execution(
            "MATCH exceeds maximum pattern depth".to_string(),
        ));
    }
    for step in &program.steps {
        if let GraphMatchStep::Expand {
            relationship,
            rel_type,
            properties,
            min_hops,
            max_hops,
            ..
        } = step
            && (*min_hops != 1 || *max_hops != 1)
            && (relationship.is_some() || !properties.is_empty() || rel_type.is_empty())
        {
            return Err(HawDBError::Execution(
                "bounded MATCH expansion requires a typed pattern without relationship bindings"
                    .to_string(),
            ));
        }
    }
    Ok(())
}

struct MatchRuntime<'a> {
    indexed: indexed_node::IndexedNodeStats<'a>,
    program: &'a GraphMatchProgram,
    placed: PlacedPredicate<'a>,
    /// Set while the current partial candidate carries an early conjunct
    /// whose evaluation failed. Its descendants then skip early filtering
    /// and evaluate the whole predicate after the last step, so a candidate
    /// that never completes, or that a text-earlier conjunct rejects, raises
    /// no error the end-of-match evaluation would not have raised.
    deferred: Cell<bool>,
    store: &'a dyn GraphExecutionRead,
    context: MatchContext<'a>,
    account: &'a QueryMemoryAccount,
    source_account: &'a QueryMemoryAccount,
    scoring: bool,
    /// Charged for each visited candidate when the program runs inside an
    /// expression, whose work is bounded per evaluation.
    candidate: Option<&'a dyn Fn() -> Result<()>>,
    /// List-column id sets of `node IN column` conjuncts for this input row.
    memberships: membership::MembershipSets,
}

/// The rest of a one-hop step after its relationship is bound.
struct EdgeTarget<'p, 'l> {
    /// Conjuncts on the relationship, run before the target is read.
    conjuncts: &'p [&'p Predicate],
    pattern: &'p GraphMatchNode,
    labels: Option<&'l [hawdb_core::LabelId]>,
    /// The target to read, or `None` when the step's target is bound.
    neighbor: Option<NodeId>,
    /// The bound relationship's size, which shares the target's read budget.
    edge_bytes: usize,
}

/// One candidate target of an expansion step.
enum Target {
    /// The step's target variable is already bound to this node id.
    Bound,
    /// A record read for an unbound target variable.
    Read(NodeRecord),
}

impl MatchRuntime<'_> {
    /// The properties a node variable's reads are limited to, if any.
    fn projection(&self, variable: &str) -> Option<&BTreeSet<String>> {
        if self.scoring {
            return None;
        }
        self.program.projected_nodes.get(variable)
    }

    /// The properties a relationship variable's reads are limited to, if any.
    fn relationship_projection(&self, variable: &str) -> Option<&BTreeSet<String>> {
        if self.scoring {
            return None;
        }
        self.program.projected_relationships.get(variable)
    }

    /// Reads an unbound target, limited to its projection, with an admitted
    /// allocation retained by the caller while the record is bound.
    /// `related_bytes` is the size of the relationship read with it, which
    /// shares the read budget.
    fn read_target(
        &self,
        variable: &str,
        id: NodeId,
        label_ids: Option<&[hawdb_core::LabelId]>,
        related_bytes: usize,
    ) -> Result<Option<(NodeRecord, Box<dyn GraphReadAllocation>)>> {
        let memory = self.adjacency_memory();
        let task_context = self.context.task_context;
        if let Some(properties) = self.projection(variable) {
            return projected_node_with_allocation(
                self.store,
                id,
                label_ids,
                properties,
                &mut |bytes| memory.admit_node(bytes, related_bytes, task_context),
                task_context,
            );
        }
        let mut admit = |bytes| {
            memory
                .admit_node(bytes, related_bytes, task_context)
                .map(Some)
        };
        match self.store.node_with_allocation(
            id,
            label_ids,
            &mut hawdb_storage::read_view::ControlledGraphReadAllocator::new(
                &mut admit,
                task_context,
            ),
        )? {
            AdmittedNodeRead::Node(node) => Ok(Some(node.into_parts())),
            // This admission never requests Stop; it fails instead.
            AdmittedNodeRead::Missing | AdmittedNodeRead::Stopped => Ok(None),
        }
    }

    fn adjacency_memory(&self) -> AdjacencyReadMemory<'_> {
        AdjacencyReadMemory {
            budget_bytes: self.context.query_memory_bytes.get(),
            account: Some(self.source_account),
        }
    }

    /// The working row for one input: moved from an owned input, copied from
    /// a borrowed one (#1615). Imports resolve from the unmodified input
    /// before the row is taken; an import's error surfaces at that import,
    /// after the reads of the imports before it.
    fn prepare(
        &self,
        input: Cow<'_, Binding>,
    ) -> Result<(Binding, AdmittedVec<Box<dyn GraphReadAllocation>>)> {
        let mut admit =
            |bytes| admit_graph_read(self.source_account, self.context.task_context, bytes);
        let admission = GraphReadAdmission::new(&mut admit);
        let mut leases = AdmittedVec::new(&admission)?;
        leases.try_push(admit_graph_read(
            self.source_account,
            self.context.task_context,
            binding_memory_bytes(&input),
        )?)?;
        let mut resolved = Vec::with_capacity(self.program.imports.len());
        for import in &self.program.imports {
            let resolution = resolve_import(&input, import);
            let failed = resolution.is_err();
            resolved.push(resolution);
            if failed {
                break;
            }
        }
        let mut row = input.into_owned();
        for name in &self.program.introduced {
            row.nodes.remove(name);
            row.relationships.remove(name);
            row.values.remove(name);
        }
        for (import, resolution) in self.program.imports.iter().zip(resolved) {
            row.nodes.remove(&import.variable);
            row.relationships.remove(&import.variable);
            let Some(ResolvedImport { id, source }) = resolution? else {
                row.values.insert(import.variable.clone(), Value::Null);
                continue;
            };
            match import.kind {
                GraphEntityKind::Node
                    if let Some(properties) = self.projection(&import.variable) =>
                {
                    let node = projected_node_with_allocation(
                        self.store,
                        NodeId(id),
                        None,
                        properties,
                        &mut |bytes| {
                            admit_graph_read(
                                self.source_account,
                                self.context.task_context,
                                bytes
                                    .saturating_add(import.variable.len())
                                    .saturating_add(1024),
                            )
                        },
                        self.context.task_context,
                    )?;
                    let Some((node, allocation)) = node else {
                        return Err(HawDBError::Execution(
                            "bound node disappeared during MATCH".to_string(),
                        ));
                    };
                    leases.try_push(allocation)?;
                    row.nodes.insert(import.variable.clone(), node);
                }
                GraphEntityKind::Node => {
                    let mut admit_node = |bytes: usize| {
                        admit_graph_read(
                            self.source_account,
                            self.context.task_context,
                            bytes
                                .saturating_add(import.variable.len())
                                .saturating_add(1024),
                        )
                        .map(Some)
                    };
                    let AdmittedNodeRead::Node(node) = self.store.node_with_allocation(
                        NodeId(id),
                        None,
                        &mut hawdb_storage::read_view::ControlledGraphReadAllocator::new(
                            &mut admit_node,
                            self.context.task_context,
                        ),
                    )?
                    else {
                        return Err(HawDBError::Execution(
                            "bound node disappeared during MATCH".to_string(),
                        ));
                    };
                    let (node, allocation) = node.into_parts();
                    leases.try_push(allocation)?;
                    row.nodes.insert(import.variable.clone(), node);
                }
                GraphEntityKind::Relationship => {
                    let source = NodeId(
                        source.expect("relationships always import their source from the column"),
                    );
                    let mut found = None;
                    self.store
                        .visit_ordered_adjacent_relationships_with_allocation(
                            source,
                            None,
                            AdjacencyDirection::Outgoing,
                            self.adjacency_memory(),
                            &mut hawdb_storage::read_view::ControlledGraphReadAllocator::new(
                                &mut |bytes| {
                                    admit_graph_read(
                                        self.source_account,
                                        self.context.task_context,
                                        bytes
                                            .saturating_add(import.variable.len())
                                            .saturating_add(1024),
                                    )
                                    .map(Some)
                                },
                                self.context.task_context,
                            ),
                            &mut |input| {
                                let (relationship, allocation) = input.into_parts();
                                runtime_checkpoint(self.context.task_context)?;
                                if relationship.id == RelId(id) {
                                    found = Some((relationship, allocation));
                                    Ok(ScanControl::Stop)
                                } else {
                                    Ok(ScanControl::Continue)
                                }
                            },
                        )?;
                    let (relationship, allocation) = found.ok_or_else(|| {
                        HawDBError::Execution(
                            "bound relationship disappeared during MATCH".to_string(),
                        )
                    })?;
                    leases.try_push(allocation)?;
                    row.relationships
                        .insert(import.variable.clone(), relationship);
                }
            }
        }
        Ok((row, leases))
    }

    /// Runs the conjuncts placed before step `index`, then the step. A
    /// conjunct that is false or NULL drops the partial candidate: the final
    /// conjunction could not be true for any completion of it.
    fn visit(
        &self,
        index: usize,
        row: &mut Binding,
        used: &mut BTreeSet<RelId>,
        emit: &mut dyn FnMut(&Binding) -> Result<ScanControl>,
    ) -> Result<ScanControl> {
        runtime_checkpoint(self.context.task_context)?;
        self.charge_candidate()?;
        let conjuncts = self
            .placed
            .early
            .get(index)
            .map(Vec::as_slice)
            .unwrap_or_default();
        if self.deferred.get() || conjuncts.is_empty() {
            return self.visit_step(index, row, used, emit);
        }
        for conjunct in conjuncts {
            match self.conjunct_holds(conjunct, row) {
                Ok(true) => {}
                Ok(false) => return Ok(ScanControl::Continue),
                Err(HawDBError::Execution(_)) => {
                    // Cancellation is sticky; report it now rather than defer.
                    runtime_checkpoint(self.context.task_context)?;
                    self.deferred.set(true);
                    let control = self.visit_step(index, row, used, emit);
                    self.deferred.set(false);
                    return control;
                }
                Err(error) => return Err(error),
            }
        }
        self.visit_step(index, row, used, emit)
    }

    fn charge_candidate(&self) -> Result<()> {
        self.candidate.map_or(Ok(()), |candidate| candidate())
    }

    fn conjunct_holds(&self, conjunct: &Predicate, row: &Binding) -> Result<bool> {
        evaluate_predicate_with_context(
            conjunct,
            self.context.catalog,
            self.store,
            row,
            self.context.observer,
            self.adjacency_memory(),
            self.context.task_context,
        )
    }

    /// Accepts a complete match. Conjuncts that ran early were true, so the
    /// remaining ones decide, in their original order.
    fn complete_match_holds(&self, row: &Binding) -> Result<bool> {
        let full;
        let conjuncts: &[&Predicate] = match &self.program.predicate {
            Some(predicate) if self.deferred.get() => {
                full = [predicate];
                &full
            }
            _ => &self.placed.last,
        };
        if conjuncts.is_empty() {
            return Ok(true);
        }
        evaluate_conjunction_with_context(
            conjuncts,
            self.context.catalog,
            self.store,
            row,
            self.context.observer,
            self.adjacency_memory(),
            self.context.task_context,
        )
    }

    fn visit_step(
        &self,
        index: usize,
        row: &mut Binding,
        used: &mut BTreeSet<RelId>,
        emit: &mut dyn FnMut(&Binding) -> Result<ScanControl>,
    ) -> Result<ScanControl> {
        let Some(step) = self.program.steps.get(index) else {
            if !self.complete_match_holds(row)? {
                return Ok(ScanControl::Continue);
            }
            return emit(row);
        };
        match step {
            GraphMatchStep::Node(pattern) => {
                if let Some(node) = row.nodes.get(&pattern.variable) {
                    return if self.node_matches(pattern, node) {
                        self.visit(index + 1, row, used, emit)
                    } else {
                        Ok(ScanControl::Continue)
                    };
                }
                if row.values.get(&pattern.variable) == Some(&Value::Null) {
                    return Ok(ScanControl::Continue);
                }
                let labels = label_ids_for_pattern(self.context.catalog, &pattern.label);
                let label = labels.as_deref().and_then(|labels| {
                    if let [label] = labels {
                        Some(*label)
                    } else {
                        None
                    }
                });
                let lookup = self.indexed_node_access(pattern, label, row)?;
                // The node joins the row this visit already owns; admission
                // covers its record and slot, not another copy of the row.
                let mut admit = |bytes: usize| {
                    crate::store::admit_graph_read(
                        self.source_account,
                        self.context.task_context,
                        bytes.saturating_add(1024 + pattern.variable.len()),
                    )
                    .map(Some)
                };
                let mut allocator = hawdb_storage::read_view::ControlledGraphReadAllocator::new(
                    &mut admit,
                    self.context.task_context,
                );
                let visited = Cell::new(0usize);
                let matched = Cell::new(0usize);
                let mut bind = |node: NodeRecord| {
                    runtime_checkpoint(self.context.task_context)?;
                    self.charge_candidate()?;
                    visited.set(visited.get().saturating_add(1));
                    if !self.node_matches(pattern, &node) {
                        return Ok(ScanControl::Continue);
                    }
                    self.visit_bound(
                        index,
                        row,
                        used,
                        &pattern.variable,
                        node,
                        None,
                        &mut |row| {
                            matched.set(matched.get().saturating_add(1));
                            emit(row)
                        },
                    )
                };
                let control = match (lookup.as_ref(), self.projection(&pattern.variable)) {
                    (Some(lookup), Some(properties)) => {
                        let mut admit = |bytes: usize| {
                            crate::store::admit_graph_read(
                                self.source_account,
                                self.context.task_context,
                                bytes.saturating_add(1024 + pattern.variable.len()),
                            )
                        };
                        let mut allocator = hawdb_storage::read_view::GraphReadAllocator::new(
                            &mut admit,
                            self.context.task_context,
                        );
                        let mut visit = |node: hawdb_storage::ProjectedNodeRecord| {
                            bind(NodeRecord {
                                id: node.id,
                                labels: node.labels,
                                properties: node.properties,
                            })
                        };
                        let hawdb_plan_cypher::NodeProjectionAccess::PropertyValues {
                            property,
                            values,
                        } = &lookup.access
                        else {
                            unreachable!()
                        };
                        if !self.store.is_out_of_core()
                            && let Some(control) = self
                                .store
                                .visit_indexed_projected_nodes_by_property_admitted(
                                    lookup.label,
                                    property,
                                    values,
                                    properties,
                                    &mut allocator,
                                    &mut visit,
                                )?
                        {
                            Ok(control)
                        } else {
                            self.store.visit_projected_nodes_by_access_admitted(
                                lookup.label,
                                &lookup.access,
                                properties,
                                &mut allocator,
                                &mut visit,
                            )
                        }
                    }
                    (Some(lookup), None) => self.store.visit_nodes_by_access_with_allocation(
                        lookup.label,
                        &lookup.access,
                        &mut allocator,
                        &mut |input| {
                            let (node, _allocation) = input.into_parts();
                            bind(node)
                        },
                    ),
                    (None, Some(properties)) => self.store.visit_projected_nodes_with_allocation(
                        label,
                        properties,
                        &mut allocator,
                        &mut |input| {
                            let (node, _allocation) = input.into_parts();
                            bind(NodeRecord {
                                id: node.id,
                                labels: node.labels,
                                properties: node.properties,
                            })
                        },
                    ),
                    (None, None) => self.store.visit_nodes_with_allocation(
                        label,
                        &mut allocator,
                        &mut |input| {
                            let (node, _allocation) = input.into_parts();
                            bind(node)
                        },
                    ),
                }?;
                if let Some(lookup) = lookup.as_ref().filter(|lookup| lookup.reported) {
                    let total = self.store.node_count_for_label(Some(lookup.label));
                    self.indexed
                        .record(lookup, total, visited.get(), matched.get());
                }
                Ok(control)
            }
            GraphMatchStep::Expand {
                source,
                relationship,
                rel_type,
                rel_types,
                properties,
                direction,
                min_hops,
                max_hops,
                target,
            } => {
                let bounded = *min_hops != 1 || *max_hops != 1;
                let Some(source_id) = row.nodes.get(source).map(|node| node.id) else {
                    if row.values.get(source) == Some(&Value::Null) {
                        return Ok(ScanControl::Continue);
                    }
                    return Err(HawDBError::Execution(format!(
                        "missing MATCH source '{source}'"
                    )));
                };
                // `None` reads every type. Otherwise the step reads these
                // types: its one type, or the disjunction's types that exist.
                let single;
                let disjunction: Vec<RelTypeId>;
                let rel_type_ids = if !rel_types.is_empty() {
                    disjunction = rel_types
                        .iter()
                        .filter_map(|name| self.context.catalog.rel_type_id(name))
                        .collect();
                    Some(disjunction.as_slice())
                } else if rel_type.is_empty() {
                    None
                } else {
                    single = self.context.catalog.rel_type_id(rel_type);
                    Some(single.as_slice())
                };
                let rel_type_ids = match rel_type_ids {
                    Some([]) => {
                        // No named type exists, so only a zero-hop trail matches.
                        if *min_hops == 0 {
                            let labels = label_ids_for_pattern(self.context.catalog, &target.label);
                            return visit_zero_hop_expand_target(
                                self.store,
                                source_id,
                                labels.as_deref(),
                                *max_hops,
                                self.adjacency_memory(),
                                self.context.task_context,
                                &mut |node, hop| {
                                    self.visit_target(
                                        index,
                                        row,
                                        used,
                                        target,
                                        (Target::Read(node), hop),
                                        emit,
                                    )
                                },
                            );
                        }
                        return Ok(ScanControl::Continue);
                    }
                    rel_type_ids => rel_type_ids,
                };
                let labels = label_ids_for_pattern(self.context.catalog, &target.label);
                // A bound target is compared by id and matched against its
                // bound record; reading it again would return the same node.
                let bound_target = row.nodes.get(&target.variable).map(|node| node.id);
                let no_properties = BTreeSet::new();
                let target_properties = if bound_target.is_some() {
                    Some(&no_properties)
                } else {
                    self.projection(&target.variable)
                };
                let observed = |node: NodeRecord| match bound_target {
                    Some(_) => Target::Bound,
                    None => Target::Read(node),
                };
                if bounded {
                    // Trails exclude relationships bound earlier in the
                    // pattern, and later steps exclude the trail's own.
                    let excluded = used.clone();
                    let _excluded = self
                        .account
                        .reserve(excluded.len().saturating_mul(USED_RELATIONSHIP_BYTES))?;
                    // Validation rejects untyped bounded steps before any row.
                    let Some(rel_type_ids) = rel_type_ids else {
                        return Err(HawDBError::Execution(
                            "bounded MATCH expansion requires a typed pattern".to_string(),
                        ));
                    };
                    return visit_bounded_expand_trails(
                        self.store,
                        BoundedTrailSpec {
                            source: source_id,
                            rel_type_ids,
                            direction: *direction,
                            target_label_ids: labels.as_deref(),
                            min_hops: *min_hops,
                            max_hops: *max_hops,
                        },
                        &excluded,
                        target_properties,
                        self.adjacency_memory(),
                        self.context.task_context,
                        &mut |node, hop, trail| {
                            if bound_target.is_some_and(|id| id != node.id) {
                                return Ok(ScanControl::Continue);
                            }
                            let _used = self
                                .account
                                .reserve(trail.len().saturating_mul(USED_RELATIONSHIP_BYTES))?;
                            used.extend(trail.iter().copied());
                            let control = self.visit_target(
                                index,
                                row,
                                used,
                                target,
                                (observed(node), hop),
                                emit,
                            );
                            for id in trail {
                                used.remove(id);
                            }
                            control
                        },
                    );
                }
                let bound_relationship = relationship
                    .as_ref()
                    .and_then(|name| row.relationships.get(name))
                    .map(|record| record.id);
                if relationship
                    .as_ref()
                    .is_some_and(|name| row.values.get(name) == Some(&Value::Null))
                {
                    return Ok(ScanControl::Continue);
                }
                if relationship.is_none() && properties.is_empty() {
                    // Nothing reads an anonymous relationship without property
                    // constraints beyond its id and endpoint.
                    return visit_step_types(rel_type_ids, &mut |rel_type_id| {
                        visit_one_hop_adjacency_entries(
                            self.store,
                            source_id,
                            rel_type_id,
                            *direction,
                            self.adjacency_memory(),
                            self.context.task_context,
                            &mut |relationship_id, neighbor| {
                                if used.contains(&relationship_id)
                                    || bound_target.is_some_and(|id| id != neighbor)
                                {
                                    return Ok(ScanControl::Continue);
                                }
                                if bound_target.is_none()
                                    && self.membership_rejects(
                                        index,
                                        &target.variable,
                                        neighbor,
                                        row,
                                    )?
                                {
                                    return Ok(ScanControl::Continue);
                                }
                                let (observed, _allocation) = match bound_target {
                                    Some(_) => (Target::Bound, None),
                                    None => match self.read_target(
                                        &target.variable,
                                        neighbor,
                                        labels.as_deref(),
                                        0,
                                    )? {
                                        Some((node, allocation)) => {
                                            (Target::Read(node), Some(allocation))
                                        }
                                        None => return Ok(ScanControl::Continue),
                                    },
                                };
                                let _used = self.account.reserve(USED_RELATIONSHIP_BYTES)?;
                                used.insert(relationship_id);
                                let control = self.visit_target(
                                    index,
                                    row,
                                    used,
                                    target,
                                    (observed, 1),
                                    emit,
                                );
                                used.remove(&relationship_id);
                                control
                            },
                        )
                    });
                }
                // Conjuncts on this relationship run before its target is read.
                let edge_conjuncts = self
                    .placed
                    .edge
                    .get(index)
                    .map(Vec::as_slice)
                    .unwrap_or_default();
                let projection = match relationship {
                    Some(variable) if bound_relationship.is_none() => {
                        self.relationship_projection(variable)
                    }
                    _ => None,
                };
                visit_step_types(rel_type_ids, &mut |rel_type_id| {
                    visit_one_hop_relationship_records(
                        self.store,
                        OneHopRecordSpec {
                            source: source_id,
                            rel_type_id,
                            direction: *direction,
                            rel_properties: properties,
                            projection,
                        },
                        self.adjacency_memory(),
                        self.context.observer,
                        self.context.task_context,
                        &mut |edge, neighbor| {
                            if used.contains(&edge.id)
                                || bound_relationship.is_some_and(|id| id != edge.id)
                                || bound_target.is_some_and(|id| id != neighbor)
                                || !properties_match(properties, &edge.properties)
                            {
                                return Ok(ScanControl::Continue);
                            }
                            let edge_bytes = relationship_memory_bytes(&edge);
                            let _used = self.account.reserve(USED_RELATIONSHIP_BYTES)?;
                            let _edge = self.source_account.reserve(
                                edge_bytes.saturating_add(
                                    relationship
                                        .as_ref()
                                        .map_or(0, |name| graph_slot_entry_bytes(name)),
                                ),
                            )?;
                            let edge_id = edge.id;
                            used.insert(edge_id);
                            // A bound relationship keeps its record: the ids match.
                            let inserted = match relationship {
                                Some(variable) if bound_relationship.is_none() => {
                                    row.relationships.insert(variable.clone(), edge);
                                    Some(variable)
                                }
                                _ => None,
                            };
                            let control = self.visit_edge_target(
                                index,
                                row,
                                used,
                                EdgeTarget {
                                    conjuncts: edge_conjuncts,
                                    pattern: target,
                                    labels: labels.as_deref(),
                                    neighbor: bound_target.is_none().then_some(neighbor),
                                    edge_bytes,
                                },
                                emit,
                            );
                            if let Some(variable) = inserted {
                                row.relationships.remove(variable);
                            }
                            used.remove(&edge_id);
                            control
                        },
                    )
                })
            }
            GraphMatchStep::ShortestPath(step) => {
                self.visit_shortest_paths(index, row, used, step, emit)
            }
        }
    }

    /// Runs `conjuncts` on the relationship step `index` has just bound in
    /// `row`, then reads the step's target, `neighbor` when it is unbound, and
    /// continues with it. A false or NULL conjunct drops the relationship
    /// before its target is read, as it would drop the candidate after the
    /// step. A failing one defers the whole predicate to the end of the match
    /// for this candidate, as [`Self::visit`] does.
    fn visit_edge_target(
        &self,
        index: usize,
        row: &mut Binding,
        used: &mut BTreeSet<RelId>,
        edge: EdgeTarget<'_, '_>,
        emit: &mut dyn FnMut(&Binding) -> Result<ScanControl>,
    ) -> Result<ScanControl> {
        let EdgeTarget {
            conjuncts,
            pattern,
            labels,
            neighbor,
            edge_bytes,
        } = edge;
        let mut defer = false;
        if !self.deferred.get() {
            for conjunct in conjuncts {
                match self.conjunct_holds(conjunct, row) {
                    Ok(true) => {}
                    Ok(false) => return Ok(ScanControl::Continue),
                    Err(HawDBError::Execution(_)) => {
                        // Cancellation is sticky; report it now rather than defer.
                        runtime_checkpoint(self.context.task_context)?;
                        defer = true;
                        break;
                    }
                    Err(error) => return Err(error),
                }
            }
        }
        if let Some(id) = neighbor
            && !defer
            && self.membership_rejects(index, &pattern.variable, id, row)?
        {
            return Ok(ScanControl::Continue);
        }
        let (observed, _allocation) = match neighbor {
            None => (Target::Bound, None),
            Some(id) => match self.read_target(&pattern.variable, id, labels, edge_bytes)? {
                Some((node, allocation)) => (Target::Read(node), Some(allocation)),
                None => return Ok(ScanControl::Continue),
            },
        };
        if !defer {
            return self.visit_target(index, row, used, pattern, (observed, 1), emit);
        }
        self.deferred.set(true);
        let control = self.visit_target(index, row, used, pattern, (observed, 1), emit);
        self.deferred.set(false);
        control
    }

    /// Binds `variable` to `node` in the row for the rest of the pattern,
    /// then restores the row. With seed scoring the extended row is a copy
    /// carrying the hop annotation `hop`.
    #[allow(clippy::too_many_arguments)]
    fn visit_bound(
        &self,
        index: usize,
        row: &mut Binding,
        used: &mut BTreeSet<RelId>,
        variable: &str,
        node: NodeRecord,
        hop: Option<usize>,
        emit: &mut dyn FnMut(&Binding) -> Result<ScanControl>,
    ) -> Result<ScanControl> {
        if self.scoring {
            let _lease = self.source_account.reserve(
                binding_memory_bytes(row)
                    .saturating_add(node_memory_bytes(&node))
                    .saturating_add(variable.len()),
            )?;
            let mut next = row.clone();
            next.nodes.insert(variable.to_string(), node);
            if let Some(hop) = hop {
                crate::scoring::advance_seed_hop(&mut next, hop, true)?;
            }
            return self.visit(index + 1, &mut next, used, emit);
        }
        let _lease = self
            .source_account
            .reserve(node_memory_bytes(&node).saturating_add(graph_slot_entry_bytes(variable)))?;
        row.nodes.insert(variable.to_string(), node);
        // Evaluate placed conjuncts while this candidate's slot is bound.
        let control = self.visit(index + 1, row, used, emit);
        row.nodes.remove(variable);
        control
    }

    /// Binds the path variable to each selected shortest path between the two
    /// bound endpoints. Relationships bound earlier in the clause are not
    /// traversed, and the path's relationships are unavailable to later steps.
    fn visit_shortest_paths(
        &self,
        index: usize,
        row: &mut Binding,
        used: &mut BTreeSet<RelId>,
        step: &GraphMatchShortestPath,
        emit: &mut dyn FnMut(&Binding) -> Result<ScanControl>,
    ) -> Result<ScanControl> {
        let endpoint = |name: &str| match row.nodes.get(name) {
            Some(node) => Ok(Some(node.id)),
            None if row.values.get(name) == Some(&Value::Null) => Ok(None),
            None => Err(HawDBError::Execution(format!(
                "shortestPath endpoint '{name}' is not bound"
            ))),
        };
        let (Some(source), Some(target)) = (endpoint(&step.source)?, endpoint(&step.target)?)
        else {
            return Ok(ScanControl::Continue);
        };
        let rel_type_id = if step.rel_type.is_empty() {
            None
        } else {
            match self.context.catalog.rel_type_id(&step.rel_type) {
                Some(id) => Some(id),
                // An unknown type has no relationships; only a zero-length
                // path can match.
                None if source != target => return Ok(ScanControl::Continue),
                None => None,
            }
        };
        // The search excludes the relationships bound so far while each path
        // extends `used` in place.
        let excluded = used.clone();
        let _excluded = self
            .account
            .reserve(excluded.len().saturating_mul(USED_RELATIONSHIP_BYTES))?;
        let spec = ShortestPathBfsSpec {
            source,
            target,
            direction: step.direction,
            min_hops: step.min_hops,
            max_hops: step.max_hops,
            bounded: step.bounded,
            all: step.selection == ShortestPathSelection::All,
            excluded: &excluded,
        };
        let task_context = self.context.task_context;
        let memory = self.adjacency_memory();
        let mut tracker = OperatorMemoryTracker::with_account(
            self.context.blocking_operator_bytes,
            self.account.clone(),
        );
        let mut checkpoint = || runtime_checkpoint(task_context);
        let mut adjacency =
            |node: NodeId,
             direction: AdjacencyDirection,
             visit: &mut dyn FnMut(RelId, NodeId) -> Result<ScanControl>| {
                // The search needs only relationship ids and neighbors.
                self.store.visit_ordered_adjacency_entries_with_allocation(
                    (node, rel_type_id, direction),
                    memory,
                    &mut hawdb_storage::read_view::ControlledGraphReadAllocator::new(
                        &mut |bytes| memory.admit_node(bytes, 0, task_context).map(Some),
                        task_context,
                    ),
                    &mut |entry| {
                        // An undirected self-loop appears in both adjacency
                        // directions; traverse it once, as other patterns do.
                        if direction == AdjacencyDirection::Incoming
                            && step.direction == hawdb_core::RelationshipDirection::Undirected
                            && entry.neighbor_id == node
                        {
                            return Ok(ScanControl::Continue);
                        }
                        visit(entry.relationship_id, entry.neighbor_id)
                    },
                )
            };
        let search =
            match ShortestPathBfs::search(&spec, &mut adjacency, &mut tracker, &mut checkpoint)? {
                ShortestPathBfsOutcome::NotFound => return Ok(ScanControl::Continue),
                ShortestPathBfsOutcome::ZeroLength => {
                    return self.visit_path(index, row, used, step, (&[source], &[]), emit)
                }
                ShortestPathBfsOutcome::Found(search) => search,
            };
        let control = search.visit_paths(
            &mut tracker,
            &mut checkpoint,
            &mut |nodes, relationships| {
                self.visit_path(index, row, used, step, (nodes, relationships), emit)
            },
        );
        (*search).release(&mut tracker);
        control
    }

    fn visit_path(
        &self,
        index: usize,
        row: &mut Binding,
        used: &mut BTreeSet<RelId>,
        step: &GraphMatchShortestPath,
        path: (&[NodeId], &[RelId]),
        emit: &mut dyn FnMut(&Binding) -> Result<ScanControl>,
    ) -> Result<ScanControl> {
        runtime_checkpoint(self.context.task_context)?;
        let (node_ids, relationship_ids) = path;
        let catalog = self.context.catalog;
        let task_context = self.context.task_context;
        let mut admit =
            |bytes: usize| admit_graph_read(self.source_account, task_context, bytes).map(Some);
        // Owns the copied path payload until the bound row is released.
        let mut payload = self.source_account.reserve(
            node_ids
                .len()
                .saturating_add(relationship_ids.len())
                .saturating_mul(std::mem::size_of::<Value>())
                .saturating_add(256),
        )?;
        let mut nodes = Vec::with_capacity(node_ids.len());
        for &id in node_ids {
            let AdmittedNodeRead::Node(node) = self.store.node_with_allocation(
                id,
                None,
                &mut hawdb_storage::read_view::ControlledGraphReadAllocator::new(
                    &mut admit,
                    task_context,
                ),
            )?
            else {
                return Err(HawDBError::Execution(
                    "shortestPath node disappeared during MATCH".to_string(),
                ));
            };
            let (node, _allocation) = node.into_parts();
            let value = node_value(&node, catalog);
            payload.grow(value_memory_bytes(&value))?;
            nodes.push(value);
        }
        let mut relationships = Vec::with_capacity(relationship_ids.len());
        for &id in relationship_ids {
            let AdmittedRelationshipRead::Relationship(relationship) =
                self.store.relationship_with_allocation(
                    id,
                    &mut hawdb_storage::read_view::ControlledGraphReadAllocator::new(
                        &mut admit,
                        task_context,
                    ),
                )?
            else {
                return Err(HawDBError::Execution(
                    "shortestPath relationship disappeared during MATCH".to_string(),
                ));
            };
            let (relationship, _allocation) = relationship.into_parts();
            let value = relationship_value(&relationship, catalog);
            payload.grow(value_memory_bytes(&value))?;
            relationships.push(value);
        }
        let value = path_value(nodes, relationships);
        let _lease = self.source_account.reserve(
            graph_slot_entry_bytes(&step.path).saturating_add(
                relationship_ids
                    .len()
                    .saturating_mul(USED_RELATIONSHIP_BYTES),
            ),
        )?;
        // The path variable is introduced by this clause, so the row has no
        // value under its name to restore.
        row.values.insert(step.path.clone(), value);
        used.extend(relationship_ids.iter().copied());
        let control = self.visit(index + 1, row, used, emit);
        for id in relationship_ids {
            used.remove(id);
        }
        row.values.remove(&step.path);
        control
    }

    fn visit_target(
        &self,
        index: usize,
        row: &mut Binding,
        used: &mut BTreeSet<RelId>,
        pattern: &GraphMatchNode,
        observed_target: (Target, usize),
        emit: &mut dyn FnMut(&Binding) -> Result<ScanControl>,
    ) -> Result<ScanControl> {
        let (target, hop) = observed_target;
        self.charge_candidate()?;
        if row.values.get(&pattern.variable) == Some(&Value::Null) {
            return Ok(ScanControl::Continue);
        }
        let node = match target {
            Target::Bound => {
                let Some(bound) = row.nodes.get(&pattern.variable) else {
                    return Err(HawDBError::Execution(format!(
                        "missing MATCH target '{}'",
                        pattern.variable
                    )));
                };
                if !self.node_matches(pattern, bound) {
                    return Ok(ScanControl::Continue);
                }
                if !self.scoring {
                    return self.visit(index + 1, row, used, emit);
                }
                bound.clone()
            }
            Target::Read(node) => {
                let bound = row.nodes.get(&pattern.variable);
                if !self.node_matches(pattern, &node)
                    || bound.is_some_and(|bound| bound.id != node.id)
                {
                    return Ok(ScanControl::Continue);
                }
                // The same node is already bound; keep its record.
                if bound.is_some() && !self.scoring {
                    return self.visit(index + 1, row, used, emit);
                }
                node
            }
        };
        self.visit_bound(index, row, used, &pattern.variable, node, Some(hop), emit)
    }

    fn node_matches(&self, pattern: &GraphMatchNode, node: &NodeRecord) -> bool {
        node_matches_label_pattern(
            node,
            label_ids_for_pattern(self.context.catalog, &pattern.label).as_deref(),
        ) && properties_match(&pattern.properties, &node.properties)
    }
}

/// Checks that an imported column holds an entity of the import's kind. The
/// column may come from an untyped source such as an UNWIND element (#1486),
/// so a non-entity value fails with the variable named rather than being read
/// as an identity.
/// The identity of one graph import, read from the unmodified input row.
struct ResolvedImport {
    id: u64,
    /// The source node of an imported relationship.
    source: Option<u64>,
}

/// `None` when the import's column is NULL. A node bound by an earlier
/// expansion of the same plan, rather than a projected column, imports by
/// its record (#1485); relationships always import from their column.
fn resolve_import(input: &Binding, import: &GraphBindingImport) -> Result<Option<ResolvedImport>> {
    let bound = (import.kind == GraphEntityKind::Node
        && !input.values.contains_key(&import.column))
    .then(|| input.nodes.get(&import.column).map(|node| node.id.0))
    .flatten();
    if let Some(id) = bound {
        return Ok(Some(ResolvedImport { id, source: None }));
    }
    let value = input.values.get(&import.column).ok_or_else(|| {
        HawDBError::Execution(format!(
            "missing graph column '{}' during MATCH",
            import.column
        ))
    })?;
    if value == &Value::Null {
        return Ok(None);
    }
    let values = imported_entity(value, import)?;
    let id = entity_id(values, "_id")?;
    let source = match import.kind {
        GraphEntityKind::Node => None,
        GraphEntityKind::Relationship => Some(entity_id(values, "source_id")?),
    };
    Ok(Some(ResolvedImport { id, source }))
}

fn imported_entity<'a>(
    value: &'a Value,
    import: &GraphBindingImport,
) -> Result<&'a BTreeMap<String, Value>> {
    let (expected, fields): (&str, &[&str]) = match import.kind {
        GraphEntityKind::Node => ("a node", &["_id", "labels"]),
        GraphEntityKind::Relationship => {
            ("a relationship", &["_id", "source_id", "target_id", "type"])
        }
    };
    let found = match value {
        Value::Map(values) if fields.iter().all(|field| values.contains_key(*field)) => {
            return Ok(values);
        }
        Value::Map(_) => "a map",
        Value::Bool(_) => "a boolean",
        Value::Int(_) => "an integer",
        Value::Float(_) => "a float",
        Value::Decimal(_) => "a decimal",
        Value::String(_) => "a string",
        Value::List(_) => "a list",
        _ => "a non-entity value",
    };
    Err(HawDBError::Execution(format!(
        "MATCH variable '{}' must be bound to {expected}, found {found}",
        import.variable
    )))
}

fn entity_id(values: &BTreeMap<String, Value>, field: &str) -> Result<u64> {
    match values.get(field) {
        Some(Value::Int(id)) => Ok(*id as u64),
        _ => Err(HawDBError::Execution(format!(
            "typed graph value lacks identity field '{field}'"
        ))),
    }
}

fn properties_match(expected: &BTreeMap<String, Value>, actual: &BTreeMap<String, Value>) -> bool {
    expected
        .iter()
        .all(|(name, value)| value != &Value::Null && actual.get(name) == Some(value))
}