waratah_compute/query/tunables.rs
1//! Query-execution tunables: page-size / transport-ceiling constants with
2//! their process-wide override setters (tests and tuning).
3
4use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
5
6use crate::filter_residual::RESIDUAL_RESOLVE_WINDOW;
7use crate::query::caches::MEMO_SPILL_CELLS;
8
9/// Default encoded rows pulled per scan RPC when filling a `Slice` — a
10/// pacing policy, not a wire bound, and deliberately not tied to any
11/// other constant. It must stay AT MOST both of its two ceilings
12/// (compile-time asserts in `join_chunks.rs` enforce `<=`; the value
13/// sits strictly below both so the legality properties are margins, not
14/// boundary coincidences):
15/// * [`waratah_stats::PUSHDOWN_TERMS_LIMIT`] (24,576) — the first EXISTS
16/// probe page broadcasts its key list UNCONDITIONALLY (cheap for
17/// `LIMIT 1`, no measurement gate), which is only within the terms
18/// budget while a page of `N` rows holds at most `N` distinct keys;
19/// staying strictly below the limit keeps that legality a margin
20/// property, not a boundary property. Raising past the limit requires
21/// giving that first page a measurement gate or chunked delivery
22/// first.
23/// * [`MAX_UNARY_SCAN_QUADS`] (the derived unary ceiling, 29,330) — the
24/// direct-unary exceptions (path windows, the detached prefetch
25/// threshold) page at this size and bypass `fetch_window`'s own
26/// ceiling check.
27///
28/// The value is retunable on its own (candidates to sweep under load:
29/// 12,000 / 15,000); larger pages amortize per-request overhead for
30/// hintless classic consumers at the cost of proportionally larger
31/// working batches through every operator above.
32///
33/// **Used by:** the `OpenNode` pull loop's page demand, the detached
34/// prefetch threshold in
35/// [`crate::clients::HexastoreScan::scan_pattern_detached`] (demands at or
36/// under this take one unary message, larger ones open the storage-driven
37/// stream), and the batched pull loop's unary-vs-`scan_stream_drain_n`
38/// check.
39///
40/// **Changing it affects:** compute-side page demand, the window sizes of
41/// the direct-unary exceptions (path windows on `scan_page_at`, the
42/// detached GROUP BY prefetch threshold), and compute-side page memory.
43/// It does **not** decide any transport by itself: window producers route
44/// through `fetch_window`, which compares the demand against
45/// [`MAX_UNARY_SCAN_QUADS`] itself. The one-directional dependency: keep
46/// `SCAN_BATCH <= MAX_UNARY_SCAN_QUADS` so the direct-unary exceptions'
47/// fixed pages stay within the unary ceiling (pinned by a compile-time
48/// assert in `join_chunks.rs`; `scan_page_at`'s `ResourceExhausted`
49/// escalation degrades a violating page to a bounded stream).
50///
51/// FILTER EXISTS SemiJoin OpenNode pages are this size. The default is
52/// below [`waratah_stats::PUSHDOWN_TERMS_LIMIT`] (24_576), so the first
53/// streaming Filter page always broadcasts; later pages on the same
54/// EXISTS cursor promote to hash (`use_broadcast_semi` in `exists.rs`,
55/// which measures the page's actual distinct-key count against the
56/// limit).
57pub const SCAN_BATCH: usize = 10_000;
58
59/// Maximum rows one fluid leaf request fetches per wire page
60/// (`OpenNode::Scan`'s demand-hinted pulls): the leaf may serve a batch
61/// up to the consumer's declared total interest, but each REQUEST stays
62/// at or under this page so every fluid page rides one unary round trip
63/// and a page's distinct key terms never exceed one broadcast budget.
64///
65/// **Couplings (both enforced by compile-time asserts in
66/// `join_chunks.rs`):**
67/// * ≤ [`MAX_UNARY_SCAN_QUADS`] (29,330, the derived unary ceiling) — a
68/// fluid page is a plain paged demand through `fetch_window`, which
69/// routes demands within the ceiling to the unary RPC; staying under
70/// it with margin keeps every fluid page off the escalation path.
71/// * ≤ [`waratah_stats::PUSHDOWN_TERMS_LIMIT`] (24,576) — the page→terms
72/// invariant: a page of N rows holds at most N distinct key terms, so
73/// a fluid page's key list (the chunk slice or the whole under-
74/// threshold list) stays within one request's wire budget by
75/// construction. The value equals the terms limit deliberately; it is
76/// its own constant so the two policies can retune independently (the
77/// assert, not an alias, is the contract).
78///
79/// **Used by:** the fluid leaf loop's per-request demand
80/// `L = min(total_interest − accumulated, LEAF_FLUID_PAGE_MAX)`.
81///
82/// **Changing it affects:** the unary round-trip count of demand-hinted
83/// leaf pulls and the largest one-request key list a chunked leaf can
84/// derive. Raising it past either ceiling fails to compile.
85pub const LEAF_FLUID_PAGE_MAX: usize = 24_576;
86
87/// Rows per fold batch in the `GROUP BY` executor's pipelined loop.
88///
89/// The `GROUP BY` executor consumes its whole input regardless of any parent
90/// `LIMIT` (exact counts), so a larger page amortizes the per-batch round
91/// trip without over-scanning: each page is fully folded while the next page
92/// streams in. Deliberately OVER the unary wire budget (~150 B/quad means
93/// 65536 rows ≈ 9.8 MiB, far past the 4 MiB [`waratah_proto::GRPC_MAX_MESSAGE_SIZE`]):
94/// fold pages always exceed [`SCAN_BATCH`], so they always take the streaming
95/// transport, whose frames are chunked under the cap — a page demand only
96/// sizes the drain, never one wire message.
97pub const GROUP_FOLD_BATCH: usize = 65_536;
98
99/// Ceiling for "provably small" unlimited scans that may take the unary
100/// `ScanPattern` RPC (one round trip) instead of the storage-driven
101/// `ScanPatternStream` endpoint. **Derived, not chosen**: the worst-case
102/// serialized row is [`waratah_proto::WORST_CASE_QUAD_WIRE`] (143 bytes —
103/// four max-width encoded terms plus proto framing, pinned by a test
104/// against the real encoder), so one
105/// [`waratah_proto::GRPC_MAX_MESSAGE_SIZE`] message holds at most this
106/// many rows no matter what data the encoder produces. The value sits at
107/// the exact floor of that division by design — worst-case means the
108/// message may be full to the last varint.
109///
110/// Deliberately decoupled from [`GROUP_FOLD_BATCH`]: the aggregate executor's larger
111/// pages stream their rows and must not raise this unary ceiling.
112///
113/// **Used by:** `scan_page_at`'s unbounded-demand decision (`limit == 0`:
114/// prove the result ≤ this via `unary_scan_quads_bound` to take one unary
115/// message, else drain the stream) and the `ResourceExhausted` escalation
116/// fallback for a mis-proven bound.
117///
118/// **Changing it affects:** how often an unbounded scan takes one unary
119/// round trip vs the streaming endpoint. Raising it past the division
120/// result is not possible without widening the message limit or shrinking
121/// the term encoding; lowering it is a policy choice that sends more
122/// drains to the stream endpoint.
123///
124/// **Relationship to [`SCAN_BATCH`]:** that constant sizes compute-side
125/// page demand; this one sizes the unary transport ceiling. The mainline
126/// self-checks — `fetch_window` compares every demand against this
127/// constant — but the direct-unary exceptions page at `SCAN_BATCH`, so a
128/// retune of this constant below `SCAN_BATCH` pushes those pages into the
129/// escalation path (correct, but every such page pays a wasted oversized
130/// attempt first). Prefer retuning upward, toward the message-size bound.
131pub const MAX_UNARY_SCAN_QUADS: usize =
132 waratah_proto::GRPC_MAX_MESSAGE_SIZE / waratah_proto::WORST_CASE_QUAD_WIRE;
133
134static SCAN_BATCH_SIZE: AtomicUsize = AtomicUsize::new(SCAN_BATCH);
135
136static GROUP_FOLD_BATCH_SIZE: AtomicUsize = AtomicUsize::new(GROUP_FOLD_BATCH);
137
138static MAX_UNARY_SCAN_QUADS_SETTING: AtomicUsize = AtomicUsize::new(MAX_UNARY_SCAN_QUADS);
139
140pub(crate) fn residual_window() -> usize {
141 RESIDUAL_WINDOW.load(Ordering::Relaxed)
142}
143
144/// Override residual resolve window (tests / tuning).
145pub fn set_residual_resolve_window(window: usize) {
146 RESIDUAL_WINDOW.store(window.max(1), Ordering::Relaxed);
147}
148
149/// Restore default residual resolve window.
150pub fn reset_residual_resolve_window() {
151 set_residual_resolve_window(RESIDUAL_RESOLVE_WINDOW);
152}
153
154pub(crate) fn scan_batch() -> usize {
155 SCAN_BATCH_SIZE.load(Ordering::Relaxed)
156}
157
158/// Override scan batch size used while filling `LIMIT` / `OFFSET` (tests / tuning).
159pub fn set_scan_batch(n: usize) {
160 SCAN_BATCH_SIZE.store(n.max(1), Ordering::Relaxed);
161}
162
163/// Restore the default scan batch size.
164pub fn reset_scan_batch() {
165 set_scan_batch(SCAN_BATCH);
166}
167
168/// Rows per fold batch in the `GROUP BY` executor's pipelined loop.
169pub(crate) fn group_fold_batch() -> usize {
170 GROUP_FOLD_BATCH_SIZE.load(Ordering::Relaxed)
171}
172
173/// Override the `GROUP BY` executor's fold batch size (tests / tuning).
174pub fn set_group_fold_batch(n: usize) {
175 GROUP_FOLD_BATCH_SIZE.store(n.max(1), Ordering::Relaxed);
176}
177
178/// Restore the default fold batch size.
179pub fn reset_group_fold_batch() {
180 set_group_fold_batch(GROUP_FOLD_BATCH);
181}
182
183pub(crate) fn max_unary_scan_quads() -> u64 {
184 MAX_UNARY_SCAN_QUADS_SETTING.load(Ordering::Relaxed) as u64
185}
186
187/// Override the proven-bound ceiling under which an unlimited scan still
188/// uses the unary `ScanPattern` RPC (tests / tuning). `0` forces every
189/// unlimited scan onto the streaming endpoint — unlike [`set_scan_batch`],
190/// zero is meaningful here, not degenerate.
191pub fn set_max_unary_scan_quads(n: usize) {
192 MAX_UNARY_SCAN_QUADS_SETTING.store(n, Ordering::Relaxed);
193}
194
195/// Restore the default unary-scan ceiling.
196pub fn reset_max_unary_scan_quads() {
197 set_max_unary_scan_quads(MAX_UNARY_SCAN_QUADS);
198}
199
200/// Spill threshold of the query-local CustomOp memo, in term cells
201/// (`n_rows × n_cols`; see [`crate::filter_residual::MEMO_SPILL_CELLS`]).
202static MEMO_SPILL_CELLS_SETTING: AtomicUsize = AtomicUsize::new(MEMO_SPILL_CELLS);
203
204pub(crate) fn memo_spill_cells() -> usize {
205 MEMO_SPILL_CELLS_SETTING.load(Ordering::Relaxed)
206}
207
208/// Override the memo spill threshold in term cells (tests / tuning).
209pub fn set_memo_spill_cells(cells: usize) {
210 MEMO_SPILL_CELLS_SETTING.store(cells.max(1), Ordering::Relaxed);
211}
212
213/// Restore the default memo spill threshold.
214pub fn reset_memo_spill_cells() {
215 set_memo_spill_cells(MEMO_SPILL_CELLS);
216}
217
218/// Per-entry admission limit of the geo drain memo, in distinct candidate
219/// terms (see
220/// [`crate::query::caches::GEO_DRAIN_MEMO_MAX_ENTRY_TERMS`]).
221static GEO_DRAIN_MEMO_ENTRY_TERMS_SETTING: AtomicUsize =
222 AtomicUsize::new(crate::query::caches::GEO_DRAIN_MEMO_MAX_ENTRY_TERMS);
223
224pub(crate) fn geo_drain_memo_entry_terms() -> usize {
225 GEO_DRAIN_MEMO_ENTRY_TERMS_SETTING.load(Ordering::Relaxed)
226}
227
228/// Override the geo drain memo per-entry limit (tests / tuning).
229pub fn set_geo_drain_memo_entry_terms(terms: usize) {
230 GEO_DRAIN_MEMO_ENTRY_TERMS_SETTING.store(terms, Ordering::Relaxed);
231}
232
233/// Restore the default geo drain memo per-entry limit.
234pub fn reset_geo_drain_memo_entry_terms() {
235 GEO_DRAIN_MEMO_ENTRY_TERMS_SETTING.store(
236 crate::query::caches::GEO_DRAIN_MEMO_MAX_ENTRY_TERMS,
237 Ordering::Relaxed,
238 );
239}
240
241/// Total-term budget of the geo drain memo (see
242/// [`crate::query::caches::GEO_DRAIN_MEMO_MAX_TOTAL_TERMS`]).
243static GEO_DRAIN_MEMO_TOTAL_TERMS_SETTING: AtomicUsize =
244 AtomicUsize::new(crate::query::caches::GEO_DRAIN_MEMO_MAX_TOTAL_TERMS);
245
246pub(crate) fn geo_drain_memo_total_terms() -> usize {
247 GEO_DRAIN_MEMO_TOTAL_TERMS_SETTING.load(Ordering::Relaxed)
248}
249
250/// Override the geo drain memo total budget (tests / tuning).
251pub fn set_geo_drain_memo_total_terms(terms: usize) {
252 GEO_DRAIN_MEMO_TOTAL_TERMS_SETTING.store(terms, Ordering::Relaxed);
253}
254
255/// Restore the default geo drain memo total budget.
256pub fn reset_geo_drain_memo_total_terms() {
257 GEO_DRAIN_MEMO_TOTAL_TERMS_SETTING.store(
258 crate::query::caches::GEO_DRAIN_MEMO_MAX_TOTAL_TERMS,
259 Ordering::Relaxed,
260 );
261}
262
263static RESIDUAL_WINDOW: AtomicUsize = AtomicUsize::new(RESIDUAL_RESOLVE_WINDOW);
264
265/// Extra probe rows a concurrent star may read, per 100 rows the plain-join
266/// plan would have returned from that probe. 15 means at most 1.15×.
267///
268/// The check is [`crate::concurrent_star`]'s over-fetch gate. It does not
269/// change join cardinality estimates or the reorderer's seating cost.
270pub const CONCURRENT_STAR_OVER_FETCH_PERCENT: u64 = 15;
271
272/// Seek-vs-scan exchange rate for the **fetch-once trigger predicate**, in
273/// milli-rows: one index seek costs this many sequentially-streamed rows.
274///
275/// **Used by:** the priced comparison in [`crate::plan`] that decides
276/// whether a probe arm broadcasts per-page key lists (per-page mode) or drains
277/// once into a built table (fetch-once mode):
278/// `pages × (broadcast seeks × this + matched rows × MATCHED_ROW_EQUIV)
279/// ≥ MARGIN × whole_read_rows`
280/// (one seek list per page — the first surviving key's, the runtime's
281/// `join_keys_scan_filter` pick; `whole_read_rows` is the unclamped whole-arm
282/// estimate).
283/// Both consumers — the seating comparator's build price and the
284/// `ScanOp::fetch_once` plan stamp — read the same constant through the
285/// same predicate, so plan and runtime cannot diverge.
286///
287/// **Measured:** 3.6–4.9 rows per seek across the bellendena corpus arms
288/// (`scripts/calibrate_seek_ratio.py` realworld mode, release builds): the
289/// stable arms sit at ~3.6 under every reconstructable condition, and the
290/// warm-cache big arms reach ~4.9. One arm class (a multi-million-row
291/// whole read) is regime-volatile by at least ±40% cold-to-warm — a pin
292/// must never rest on that arm alone; anchor on the stable arms or take
293/// cold+warm bands. The default is the measured band's midpoint region
294/// (the calibration script's own historical range was 3.6–5.0), chosen to
295/// sit off the corpus verdicts' flip points rather than on one, so
296/// run-to-run regime swing cannot silently flip a verdict. Re-measure
297/// when the transport or index shape changes.
298///
299/// **Placement rule:** this exchange rate belongs
300/// ONLY to fetch-once-class decisions (whole-fetch vs selective-push).
301/// The seating comparator's own {rows, seeks} lexicographic order must
302/// never fold it in — the ordering is deliberately rate-free.
303pub const FETCH_ONCE_SEEK_EQUIV_MILLI: u64 = 4_200;
304
305/// How many times over its whole-read price per-page mode may cost before
306/// the fetch-once trigger fires, in milli (1400 = 1.4×). The build price
307/// is one sequential drain of the arm's UNCLAMPED estimate
308/// (`whole_read_rows`); the probe price is
309/// `pages × (seeks × SEEK_EQUIV + matched × MATCHED_ROW_EQUIV)`.
310///
311/// This is NOT an error correction on the price — it is the empirical
312/// placement of the two roads' FULL-COST crossover, which the fetch-only
313/// price cannot see. The drain road pays hash-build, table memory and
314/// the bail-out risk on top of its per-row fetch; the per-page road pays
315/// its per-batch/per-chunk fixed and consumer assembly on top of its
316/// seeks. Measured by forced-side A/B: the flagship's polluted arm wins
317/// as PerPage at a fetch ratio of 1.16, and the deadvar/optional arms
318/// win as FetchOnce at 1.52+, so the true crossover lives in (1.2, 1.5).
319/// The 2026-11-15 corpus census (40 stamped arms, both scales) centered
320/// that gap: every measured-correct PerPage arm prices ≤ 1.22, every
321/// measured-correct FetchOnce arm ≥ 1.52; 1.4 sits between with cushion
322/// for ρ's ±15% regime swing on both sides.
323///
324/// Expected drift: as the unmodeled terms get priced into the estimate
325/// (the per-batch fixed; the drain-side per-row assembly), the
326/// calibrated value should move toward 1000 — re-derive whenever a term
327/// lands or the pins move. If an arm ever prices inside the gap, no
328/// value here is right: the fix is more model physics, not a new
329/// boundary.
330pub const FETCH_ONCE_MARGIN_MILLI: u64 = 1_400;
331
332/// Cost of one MATCHED row in the fetch-once trigger's per-page price, in
333/// milli-rows: one row an allow-list fetch returns costs this many
334/// sequentially-streamed rows. Matched rows are not free even though the
335/// seek-union transport fetches them in one pass: each returned row pays
336/// the wire fetch (≈ 1.0) plus decode, intern and batch-table assembly
337/// (≈ 0.23) on the compute side.
338///
339/// **Used by:** the same priced comparison as
340/// [`FETCH_ONCE_SEEK_EQUIV_MILLI`] — the matched-rows multiplier in
341/// `pages × (seeks × SEEK_EQUIV + matched × this) ≥ MARGIN ×
342/// whole_read_rows` (previously hardcoded at 1000).
343///
344/// **Measured:** 1.15–1.40 rows per matched row across the parallel-probe road's
345/// two-domain, three-multiplicity calibration matrix
346/// (`scripts/calibrate_seek_ratio.py` synthetic mode; the assembly share
347/// is the most stable quantity that calibration produced).
348///
349/// **Do not re-pin to a fresh synthetic reading.** A single sweep
350/// measures ~1150 milli — the band's floor — and that is the *expected*
351/// reading, not drift: the calibration's tightest pass (15 runs)
352/// measured exactly this value, and the pin was still placed at 1400 on
353/// purpose. The pin is an arm-placement decision, not a point estimate.
354/// The corpus's deadvar arm prices mostly matched rows and carries the
355/// thinnest FetchOnce margin of the pinned arms: +4.5% price over its
356/// threshold at 1400, thinning to +1.4% at 1300. At 1153 it flips to
357/// PerPage (price 786,118 vs threshold 812,258 row-equivalents, −3.2%),
358/// misclassifying a wall-clock-correct FetchOnce arm onto the slower
359/// road. A synthetic sweep cannot see arms like this one — its fixtures
360/// have no per-arm verdict margins to protect — so re-pinning requires
361/// a corpus verdict census confirming every thin-margin arm still
362/// classifies on its measured-correct side. Re-measure the band when
363/// the fetch path's decode/intern/assembly work changes shape; expect
364/// the re-measurement to reproduce the floor unless that shape moved.
365pub const FETCH_ONCE_MATCHED_ROW_EQUIV_MILLI: u64 = 1_400;
366
367/// Cost of one row in the fetch-once trigger's per-page price when the
368/// matched count is the **unknown-domain fallback** rather than an estimate,
369/// in milli-rows.
370///
371/// `probe_broadcast_price` returns the whole arm as the matched count when the
372/// probe's join-key domain is unknown — a scan with an unbound predicate, such
373/// as `?s ?p ?o`, has no per-predicate subject sketch to consult. That number
374/// is an upper bound that holds for every list, so it says nothing about
375/// *this* page's list. Charging it the full
376/// [`FETCH_ONCE_MATCHED_ROW_EQUIV_MILLI`] premium lets the bound alone reach
377/// the build bar — the premium and [`FETCH_ONCE_MARGIN_MILLI`] are both 1400 —
378/// so a single seek tips a 16-key probe into a whole-store drain.
379///
380/// This rate keeps the real per-row overhead (a bound row still crosses the
381/// wire and is assembled) while leaving headroom below the margin: one page
382/// of a degenerate match prices at 1.2× the arm, under the 1.4× bar, so it
383/// stays per-page; two pages price at 2.4× and build, which is the crossover
384/// a whole-read-per-page road actually has. The value sits in the lower half
385/// of the measured 1.15–1.40 matched-row band.
386///
387/// A **known** domain whose list covers it keeps the full premium: there the
388/// saturation is exact (the push really does return every row), so the whole
389/// read is the cheaper road and the bound rate must not suppress it. Only the
390/// unknown-domain fallback takes this rate.
391///
392/// **Keep this strictly below [`FETCH_ONCE_MARGIN_MILLI`].** That gap is the
393/// only thing stopping a vacuous bound from ordering a build. A gap of 100
394/// milli-rows is too thin: a one-page build then needs a key list worth a
395/// tenth of the arm in seeks, which a page-sized list can reach on a large
396/// arm. The 200-point gap here keeps the one-page tipping point far above
397/// [`waratah_stats::PUSHDOWN_TERMS_LIMIT`] on corpus-scale arms, so a page
398/// cannot hold enough keys to tip a one-page degenerate match into a build.
399pub const FETCH_ONCE_MATCHED_BOUND_EQUIV_MILLI: u64 = 1_200;
400
401// The bound rate must leave room below the margin: at equality (or above),
402// a vacuous whole-arm matched term reaches the build bar on its own and a
403// single seek orders a whole-arm drain. See the constant's doc for the
404// one-page tipping point at smaller gaps.
405const _: () = assert!(FETCH_ONCE_MATCHED_BOUND_EQUIV_MILLI < FETCH_ONCE_MARGIN_MILLI);
406
407/// How many times its own priced cost the general semi-join build may pay
408/// before the per-page road wins, in milli (1000 = no extra margin).
409///
410/// This is deliberately **not** [`FETCH_ONCE_MARGIN_MILLI`]. That margin was
411/// calibrated for the whole-scan table build: a memoizable scan whose table
412/// carries every column. The general semi build reads a filtered subtree
413/// that cannot be memoized and retains only the join key set. The residual
414/// unmodeled work differs on both sides — no memo reuse on the build side,
415/// a narrower key-set table on the other — so the fetch-once value has no
416/// claim here.
417///
418/// **Provisional.** The executor that runs the domain-pushed build lands
419/// with the strategy stamp; the forced-side A/B on the t4 shape (and the
420/// corpus regression) pins this value. Until then the verdict is a
421/// diagnostic, so the neutral 1000 keeps the arithmetic honest instead of
422/// borrowing a calibrated constant from a different road.
423pub const SEMI_BUILD_MARGIN_MILLI: u64 = 1_000;
424
425/// Cost of one key-set output row above its read cost, in milli-rows: the
426/// filter evaluation, key projection, hash insert and duplicate check that
427/// turn one matched right row into a key-set entry. The row's wire, decode
428/// and intern cost is already in the matched-row term of the same price.
429///
430/// **Provisional** for the same reason as [`SEMI_BUILD_MARGIN_MILLI`]: the
431/// key-set build does not exist yet. Re-derive it with the build road's
432/// A/B; do not fold it into the fetch-once matched rate, which prices a
433/// different build shape.
434pub const SEMI_KEY_SET_ROW_EQUIV_MILLI: u64 = 1_000;
435
436/// Cost of one **AlwaysEncoded** FILTER conjunct per input row, in
437/// milli-row-equivalents (5 = 0.005 row-equivalents). A filter always costs
438/// something even when it is fully encoded: the expression is evaluated
439/// once per input row and the surviving rows still pay the normal stream.
440/// The rate is per conjunct, so a three-conjunct AND pays three times.
441///
442/// The split from the maybe/resolve rates is the plan's existing
443/// `ExprCapability` classification: encoded conjuncts never touch the
444/// string registry, maybe-encoded ones sometimes materialize a term, and
445/// resolve conjuncts go through the deferred string path. The values are
446/// **provisional** placeholders that keep a filtered arm strictly more
447/// expensive than its unfiltered twin; the forced-side A/B replaces them.
448pub const FILTER_ENCODED_ROW_EQUIV_MILLI: u64 = 5;
449
450/// Cost of one **MaybeEncoded** FILTER conjunct per input row, in
451/// milli-row-equivalents. See [`FILTER_ENCODED_ROW_EQUIV_MILLI`] for the
452/// capability split and the provisional calibration status.
453pub const FILTER_MAYBE_ENCODED_ROW_EQUIV_MILLI: u64 = 50;
454
455/// Cost of one **AlwaysResolve** FILTER conjunct per input row, in
456/// milli-row-equivalents. These conjuncts go through the deferred string
457/// path (registry resolve / materialization), so they are the most
458/// expensive scalar filters. See [`FILTER_ENCODED_ROW_EQUIV_MILLI`] for the
459/// provisional calibration status.
460pub const FILTER_RESOLVE_ROW_EQUIV_MILLI: u64 = 200;
461
462// The capability ladder is load-bearing: a resolve conjunct must not price
463// below a maybe-encoded one, or the "filtered is more expensive" direction
464// inverts inside a single FILTER.
465const _: () = assert!(FILTER_ENCODED_ROW_EQUIV_MILLI < FILTER_MAYBE_ENCODED_ROW_EQUIV_MILLI);
466const _: () = assert!(FILTER_MAYBE_ENCODED_ROW_EQUIV_MILLI < FILTER_RESOLVE_ROW_EQUIV_MILLI);
467
468/// Measured realized-seek-concurrency curve for the parallel probe road:
469/// (funded fetch concurrency in milli → realized wall-clock speedup in milli).
470/// Funding `w` permits of concurrent chunk fetches buys `realized(w)`
471/// speedup — sublinear, because the fetch path is part CPU work (decode,
472/// dedup, table assembly), and saturating near the box's physical core
473/// count. Lookup interpolates linearly between points; a funded fetch
474/// concurrency above the last point clamps to it, and below the first point returns
475/// 1000 (one outstanding fetch at a time realizes exactly itself). The
476/// table must be STRICTLY INCREASING in its funded value — the lookup
477/// debug-asserts it, and a duplicate funded value (which would make the
478/// interpolation span zero) resolves to the higher point's realized
479/// value instead of dividing by zero.
480///
481/// **Measured:** 2026-11-15 on the dev box (8 physical cores), 100m-row
482/// flagship scale (32 allow-list chunks per batch), Side-C method —
483/// per-batch walls with every chunk dispatched at once against sequential
484/// anchors bracketing the sweep (0.8% anchor drift). Points: funded
485/// 1000 → 990 (carried as the by-construction sequential value 1000,
486/// which the measurement confirms within 1%), 2000 → 1820,
487/// 3000 → 2420, 5000 → 3330, 7000 → 4050 (saturation onset ≈ physical
488/// core count; funded 9000–15000 plateau at 3940–4260, carried as the
489/// last point). The 10m tier
490/// (12 chunks per batch) saturates lower (~2.5): realization is
491/// work-per-chunk dependent, so a chunk-scale regime change re-derives
492/// this table.
493///
494/// **Re-derive when:** the engine fetch-concurrency default moves materially, the
495/// wave ceiling ([`PARALLEL_PUSHDOWN_WAVE_MAX`]) starts binding below the
496/// curve, the transport changes, or the chunk-scale regime changes. This
497/// curve is config-relative (a property of the funded fetch concurrency), unlike
498/// [`FETCH_ONCE_SEEK_EQUIV_MILLI`], which is a per-unit cost.
499pub const PROBE_SEEK_CONCURRENCY_CURVE: &[(u64, u64)] = &[
500 (1_000, 1_000),
501 (2_000, 1_820),
502 (3_000, 2_420),
503 (5_000, 3_330),
504 (7_000, 4_050),
505];
506
507/// Realized concurrency (milli) for a funded fetch concurrency (milli), from
508/// [`PROBE_SEEK_CONCURRENCY_CURVE`] — see it for the measurement and the
509/// clamp rules.
510pub(crate) fn probe_seek_concurrency_realized_milli(funded_milli: u64) -> u64 {
511 let curve = PROBE_SEEK_CONCURRENCY_CURVE;
512 let &(first_funded, first_realized) = &curve[0];
513 if funded_milli <= first_funded {
514 return first_realized;
515 }
516 let mut prev = (first_funded, first_realized);
517 for &point in curve.iter().skip(1) {
518 if funded_milli <= point.0 {
519 let span = point.0 - prev.0;
520 debug_assert!(
521 span > 0,
522 "curve must be strictly increasing in funded milli"
523 );
524 // The release-build answer for a duplicate funded value (no
525 // assert there): the higher point's realized value, not a
526 // division by a zero span.
527 if span == 0 {
528 return point.1;
529 }
530 let part = funded_milli - prev.0;
531 return prev.1 + (point.1 - prev.1) * part / span;
532 }
533 prev = point;
534 }
535 curve[curve.len() - 1].1
536}
537
538static FETCH_ONCE_SEEK_EQUIV_SETTING: AtomicUsize =
539 AtomicUsize::new(FETCH_ONCE_SEEK_EQUIV_MILLI as usize);
540static FETCH_ONCE_MARGIN_SETTING: AtomicUsize = AtomicUsize::new(FETCH_ONCE_MARGIN_MILLI as usize);
541static FETCH_ONCE_MATCHED_ROW_SETTING: AtomicUsize =
542 AtomicUsize::new(FETCH_ONCE_MATCHED_ROW_EQUIV_MILLI as usize);
543static FETCH_ONCE_MATCHED_BOUND_SETTING: AtomicUsize =
544 AtomicUsize::new(FETCH_ONCE_MATCHED_BOUND_EQUIV_MILLI as usize);
545
546pub(crate) fn fetch_once_seek_equiv_milli() -> u128 {
547 FETCH_ONCE_SEEK_EQUIV_SETTING.load(Ordering::Relaxed) as u128
548}
549
550/// Override the fetch-once seek exchange rate, milli-rows per seek
551/// (tests / tuning). See [`FETCH_ONCE_SEEK_EQUIV_MILLI`] for placement.
552pub fn set_fetch_once_seek_equiv_milli(milli: usize) {
553 FETCH_ONCE_SEEK_EQUIV_SETTING.store(milli, Ordering::Relaxed);
554}
555
556/// Restore the default fetch-once seek exchange rate.
557pub fn reset_fetch_once_seek_equiv_milli() {
558 FETCH_ONCE_SEEK_EQUIV_SETTING.store(FETCH_ONCE_SEEK_EQUIV_MILLI as usize, Ordering::Relaxed);
559}
560
561pub(crate) fn fetch_once_margin_milli() -> u128 {
562 FETCH_ONCE_MARGIN_SETTING.load(Ordering::Relaxed) as u128
563}
564
565/// Override the fetch-once trigger margin, milli (1400 = 1.4×)
566/// (tests / tuning).
567pub fn set_fetch_once_margin_milli(milli: usize) {
568 FETCH_ONCE_MARGIN_SETTING.store(milli, Ordering::Relaxed);
569}
570
571/// Restore the default fetch-once trigger margin.
572pub fn reset_fetch_once_margin_milli() {
573 FETCH_ONCE_MARGIN_SETTING.store(FETCH_ONCE_MARGIN_MILLI as usize, Ordering::Relaxed);
574}
575
576pub(crate) fn fetch_once_matched_row_equiv_milli() -> u128 {
577 FETCH_ONCE_MATCHED_ROW_SETTING.load(Ordering::Relaxed) as u128
578}
579
580/// Override the matched-row cost, milli-rows per matched row
581/// (tests / tuning). See [`FETCH_ONCE_MATCHED_ROW_EQUIV_MILLI`].
582pub fn set_fetch_once_matched_row_equiv_milli(milli: usize) {
583 FETCH_ONCE_MATCHED_ROW_SETTING.store(milli, Ordering::Relaxed);
584}
585
586/// Restore the default matched-row cost.
587pub fn reset_fetch_once_matched_row_equiv_milli() {
588 FETCH_ONCE_MATCHED_ROW_SETTING.store(
589 FETCH_ONCE_MATCHED_ROW_EQUIV_MILLI as usize,
590 Ordering::Relaxed,
591 );
592}
593
594pub(crate) fn fetch_once_matched_bound_equiv_milli() -> u128 {
595 FETCH_ONCE_MATCHED_BOUND_SETTING.load(Ordering::Relaxed) as u128
596}
597
598/// Override the degenerate-matched-bound cost, milli-rows per bound row
599/// (tests / tuning). See [`FETCH_ONCE_MATCHED_BOUND_EQUIV_MILLI`].
600pub fn set_fetch_once_matched_bound_equiv_milli(milli: usize) {
601 FETCH_ONCE_MATCHED_BOUND_SETTING.store(milli, Ordering::Relaxed);
602}
603
604/// Restore the default degenerate-matched-bound cost.
605pub fn reset_fetch_once_matched_bound_equiv_milli() {
606 FETCH_ONCE_MATCHED_BOUND_SETTING.store(
607 FETCH_ONCE_MATCHED_BOUND_EQUIV_MILLI as usize,
608 Ordering::Relaxed,
609 );
610}
611
612/// Wave ceiling on chunk fetches dispatched concurrently for one
613/// over-threshold broadcast pushdown (the parallel pushdown transport in
614/// [`crate::query::parallel_pushdown`]). An over-threshold term list is sliced
615/// into [`waratah_stats::PUSHDOWN_TERMS_LIMIT`]-term chunks; at most
616/// this many chunk fetches are outstanding at once, the rest queue and
617/// dispatch as the pool frees. The EFFECTIVE ceiling is the query's
618/// free-permit count: the arm-permit pool — sized from
619/// `QUERY_FETCH_CONCURRENCY` in `context.rs` as the engine fetch
620/// concurrency plus one permit for the query root's own
621/// whole-execution hold — funds what actually dispatches, so at the
622/// default fetch concurrency (3, a 4-permit pool) this knob rarely
623/// binds, and a pool with nothing free degrades the transport to
624/// `degrade_to_chunked_serial`: one sequential RPC per remaining chunk,
625/// never a concatenated multi-chunk request and never the unfiltered
626/// whole read the producing verdict rejected.
627///
628/// **Used by:** every chunked-filtered-fetch consumer — the eager
629/// Broadcast-stamped join's Filter branch (the one whose allow-list can
630/// exceed the PUSHDOWN_TERMS_LIMIT terms limit at execute
631/// time; join products are not driver-cut, see the `star_built` field doc in
632/// `join_chunks.rs`), the leaf over-threshold hook in `fetch_whole`, and
633/// the parallel-probe road's per-arm suffix chunks. Note the name: this bounds concurrent fetches of one
634/// query's allow-list transport — it has nothing to do with storage
635/// sharding.
636///
637/// **Changing it affects:** concurrent load on the storage partitions'
638/// allow-list walks (`visit_allow_list_rows`) and the peak memory held in
639/// unjoined chunk results. Two bounds interact: the term-chunk size is the
640/// PUSHDOWN_TERMS_LIMIT terms limit (fixed), this only bounds how many such chunks dispatch
641/// at once. The knob's own load effect is NOT yet measured — before
642/// tuning this value at the 100m tier,
643/// sweep it together with the arm-permit pool sizing (the same pool funds
644/// every parallel arm evaluation, so raising one competes with the
645/// other), and re-check the q-broadcast-critical parallel-walk regression.
646///
647/// Measured 2026-11-14 (parallel probe road): at defaults this knob NEVER
648/// binds that road — 8 sits above the engine fetch concurrency (the pool's free
649/// permits after the root hold: `QUERY_FETCH_CONCURRENCY` = 3 at defaults), so
650/// the pool funds what actually dispatches and the knob only bounds a wave
651/// on a pool much larger than today's. Widening the probe road's dispatch
652/// is engine fetch-concurrency policy, not this knob.
653pub const PARALLEL_PUSHDOWN_WAVE_MAX: usize = 8;
654
655static PARALLEL_PUSHDOWN_WAVE_MAX_SETTING: AtomicUsize =
656 AtomicUsize::new(PARALLEL_PUSHDOWN_WAVE_MAX);
657
658pub(crate) fn parallel_pushdown_wave_max() -> usize {
659 PARALLEL_PUSHDOWN_WAVE_MAX_SETTING.load(Ordering::Relaxed)
660}
661
662/// Override the concurrent chunk-fetch wave ceiling (tests / tuning).
663pub fn set_parallel_pushdown_wave_max(n: usize) {
664 PARALLEL_PUSHDOWN_WAVE_MAX_SETTING.store(n.max(1), Ordering::Relaxed);
665}
666
667/// Restore the default concurrent chunk-fetch wave ceiling.
668pub fn reset_parallel_pushdown_wave_max() {
669 PARALLEL_PUSHDOWN_WAVE_MAX_SETTING.store(PARALLEL_PUSHDOWN_WAVE_MAX, Ordering::Relaxed);
670}
671
672/// Minimum milli-scale vocabulary pollution for an over-threshold Broadcast
673/// term list to stay on the parallel pushdown transport, instead of
674/// dropping the key to the unfiltered whole read. Pollution is the fraction
675/// of the probed arm's rows that no pushed term can match: at or below this
676/// threshold the whole read fetches mostly useful rows and is the cheaper
677/// road (no seeks at all); above it the majority of a whole read would be
678/// dead rows and the seek-union transport wins. An unresolvable estimate
679/// (probe key domain unknown) reads as maximally polluted, so the gate can
680/// only ever *keep* the transport — it never introduces a whole read the
681/// pre-gate code would not have taken.
682///
683/// **Changing it affects:** which over-threshold Broadcast arms fetch their
684/// whole probe relation unfiltered versus as chunked filtered fetches. The
685/// value 300 means "the pushed list reaches ≥70% of the probe's key
686/// domain"; lower it to push more arms through the seek-union transport,
687/// raise it to prefer whole reads. The estimate carries no rows-per-key
688/// information (key-vocabulary ratio, not row ratio), so treat it as
689/// advisory per the stats invariant in ARCH.md §10.
690pub const PUSHDOWN_MIN_POLLUTION_MILLI: u64 = 300;
691
692static PUSHDOWN_MIN_POLLUTION_MILLI_SETTING: AtomicU64 =
693 AtomicU64::new(PUSHDOWN_MIN_POLLUTION_MILLI);
694
695pub(crate) fn pushdown_min_pollution_milli() -> u64 {
696 PUSHDOWN_MIN_POLLUTION_MILLI_SETTING.load(Ordering::Relaxed)
697}
698
699/// Override the minimum over-threshold pollution for the parallel pushdown
700/// transport (tests / tuning).
701pub fn set_pushdown_min_pollution_milli(milli: u64) {
702 PUSHDOWN_MIN_POLLUTION_MILLI_SETTING.store(milli, Ordering::Relaxed);
703}
704
705/// Restore the default minimum over-threshold pollution.
706pub fn reset_pushdown_min_pollution_milli() {
707 PUSHDOWN_MIN_POLLUTION_MILLI_SETTING.store(PUSHDOWN_MIN_POLLUTION_MILLI, Ordering::Relaxed);
708}
709
710/// Page ceiling for the parallel probe road (default 16) — the general
711/// road — star spines and single-arm joins alike. The batch consumes up to
712/// this many coalesced driver pages per batch, bounded jointly by the
713/// query memory budget (held driver pages + the per-arm term lists must
714/// fit half the budget — the assembled batch tables and their join
715/// hashes are bounded by the matched rows the fetch was priced for, and
716/// the join kernels' own spill checks cover them). A one-page batch runs
717/// the per-page allow-list road unchanged.
718static PARALLEL_PROBE_PAGES_SETTING: AtomicUsize = AtomicUsize::new(PARALLEL_PROBE_PAGES_DEFAULT);
719
720/// The default batch-fill page ceiling. Kept as a named constant so
721/// `reset_parallel_probe_pages` and the static's initializer share one
722/// number.
723pub const PARALLEL_PROBE_PAGES_DEFAULT: usize = 16;
724
725pub(crate) fn parallel_probe_pages() -> usize {
726 PARALLEL_PROBE_PAGES_SETTING.load(Ordering::Relaxed)
727}
728
729/// Override the batch-fill page ceiling (tests / tuning). At 1 every
730/// batch holds exactly one driver page and each page takes the
731/// per-page allow-list road's own filtered fetch.
732pub fn set_parallel_probe_pages(pages: usize) {
733 PARALLEL_PROBE_PAGES_SETTING.store(pages, Ordering::Relaxed);
734}
735
736/// Restore the default batch-fill page ceiling.
737pub fn reset_parallel_probe_pages() {
738 PARALLEL_PROBE_PAGES_SETTING.store(PARALLEL_PROBE_PAGES_DEFAULT, Ordering::Relaxed);
739}
740
741/// Calibration knob (`WARATAH_CALIBRATION_FORCE_PROBE`, set by
742/// `scripts/calibrate_seek_ratio.py --realworld`): when this environment
743/// variable is present, the fetch-once stamp walk always stamps PerPage, so
744/// the executor runs the per-page allow-list (seek) road and the
745/// calibration script can measure real-store sequential seek cost against
746/// the whole-read baseline on the same queries.
747///
748/// Advisory-safe: both roads return identical rows, so the knob moves work
749/// between roads only. Deliberately stamp-only: the cost model keeps pricing
750/// both roads by its own arithmetic, so EXPLAIN stays honest about what
751/// was priced while the executed road diverges under this explicit
752/// operator knob. Nothing in production sets it.
753pub(crate) fn calibration_force_probe() -> bool {
754 static ONCE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
755 *ONCE.get_or_init(|| std::env::var("WARATAH_CALIBRATION_FORCE_PROBE").is_ok())
756}
757
758#[cfg(test)]
759mod tests {
760 use super::*;
761
762 #[test]
763 fn seek_concurrency_curve_hits_measured_points() {
764 for &(funded, realized) in PROBE_SEEK_CONCURRENCY_CURVE {
765 assert_eq!(probe_seek_concurrency_realized_milli(funded), realized);
766 }
767 }
768
769 #[test]
770 fn seek_concurrency_curve_matches_measured_pins() {
771 // The measured 2026-11-15 table itself (the constant's doc holds
772 // the derivation). Any change to these points is a re-measurement
773 // that must update this pin — a silent table edit otherwise
774 // shifts every fetch-once verdict's credit.
775 assert_eq!(
776 PROBE_SEEK_CONCURRENCY_CURVE,
777 &[
778 (1_000u64, 1_000u64),
779 (2_000, 1_820),
780 (3_000, 2_420),
781 (5_000, 3_330),
782 (7_000, 4_050),
783 ]
784 );
785 }
786
787 #[test]
788 fn seek_concurrency_curve_interpolates_linearly() {
789 // Halfway between funded 1000 (realized 1000) and 2000 (1820): 1410.
790 assert_eq!(probe_seek_concurrency_realized_milli(1_500), 1_410);
791 // A third of the way between funded 3000 (2420) and 5000 (3330): 2420 + 910/3.
792 assert_eq!(probe_seek_concurrency_realized_milli(3_666), 2_723);
793 }
794
795 #[test]
796 fn seek_concurrency_curve_clamps_outside_the_table() {
797 // Below the first point: sequential (one outstanding fetch
798 // realizes exactly itself).
799 assert_eq!(probe_seek_concurrency_realized_milli(0), 1_000);
800 assert_eq!(probe_seek_concurrency_realized_milli(500), 1_000);
801 // Above the last point: the measured plateau.
802 assert_eq!(probe_seek_concurrency_realized_milli(u64::MAX), 4_050);
803 }
804
805 #[test]
806 fn seek_concurrency_curve_never_overpromises_funding() {
807 // Realized speedup cannot exceed the funded fetch concurrency, or the credit
808 // divisor would price concurrency the executor cannot deliver.
809 for &(funded, realized) in PROBE_SEEK_CONCURRENCY_CURVE {
810 assert!(realized <= funded, "curve overpromises at funded {funded}");
811 }
812 }
813
814 #[test]
815 fn fetch_once_constants_match_their_pins() {
816 assert_eq!(FETCH_ONCE_SEEK_EQUIV_MILLI, 4_200);
817 assert_eq!(FETCH_ONCE_MATCHED_ROW_EQUIV_MILLI, 1_400);
818 assert_eq!(FETCH_ONCE_MARGIN_MILLI, 1_400);
819 }
820
821 #[test]
822 fn filter_cost_constants_match_their_provisional_pins() {
823 // A filter always costs at least the encoded rate; the capability
824 // split is provisional until the filter-cost A/B.
825 assert_eq!(FILTER_ENCODED_ROW_EQUIV_MILLI, 5);
826 assert_eq!(FILTER_MAYBE_ENCODED_ROW_EQUIV_MILLI, 50);
827 assert_eq!(FILTER_RESOLVE_ROW_EQUIV_MILLI, 200);
828 }
829
830 #[test]
831 fn semi_build_constants_are_the_provisional_neutral_pins() {
832 // Neither value borrows the fetch-once margin: the semi build is a
833 // domain-pushed key-set build, not a memoizable whole-scan table.
834 // The Phase 3 forced-side A/B replaces these.
835 assert_eq!(SEMI_BUILD_MARGIN_MILLI, 1_000);
836 assert_eq!(SEMI_KEY_SET_ROW_EQUIV_MILLI, 1_000);
837 }
838}