rete-core 0.7.6

Core format types for the Rete cloud-native RDF graph file.
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
//! A grouped query on several threads.
//!
//! `SELECT … (COUNT(*) AS ?n) WHERE { … } GROUP BY …` over ten million rows
//! spends its time per row: decoding a term, a string function, a lookup in
//! the row's graph, a probe of a join. None of it depends on any other row,
//! and the evaluator ran all of it on one thread.
//!
//! Here the scan that drives the pattern is cut into slices. Each worker
//! thread takes slices in order and evaluates the *same* plan over one slice
//! at a time, in its own context (its own term memos). What the slices have
//! in common is made once, by the calling thread, and read by all of them:
//! rows are `Send + Sync`, so a hash join's table, a basic graph pattern's
//! prefix, or the list of graphs a block visits is one copy behind an `Arc`
//! ([`crate::row::Shard::shared`]).
//!
//! **Two ways to aggregate.**
//!
//! - *Merged groups.* Each worker folds its slices into partial aggregates
//!   and the calling thread merges them in slice order, which is scan order,
//!   so every aggregate sees its rows in the order the single fold does (see
//!   the partial aggregation notes in `aggregate`). The slices are fixed by
//!   the file ([`SHARDS`]), not by the machine.
//! - *One fold.* When an aggregate keeps a set of the values it saw
//!   (`COUNT(DISTINCT …)`, `GROUP_CONCAT(DISTINCT …)`), or a slice holds more
//!   groups than may wait for a merge ([`MAX_SHARD_GROUPS`]), the workers do
//!   the per-row work and send their rows, cut down to the slots the fold
//!   reads, to the calling thread, which folds them slice after slice exactly
//!   as it folds the one scan. Memory is the single fold's, plus the rows in
//!   flight ([`ROWS_AHEAD`]).
//!
//! **Which queries.** The driving scan has to sit where the algebra
//! distributes over a union of its rows. The path from the top of the pattern
//! to it goes through FILTER and BIND, UNION (each branch split, or run in
//! slice 0 alone when it cannot be), a sub-select that only projects, and
//! the left side of a join, an OPTIONAL or a MINUS. An EXISTS in a FILTER
//! has its solutions evaluated once, by the first slice that needs them
//! (`ExistsCell`); a MINUS has its right side indexed once, as a join has.
//! The right side of that join is either what the single
//! thread looks up once per left row (`GRAPH ?g { … }` with `?g` bound on the
//! left, a path from a bound endpoint, a BGP whose cheapest pattern is a fat
//! scan), or it is built once into the hash table every slice probes. The
//! scan itself is:
//!
//! - a basic graph pattern: its one pattern's tiles; or, with several
//!   patterns, the tiles of the pattern `BgpSolutions` streams, the prefix
//!   rows that look the last pattern up, or a range of subjects when two
//!   large patterns are merge-joined on theirs (`bgp::shard_bgp_rows`);
//! - a block under `GRAPH ?g`: a one-pattern scan over the quad orders, the
//!   subjects of a class probe, the graphs its required pattern is found in,
//!   or every graph.
//!
//! **Checked, not assumed.** The plan nodes are named by address and every one
//! of them must be reached exactly once per slice ([`crate::row::Shard`]). A
//! pushdown that evaluates a node some other way would hand its rows to every
//! slice; this is checked on a dry run before any thread starts and again on
//! every slice, and a miss means the query runs on one thread as before. The
//! dry run measures first and builds second: a query whose scan is too short
//! to split never pays for a table the single thread would not build.
//!
//! **Over a network.** A slice reads its tiles ahead in one batch (a cut scan
//! starts at the largest window; a restricted quad scan faults its own
//! tiles), so a remote file is cut into fewer, larger slices
//! ([`REMOTE_SHARDS`], each at least [`REMOTE_MIN_TILES`] tiles) and a short
//! scan stays one scan. A join that looks something up per row is not split
//! there: lookups from several threads read half as many bytes again as one
//! thread's in order. Nor is a walk of every graph, which fetches its section
//! in bulk.
//!
//! **Memory.** Workers run at most `2 × workers` slices ahead of the calling
//! thread. Each worker's term memos are capped at its share of one
//! context's. A table built for all slices is the table the single thread's
//! hash join builds.
//!
//! Native builds with the `parallel` feature only. `RETE_QUERY_THREADS=1` (or
//! [`set_query_threads`]) turns it off.

use std::sync::atomic::{AtomicUsize, Ordering};

/// How many worker threads a grouped query may use; 0 = not set.
static THREADS: AtomicUsize = AtomicUsize::new(0);

/// Grouped queries answered on several threads so far, process-wide.
static SHARDED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// How many grouped queries (subqueries included) have been answered on
/// several threads so far, in this process. A counter for tests and
/// diagnostics: whether a query took that path is the difference around it.
pub fn sharded_queries() -> u64 {
    SHARDED.load(Ordering::Relaxed)
}

/// The most threads used when nothing says otherwise.
const DEFAULT_MAX_THREADS: usize = 16;

/// Set how many threads a grouped query may run on (`1`: always one thread;
/// `0`: the default, the machine's cores up to 16, or `RETE_QUERY_THREADS`).
/// Process-wide. The rows a query returns do not depend on it.
pub fn set_query_threads(n: usize) {
    THREADS.store(n, Ordering::Relaxed);
}

/// How many threads a grouped query may run on: see [`set_query_threads`].
pub fn query_threads() -> usize {
    match THREADS.load(Ordering::Relaxed) {
        0 => default_threads(),
        n => n,
    }
}

fn default_threads() -> usize {
    static DEFAULT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
    *DEFAULT.get_or_init(|| {
        if let Some(n) = std::env::var("RETE_QUERY_THREADS")
            .ok()
            .and_then(|v| v.trim().parse::<usize>().ok())
            .filter(|&n| n > 0)
        {
            return n;
        }
        std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(1)
            .min(DEFAULT_MAX_THREADS)
    })
}

/// The group rows of `sel` (as `aggregate` returns them), computed on several
/// threads; `None` when the query is not one this can split, or the attempt
/// was given up: the caller then aggregates as it always did.
#[cfg(not(feature = "parallel"))]
pub(super) fn aggregate_shards<'q>(
    _ctx: &'q crate::row::Ctx<'q>,
    _sel: &'q super::Select,
    _active: &'q crate::index::GraphIndex,
    _nf: Option<&'q [String]>,
    _g: &'q super::GroupSpec,
) -> Option<Vec<crate::row::Row>> {
    None
}

#[cfg(feature = "parallel")]
pub(super) use threaded::aggregate_shards;

#[cfg(feature = "parallel")]
mod threaded {
    use std::cell::Cell;
    use std::collections::BTreeMap;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::{mpsc, Condvar, Mutex};

    use super::super::aggregate::{
        aggregate_folded, aggregate_partial, apply_pre, fold_slots, mergeable, Merger,
        PartialGroups,
    };
    use super::super::eval::{
        certain_bound, eval_plan_iter, expr_has_exists, only_projects, path_endpoint_bound,
        possible_bound, query_ctx, shares_certain_var,
    };
    use super::super::{diag, ExistsCell, FExpr, GraphTarget, GroupSpec, Plan, Select};
    use super::query_threads;
    use crate::index::GraphIndex;
    use crate::row::{Ctx, Row, SharedState, MEMO_CAP_BYTES};

    /// How many slices the driving scan is cut into (fewer when it has fewer
    /// tiles). Fixed, so the slices, and with them the order in which a
    /// floating-point SUM adds up, do not depend on the machine's core count.
    const SHARDS: usize = 64;

    /// The slices of a file read over a network: as many as the most workers,
    /// each at least [`REMOTE_MIN_TILES`] tiles of the driving scan.
    const REMOTE_SHARDS: usize = 16;

    /// The fewest tiles a slice of a remote file's scan holds (about half a
    /// megabyte): below it the requests would outnumber the single scan's.
    const REMOTE_MIN_TILES: usize = 8;

    /// The most groups one slice may hold when the slices' groups are merged:
    /// see the module notes on memory.
    const MAX_SHARD_GROUPS: usize = 100_000;

    /// Rows per message when the workers send rows to the one fold.
    const ROW_CHUNK: usize = 2048;

    /// About how many rows may wait for the one fold, over all workers.
    const ROWS_AHEAD: usize = 1 << 21;

    /// How many slices the driving scan is cut into when the rows go to one
    /// fold. The fold sees the scan's rows in the scan's order whatever the
    /// slices are, so they can be small: a worker then finishes a slice
    /// before its share of the waiting rows is full, and does not stop to
    /// wait for the fold.
    const ROW_SHARDS: usize = 1024;

    /// A worker's stack: the main thread's usual 8 MiB, not a spawned
    /// thread's 2 MiB, since a worker evaluates the same (possibly deeply
    /// nested) plan the calling thread would.
    const WORKER_STACK: usize = 8 << 20;

    /// The floor of a worker's share of the term memos.
    const MIN_MEMO_CAP: usize = 4 << 20;

    thread_local! {
        /// Set on a worker thread: a subquery it evaluates must not fan out again.
        static IN_WORKER: Cell<bool> = const { Cell::new(false) };
    }

    /// The plan nodes a grouped query is split on, by address.
    #[derive(Default)]
    struct Split {
        leaves: Vec<usize>,
        only_first: Vec<usize>,
        /// Joins and MINUSes whose right side is built once for all slices.
        builds: Vec<usize>,
        /// EXISTS sub-plans of the filters on the way to the scan: each is
        /// evaluated once, by the first slice that needs it.
        exists: Vec<usize>,
    }

    /// The EXISTS sub-plans of `e` (not the ones nested inside them, which
    /// belong to their own evaluation).
    fn exists_plans(e: &FExpr, out: &mut Vec<usize>) {
        match e {
            FExpr::Exists(plan) => out.push(plan.as_ref() as *const Plan as usize),
            FExpr::Var(_) | FExpr::Const(_) | FExpr::Bound(_) => {}
            FExpr::Not(a) => exists_plans(a, out),
            FExpr::Arith(_, a, b)
            | FExpr::SameTerm(a, b)
            | FExpr::Compare(_, a, b)
            | FExpr::And(a, b)
            | FExpr::Or(a, b) => {
                exists_plans(a, out);
                exists_plans(b, out);
            }
            FExpr::If(c, t, f) => {
                exists_plans(c, out);
                exists_plans(t, out);
                exists_plans(f, out);
            }
            FExpr::In(x, list) => {
                exists_plans(x, out);
                list.iter().for_each(|e| exists_plans(e, out));
            }
            FExpr::Func(_, args) | FExpr::Coalesce(args) => {
                args.iter().for_each(|e| exists_plans(e, out));
            }
        }
    }

    /// May a condition (a FILTER, an OPTIONAL's) sit on the way to the scan?
    /// Yes without EXISTS. With it, on a local file: its sub-plans are noted
    /// and each is evaluated once for all slices. Over a network not: an
    /// EXISTS probed per row would be one request per row from every thread.
    fn condition(ctx: &Ctx, e: &FExpr, out: &mut Split) -> bool {
        if !expr_has_exists(e) {
            return true;
        }
        if ctx.rete.reads_are_remote() {
            return false;
        }
        exists_plans(e, &mut out.exists);
        true
    }

    /// Find the driving scans under `plan` (see the module notes); `index` is
    /// the graph `plan` is evaluated on. `false`: this pattern cannot be
    /// split, and `out` holds nothing to rely on.
    fn split(
        ctx: &Ctx,
        plan: &Plan,
        index: &GraphIndex,
        from_named: bool,
        out: &mut Split,
    ) -> bool {
        let node = plan as *const Plan as usize;
        match plan {
            Plan::Bgp(patterns) if !patterns.is_empty() => {
                out.leaves.push(node);
                true
            }
            // Any block under a graph variable: its one-pattern scan, the
            // graphs its required pattern is found in, or every graph, sliced.
            Plan::Graph(GraphTarget::Var(v), _) => {
                if ctx.slots.slot(v).is_some() {
                    out.leaves.push(node);
                    true
                } else {
                    false
                }
            }
            Plan::Graph(GraphTarget::Named(iri), inner) => match ctx.rete.graph_index(iri) {
                Some(gi) => split(ctx, inner, gi, from_named, out),
                None => false,
            },
            Plan::Filter(e, inner) => {
                let mark = out.exists.len();
                if condition(ctx, e, out) && split(ctx, inner, index, from_named, out) {
                    true
                } else {
                    out.exists.truncate(mark);
                    false
                }
            }
            Plan::Extend(_, e, inner) => {
                !expr_has_exists(e) && split(ctx, inner, index, from_named, out)
            }
            // A sub-select that only projects: the scan is in its pattern,
            // which has its own variables' slots.
            Plan::Subquery(sub) if only_projects(sub) => {
                let sub_ctx = query_ctx(ctx.rete, sub);
                split(&sub_ctx, &sub.plan, index, from_named, out)
            }
            // The left side holds the scan; the right side is probed per row
            // where the single thread does that, else indexed once.
            Plan::Minus(l, r) => {
                let lcert = certain_bound(ctx, l, ctx.slots.len());
                let probed = matches!(&**r, Plan::Bgp(patterns)
                    if crate::bgp::CorrelatedProbe::new(ctx, index, patterns, &lcert).is_some());
                if probed {
                    return !ctx.rete.reads_are_remote() && split(ctx, l, index, from_named, out);
                }
                if !buildable(r) {
                    return false;
                }
                let mark = out.builds.len();
                out.builds.push(node);
                if split(ctx, l, index, from_named, out) {
                    true
                } else {
                    out.builds.truncate(mark);
                    false
                }
            }
            Plan::Union(l, r) => {
                // A branch that cannot be split runs whole, in slice 0 alone.
                let mut branch = |p: &Plan| {
                    let mark = (
                        out.leaves.len(),
                        out.only_first.len(),
                        out.builds.len(),
                        out.exists.len(),
                    );
                    if split(ctx, p, index, from_named, out) {
                        true
                    } else {
                        out.leaves.truncate(mark.0);
                        out.only_first.truncate(mark.1);
                        out.builds.truncate(mark.2);
                        out.exists.truncate(mark.3);
                        out.only_first.push(p as *const Plan as usize);
                        false
                    }
                };
                let l = branch(l);
                let r = branch(r);
                l || r
            }
            Plan::Join(l, r) => join(ctx, node, l, r, index, from_named, out),
            Plan::LeftJoin(l, r, cond) => {
                let mark = out.exists.len();
                if cond.as_ref().is_none_or(|c| condition(ctx, c, out))
                    && join(ctx, node, l, r, index, from_named, out)
                {
                    true
                } else {
                    out.exists.truncate(mark);
                    false
                }
            }
            _ => false,
        }
    }

    /// `l ⋈ r` (or `l OPTIONAL r`) with the driving scan under `l`. The right
    /// side is either looked up once per left row, as the single thread would
    /// (nothing is built), or built once into a hash table every slice probes.
    fn join(
        ctx: &Ctx,
        node: usize,
        l: &Plan,
        r: &Plan,
        index: &GraphIndex,
        from_named: bool,
        out: &mut Split,
    ) -> bool {
        if looked_up_per_row(ctx, index, l, r) {
            // Over a network every lookup is a request, and lookups from
            // several threads at once read more than one thread's do in
            // order (measured: half as many bytes again): not split.
            return !ctx.rete.reads_are_remote() && split(ctx, l, index, from_named, out);
        }
        if !buildable(r) {
            return false;
        }
        let mark = out.builds.len();
        out.builds.push(node);
        if split(ctx, l, index, from_named, out) {
            true
        } else {
            out.builds.truncate(mark);
            false
        }
    }

    /// Is `r` joined to `l` by one lookup per left row, whatever the rows,
    /// with nothing built from `r` as a whole? The three cases `join_iter`
    /// decides before it sees a row: `GRAPH ?g { … }` with `?g` possibly
    /// bound on the left, a property path with an endpoint bound on the left,
    /// and a BGP that shares a certainly bound variable and whose cheapest
    /// pattern is a fat scan.
    fn looked_up_per_row(ctx: &Ctx, index: &GraphIndex, l: &Plan, r: &Plan) -> bool {
        let lcert = certain_bound(ctx, l, ctx.slots.len());
        match r {
            // As `join_iter` decides it: possibly bound is enough. A row that
            // leaves `?g` unbound joins with every graph, and that walk is
            // then made, once, in the slice the row is in.
            Plan::Graph(GraphTarget::Var(gv), _) => ctx
                .slots
                .slot(gv)
                .is_some_and(|slot| possible_bound(ctx, l, ctx.slots.len())[slot]),
            Plan::Path(s, _, o) => path_endpoint_bound(ctx, l, s, o),
            Plan::Bgp(patterns) => {
                !patterns.is_empty()
                    && shares_certain_var(ctx, patterns, &lcert)
                    && crate::bgp::bgp_min_estimate(ctx, index, patterns)
                        .is_none_or(|n| n >= crate::bgp::FAT_SCAN_ROWS)
            }
            _ => false,
        }
    }

    /// May the right side of a join be evaluated whole and built into a
    /// table? The shapes the single thread hash-joins. Not the ones it would
    /// rather push the left rows into (VALUES, a UNION of patterns, an
    /// entailed atom), nor a path, which it drives from a bound endpoint.
    fn buildable(r: &Plan) -> bool {
        match r {
            Plan::Bgp(_) | Plan::Subquery(_) => true,
            Plan::Graph(_, inner) => buildable(inner),
            Plan::Filter(e, inner) | Plan::Extend(_, e, inner) => {
                !expr_has_exists(e) && buildable(inner)
            }
            Plan::Join(a, b) => buildable(a) && buildable(b),
            Plan::LeftJoin(a, b, cond) => {
                cond.as_ref().is_none_or(|c| !expr_has_exists(c)) && buildable(a) && buildable(b)
            }
            _ => false,
        }
    }

    /// Runs its closure when dropped by a panic's unwinding.
    struct OnPanic<F: Fn()>(F);

    impl<F: Fn()> Drop for OnPanic<F> {
        fn drop(&mut self) {
            if std::thread::panicking() {
                (self.0)();
            }
        }
    }

    /// Which slice a worker takes next, and how far the calling thread has
    /// come (slices merged, or the slice whose rows it is folding).
    struct Claims {
        next: usize,
        merged: usize,
        stop: bool,
    }

    enum Msg {
        /// Slice `i`'s groups; `None`: the attempt is given up.
        Part(usize, Option<PartialGroups>),
        /// The type errors a worker's expressions recorded.
        Diag(diag::Taken),
    }

    /// How a run on several threads ended.
    enum Outcome {
        Done(Vec<Row>),
        /// A slice held more groups than may wait for a merge.
        TooManyGroups,
        Failed,
    }

    /// What every run needs: the query, the split, and what was built for all
    /// slices.
    struct Job<'j, 'q> {
        rete: &'q crate::file::Rete,
        sel: &'q Select,
        active: &'q GraphIndex,
        nf: Option<&'q [String]>,
        g: &'q GroupSpec,
        sp: &'j Split,
        shared: &'j SharedState,
        /// The number of slices when their groups are merged.
        n: usize,
        /// The length of the longest driving scan, in tiles (or rows).
        tiles: usize,
        /// The file is read over a network.
        remote: bool,
        workers: usize,
    }

    impl Job<'_, '_> {
        /// A worker's own context: its share of the memos, the split, and
        /// what is shared.
        fn worker_ctx(&self) -> Ctx<'_> {
            let mut wctx = query_ctx(self.rete, self.sel);
            let memo_cap = (MEMO_CAP_BYTES / self.workers).max(MIN_MEMO_CAP);
            wctx.resolver.set_memo_cap(memo_cap);
            wctx.exhaustive.set(true);
            wctx.shard.set_plan(
                self.sp.leaves.clone(),
                self.sp.only_first.clone(),
                self.sp.builds.clone(),
                self.shared.clone(),
            );
            wctx
        }
    }

    pub(in super::super) fn aggregate_shards<'q>(
        ctx: &'q Ctx<'q>,
        sel: &'q Select,
        active: &'q GraphIndex,
        nf: Option<&'q [String]>,
        g: &'q GroupSpec,
    ) -> Option<Vec<Row>> {
        let threads = query_threads();
        if threads < 2 || IN_WORKER.with(Cell::get) || crate::guard::armed_here() {
            return None;
        }
        if g.pre.iter().any(|(_, e)| expr_has_exists(e)) {
            return None;
        }
        let mut sp = Split::default();
        if !split(ctx, &sel.plan, active, nf.is_some(), &mut sp) || sp.leaves.is_empty() {
            return None;
        }

        // Dry runs: build slice 0's pipeline in this context, pull nothing.
        // The first only measures: it must reach every split node once, and
        // it tells how long the longest driving scan is. A scan too short to
        // split ends here, before anything is built for it. The second
        // builds what the slices share (a join's table).
        ctx.shard.set_plan(
            sp.leaves.clone(),
            sp.only_first.clone(),
            sp.builds.clone(),
            SharedState::new(),
        );
        let dry = |measuring: bool| {
            ctx.shard.set_measuring(measuring);
            ctx.shard.begin(Some((0, SHARDS)));
            drop(eval_plan_iter(ctx, active, nf, &sel.plan));
            (ctx.shard.exact(), ctx.shard.tiles())
        };
        let (mut exact, tiles) = dry(true);
        if exact && tiles >= 2 && !sp.builds.is_empty() {
            exact = dry(false).0;
        }
        let mut shared = ctx.shard.shared_state();
        ctx.shard.clear();
        // An empty cell for each EXISTS on the way: the first slice whose row
        // needs its solutions fills it, the others read it.
        for &plan in &sp.exists {
            shared
                .entry((plan, 0))
                .or_insert_with(|| std::sync::Arc::new(ExistsCell::default()));
        }
        // Over a network a slice is a request or two (it reads its tiles ahead
        // in one batch), so there are fewer of them and none is small: a short
        // scan stays one scan, with its few coalesced requests.
        let remote = ctx.rete.reads_are_remote();
        let n = if remote {
            REMOTE_SHARDS.min(tiles / REMOTE_MIN_TILES)
        } else {
            SHARDS.min(tiles)
        };
        if !exact || n < 2 {
            return None;
        }
        let job = Job {
            rete: ctx.rete,
            sel,
            active,
            nf,
            g,
            sp: &sp,
            shared: &shared,
            n,
            tiles,
            remote,
            workers: threads.min(n),
        };
        // The slices' groups are merged when every aggregate can be; when one
        // cannot (a set of distinct values), or a slice has too many groups
        // to hold while it waits, the workers send their rows to one fold.
        let outcome = if mergeable(g) {
            match merge_groups(ctx, &job) {
                Outcome::TooManyGroups => fold_rows(ctx, &job),
                other => other,
            }
        } else {
            fold_rows(ctx, &job)
        };
        match outcome {
            Outcome::Done(rows) => {
                super::SHARDED.fetch_add(1, Ordering::Relaxed);
                Some(rows)
            }
            _ => None,
        }
    }

    /// Each worker folds its slices into partial aggregates; the calling
    /// thread merges them in slice order.
    fn merge_groups(ctx: &Ctx, job: &Job) -> Outcome {
        let (n, workers) = (job.n, job.workers);
        let window = 2 * workers;
        let claims = Mutex::new(Claims {
            next: 0,
            merged: 0,
            stop: false,
        });
        let wake = Condvar::new();
        let abort = AtomicBool::new(false);
        let too_many = AtomicBool::new(false);
        let give_up = || {
            abort.store(true, Ordering::Relaxed);
            if let Ok(mut c) = claims.lock() {
                c.stop = true;
            }
            wake.notify_all();
        };
        let (tx, rx) = mpsc::channel::<Msg>();
        let mut merger = Merger::default();
        let mut failed = false;

        std::thread::scope(|scope| {
            for _ in 0..workers {
                let tx = tx.clone();
                let (claims, wake, abort, too_many, give_up) =
                    (&claims, &wake, &abort, &too_many, &give_up);
                let worker = move || {
                    // A worker that panics never sends its slice: the others
                    // must not wait for the merge to pass it.
                    let _stop = OnPanic(give_up);
                    IN_WORKER.with(|w| w.set(true));
                    diag::begin();
                    let wctx = job.worker_ctx();
                    let wctx = &wctx;
                    loop {
                        let i = {
                            let mut c = claims.lock().unwrap();
                            loop {
                                if c.stop || c.next >= n {
                                    break None;
                                }
                                if c.next < c.merged + window {
                                    c.next += 1;
                                    break Some(c.next - 1);
                                }
                                c = wake.wait(c).unwrap();
                            }
                        };
                        let Some(i) = i else { break };
                        wctx.shard.begin(Some((i, n)));
                        let mut seen = 0u32;
                        let rows = eval_plan_iter(wctx, job.active, job.nf, &job.sel.plan)
                            .take_while(|_| {
                                seen = seen.wrapping_add(1);
                                !seen.is_multiple_of(4096) || !abort.load(Ordering::Relaxed)
                            });
                        let folded =
                            aggregate_partial(wctx, job.active, rows, job.g, MAX_SHARD_GROUPS);
                        if folded.is_none() {
                            too_many.store(true, Ordering::Relaxed);
                        }
                        let part =
                            folded.filter(|_| wctx.shard.exact() && !abort.load(Ordering::Relaxed));
                        let gone = part.is_none();
                        if gone {
                            give_up();
                        }
                        if tx.send(Msg::Part(i, part)).is_err() || gone {
                            break;
                        }
                    }
                    let _ = tx.send(Msg::Diag(diag::take()));
                };
                // A thread that cannot be started is one worker fewer; with
                // none at all no slice arrives and the attempt fails.
                if std::thread::Builder::new()
                    .name("rete-query".into())
                    .stack_size(WORKER_STACK)
                    .spawn_scoped(scope, worker)
                    .is_err()
                {
                    break;
                }
            }
            drop(tx);

            // Merge in slice order as the slices arrive.
            let mut pending: BTreeMap<usize, PartialGroups> = BTreeMap::new();
            let mut next = 0usize;
            let mut diags = Vec::new();
            for msg in rx {
                match msg {
                    Msg::Diag(taken) => diags.push(taken),
                    Msg::Part(_, None) => {
                        failed = true;
                        pending.clear();
                        give_up();
                    }
                    Msg::Part(i, Some(part)) => {
                        if failed {
                            continue;
                        }
                        pending.insert(i, part);
                        while let Some(part) = pending.remove(&next) {
                            merger.absorb(part);
                            next += 1;
                        }
                        claims.lock().unwrap().merged = next;
                        wake.notify_all();
                    }
                }
            }
            if next != n {
                failed = true;
            }
            // Only a run that is kept reports what its workers recorded: a
            // run given up is evaluated again, and records it all again.
            if !failed {
                diags.into_iter().for_each(diag::absorb);
            }
        });

        if failed {
            return if too_many.load(Ordering::Relaxed) {
                Outcome::TooManyGroups
            } else {
                Outcome::Failed
            };
        }
        Outcome::Done(merger.finish(ctx, job.g))
    }

    /// Each worker evaluates its slices and sends the rows; the calling
    /// thread folds them, slice after slice, exactly as it folds the one
    /// scan's rows. Whatever the aggregates keep (distinct sets, any number of
    /// groups) is kept once, by the one fold. The workers do the per-row work
    /// of the pattern and of the aggregated expressions.
    fn fold_rows(ctx: &Ctx, job: &Job) -> Outcome {
        // (A remote file keeps its few large slices: see `aggregate_shards`.)
        let n = if job.remote {
            job.n
        } else {
            ROW_SHARDS.min(job.tiles)
        };
        let workers = job.workers;
        // The slots the fold reads: a row is cut down to them before it is
        // sent, so what waits for the fold is a few values a row.
        let keep = fold_slots(ctx, job.g);
        let keep = &keep;
        // A slice's rows wait in its own bounded channel, so a worker ahead
        // of the fold stops when its share of the rows that may wait is full.
        let chunks_ahead = (ROWS_AHEAD / workers / ROW_CHUNK).max(1);
        let mut senders = Vec::with_capacity(n);
        let mut receivers = Vec::with_capacity(n);
        for _ in 0..n {
            let (tx, rx) = mpsc::sync_channel::<Vec<Row>>(chunks_ahead);
            senders.push(Some(tx));
            receivers.push(rx);
        }
        let senders = Mutex::new(senders);
        let claims = Mutex::new(Claims {
            next: 0,
            merged: 0,
            stop: false,
        });
        let wake = Condvar::new();
        let abort = AtomicBool::new(false);
        let give_up = || {
            abort.store(true, Ordering::Relaxed);
            if let Ok(mut c) = claims.lock() {
                c.stop = true;
            }
            // A slice nobody took has its sender here: dropped, so the fold
            // does not wait for it.
            if let Ok(mut s) = senders.lock() {
                s.iter_mut().for_each(|tx| *tx = None);
            }
            wake.notify_all();
        };
        let (dtx, drx) = mpsc::channel::<diag::Taken>();
        let mut out = Vec::new();

        std::thread::scope(|scope| {
            for _ in 0..workers {
                let dtx = dtx.clone();
                let (claims, wake, abort, give_up, senders) =
                    (&claims, &wake, &abort, &give_up, &senders);
                let worker = move || {
                    let _stop = OnPanic(give_up);
                    IN_WORKER.with(|w| w.set(true));
                    diag::begin();
                    let wctx = job.worker_ctx();
                    let wctx = &wctx;
                    loop {
                        // At most `2 × workers` slices ahead of the one being
                        // folded: what waits is bounded by slices in flight.
                        let i = {
                            let mut c = claims.lock().unwrap();
                            loop {
                                if c.stop || c.next >= n {
                                    break None;
                                }
                                if c.next < c.merged + 2 * workers {
                                    c.next += 1;
                                    break Some(c.next - 1);
                                }
                                c = wake.wait(c).unwrap();
                            }
                        };
                        let Some(i) = i else { break };
                        let Some(tx) = senders.lock().unwrap()[i].take() else {
                            break;
                        };
                        wctx.shard.begin(Some((i, n)));
                        let mut chunk: Vec<Row> = Vec::with_capacity(ROW_CHUNK);
                        let mut open = true;
                        // Unused: a query with an EXISTS in an aggregate's argument
                        // never runs on several threads (`aggregate_shards` refuses it).
                        let mut cache = super::super::ExistsCache::new();
                        for mut row in eval_plan_iter(wctx, job.active, job.nf, &job.sel.plan) {
                            apply_pre(wctx, job.active, &mut row, job.g, &mut cache);
                            chunk.push(keep.iter().map(|&s| row[s].take()).collect());
                            if chunk.len() == ROW_CHUNK {
                                let full =
                                    std::mem::replace(&mut chunk, Vec::with_capacity(ROW_CHUNK));
                                if tx.send(full).is_err() || abort.load(Ordering::Relaxed) {
                                    open = false;
                                    break;
                                }
                            }
                        }
                        if open && !chunk.is_empty() {
                            open = tx.send(chunk).is_ok();
                        }
                        if !wctx.shard.exact() {
                            give_up();
                        }
                        if !open || abort.load(Ordering::Relaxed) {
                            break;
                        }
                    }
                    let _ = dtx.send(diag::take());
                };
                if std::thread::Builder::new()
                    .name("rete-query".into())
                    .stack_size(WORKER_STACK)
                    .spawn_scoped(scope, worker)
                    .is_err()
                {
                    // Fewer workers; with none, no slice would ever be taken.
                    give_up();
                    break;
                }
            }
            drop(dtx);

            // The one fold: slice after slice, each slice's rows in order.
            let (claims, wake, abort) = (&claims, &wake, &abort);
            let rows = receivers
                .into_iter()
                .enumerate()
                .flat_map(move |(i, rx)| {
                    if let Ok(mut c) = claims.lock() {
                        c.merged = i;
                    }
                    wake.notify_all();
                    rx.into_iter().flatten()
                })
                .take_while(|_| !abort.load(Ordering::Relaxed));
            out = aggregate_folded(ctx, rows, job.g, keep);
            if abort.load(Ordering::Relaxed) {
                // Workers blocked on a full channel see it closed (the
                // receivers went with the iterator) and stop.
                give_up();
            } else {
                // Every slice was folded to its end; the workers are done or
                // about to be. Their records come once they have all gone.
                wake.notify_all();
            }
        });
        if abort.load(Ordering::Relaxed) {
            return Outcome::Failed;
        }
        drx.into_iter().for_each(diag::absorb);
        Outcome::Done(out)
    }
}