relate-executor 1.5.0

In-memory graph and Cypher physical executor
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
//! Composable multi-hop morsel pipeline (ADR-0727).
//!
//! Replaces bespoke `chain.rs` and `chain_count.rs` with a composable,
//! columnar morsel execution pipeline:
//!
//! `Scan → Filter(NodeBytecode::eval_batch) → (Expand / ExpandInto → Filter)* → Sink(Count / Rows / Exists)`
//!
//! # Invariants
//! - **Bounded morsels (ADR-0555)**: Every stage processes morsels of at most
//!   [`BATCH_ROWS`] (= 1024) rows. Intermediate buffers never accumulate unbounded
//!   path vectors; peak execution memory stays `O(k * BATCH_ROWS)` regardless of total
//!   paths.
//! - **Memory accounting (ADR-0463)**: Reusable stage column buffers are charged via
//!   [`WorkspaceCharge`] before allocation.
//! - **Predicate reuse (ADR-0720, ADR-0726)**: Node predicates compile to flat
//!   [`NodeBytecode`], evaluated over morsel chunks via [`PreparedBytecode::eval_batch`]
//!   with fixed-capacity [`SelectionMask`].
//! - **Bound-both-ends expansion (ADR-0722)**: Cycles and repeated pattern variables
//!   expand via adaptive-degree [`ExpandInto`], probing the smaller-degree endpoint in
//!   `O(1)` before lineage or property validation, and running the target node filter.
//! - **Unconstrained hop count**: Arbitrary fixed hop count `k >= 1`, lifting legacy
//!   `MAX_CHAIN_HOPS = 4` limitations.

use std::collections::HashSet;

use relate_core::tokens::WorkspaceCharge;
use relate_core::{Error, NodeId, RelId, Result, Value};
use relate_ir::{var_prop_named, Direction};
use relate_names::NamedToken;

use crate::ctx::ExecCtx;
use crate::eval::bytecode::{PreparedBytecode, SelectionMask, BATCH_ROWS};
use crate::exec::agg_fold::FoldedReturn;
use crate::exec::chunk::{Chunk, Column};
use crate::exec::kernels::count_entry::CountEntry;
use crate::exec::kernels::matcher::Chain;
use crate::exec::kernels::memo::MemoState;
use crate::exec::kernels::program::{InternedLabels, NodeTarget};
use crate::exec::kernels::{chain_stages_fit, count_fold_tail, KernelMode, KernelOutput};
use crate::exec::match_folds::FoldCtx;
use crate::exec::WalkTallies;
use crate::pattern_walk::{bind_node_stub, bind_rel_stub};
use crate::row::Row;
use crate::store::RelTypes;

/// One columnar morsel chunk with fixed primitive ID vectors.
#[derive(Clone, Debug)]
pub(crate) struct MorselChunk {
    /// Primitive NodeId columns for node slots `0..=k`.
    pub(crate) nodes: Vec<Vec<NodeId>>,
    /// Primitive RelId columns for rel slots `0..k`.
    pub(crate) rels: Vec<Vec<RelId>>,
}

impl MorselChunk {
    /// Allocate a morsel chunk with capacity for `k` hops (k + 1 node slots, k rel slots).
    pub(crate) fn with_hops(k: usize) -> Self {
        let mut nodes = Vec::with_capacity(k + 1);
        for _ in 0..=k {
            nodes.push(Vec::with_capacity(BATCH_ROWS));
        }
        let mut rels = Vec::with_capacity(k);
        for _ in 0..k {
            rels.push(Vec::with_capacity(BATCH_ROWS));
        }
        Self { nodes, rels }
    }

    /// Number of active rows in this chunk (derived from the first node column).
    #[inline]
    pub(crate) fn len(&self) -> usize {
        self.nodes[0].len()
    }

    #[inline]
    pub(crate) fn is_full(&self) -> bool {
        self.len() >= BATCH_ROWS
    }

    #[inline]
    pub(crate) fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Clear all columns without reallocating underlying capacity.
    pub(crate) fn clear(&mut self) {
        for col in &mut self.nodes {
            col.clear();
        }
        for col in &mut self.rels {
            col.clear();
        }
    }

    /// Push a tuple derived from `input` row `r`, extending it with rel `rid` and `arrival`.
    #[inline]
    pub(crate) fn push_step(
        &mut self,
        input: &MorselChunk,
        r: usize,
        j: usize,
        rid: RelId,
        arrival: NodeId,
    ) {
        for slot in 0..=j {
            self.nodes[slot].push(input.nodes[slot][r]);
        }
        self.nodes[j + 1].push(arrival);
        for slot in 0..j {
            self.rels[slot].push(input.rels[slot][r]);
        }
        self.rels[j].push(rid);
    }

    /// Compact this chunk in place according to `mask`, retaining rows where bit is set.
    pub(crate) fn compact_with_mask(
        &mut self,
        mask: &SelectionMask,
        active_nodes: usize,
        active_rels: usize,
    ) {
        let mut write_idx = 0;
        let count = self.len();
        for read_idx in 0..count {
            if mask.is_set(read_idx) {
                if write_idx != read_idx {
                    for slot in 0..active_nodes {
                        self.nodes[slot][write_idx] = self.nodes[slot][read_idx];
                    }
                    for slot in 0..active_rels {
                        self.rels[slot][write_idx] = self.rels[slot][read_idx];
                    }
                }
                write_idx += 1;
            }
        }
        for slot in 0..active_nodes {
            self.nodes[slot].truncate(write_idx);
        }
        for slot in 0..active_rels {
            self.rels[slot].truncate(write_idx);
        }
    }
}

/// Whether relationship `rid` was already traversed in row `r`'s lineage up to hop `j`.
#[inline]
fn lineage_contains(chunk: &MorselChunk, r: usize, j: usize, rid: RelId) -> bool {
    (0..j).any(|slot| chunk.rels[slot][r] == rid)
}

/// Prepared node filter checking static labels and compiled [`PreparedBytecode`].
pub(crate) struct PreparedNodeFilter<'a> {
    pub(crate) labels: InternedLabels<'a>,
    pub(crate) bytecode: Option<PreparedBytecode<'a>>,
    pub(crate) memo: Option<MemoState<()>>,
}

impl<'a> PreparedNodeFilter<'a> {
    pub(crate) fn prepare(ctx: ExecCtx<'_>, target: &'a NodeTarget<'a>) -> Result<Self> {
        let labels = InternedLabels::resolve(ctx, target.pattern);
        let bytecode = target
            .bytecode
            .as_ref()
            .map(|code| code.prepare(ctx))
            .transpose()?;
        // Enable memo only when there is no bytecode so eval_batch executes directly:
        let memo = if target.bytecode.is_none() && !target.unfiltered() {
            Some(MemoState::new((), ctx.graph))
        } else {
            None
        };
        Ok(Self {
            labels,
            bytecode,
            memo,
        })
    }

    #[inline]
    pub(crate) fn filter_batch(
        &mut self,
        ctx: ExecCtx<'_>,
        nodes: &[NodeId],
        mask: &mut SelectionMask,
    ) -> Result<()> {
        let graph = ctx.graph;
        if let Some(memo) = &mut self.memo {
            for (i, &node) in nodes.iter().enumerate() {
                if mask.is_set(i) {
                    let admits = memo.answer(graph, node, || {
                        if !self.labels.admits(graph, node) {
                            return Ok(false);
                        }
                        Ok(true)
                    })?;
                    if !admits {
                        mask.clear(i);
                    }
                }
            }
        } else {
            for (i, &node) in nodes.iter().enumerate() {
                if mask.is_set(i) && !self.labels.admits(graph, node) {
                    mask.clear(i);
                }
            }
            if let Some(bc) = &mut self.bytecode {
                if mask.count_ones(nodes.len()) > 0 {
                    bc.eval_batch(ctx, nodes, mask)?;
                }
            }
        }
        Ok(())
    }
}

/// Which chunk element a named binding reads.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Binding {
    Start,
    Rel(usize),
    Node(usize),
}

fn binding_value(ctx: ExecCtx<'_>, chunk: &MorselChunk, r: usize, binding: Binding) -> Value {
    let graph = ctx.graph;
    match binding {
        Binding::Start => bind_node_stub(graph, chunk.nodes[0][r]),
        Binding::Rel(j) => bind_rel_stub(graph, chunk.rels[j][r]),
        Binding::Node(j) => bind_node_stub(graph, chunk.nodes[j + 1][r]),
    }
}

/// Extract unique named variable bindings in pattern order.
fn named_bindings(chain: &Chain<'_>) -> Vec<(String, Binding)> {
    let mut named = Vec::new();
    let mut seen = HashSet::new();
    if let Some(var) = chain.start.pattern.variable.as_ref() {
        let name = var.to_string();
        if seen.insert(name.clone()) {
            named.push((name, Binding::Start));
        }
    }
    for (j, hop) in chain.hops.iter().enumerate() {
        if let Some(var) = hop.rel.variable.as_ref() {
            let name = var.to_string();
            if seen.insert(name.clone()) {
                named.push((name, Binding::Rel(j)));
            }
        }
        if let Some(var) = hop.target.pattern.variable.as_ref() {
            let name = var.to_string();
            if seen.insert(name.clone()) {
                named.push((name, Binding::Node(j)));
            }
        }
    }
    named
}

/// Pipeline terminal sink trait for consuming chunks.
pub(crate) trait MorselSink {
    fn halted(&self) -> bool {
        false
    }

    fn remaining_want(&self) -> Option<usize> {
        None
    }

    fn consume(&mut self, ctx: ExecCtx<'_>, chunk: &MorselChunk) -> Result<()>;
}

/// Pipeline terminal sink mode.
pub(crate) enum SinkMode {
    Count {
        tally: u64,
    },
    Rows {
        halt: Option<usize>,
        names: Vec<String>,
        bindings: Vec<Binding>,
        rows: Vec<Row>,
    },
    Exists {
        counted: Option<(usize, NamedToken)>,
        hit: bool,
    },
}

impl MorselSink for SinkMode {
    #[inline]
    fn halted(&self) -> bool {
        match self {
            Self::Count { .. } => false,
            Self::Rows { halt, rows, .. } => halt.is_some_and(|want| rows.len() >= want),
            Self::Exists { hit, .. } => *hit,
        }
    }

    #[inline]
    fn remaining_want(&self) -> Option<usize> {
        match self {
            Self::Rows {
                halt: Some(want),
                rows,
                ..
            } => Some(want.saturating_sub(rows.len())),
            Self::Exists { hit: false, .. } => Some(1),
            _ => None,
        }
    }

    fn consume(&mut self, ctx: ExecCtx<'_>, chunk: &MorselChunk) -> Result<()> {
        let chunk_len = chunk.len();
        match self {
            Self::Count { tally } => {
                *tally += chunk_len as u64;
            }
            Self::Rows {
                halt,
                names,
                bindings,
                rows,
            } => {
                if names.is_empty() {
                    let to_add = if let Some(want) = *halt {
                        (want - rows.len()).min(chunk_len)
                    } else {
                        chunk_len
                    };
                    for _ in 0..to_add {
                        ctx.graph.cancel_tick()?;
                        rows.push(Row::new());
                    }
                } else {
                    let mut chunk_cols: Vec<Vec<Value>> =
                        vec![Vec::with_capacity(chunk_len); names.len()];
                    for r in 0..chunk_len {
                        ctx.graph.cancel_tick()?;
                        if halt.is_some_and(|want| rows.len() + chunk_cols[0].len() >= want) {
                            break;
                        }
                        for (col_idx, binding) in bindings.iter().enumerate() {
                            chunk_cols[col_idx].push(binding_value(ctx, chunk, r, *binding));
                        }
                    }
                    if !chunk_cols[0].is_empty() {
                        let cols: Vec<Column> =
                            chunk_cols.iter().map(|c| Column::from_values(c)).collect();
                        let decoded = Chunk::from_columns(names, cols).to_rows();
                        rows.extend(decoded);
                    }
                }
            }
            Self::Exists { counted, hit } => {
                if let Some((slot, key)) = counted {
                    for r in 0..chunk_len {
                        ctx.graph.cancel_tick()?;
                        let node = chunk.nodes[*slot][r];
                        if matches!(
                            ctx.graph.node_prop_resolved(node, key),
                            Some(v) if !v.is_null()
                        ) {
                            *hit = true;
                            break;
                        }
                    }
                } else if chunk_len > 0 {
                    *hit = true;
                }
            }
        }
        Ok(())
    }
}

/// One hop stage prepared for morsel traversal.
struct PreparedHop<'a> {
    types: RelTypes,
    traverse: Direction,
    expand_into: Option<usize>,
    filter: PreparedNodeFilter<'a>,
}

/// Pipeline core state without chunks.
struct PipelineCore<'a> {
    k: usize,
    hops: Vec<PreparedHop<'a>>,
    tallies: WalkTallies,
}

impl<'a> PipelineCore<'a> {
    fn expand_stage(
        &mut self,
        ctx: ExecCtx<'a>,
        chunks: &mut [MorselChunk],
        j: usize,
        sink: &mut dyn MorselSink,
    ) -> Result<()> {
        if j == self.k {
            sink.consume(ctx, &chunks[0])?;
            return Ok(());
        }

        let hop_types = self.hops[j].types.clone();
        let hop_dir = self.hops[j].traverse;
        let expand_into = self.hops[j].expand_into;

        let (curr, rest) = chunks.split_at_mut(1);
        let input = &curr[0];
        let input_len = input.len();

        for r in 0..input_len {
            ctx.graph.cancel_tick()?;
            if sink.halted() {
                break;
            }
            let from = input.nodes[j][r];

            if let Some(target_slot) = expand_into {
                let target = input.nodes[target_slot][r];
                let from_deg = ctx.graph.typed_adj_len_resolved(from, hop_dir, &hop_types);
                let to_deg = ctx
                    .graph
                    .typed_adj_len_resolved(target, hop_dir.flip(), &hop_types);

                let (anchor, scan_dir, reversed) = if to_deg < from_deg {
                    (target, hop_dir.flip(), true)
                } else {
                    (from, hop_dir, false)
                };

                self.tallies.expand_into(reversed);
                ctx.graph.try_for_each_neighbor_resolved::<Error>(
                    anchor,
                    scan_dir,
                    &hop_types,
                    |rid| {
                        ctx.graph.cancel_tick()?;
                        if sink.halted() {
                            return Ok(());
                        }
                        if ctx.graph.hop(from, rid, hop_dir) != Some(target) {
                            return Ok(());
                        }
                        if lineage_contains(input, r, j, rid) {
                            return Ok(());
                        }
                        self.tallies.walk();
                        self.tallies.expansion_hop(j);
                        rest[0].push_step(input, r, j, rid, target);
                        if rest[0].is_full()
                            || sink.remaining_want().is_some_and(|w| rest[0].len() >= w)
                        {
                            self.flush_and_filter_hop(ctx, rest, j, sink)?;
                        }
                        Ok(())
                    },
                )?;
            } else {
                ctx.graph.try_for_each_hop_resolved::<Error>(
                    from,
                    hop_dir,
                    &hop_types,
                    |rid, arrival| {
                        ctx.graph.cancel_tick()?;
                        if sink.halted() {
                            return Ok(());
                        }
                        if lineage_contains(input, r, j, rid) {
                            return Ok(());
                        }
                        self.tallies.walk();
                        self.tallies.expansion_hop(j);
                        rest[0].push_step(input, r, j, rid, arrival);
                        if rest[0].is_full()
                            || sink.remaining_want().is_some_and(|w| rest[0].len() >= w)
                        {
                            self.flush_and_filter_hop(ctx, rest, j, sink)?;
                        }
                        Ok(())
                    },
                )?;
            }

            if sink.halted() {
                break;
            }
        }

        if !rest[0].is_empty() && !sink.halted() {
            self.flush_and_filter_hop(ctx, rest, j, sink)?;
        }
        Ok(())
    }

    fn flush_and_filter_hop(
        &mut self,
        ctx: ExecCtx<'a>,
        rest: &mut [MorselChunk],
        j: usize,
        sink: &mut dyn MorselSink,
    ) -> Result<()> {
        let count = rest[0].len();
        if count == 0 {
            return Ok(());
        }

        let mut mask = SelectionMask::all_set(count);
        let arrivals = rest[0].nodes[j + 1].as_slice();
        self.hops[j].filter.filter_batch(ctx, arrivals, &mut mask)?;

        let surviving = mask.count_ones(count);
        if surviving == 0 {
            rest[0].clear();
            return Ok(());
        }

        if surviving < count {
            let active_nodes = j + 2;
            let active_rels = j + 1;
            rest[0].compact_with_mask(&mask, active_nodes, active_rels);
        }

        self.expand_stage(ctx, rest, j + 1, sink)?;
        rest[0].clear();
        Ok(())
    }
}

/// Internal pipeline runner state holding pre-allocated stage buffers.
pub(crate) struct PipelineRunner<'a> {
    ctx: ExecCtx<'a>,
    core: PipelineCore<'a>,
    stage_chunks: Vec<MorselChunk>,
    _charge: WorkspaceCharge,
}

impl<'a> PipelineRunner<'a> {
    fn total_stage_bytes(k: usize) -> usize {
        let mut total = 0;
        for stage in 0..=k {
            let node_bytes = (stage + 1) * BATCH_ROWS * std::mem::size_of::<NodeId>();
            let rel_bytes = stage * BATCH_ROWS * std::mem::size_of::<RelId>();
            let vec_overhead = (2 * stage + 1) * std::mem::size_of::<Vec<u64>>();
            total += node_bytes + rel_bytes + vec_overhead;
        }
        total
    }

    pub(crate) fn new(ctx: ExecCtx<'a>, chain: &'a Chain<'a>) -> Result<Self> {
        let k = chain.hops.len();
        if k == 0 || k > crate::exec::kernels::matcher::MAX_UNROLL_HOPS {
            return Err(relate_core::Error::semantic(
                "morsel pipeline requires 1..=32 hops",
            ));
        }

        // Security: Charge workspace budget BEFORE allocating any heap buffer:
        let total_buffer_bytes = Self::total_stage_bytes(k);
        let charge = WorkspaceCharge::retain(total_buffer_bytes as u64)?;

        let mut hops = Vec::with_capacity(k);
        for hop in &chain.hops {
            hops.push(PreparedHop {
                types: ctx.graph.rel_types_of(hop.rel),
                traverse: hop.traverse,
                expand_into: hop.expand_into,
                filter: PreparedNodeFilter::prepare(ctx, &hop.target)?,
            });
        }

        // Allocate reusable stage buffers (stages 0..=k), each sized to its exact stage width:
        let mut stage_chunks = Vec::with_capacity(k + 1);
        for stage in 0..=k {
            stage_chunks.push(MorselChunk::with_hops(stage));
        }

        Ok(Self {
            ctx,
            core: PipelineCore {
                k,
                hops,
                tallies: WalkTallies::default(),
            },
            stage_chunks,
            _charge: charge,
        })
    }

    pub(crate) fn execute(
        &mut self,
        starts: Vec<NodeId>,
        start_target: &'a NodeTarget<'a>,
        sink: &mut dyn MorselSink,
    ) -> Result<()> {
        let mut start_filter = PreparedNodeFilter::prepare(self.ctx, start_target)?;

        // Scan in chunks of BATCH_ROWS:
        for batch in starts.chunks(BATCH_ROWS) {
            self.ctx.graph.cancel_tick()?;
            if sink.halted() {
                break;
            }

            let mut mask = SelectionMask::all_set(batch.len());
            start_filter.filter_batch(self.ctx, batch, &mut mask)?;
            if mask.count_ones(batch.len()) == 0 {
                continue;
            }

            self.stage_chunks[0].clear();
            for idx in mask.iter_set(batch.len()) {
                self.stage_chunks[0].nodes[0].push(batch[idx]);
            }

            self.core
                .expand_stage(self.ctx, &mut self.stage_chunks, 0, sink)?;
        }
        Ok(())
    }
}

/// Execute a chain contract via the morsel pipeline in rows or exists mode (subsuming `chain.rs`).
pub(crate) fn try_morsel_match(
    ctx: ExecCtx<'_>,
    chain: &Chain<'_>,
    starts: Vec<NodeId>,
    mode: KernelMode<'_>,
) -> Result<KernelOutput> {
    let mut runner = PipelineRunner::new(ctx, chain)?;

    match mode {
        KernelMode::Rows { want } => {
            let (names, bindings) = named_bindings(chain).into_iter().unzip();
            let mut sink = SinkMode::Rows {
                halt: want,
                names,
                bindings,
                rows: Vec::new(),
            };
            runner.execute(starts, &chain.start, &mut sink)?;
            if let SinkMode::Rows { rows, .. } = sink {
                Ok(KernelOutput::Rows(rows))
            } else {
                unreachable!()
            }
        }
        KernelMode::Exists { counted } => {
            let counted_slot = match counted {
                Some(expr) => {
                    let (var, key) = var_prop_named(expr)
                        .ok_or_else(|| Error::semantic("counted expression must be var.prop"))?;
                    let slot = if chain.start.pattern.variable.as_ref() == Some(var) {
                        0
                    } else {
                        let mut found = None;
                        for (j, hop) in chain.hops.iter().enumerate() {
                            if hop.target.pattern.variable.as_ref() == Some(var) {
                                found = Some(j + 1);
                                break;
                            }
                        }
                        found
                            .ok_or_else(|| Error::semantic("counted variable not bound in chain"))?
                    };
                    Some((slot, key))
                }
                None => None,
            };
            let mut sink = SinkMode::Exists {
                counted: counted_slot,
                hit: false,
            };
            runner.execute(starts, &chain.start, &mut sink)?;
            if let SinkMode::Exists { hit, .. } = sink {
                Ok(KernelOutput::Exists(hit))
            } else {
                unreachable!()
            }
        }
    }
}

/// Execute a chain count fold via the morsel pipeline without materializing rows (subsuming `chain_count.rs`).
pub(crate) fn morsel_count(
    ctx: ExecCtx<'_>,
    chain: &Chain<'_>,
    starts: Vec<NodeId>,
) -> Result<u64> {
    let mut runner = PipelineRunner::new(ctx, chain)?;
    let mut sink = SinkMode::Count { tally: 0 };
    runner.execute(starts, &chain.start, &mut sink)?;
    if let SinkMode::Count { tally } = sink {
        Ok(tally)
    } else {
        unreachable!()
    }
}

/// The fold entry: `clauses` starts at the `MATCH`, its `RETURN count(...)` follows.
pub(crate) fn try_fold_morsel_count(ctx: &FoldCtx<'_>) -> Result<Option<FoldedReturn>> {
    let Some(entry) = CountEntry::open(ctx) else {
        return Ok(None);
    };
    let Some(contract) = entry.chain() else {
        return Ok(None);
    };
    let (_tallied, landed) = contract.split_last_hop();
    if !chain_stages_fit(&entry.stats(), entry.conjuncts(), &contract, landed) {
        return Ok(None);
    }
    let (exec, starts) = entry.scan(&contract)?;
    let count = morsel_count(exec, &contract, starts)?;
    Ok(count_fold_tail(exec.graph, u128::from(count), entry.item))
}