Skip to main content

waratah_compute/
context.rs

1//! Per-query SPARQL evaluation context.
2//!
3//! [`QueryContext`] is built once per request and passed by shared reference
4//! through planning and execution. It is mostly immutable: log and trace sinks
5//! and the named-graph catalog memo use interior mutability so the context
6//! itself stays `&QueryContext` across `.await` points.
7//!
8//! Recursion-scoped state (`IncomingBound`, [`crate::query::pushdown::PushedKeyVals`]) and
9//! the late-materialize [`crate::filter_residual::QueryCaches`] stay extra
10//! arguments. Process-lifetime clients and sketch cache stay on
11//! [`crate::query::QueryEngine`].
12
13use oxsdatatypes::DateTime;
14use std::fmt;
15use std::future::Future;
16use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
17use std::sync::{Arc, Mutex, OnceLock};
18use std::time::{Duration, Instant, SystemTime};
19
20use waratah_exec::TermDict;
21use waratah_stats::JoinStrategy;
22use waratah_storage::{EncodedTerm, SnapshotId};
23
24use crate::dataset::QueryDataset;
25use crate::error::ComputeError;
26use crate::expr::ExprEvalEnv;
27
28/// Permissions for the user running this query.
29///
30/// Always allows every graph and triple until a security model exists.
31/// GRAPH / FROM evaluation will intersect this with the query dataset later.
32#[derive(Debug, Clone, Default, PartialEq, Eq)]
33pub struct SecurityContext {
34    _private: (),
35}
36
37impl SecurityContext {
38    /// Unrestricted stub (the only implementation today).
39    pub fn allow_all() -> Self {
40        Self { _private: () }
41    }
42}
43
44/// Wall-clock epoch milliseconds for correlating compute-side RPC timing
45/// lines (`scan-rpc[...] sent_at=`) with the partition-side handler traces
46/// (`recv_at=` / `resp_at=`) in `--debug` investigations.
47pub(crate) fn epoch_millis_now() -> u128 {
48    std::time::SystemTime::now()
49        .duration_since(std::time::UNIX_EPOCH)
50        .map(|d| d.as_millis())
51        .unwrap_or(0)
52}
53
54/// Operational log severity. Higher values are more verbose.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
56pub enum LogLevel {
57    /// Failures that abort or degrade the query.
58    Error,
59    /// Recoverable problems (retries exhausted, budget warnings).
60    Warn,
61    /// Significant non-error events.
62    Info,
63    /// Diagnostic detail (not scan-page trace recording; that is [`TraceSink`]).
64    Debug,
65}
66
67impl fmt::Display for LogLevel {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        f.write_str(match self {
70            Self::Error => "ERROR",
71            Self::Warn => "WARN",
72            Self::Info => "INFO",
73            Self::Debug => "DEBUG",
74        })
75    }
76}
77
78#[derive(Debug, Clone)]
79enum LogEmit {
80    Off,
81    Stderr,
82    /// Append to a shared file (the daemonized `waratah start` debug log).
83    File(Arc<Mutex<std::fs::File>>),
84    Capture(Arc<Mutex<Vec<String>>>),
85}
86
87/// Always-compiled operational logger for the SPARQL executor.
88///
89/// Every line includes `query_id`. Unlike [`TraceSink`], this is not compiled
90/// out of release builds.
91#[derive(Debug, Clone)]
92pub struct LogSink {
93    min: LogLevel,
94    emit: LogEmit,
95}
96
97impl LogSink {
98    /// Discard every message.
99    pub fn off() -> Self {
100        Self {
101            min: LogLevel::Error,
102            emit: LogEmit::Off,
103        }
104    }
105
106    /// Write messages at `min` or more severe to stderr.
107    pub fn stderr(min: LogLevel) -> Self {
108        Self {
109            min,
110            emit: LogEmit::Stderr,
111        }
112    }
113
114    /// Append messages at `min` or more severe to an already-open file.
115    ///
116    /// The handle is shared (`Arc<Mutex<..>>`) so a caller can hand the same
117    /// file to [`TraceSink::file`] and keep one interleaved debug log. Write
118    /// failures are swallowed: a lost diagnostic line must not abort a query.
119    pub fn file(min: LogLevel, file: Arc<Mutex<std::fs::File>>) -> Self {
120        Self {
121            min,
122            emit: LogEmit::File(file),
123        }
124    }
125
126    /// Capture messages for tests (`min` still applies).
127    pub fn capture(min: LogLevel, lines: Arc<Mutex<Vec<String>>>) -> Self {
128        Self {
129            min,
130            emit: LogEmit::Capture(lines),
131        }
132    }
133
134    /// Whether `level` would be emitted.
135    pub fn enabled_at(&self, level: LogLevel) -> bool {
136        !matches!(self.emit, LogEmit::Off) && level <= self.min
137    }
138
139    /// Write `message` tagged with `query_id` when `level` is enabled.
140    pub fn emit(&self, query_id: u64, level: LogLevel, message: &str) {
141        if !self.enabled_at(level) {
142            return;
143        }
144        let line = format!("q#{query_id} {level} {message}");
145        match &self.emit {
146            LogEmit::Off => {}
147            LogEmit::Stderr => eprintln!("{line}"),
148            LogEmit::File(file) => {
149                use std::io::Write;
150                // Poison recovery: a panic mid-write leaves the guard
151                // poisoned but the file handle valid — keep logging.
152                let mut file = file.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
153                let _ = writeln!(file, "{line}");
154            }
155            LogEmit::Capture(lines) => lines.lock().expect("log capture mutex").push(line),
156        }
157    }
158}
159
160impl Default for LogSink {
161    fn default() -> Self {
162        Self::off()
163    }
164}
165
166/// Structured execution-trace event (scan / join / path / RPC timing).
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub enum TraceEvent {
169    /// About to issue a hexastore scan RPC.
170    ScanStart {
171        /// `0` means no LIMIT (full scan / fill until storage stops).
172        limit: u64,
173    },
174    /// One scan page returned.
175    ScanPage {
176        /// Rows in this page.
177        rows: usize,
178        /// Wall time of the RPC in microseconds.
179        elapsed_us: u128,
180    },
181    /// Inner-join strategy chosen at execution.
182    Join {
183        /// Broadcast / hash / shuffle.
184        strategy: JoinStrategy,
185    },
186    /// Property-path walker entry.
187    Path,
188    /// A nested `SELECT` (`PlanNode::SubSelect`) boundary was materialized.
189    ///
190    /// The opaque boundary evaluates independently, so a query whose left
191    /// side streams B batches should see exactly one of these per boundary
192    /// (the built relation is reused across batches).
193    SubSelectBuild,
194    /// FILTER EXISTS SemiJoin materialized the unbound inner once
195    /// (`SemiJoinSet` / Grace files). OpenNode reuses it across later pages.
196    ExistsSemiBuild,
197    /// A childless CustomOp execution hit the query-local memo instead of
198    /// re-draining the plugin (EXISTS re-opens, expr-subst groups, duplicate
199    /// conjuncts). Keeps cost attribution honest: one drain, N hits.
200    CustomOpMemoHit {
201        /// Plugin that owns the memoized op.
202        plugin: &'static str,
203        /// Op id inside the plugin.
204        op: &'static str,
205    },
206    /// A `GeoCandidateScan` window was served from the geo drain memo
207    /// instead of re-draining the partition (keyed semi-join pages 2..N,
208    /// EXISTS re-opens, ops the whole-result memo refuses). The candidate
209    /// window is key-invariant, so this hit is always sound; keeps cost
210    /// attribution honest: one drain per window, N hits.
211    GeoDrainMemoHit {
212        /// Terms the memoized window holds.
213        terms: usize,
214    },
215}
216
217impl fmt::Display for TraceEvent {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        match self {
220            Self::ScanStart { limit } => write!(f, "scan start limit={limit}"),
221            Self::ScanPage { rows, elapsed_us } => {
222                write!(f, "scan page rows={rows} {elapsed_us}µs")
223            }
224            Self::Join { strategy } => write!(f, "join {strategy:?}"),
225            Self::Path => f.write_str("path"),
226            Self::SubSelectBuild => f.write_str("subselect build"),
227            Self::ExistsSemiBuild => f.write_str("exists semi build"),
228            Self::CustomOpMemoHit { plugin, op } => {
229                write!(f, "custom op memo hit {plugin}/{op}")
230            }
231            Self::GeoDrainMemoHit { terms } => {
232                write!(f, "geo drain memo hit terms={terms}")
233            }
234        }
235    }
236}
237
238#[derive(Debug, Clone)]
239enum TraceEmit {
240    Off,
241    Stderr,
242    /// Append to a shared file (the daemonized `waratah start` debug log).
243    File(Arc<Mutex<std::fs::File>>),
244    Capture(Arc<Mutex<Vec<String>>>),
245}
246
247/// High-volume execution-order / RPC / timing sink.
248///
249/// The field always exists on [`QueryContext`]. [`Self::is_enabled`] is
250/// compiled to `false` in release unless the `query-trace` feature is on, so
251/// event construction behind `query_trace!` is dead-code-eliminated.
252#[derive(Debug, Clone)]
253pub struct TraceSink {
254    emit: TraceEmit,
255}
256
257impl TraceSink {
258    /// Discard every event.
259    pub fn off() -> Self {
260        Self {
261            emit: TraceEmit::Off,
262        }
263    }
264
265    /// Write events to stderr (still a no-op at runtime in release without
266    /// `query-trace`).
267    pub fn stderr() -> Self {
268        Self {
269            emit: TraceEmit::Stderr,
270        }
271    }
272
273    /// Append events to an already-open file (still a no-op at runtime in
274    /// release without `query-trace`). Share the handle with
275    /// [`LogSink::file`] to keep one interleaved debug log.
276    pub fn file(file: Arc<Mutex<std::fs::File>>) -> Self {
277        Self {
278            emit: TraceEmit::File(file),
279        }
280    }
281
282    /// Capture events for tests.
283    pub fn capture(lines: Arc<Mutex<Vec<String>>>) -> Self {
284        Self {
285            emit: TraceEmit::Capture(lines),
286        }
287    }
288
289    /// Whether [`Self::emit`] will record anything.
290    ///
291    /// In release builds without `query-trace` this is `const false`.
292    #[inline(always)]
293    pub fn is_enabled(&self) -> bool {
294        #[cfg(any(debug_assertions, feature = "query-trace"))]
295        {
296            !matches!(self.emit, TraceEmit::Off)
297        }
298        #[cfg(not(any(debug_assertions, feature = "query-trace")))]
299        {
300            false
301        }
302    }
303
304    /// Record `event` when enabled.
305    pub fn emit(&self, query_id: u64, event: TraceEvent) {
306        if !self.is_enabled() {
307            return;
308        }
309        let line = format!("q#{query_id} TRACE {event}");
310        match &self.emit {
311            TraceEmit::Off => {}
312            TraceEmit::Stderr => eprintln!("{line}"),
313            TraceEmit::File(file) => {
314                use std::io::Write;
315                // Poison recovery: a panic mid-write leaves the guard
316                // poisoned but the file handle valid — keep logging.
317                let mut file = file.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
318                let _ = writeln!(file, "{line}");
319            }
320            TraceEmit::Capture(lines) => lines.lock().expect("trace capture mutex").push(line),
321        }
322    }
323}
324
325impl Default for TraceSink {
326    fn default() -> Self {
327        Self::off()
328    }
329}
330
331/// Emit a [`TraceEvent`] only when tracing is enabled.
332///
333/// `$event` is not evaluated when [`TraceSink::is_enabled`] is false.
334#[macro_export]
335macro_rules! query_trace {
336    ($ctx:expr, $event:expr) => {
337        if $ctx.trace().is_enabled() {
338            $ctx.trace().emit($ctx.query_id(), $event);
339        }
340    };
341}
342
343/// Memo of the S-axis named-graph catalog for one query execute.
344///
345/// [`crate::plan::PlanNode::NamedGraphs`] and Collect `*` / `?` path
346/// identities both need this list at the same snapshot. Clone starts empty so
347/// [`crate::query::QueryEngine::query`] (which clones the caller's context)
348/// does not reuse another request's listing.
349///
350/// With parallel arm evaluation ([`QUERY_FETCH_CONCURRENCY`]) two arms may race
351/// to fill this slot: both can observe it empty and run the load closure (a
352/// duplicate catalog RPC), and `OnceLock::set` keeps only the first listing.
353/// Results stay correct; the race costs one extra RPC per losing arm.
354/// `OnceLock` keeps [`QueryContext`] `Sync` (the execute future is `Send`).
355#[derive(Debug)]
356struct NamedGraphListCache {
357    slot: OnceLock<Arc<[EncodedTerm]>>,
358}
359
360impl NamedGraphListCache {
361    fn empty() -> Self {
362        Self {
363            slot: OnceLock::new(),
364        }
365    }
366}
367
368impl Clone for NamedGraphListCache {
369    fn clone(&self) -> Self {
370        Self::empty()
371    }
372}
373
374/// How many arms a single query evaluates concurrently: `UNION` arms,
375/// disjoint cross-product join sides, and the parallel-probe engine's
376/// concurrent arm fetches all draw from one permit pool, and extra arms
377/// fall back to the sequential path. The value is therefore also the
378/// parallel-probe engine's fetch concurrency (the parallel-probe roads in `join_chunks.rs`).
379/// The run-time value comes from [`query_fetch_concurrency`] (the
380/// `WARATAH_QUERY_FETCH_CONCURRENCY` environment variable, read once; this
381/// const is the default). The permit pool is one larger —
382/// [`arm_pool_permits`] — because the query root holds one permit for the
383/// whole execution, so exactly this many arms run at once.
384///
385/// Values below 2 disable the parallel-probe engine: the pool holds the
386/// root's permit only, every probe road takes its per-page sequential
387/// path, and the fetch-once verdict prices seeks sequentially. 0 and 1
388/// mean the same thing.
389///
390/// Values above [`MAX_QUERY_FETCH_CONCURRENCY`] (64) clamp to it at every
391/// entry point — the environment parse, the setter, and the permit-pool
392/// sizing — so no configured value can wrap the pool arithmetic into a
393/// zero-permit pool or reach the semaphore's permit ceiling; anything
394/// past the realized-concurrency curve's measured range (which plateaus
395/// at funded 7000 milli) buys nothing anyway.
396///
397/// The pool lives on [`QueryContext`] and survives `Clone`,
398/// so it is per-query only while every concurrent query builds its own
399/// context (what all current callers do). Cloning one context across
400/// concurrent queries shares this budget between them, including the root
401/// [`QueryContext::acquire_arm_permit`] wait — those queries would queue on
402/// query start instead of running independently.
403///
404/// Re-measure [`crate::query::tunables::PROBE_SEEK_CONCURRENCY_CURVE`] when
405/// changing the default: the realized-concurrency curve moves with the
406/// funded fetch concurrency, and the fetch-once verdict's credit divisor reads that
407/// curve.
408pub(crate) const QUERY_FETCH_CONCURRENCY: usize = 3;
409
410/// The documented ceiling for [`QUERY_FETCH_CONCURRENCY`]: configured
411/// values (environment or setter) clamp to this at every entry point,
412/// and [`arm_pool_permits_for`] clamps again so even a direct call with
413/// an unclamped value cannot build a pool large enough to trip the
414/// semaphore's permit ceiling. 64 sits far above the measured
415/// realized-concurrency curve's plateau (funded 7000 milli) while
416/// staying trivially inside `usize` arithmetic.
417pub(crate) const MAX_QUERY_FETCH_CONCURRENCY: usize = 64;
418
419/// Sentinel for [`QUERY_FETCH_CONCURRENCY_SETTING`]: the setting has not been
420/// resolved from the environment yet. `usize::MAX` cannot be a meaningful
421/// fetch concurrency, so it cannot collide with a configured value — and
422/// every configured value clamps to [`MAX_QUERY_FETCH_CONCURRENCY`]
423/// before storage, so the sentinel cannot reappear through the setter
424/// either.
425const QUERY_FETCH_CONCURRENCY_UNRESOLVED: usize = usize::MAX;
426
427static QUERY_FETCH_CONCURRENCY_SETTING: AtomicUsize =
428    AtomicUsize::new(QUERY_FETCH_CONCURRENCY_UNRESOLVED);
429
430/// The configured parallel-probe engine fetch concurrency: the
431/// `WARATAH_QUERY_FETCH_CONCURRENCY` environment variable, read once, with
432/// [`QUERY_FETCH_CONCURRENCY`] as the default. An absent or unparseable value
433/// keeps the default.
434pub(crate) fn query_fetch_concurrency() -> usize {
435    match QUERY_FETCH_CONCURRENCY_SETTING.load(Ordering::Relaxed) {
436        QUERY_FETCH_CONCURRENCY_UNRESOLVED => {
437            let configured = std::env::var("WARATAH_QUERY_FETCH_CONCURRENCY")
438                .ok()
439                .and_then(|value| value.parse::<usize>().ok())
440                .unwrap_or(QUERY_FETCH_CONCURRENCY)
441                .min(MAX_QUERY_FETCH_CONCURRENCY);
442            QUERY_FETCH_CONCURRENCY_SETTING.store(configured, Ordering::Relaxed);
443            configured
444        }
445        configured => configured,
446    }
447}
448
449/// Permit-pool size for a configured fetch concurrency: that many
450/// permits plus the query root's own hold, or a single root-only permit
451/// when the engine is off (fetch concurrency below 2). Values above
452/// [`MAX_QUERY_FETCH_CONCURRENCY`] clamp before the arithmetic, so no
453/// input can overflow the permit count or build a pool above the
454/// semaphore's ceiling. A pool of at
455/// least 1 keeps the root's blocking
456/// [`QueryContext::acquire_arm_permit`] dead-lock-free in every
457/// configuration.
458pub(crate) fn arm_pool_permits_for(fetch_concurrency: usize) -> usize {
459    let fetch_concurrency = fetch_concurrency.min(MAX_QUERY_FETCH_CONCURRENCY);
460    if fetch_concurrency < 2 {
461        1
462    } else {
463        fetch_concurrency + 1
464    }
465}
466
467/// Whether the parallel-probe engine (the parallel-probe roads) may run at this
468/// configured fetch concurrency. Below 2 there is no engine: every probe road runs
469/// per page.
470pub(crate) fn parallel_probe_engine_on(fetch_concurrency: usize) -> bool {
471    fetch_concurrency >= 2
472}
473
474/// Permit-pool size for the configured fetch concurrency — see
475/// [`arm_pool_permits_for`].
476pub(crate) fn arm_pool_permits() -> usize {
477    arm_pool_permits_for(query_fetch_concurrency())
478}
479
480/// Whether the parallel-probe engine may run at the configured fetch
481/// concurrency —
482/// see [`parallel_probe_engine_on`].
483pub(crate) fn parallel_probe_engine_enabled() -> bool {
484    parallel_probe_engine_on(query_fetch_concurrency())
485}
486
487/// Override the configured parallel-probe engine fetch concurrency
488/// (tests / tuning). Values above [`MAX_QUERY_FETCH_CONCURRENCY`] clamp
489/// to it.
490/// The value persists for the rest of the process unless reset.
491///
492/// ORDERING: the permit pool is sized once, when a [`QueryContext`] is
493/// built ([`arm_pool_permits`]), while plan-time pricing reads this knob
494/// live — calling this after contexts exist desynchronizes the two
495/// (plans price one fetch concurrency, the pool enforces another). Call
496/// it before any context construction, or after every live context is
497/// dropped.
498pub fn set_query_fetch_concurrency(fetch_concurrency: usize) {
499    QUERY_FETCH_CONCURRENCY_SETTING.store(
500        fetch_concurrency.min(MAX_QUERY_FETCH_CONCURRENCY),
501        Ordering::Relaxed,
502    );
503}
504
505/// Restore the environment-derived parallel-probe engine fetch
506/// concurrency: the next
507/// [`query_fetch_concurrency`] read resolves `WARATAH_QUERY_FETCH_CONCURRENCY`
508/// (or the default) again. The same ordering rule as
509/// [`set_query_fetch_concurrency`] applies: only before context
510/// construction, or after every live context is dropped.
511pub fn reset_query_fetch_concurrency() {
512    QUERY_FETCH_CONCURRENCY_SETTING.store(QUERY_FETCH_CONCURRENCY_UNRESOLVED, Ordering::Relaxed);
513}
514
515/// Test-only RAII pin for the process-global fetch concurrency: sets the
516/// given value on construction and restores the environment-derived value
517/// on drop — including unwind, so a panicking test cannot leak the
518/// override into sibling tests sharing this process. The stamp-walk
519/// fixtures read the global through `query_fetch_concurrency`, so tests
520/// whose expected stamps depend on the pricing must pin it explicitly
521/// (an ambient `WARATAH_QUERY_FETCH_CONCURRENCY=0/1` would otherwise flip
522/// them: engine off prices every arm sequentially).
523///
524/// Every pin serializes on one lock: without it, two pinned tests
525/// running concurrently would race — one's Drop restores the
526/// unresolved sentinel while the other's fixture is mid-walk, and the
527/// next read re-resolves the AMBIENT value into the middle of the
528/// other test. Sync tests take [`Self::set`] (which must not be called
529/// from inside an async runtime); async tests take
530/// [`Self::set_async`].
531#[cfg(test)]
532pub(crate) struct FetchConcurrencyPin {
533    _lock: tokio::sync::MutexGuard<'static, ()>,
534}
535
536#[cfg(test)]
537static FETCH_CONCURRENCY_PIN_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
538
539#[cfg(test)]
540impl FetchConcurrencyPin {
541    /// For synchronous tests. MUST NOT be called from inside an async
542    /// runtime — `blocking_lock` panics there; use [`Self::set_async`].
543    pub(crate) fn set(value: usize) -> Self {
544        let _lock = FETCH_CONCURRENCY_PIN_LOCK.blocking_lock();
545        set_query_fetch_concurrency(value);
546        Self { _lock }
547    }
548
549    /// For async tests — see [`Self::set`].
550    pub(crate) async fn set_async(value: usize) -> Self {
551        let _lock = FETCH_CONCURRENCY_PIN_LOCK.lock().await;
552        set_query_fetch_concurrency(value);
553        Self { _lock }
554    }
555}
556
557#[cfg(test)]
558impl Drop for FetchConcurrencyPin {
559    fn drop(&mut self) {
560        reset_query_fetch_concurrency();
561    }
562}
563
564/// Per-query budget of concurrent Grace hash-join CPU workers
565/// ([`GraceWorkerPool`]). A separate knob from [`QUERY_FETCH_CONCURRENCY`]:
566/// arm permits bound scan-arm *evaluations* (partition RPCs plus their
567/// decode/intern work), this bounds compute-node *join workers* — and the
568/// two phases are designed to overlap (the eager whole-read issue runs
569/// drains while joins execute), so one shared budget would make each knob's
570/// tuning perturb the other. The pool lives on [`QueryContext`], survives
571/// `Clone`, and is shared by every Grace join of the query — nested
572/// recursion levels and sibling arms draw from the same tokens, so at most
573/// this many grace workers exist per query, period. Try-only acquisition:
574/// a join that finds the pool empty runs the serial bucket loop instead of
575/// waiting, so there is no blocking and no deadlock surface.
576pub(crate) const QUERY_GRACE_WORKER_BUDGET: usize = 8;
577
578/// The per-query token pool behind [`QUERY_GRACE_WORKER_BUDGET`] — a pure
579/// counter, no data is published through it (worker results travel the
580/// join's std::sync::mpsc channel; the pool only gates how many bucket
581/// workers a query may run).
582#[derive(Debug)]
583pub(crate) struct GraceWorkerPool {
584    remaining: AtomicUsize,
585}
586
587impl GraceWorkerPool {
588    fn new(budget: usize) -> Self {
589        Self {
590            remaining: AtomicUsize::new(budget),
591        }
592    }
593
594    /// Reserve up to `want` tokens; fewer when the pool is partly spent,
595    /// zero when it is exhausted (the caller then takes the serial path).
596    /// Never blocks.
597    fn try_acquire(&self, want: usize) -> GraceWorkerLease<'_> {
598        let mut count = 0usize;
599        while count < want {
600            match self
601                .remaining
602                .fetch_update(Ordering::AcqRel, Ordering::Acquire, |remaining| {
603                    (remaining > 0).then(|| remaining - 1)
604                }) {
605                Ok(_) => count += 1,
606                Err(_) => break,
607            }
608        }
609        GraceWorkerLease { pool: self, count }
610    }
611}
612
613/// RAII lease of `count` Grace worker tokens. Returns them on drop — scope
614/// exit, `?`, and panic unwind all included.
615#[derive(Debug)]
616pub(crate) struct GraceWorkerLease<'a> {
617    pool: &'a GraceWorkerPool,
618    count: usize,
619}
620
621impl GraceWorkerLease<'_> {
622    /// Tokens actually reserved (may be fewer than requested).
623    pub(crate) fn count(&self) -> usize {
624        self.count
625    }
626}
627
628impl Drop for GraceWorkerLease<'_> {
629    fn drop(&mut self) {
630        if self.count > 0 {
631            self.pool.remaining.fetch_add(self.count, Ordering::AcqRel);
632        }
633    }
634}
635
636/// Cumulative wall-time counters for one query execute: hexastore scan RPCs
637/// and string-registry resolve RPCs.
638///
639/// Lives behind an `Arc` on [`QueryContext`] and is shared across clones, so
640/// sub-executions and the post-execute materialize all land in the same
641/// totals. Updates are unconditional atomic adds — cheap enough to leave on
642/// in release builds, unlike [`TraceSink`] event formatting. Read the totals
643/// at query end for the phase split (`waratah start --debug` logs it as
644/// `phases:`), e.g. to tell scan-bound from materialize-bound queries.
645#[derive(Debug, Default)]
646pub struct PhaseTimers {
647    scan_rpcs: AtomicU64,
648    scan_micros: AtomicU64,
649    /// Outstanding scan RPC count; 0→1 opens the wall union, 1→0 closes it.
650    scan_inflight: AtomicUsize,
651    /// Union of wall-clock intervals with at least one outstanding scan RPC
652    /// — overlapping concurrent fetches count once, unlike `scan_micros`,
653    /// which sums every RPC's full duration.
654    scan_wall_micros: AtomicU64,
655    /// Origin of the currently-open wall-union interval (`None` = no scan
656    /// RPC outstanding).
657    scan_wall_start: Mutex<Option<Instant>>,
658    resolve_rpcs: AtomicU64,
659    resolve_hashes: AtomicU64,
660    resolve_micros: AtomicU64,
661    plan_micros: AtomicU64,
662    execute_micros: AtomicU64,
663    materialize_micros: AtomicU64,
664    custom_op_micros: AtomicU64,
665    custom_op_count: AtomicU64,
666    blob_micros: AtomicU64,
667    blob_rpcs: AtomicU64,
668    blob_payloads: AtomicU64,
669    geo_scan_micros: AtomicU64,
670    geo_scan_count: AtomicU64,
671    geo_scan_terms: AtomicU64,
672    /// Windows served from the geo drain memo (no RPC): the hit side of
673    /// `geo_scan_count`, so a query's per-window drain count reads as
674    /// `geo_scan_count` and its reuse as this counter.
675    geo_drain_memo_hits: AtomicU64,
676    temporal_scan_micros: AtomicU64,
677    temporal_scan_count: AtomicU64,
678    temporal_scan_terms: AtomicU64,
679    text_scan_micros: AtomicU64,
680    text_scan_count: AtomicU64,
681    text_scan_terms: AtomicU64,
682    /// Windows served from the text drain memo (no RPC): the hit side of
683    /// `text_scan_count`, mirroring the geo counters.
684    text_drain_memo_hits: AtomicU64,
685    text_subject_scan_micros: AtomicU64,
686    text_subject_scan_count: AtomicU64,
687    text_subject_scan_rows: AtomicU64,
688    /// Subject windows served from the text subject memo (no RPC): the hit
689    /// side of `text_subject_scan_count`.
690    text_subject_memo_hits: AtomicU64,
691}
692
693impl PhaseTimers {
694    /// Record one hexastore scan RPC (or scan-shaped retry drain).
695    pub(crate) fn record_scan(&self, elapsed: Duration) {
696        self.scan_rpcs.fetch_add(1, Ordering::Relaxed);
697        self.scan_micros
698            .fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
699    }
700
701    /// Open one scan wall interval — the union opens when the first of
702    /// possibly concurrent scan RPCs leaves the caller.
703    fn scan_wall_begin(&self) {
704        if self.scan_inflight.fetch_add(1, Ordering::Relaxed) == 0 {
705            *self.scan_wall_start.lock().expect("scan wall mutex") = Some(Instant::now());
706        }
707    }
708
709    /// Close one scan wall interval — the union closes when the last
710    /// outstanding scan RPC lands, accumulating the whole open interval.
711    fn scan_wall_end(&self) {
712        if self.scan_inflight.fetch_sub(1, Ordering::Relaxed) == 1
713            && let Some(started) = self.scan_wall_start.lock().expect("scan wall mutex").take()
714        {
715            self.scan_wall_micros
716                .fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
717        }
718    }
719
720    /// RAII form of [`Self::scan_wall_begin`] / [`Self::scan_wall_end`]:
721    /// holds the wall union open until dropped, so early returns between
722    /// send and completion cannot leave it open forever.
723    pub(crate) fn scan_wall_guard(&self) -> ScanWallGuard<'_> {
724        self.scan_wall_begin();
725        ScanWallGuard { timers: self }
726    }
727
728    /// Add a pre-measured interval for a fetch that ran context-free and
729    /// only reports an elapsed duration (the OpenNode page path).
730    /// Additive, not unioned: if such a fetch overlaps an outstanding one,
731    /// both durations count.
732    pub(crate) fn scan_wall_add(&self, elapsed: Duration) {
733        self.scan_wall_micros
734            .fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
735    }
736
737    /// Wall-union counterpart of [`Self::scan_micros`].
738    pub fn scan_wall_micros(&self) -> u64 {
739        self.scan_wall_micros.load(Ordering::Relaxed)
740    }
741
742    /// Record logical-plan construction (lowering, plugin rewrites,
743    /// refinalize passes).
744    pub(crate) fn record_plan(&self, elapsed: Duration) {
745        self.plan_micros
746            .fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
747    }
748
749    /// Record operator execution (everything `execute_with_cache` runs —
750    /// scans, joins, custom ops, residual evaluation).
751    pub(crate) fn record_execute(&self, elapsed: Duration) {
752        self.execute_micros
753            .fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
754    }
755
756    /// Record output shaping (projection, string resolution of results,
757    /// CONSTRUCT/DESCRIBE emission).
758    pub(crate) fn record_materialize(&self, elapsed: Duration) {
759        self.materialize_micros
760            .fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
761    }
762
763    /// Record one CustomOp drain (executor run + row assembly; memo hits
764    /// included so N executions of one op are all visible).
765    pub(crate) fn record_custom_op(&self, elapsed: Duration) {
766        self.custom_op_count.fetch_add(1, Ordering::Relaxed);
767        self.custom_op_micros
768            .fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
769    }
770
771    /// Record one batched blob fetch (LRU probe + misses over the wire).
772    pub(crate) fn record_blob(&self, payloads: usize, elapsed: Duration) {
773        self.blob_rpcs.fetch_add(1, Ordering::Relaxed);
774        self.blob_payloads
775            .fetch_add(payloads as u64, Ordering::Relaxed);
776        self.blob_micros
777            .fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
778    }
779
780    /// Record one GeoCandidateScan drain (the O-axis S2 sweep).
781    pub(crate) fn record_geo_scan(&self, terms: usize, elapsed: Duration) {
782        self.geo_scan_count.fetch_add(1, Ordering::Relaxed);
783        self.geo_scan_terms
784            .fetch_add(terms as u64, Ordering::Relaxed);
785        self.geo_scan_micros
786            .fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
787    }
788
789    /// Record one geo drain memo hit (a window served without its
790    /// `GeoCandidateScan` RPC).
791    pub(crate) fn record_geo_drain_memo_hit(&self) {
792        self.geo_drain_memo_hits.fetch_add(1, Ordering::Relaxed);
793    }
794
795    /// Record one TemporalCandidateScan drain (the O-axis dyadic sweep).
796    pub(crate) fn record_temporal_scan(&self, terms: usize, elapsed: Duration) {
797        self.temporal_scan_count.fetch_add(1, Ordering::Relaxed);
798        self.temporal_scan_terms
799            .fetch_add(terms as u64, Ordering::Relaxed);
800        self.temporal_scan_micros
801            .fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
802    }
803
804    /// Record one TextCandidateScan drain (the O-axis term sweep).
805    pub(crate) fn record_text_scan(&self, terms: usize, elapsed: Duration) {
806        self.text_scan_count.fetch_add(1, Ordering::Relaxed);
807        self.text_scan_terms
808            .fetch_add(terms as u64, Ordering::Relaxed);
809        self.text_scan_micros
810            .fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
811    }
812
813    /// Record one text drain memo hit (a window served without its
814    /// `TextCandidateScan` RPC).
815    pub(crate) fn record_text_drain_memo_hit(&self) {
816        self.text_drain_memo_hits.fetch_add(1, Ordering::Relaxed);
817    }
818
819    /// Record one `TextSubjectScan` resolve (the O-axis search + OPSG walk
820    /// of the subject form).
821    pub(crate) fn record_text_subject_scan(&self, rows: usize, elapsed: Duration) {
822        self.text_subject_scan_count.fetch_add(1, Ordering::Relaxed);
823        self.text_subject_scan_rows
824            .fetch_add(rows as u64, Ordering::Relaxed);
825        self.text_subject_scan_micros
826            .fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
827    }
828
829    /// Record one text subject memo hit (a window served without its
830    /// `TextSubjectScan` RPC).
831    pub(crate) fn record_text_subject_memo_hit(&self) {
832        self.text_subject_memo_hits.fetch_add(1, Ordering::Relaxed);
833    }
834
835    /// Record one registry resolve RPC covering `hashes` hashes.
836    pub(crate) fn record_resolve(&self, hashes: usize, elapsed: Duration) {
837        self.resolve_rpcs.fetch_add(1, Ordering::Relaxed);
838        self.resolve_hashes
839            .fetch_add(hashes as u64, Ordering::Relaxed);
840        self.resolve_micros
841            .fetch_add(elapsed.as_micros() as u64, Ordering::Relaxed);
842    }
843
844    /// Scan RPCs issued so far.
845    pub fn scan_rpcs(&self) -> u64 {
846        self.scan_rpcs.load(Ordering::Relaxed)
847    }
848
849    /// Cumulative scan RPC wall time (microseconds).
850    pub fn scan_micros(&self) -> u64 {
851        self.scan_micros.load(Ordering::Relaxed)
852    }
853
854    /// Resolve RPCs issued so far.
855    pub fn resolve_rpcs(&self) -> u64 {
856        self.resolve_rpcs.load(Ordering::Relaxed)
857    }
858
859    /// Hashes requested across all resolve RPCs.
860    pub fn resolve_hashes(&self) -> u64 {
861        self.resolve_hashes.load(Ordering::Relaxed)
862    }
863
864    /// Cumulative resolve RPC wall time (microseconds).
865    pub fn resolve_micros(&self) -> u64 {
866        self.resolve_micros.load(Ordering::Relaxed)
867    }
868
869    /// Cumulative plan-construction wall time (microseconds).
870    pub fn plan_micros(&self) -> u64 {
871        self.plan_micros.load(Ordering::Relaxed)
872    }
873
874    /// Cumulative operator-execution wall time (microseconds).
875    pub fn execute_micros(&self) -> u64 {
876        self.execute_micros.load(Ordering::Relaxed)
877    }
878
879    /// Cumulative output-shaping wall time (microseconds).
880    pub fn materialize_micros(&self) -> u64 {
881        self.materialize_micros.load(Ordering::Relaxed)
882    }
883
884    /// Cumulative CustomOp drain wall time (microseconds).
885    pub fn custom_op_micros(&self) -> u64 {
886        self.custom_op_micros.load(Ordering::Relaxed)
887    }
888
889    /// CustomOp drains executed (memo hits included).
890    pub fn custom_op_count(&self) -> u64 {
891        self.custom_op_count.load(Ordering::Relaxed)
892    }
893
894    /// Cumulative blob-fetch wall time (microseconds).
895    pub fn blob_micros(&self) -> u64 {
896        self.blob_micros.load(Ordering::Relaxed)
897    }
898
899    /// Batched blob fetches issued.
900    pub fn blob_rpcs(&self) -> u64 {
901        self.blob_rpcs.load(Ordering::Relaxed)
902    }
903
904    /// Payloads answered across all blob fetches (hits + misses).
905    pub fn blob_payloads(&self) -> u64 {
906        self.blob_payloads.load(Ordering::Relaxed)
907    }
908
909    /// Cumulative GeoCandidateScan drain wall time (microseconds).
910    pub fn geo_scan_micros(&self) -> u64 {
911        self.geo_scan_micros.load(Ordering::Relaxed)
912    }
913
914    /// GeoCandidateScan drains issued.
915    pub fn geo_scan_count(&self) -> u64 {
916        self.geo_scan_count.load(Ordering::Relaxed)
917    }
918
919    /// Candidate terms returned across all geo drains.
920    pub fn geo_scan_terms(&self) -> u64 {
921        self.geo_scan_terms.load(Ordering::Relaxed)
922    }
923
924    /// Geo drain memo hits (windows served without their RPC).
925    pub fn geo_drain_memo_hits(&self) -> u64 {
926        self.geo_drain_memo_hits.load(Ordering::Relaxed)
927    }
928
929    /// Cumulative TemporalCandidateScan drain wall time (microseconds).
930    pub fn temporal_scan_micros(&self) -> u64 {
931        self.temporal_scan_micros.load(Ordering::Relaxed)
932    }
933
934    /// TemporalCandidateScan drains issued.
935    pub fn temporal_scan_count(&self) -> u64 {
936        self.temporal_scan_count.load(Ordering::Relaxed)
937    }
938
939    /// Candidate terms returned across all temporal drains.
940    pub fn temporal_scan_terms(&self) -> u64 {
941        self.temporal_scan_terms.load(Ordering::Relaxed)
942    }
943
944    /// Cumulative TextCandidateScan drain wall time (microseconds).
945    pub fn text_scan_micros(&self) -> u64 {
946        self.text_scan_micros.load(Ordering::Relaxed)
947    }
948
949    /// TextCandidateScan drains issued.
950    pub fn text_scan_count(&self) -> u64 {
951        self.text_scan_count.load(Ordering::Relaxed)
952    }
953
954    /// Candidate terms returned across all text drains.
955    pub fn text_scan_terms(&self) -> u64 {
956        self.text_scan_terms.load(Ordering::Relaxed)
957    }
958
959    /// Text drain memo hits (windows served without their RPC).
960    pub fn text_drain_memo_hits(&self) -> u64 {
961        self.text_drain_memo_hits.load(Ordering::Relaxed)
962    }
963
964    /// Cumulative TextSubjectScan resolve wall time (microseconds).
965    pub fn text_subject_scan_micros(&self) -> u64 {
966        self.text_subject_scan_micros.load(Ordering::Relaxed)
967    }
968
969    /// TextSubjectScan resolves issued.
970    pub fn text_subject_scan_count(&self) -> u64 {
971        self.text_subject_scan_count.load(Ordering::Relaxed)
972    }
973
974    /// Rows returned across all text subject resolves.
975    pub fn text_subject_scan_rows(&self) -> u64 {
976        self.text_subject_scan_rows.load(Ordering::Relaxed)
977    }
978
979    /// Text subject memo hits (windows served without their RPC).
980    pub fn text_subject_memo_hits(&self) -> u64 {
981        self.text_subject_memo_hits.load(Ordering::Relaxed)
982    }
983}
984
985/// Holds one scan wall-union interval open from construction to drop —
986/// see [`PhaseTimers::scan_wall_guard`].
987pub(crate) struct ScanWallGuard<'a> {
988    timers: &'a PhaseTimers,
989}
990
991impl Drop for ScanWallGuard<'_> {
992    fn drop(&mut self) {
993        self.timers.scan_wall_end();
994    }
995}
996
997/// Default per-query RAM budget used to size eager join chunks (Phase 2).
998///
999/// This is a sizing knob, not a precise allocator. Concurrent queries each
1000/// get their own budget; they do not subtract from a process-wide pool yet.
1001pub const DEFAULT_QUERY_MEMORY_BUDGET_BYTES: u64 = 64 * 1024 * 1024;
1002
1003/// Cap one eager join chunk at this many rows when the budget would allow more
1004/// (matches [`crate::SCAN_BATCH`] so a chunk is not the whole query).
1005pub const DEFAULT_JOIN_CHUNK_CAP: usize = 10_000;
1006
1007/// Per-query policy, identity, and sinks for SPARQL plan + execute.
1008///
1009/// Clone is cheap (sinks are `Arc`; the named-graph memo starts empty). Pass
1010/// `&QueryContext`; do not put recursion-scoped join keys or the string cache
1011/// here. The parallel-arm-permit pool is the one shared (not recursion-scoped) budget:
1012/// it caps how many plan arms of this query run at once, and `Clone` shares
1013/// the pool so sub-executions stay inside the same query's budget. The
1014/// [`TermDict`] is likewise shared across clones of one execute.
1015#[derive(Debug, Clone)]
1016pub struct QueryContext {
1017    query_id: u64,
1018    /// Wall-clock origin for the `at=+…` suffix on every log line, so
1019    /// gaps between lines read directly off the log.
1020    start: Instant,
1021    snapshot: SnapshotId,
1022    now: SystemTime,
1023    eval_env: Arc<ExprEvalEnv>,
1024    default_union: bool,
1025    /// Seat inner-join arms by the total seating cost (the `join-seat-shadow`
1026    /// comparator promoted to decision) instead of the `driver_cost` pair.
1027    /// Copied from the engine config at context build; `false` keeps the
1028    /// legacy comparator and the shadow log only.
1029    seat_by_total_cost: bool,
1030    /// Benchmark/diagnostic: override a `PerPage` semi-admission cost
1031    /// verdict and stamp `Semi`. The semantic gates still refuse. Never a
1032    /// production default.
1033    force_semi: bool,
1034    /// Whether the planner stamps and applies slot comparisons: it attaches
1035    /// `FILTER(?v OP literal)` comparisons to the scans that bind them,
1036    /// removes `AlwaysEncoded` conjuncts into the scan's eager authority
1037    /// (Track A), and the executor applies the eager filter. `false` is the
1038    /// pre-feature path: nothing is stamped, so no comparison reaches the
1039    /// wire, the memo/Slice/omitted-slot rules see a plain scan, and every
1040    /// conjunct stays in the plan (diagnostic/benchmark switch).
1041    eager_scan_filter: bool,
1042    /// Geo-index rebuild epoch reported by the O partition at startup.
1043    /// `None` = never stamped (or the describe probe failed) — the geo
1044    /// planner rewrite treats a missing epoch as trusted.
1045    geo_index_epoch: Option<u64>,
1046    /// Temporal-index rebuild epoch reported by the O partition at startup.
1047    /// `None` = never stamped — UNTRUSTED for the temporal rewrite (the
1048    /// auto-rebuild stamps it at compute startup before queries serve).
1049    temporal_index_epoch: Option<u64>,
1050    /// Text-index rebuild epoch reported by the O partition at startup.
1051    /// `None` = UNTRUSTED: string literals predate the plugin, so the text
1052    /// `text:query` rewrite hard-fails and the prefix/suffix rewrite stays
1053    /// on the exact residual path until the auto-build stamps an epoch.
1054    text_index_epoch: Option<u64>,
1055    /// Config fingerprint the text index was built with (empty when the
1056    /// partition has no index). Compared against the plugin's own config at
1057    /// plan time; a mismatch means rebuild required, never silent trust.
1058    text_index_fingerprint: std::sync::Arc<str>,
1059    /// Rolled-up temporal tick histogram snapshot (advisory row estimates
1060    /// for the temporal rewrite; `None` when the profile carries none).
1061    temporal_histogram: Option<std::sync::Arc<waratah_stats::TickHistogram>>,
1062    /// Rolled-up geo cell-count histogram snapshot (advisory row estimates
1063    /// for the geo rewrite; `None` when the profile carries none).
1064    geo_cell_histogram: Option<std::sync::Arc<waratah_stats::GeoCellHistogram>>,
1065    /// Rolled-up text seed-population sketch (advisory candidate-drain
1066    /// estimates for the text planner; `None` when the profile carries
1067    /// none).
1068    text_seed_sketch: Option<std::sync::Arc<waratah_stats::TextSeedSketch>>,
1069    dataset: QueryDataset,
1070    protocol_default_graphs: Vec<String>,
1071    protocol_named_graphs: Vec<String>,
1072    base_iri: Option<String>,
1073    security: SecurityContext,
1074    trace: TraceSink,
1075    log: LogSink,
1076    perf: Arc<PhaseTimers>,
1077    deadline: Option<Instant>,
1078    cancel: Option<Arc<AtomicBool>>,
1079    named_graphs: NamedGraphListCache,
1080    parallel_arm_permits: Arc<tokio::sync::Semaphore>,
1081    /// Per-query Grace join worker tokens (see [`QUERY_GRACE_WORKER_BUDGET`]).
1082    /// `Arc` so clones share the pool, like [`Self::parallel_arm_permits`].
1083    grace_workers: Arc<GraceWorkerPool>,
1084    term_dict: Arc<TermDict>,
1085    memory_budget_bytes: u64,
1086    spill_dir: Option<std::path::PathBuf>,
1087    spill_session: Arc<SpillSession>,
1088}
1089
1090/// Per-query spill directory; removed when the last [`QueryContext`] clone drops.
1091#[derive(Debug)]
1092struct SpillSession {
1093    created: Mutex<Option<std::path::PathBuf>>,
1094    page_seq: AtomicU64,
1095}
1096
1097impl Drop for SpillSession {
1098    fn drop(&mut self) {
1099        if let Ok(guard) = self.created.lock()
1100            && let Some(dir) = guard.as_ref()
1101        {
1102            let _ = std::fs::remove_dir_all(dir);
1103        }
1104    }
1105}
1106
1107/// Process-lifetime counter so two contexts created in the same process can
1108/// never derive the same spill directory name, even with identical
1109/// `query_id` (test contexts share `0`) and identical nanosecond clocks.
1110static SPILL_WORKDIR_SEQ: AtomicU64 = AtomicU64::new(0);
1111
1112impl QueryContext {
1113    /// Test / convenience context: `query_id = 0`, `NOW()` captured here,
1114    /// `default_union = false`, sinks off, unrestricted security.
1115    pub fn from_snapshot(snapshot: SnapshotId) -> Self {
1116        Self {
1117            query_id: 0,
1118            start: Instant::now(),
1119            snapshot,
1120            now: SystemTime::now(),
1121            eval_env: Arc::new(ExprEvalEnv::new(DateTime::now(), None)),
1122            default_union: false,
1123            seat_by_total_cost: false,
1124            force_semi: false,
1125            eager_scan_filter: true,
1126            geo_index_epoch: None,
1127            temporal_index_epoch: None,
1128            text_index_epoch: None,
1129            text_index_fingerprint: std::sync::Arc::from(""),
1130            temporal_histogram: None,
1131            geo_cell_histogram: None,
1132            text_seed_sketch: None,
1133            dataset: QueryDataset::engine_fallback(false),
1134            protocol_default_graphs: Vec::new(),
1135            protocol_named_graphs: Vec::new(),
1136            base_iri: None,
1137            security: SecurityContext::allow_all(),
1138            trace: TraceSink::off(),
1139            log: LogSink::off(),
1140            perf: Arc::new(PhaseTimers::default()),
1141            deadline: None,
1142            cancel: None,
1143            named_graphs: NamedGraphListCache::empty(),
1144            parallel_arm_permits: Arc::new(tokio::sync::Semaphore::new(arm_pool_permits())),
1145            grace_workers: Arc::new(GraceWorkerPool::new(QUERY_GRACE_WORKER_BUDGET)),
1146            term_dict: TermDict::new_shared(),
1147            memory_budget_bytes: DEFAULT_QUERY_MEMORY_BUDGET_BYTES,
1148            spill_dir: None,
1149            spill_session: Arc::new(SpillSession {
1150                created: Mutex::new(None),
1151                page_seq: AtomicU64::new(0),
1152            }),
1153        }
1154    }
1155
1156    /// Same as [`Self::from_snapshot`] but copies the engine `default_union`
1157    /// knob and the storage-reported `geo_index_epoch`.
1158    ///
1159    /// RDF `DefaultGraph` is the unnamed graph. SPARQL's default graph is the
1160    /// window a bare BGP scans: `FROM` graphs, protocol `default-graph-uri`,
1161    /// or this fallback (`true` = all graphs named and unnamed; `false` = only
1162    /// the RDF unnamed graph).
1163    pub fn from_engine(
1164        snapshot: SnapshotId,
1165        default_union: bool,
1166        geo_index_epoch: Option<u64>,
1167    ) -> Self {
1168        Self::from_snapshot(snapshot)
1169            .with_default_union(default_union)
1170            .with_geo_index_epoch(geo_index_epoch)
1171    }
1172
1173    /// Monotonic id for correlating API debug lines with compute log/trace.
1174    pub fn query_id(&self) -> u64 {
1175        self.query_id
1176    }
1177
1178    /// MVCC snapshot this query reads as of.
1179    pub fn snapshot(&self) -> SnapshotId {
1180        self.snapshot
1181    }
1182
1183    /// Instant captured at context construction (SPARQL `NOW()` must be stable).
1184    pub fn now(&self) -> SystemTime {
1185        self.now
1186    }
1187
1188    /// Expression-eval state (`NOW()`, `BNODE()` identity, compiled regexes).
1189    pub(crate) fn eval_env(&self) -> &ExprEvalEnv {
1190        &self.eval_env
1191    }
1192
1193    /// Engine/session fallback for the SPARQL default graph when no `FROM` list.
1194    pub fn default_union(&self) -> bool {
1195        self.default_union
1196    }
1197
1198    /// Inner-join arm seating comparator (copied from the engine; `false`
1199    /// keeps the legacy `driver_cost` decision).
1200    pub fn seat_by_total_cost(&self) -> bool {
1201        self.seat_by_total_cost
1202    }
1203
1204    /// Benchmark switch: force `Semi` past a `PerPage` cost verdict.
1205    pub fn force_semi(&self) -> bool {
1206        self.force_semi
1207    }
1208
1209    /// Whether the planner stamps slot comparisons and the executor applies
1210    /// the eager scan filter. `false` is the pre-feature path: nothing is
1211    /// stamped (no wire comparison, no memo/Slice/omitted-slot effect) and
1212    /// every conjunct stays in the plan.
1213    pub fn eager_scan_filter(&self) -> bool {
1214        self.eager_scan_filter
1215    }
1216
1217    /// Geo-index rebuild epoch reported by the O partition (`None` =
1218    /// never stamped — treated as trusted by the geo planner rewrite).
1219    pub fn geo_index_epoch(&self) -> Option<u64> {
1220        self.geo_index_epoch
1221    }
1222
1223    /// Temporal-index rebuild epoch reported by the O partition (`None` =
1224    /// never stamped — UNTRUSTED for the temporal planner rewrite: temporal
1225    /// literals predate the plugin, so a missing epoch means the index may
1226    /// not cover the store yet; the compute auto-rebuild stamps it at
1227    /// startup before queries are served).
1228    pub fn temporal_index_epoch(&self) -> Option<u64> {
1229        self.temporal_index_epoch
1230    }
1231
1232    /// Text-index rebuild epoch reported by the O partition (`None` =
1233    /// UNTRUSTED — the text plugin rewrites stay off; `text:query` fails
1234    /// the query and prefix/suffix falls back to the exact residual).
1235    pub fn text_index_epoch(&self) -> Option<u64> {
1236        self.text_index_epoch
1237    }
1238
1239    /// Config fingerprint of the partition's text index (empty when none).
1240    /// A mismatch with the plugin config means the index must be rebuilt
1241    /// before rewrites resume.
1242    pub fn text_index_fingerprint(&self) -> &str {
1243        &self.text_index_fingerprint
1244    }
1245
1246    /// Rolled-up temporal tick histogram (advisory estimates; `None` when
1247    /// the rolled-up profile carries none).
1248    pub fn temporal_histogram(&self) -> Option<&std::sync::Arc<waratah_stats::TickHistogram>> {
1249        self.temporal_histogram.as_ref()
1250    }
1251
1252    /// Rolled-up geo cell-count histogram (advisory estimates; `None` when
1253    /// the rolled-up profile carries none).
1254    pub fn geo_cell_histogram(&self) -> Option<&std::sync::Arc<waratah_stats::GeoCellHistogram>> {
1255        self.geo_cell_histogram.as_ref()
1256    }
1257
1258    /// Rolled-up text seed-population sketch (advisory candidate-drain
1259    /// estimates; `None` when the rolled-up profile carries none).
1260    pub fn text_seed_sketch(&self) -> Option<&std::sync::Arc<waratah_stats::TextSeedSketch>> {
1261        self.text_seed_sketch.as_ref()
1262    }
1263
1264    /// Resolved SPARQL dataset (FROM / protocol / engine fallback).
1265    pub fn dataset(&self) -> &QueryDataset {
1266        &self.dataset
1267    }
1268
1269    /// SPARQL Protocol `default-graph-uri` values (may be empty).
1270    pub fn protocol_default_graphs(&self) -> &[String] {
1271        &self.protocol_default_graphs
1272    }
1273
1274    /// SPARQL Protocol `named-graph-uri` values (may be empty).
1275    pub fn protocol_named_graphs(&self) -> &[String] {
1276        &self.protocol_named_graphs
1277    }
1278
1279    /// Query base IRI for resolving relative IRIs in the query text.
1280    ///
1281    /// `None` leaves the engine's current behavior: relative IRI references
1282    /// are a parse error (spargebra stores absolute IRIs only).
1283    pub fn base_iri(&self) -> Option<&str> {
1284        self.base_iri.as_deref()
1285    }
1286
1287    /// Stub security policy.
1288    pub fn security(&self) -> &SecurityContext {
1289        &self.security
1290    }
1291
1292    /// Execution trace sink.
1293    pub fn trace(&self) -> &TraceSink {
1294        &self.trace
1295    }
1296
1297    /// Operational log sink.
1298    pub fn log_sink(&self) -> &LogSink {
1299        &self.log
1300    }
1301
1302    /// Per-query scan / resolve wall-time totals (shared across clones).
1303    pub fn perf(&self) -> &PhaseTimers {
1304        &self.perf
1305    }
1306
1307    /// Query-local intern table (shared across clones of this execute).
1308    pub fn term_dict(&self) -> Arc<TermDict> {
1309        Arc::clone(&self.term_dict)
1310    }
1311
1312    /// Per-query byte budget for join chunk sizing (Phase 2) and spill (Phase 3).
1313    ///
1314    /// Concurrent queries each get their own budget; they do not subtract from
1315    /// a process-wide pool yet (follow-on work).
1316    pub fn memory_budget_bytes(&self) -> u64 {
1317        self.memory_budget_bytes
1318    }
1319
1320    /// Max output rows for one eager join chunk given column `width`.
1321    ///
1322    /// `budget / (width * 4)` clamped to `[1, cap]`. `cap` is typically
1323    /// [`DEFAULT_JOIN_CHUNK_CAP`] / `SCAN_BATCH`.
1324    pub fn join_chunk_rows(&self, width: usize, cap: usize) -> usize {
1325        let w = (width as u64).max(1);
1326        let by_budget = (self.memory_budget_bytes / (w * 4)).max(1);
1327        (by_budget as usize).clamp(1, cap.max(1))
1328    }
1329
1330    /// Override the per-query RAM budget (tests use small values).
1331    pub fn with_memory_budget_bytes(mut self, bytes: u64) -> Self {
1332        self.memory_budget_bytes = bytes.max(1);
1333        self
1334    }
1335
1336    /// Replace this context's parallel-arm pool with `permits` slots (minimum
1337    /// one).
1338    ///
1339    /// Test/benchmark hook: the process-wide fetch concurrency sizes every
1340    /// fresh context's pool, so a test that needs the sequential fallback
1341    /// cannot change that global without racing sibling tests. This overrides
1342    /// the pool for this context (and its clones) only.
1343    #[doc(hidden)]
1344    pub fn with_arm_pool_permits(mut self, permits: usize) -> Self {
1345        self.parallel_arm_permits = Arc::new(tokio::sync::Semaphore::new(permits.max(1)));
1346        self
1347    }
1348
1349    /// Directory for per-query spill files (`ORDER BY` external sort, parked pages).
1350    pub fn spill_dir(&self) -> Option<&std::path::PathBuf> {
1351        self.spill_dir.as_ref()
1352    }
1353
1354    /// Set the directory this query's spill files are created under
1355    /// (`ORDER BY` external sort runs, parked pages, Grace join partitions,
1356    /// DISTINCT seen-set partitions).
1357    ///
1358    /// Engines copy the operator-configured root here; without it files go to
1359    /// `std::env::temp_dir`, which is RAM-backed (tmpfs) on many Linux
1360    /// systems and defeats spilling. Must be set before the first spill —
1361    /// the workdir is cached once created.
1362    pub fn with_spill_dir(mut self, dir: std::path::PathBuf) -> Self {
1363        self.spill_dir = Some(dir);
1364        self
1365    }
1366
1367    /// Per-query subdirectory for TermId page files. Created on first use;
1368    /// deleted when the last clone of this context drops.
1369    pub(crate) fn spill_workdir(&self) -> Result<std::path::PathBuf, ComputeError> {
1370        let mut created = self
1371            .spill_session
1372            .created
1373            .lock()
1374            .unwrap_or_else(|poisoned| poisoned.into_inner());
1375        if let Some(dir) = created.as_ref() {
1376            return Ok(dir.clone());
1377        }
1378        let root = self.spill_dir.clone().unwrap_or_else(std::env::temp_dir);
1379        // pid + process counter + wall-clock nanos. The process counter makes
1380        // collisions between live contexts impossible even when query_id
1381        // repeats (test contexts share 0); nanos keep names unique across
1382        // process restarts. Unlike the previous Arc-pointer component, these
1383        // are never reused by a live allocation.
1384        let dir = root.join(format!(
1385            "waratah-q{}-{}-{}-{}",
1386            self.query_id,
1387            std::process::id(),
1388            SPILL_WORKDIR_SEQ.fetch_add(1, Ordering::Relaxed),
1389            SystemTime::now()
1390                .duration_since(SystemTime::UNIX_EPOCH)
1391                .map(|d| d.as_nanos())
1392                .unwrap_or_default(),
1393        ));
1394        // An existing dir under this name can only be residue from a crashed
1395        // prior process (a live peer cannot produce the same name), so
1396        // reclaim it — silently reusing stale files would mix foreign pages
1397        // into this query's spill set.
1398        if dir.exists() {
1399            std::fs::remove_dir_all(&dir)
1400                .map_err(|e| ComputeError::Spill(format!("reclaim {}: {e}", dir.display())))?;
1401        }
1402        std::fs::create_dir_all(&dir).map_err(|e| ComputeError::Spill(e.to_string()))?;
1403        *created = Some(dir.clone());
1404        Ok(dir)
1405    }
1406
1407    /// Unique file name inside [`Self::spill_workdir`] (`prefix-N.page`).
1408    ///
1409    /// The counter is per [`SpillSession`], so parallel plan arms that share
1410    /// this context cannot pick the same path. Use a readable `prefix`
1411    /// (`park`, `run`, `grace-l-0-1`, `distinct-0`).
1412    pub(crate) fn next_spill_name(&self, prefix: &str) -> String {
1413        let n = self.spill_session.page_seq.fetch_add(1, Ordering::Relaxed);
1414        format!("{prefix}-{n}.page")
1415    }
1416
1417    /// Write an operational log line when the sink enables `level`. Every
1418    /// line carries the elapsed wall time since context build (`at=+…ms`)
1419    /// so the timeline between lines reads directly off the log.
1420    ///
1421    /// The sink check happens before any formatting: callers with
1422    /// measurement work (spans, readout walks) should consult
1423    /// [`Self::log_sink`]'s `enabled_at` themselves so the disabled path
1424    /// does no work at all.
1425    pub fn log(&self, level: LogLevel, message: &str) {
1426        if !self.log.enabled_at(level) {
1427            return;
1428        }
1429        self.log.emit(
1430            self.query_id,
1431            level,
1432            &format!("{message} at=+{:?}", self.start.elapsed()),
1433        );
1434    }
1435
1436    /// Optional wall-clock deadline (honored before hexastore RPCs and materialize).
1437    pub fn deadline(&self) -> Option<Instant> {
1438        self.deadline
1439    }
1440
1441    /// Optional cancellation flag (honored before hexastore RPCs, materialize, and return).
1442    pub fn cancel(&self) -> Option<&Arc<AtomicBool>> {
1443        self.cancel.as_ref()
1444    }
1445
1446    /// Abort if the cancel token is set or the deadline has passed.
1447    ///
1448    /// Called before hexastore RPCs ([`crate::query::QueryEngine::scan_page`],
1449    /// property-path hop pages) and after execute before registry materialize.
1450    /// Compute-side joins / FILTERs are not checked.
1451    pub fn check_abort(&self) -> Result<(), ComputeError> {
1452        self.check_cancelled()?;
1453        if self
1454            .deadline()
1455            .is_some_and(|deadline| Instant::now() >= deadline)
1456        {
1457            self.log(LogLevel::Warn, "query deadline exceeded");
1458            return Err(ComputeError::DeadlineExceeded);
1459        }
1460        Ok(())
1461    }
1462
1463    /// Abort if the cancel token is set. Deadline is ignored.
1464    ///
1465    /// Used after materialize, when the query is finished and we only decide
1466    /// whether to hand the result back.
1467    pub fn check_cancelled(&self) -> Result<(), ComputeError> {
1468        if self
1469            .cancel()
1470            .is_some_and(|flag| flag.load(Ordering::Relaxed))
1471        {
1472            self.log(LogLevel::Warn, "query cancelled");
1473            return Err(ComputeError::Cancelled);
1474        }
1475        Ok(())
1476    }
1477
1478    /// Set the correlating query id (API / CLI).
1479    pub fn with_query_id(mut self, query_id: u64) -> Self {
1480        self.query_id = query_id;
1481        self
1482    }
1483
1484    /// Override SPARQL default-graph fallback (copied from the engine by default).
1485    pub fn with_default_union(mut self, default_union: bool) -> Self {
1486        self.default_union = default_union;
1487        self.dataset = QueryDataset::engine_fallback(default_union);
1488        self
1489    }
1490
1491    /// Seat inner joins by the total seating cost (copied from the engine).
1492    pub fn with_seat_by_total_cost(mut self, seat_by_total_cost: bool) -> Self {
1493        self.seat_by_total_cost = seat_by_total_cost;
1494        self
1495    }
1496
1497    /// Benchmark switch: force `Semi` past a `PerPage` cost verdict. The
1498    /// semantic semi gates (payload, multiplicity, keys, specialized scan)
1499    /// still refuse; only the price loses its veto.
1500    pub fn with_force_semi(mut self, force_semi: bool) -> Self {
1501        self.force_semi = force_semi;
1502        self
1503    }
1504
1505    /// Enable or disable slot comparison stamping and the eager scan filter.
1506    /// `false` is the pre-feature path: no comparison is stamped, so none
1507    /// reaches the wire and every conjunct stays in the plan.
1508    pub fn with_eager_scan_filter(mut self, eager_scan_filter: bool) -> Self {
1509        self.eager_scan_filter = eager_scan_filter;
1510        self
1511    }
1512
1513    /// Set the geo-index rebuild epoch (copied from the engine by default).
1514    pub fn with_geo_index_epoch(mut self, geo_index_epoch: Option<u64>) -> Self {
1515        self.geo_index_epoch = geo_index_epoch;
1516        self
1517    }
1518
1519    /// Set the temporal-index rebuild epoch (copied from the engine by default).
1520    pub fn with_temporal_index_epoch(mut self, temporal_index_epoch: Option<u64>) -> Self {
1521        self.temporal_index_epoch = temporal_index_epoch;
1522        self
1523    }
1524
1525    /// Set the text-index rebuild epoch and fingerprint (copied from the
1526    /// engine by default; `None` epoch = untrusted).
1527    pub fn with_text_index_state(
1528        mut self,
1529        text_index_epoch: Option<u64>,
1530        text_index_fingerprint: impl Into<std::sync::Arc<str>>,
1531    ) -> Self {
1532        self.text_index_epoch = text_index_epoch;
1533        self.text_index_fingerprint = text_index_fingerprint.into();
1534        self
1535    }
1536
1537    /// Set the rolled-up temporal tick histogram snapshot.
1538    pub fn with_temporal_histogram(
1539        mut self,
1540        temporal_histogram: Option<std::sync::Arc<waratah_stats::TickHistogram>>,
1541    ) -> Self {
1542        self.temporal_histogram = temporal_histogram;
1543        self
1544    }
1545
1546    /// Set the rolled-up geo cell-count histogram snapshot.
1547    pub fn with_geo_cell_histogram(
1548        mut self,
1549        geo_cell_histogram: Option<std::sync::Arc<waratah_stats::GeoCellHistogram>>,
1550    ) -> Self {
1551        self.geo_cell_histogram = geo_cell_histogram;
1552        self
1553    }
1554
1555    /// Set the rolled-up text seed-population sketch snapshot.
1556    pub fn with_text_seed_sketch(
1557        mut self,
1558        text_seed_sketch: Option<std::sync::Arc<waratah_stats::TextSeedSketch>>,
1559    ) -> Self {
1560        self.text_seed_sketch = text_seed_sketch;
1561        self
1562    }
1563
1564    /// Attach a resolved [`QueryDataset`] for planning (crate-internal setter).
1565    ///
1566    /// [`crate::query::QueryEngine::query`] always rebuilds the dataset from protocol
1567    /// IRI lists, query-text `FROM` / `FROM NAMED`, and [`Self::default_union`],
1568    /// then calls this on a clone. Setting it on the context you pass into
1569    /// `query()` has no effect.
1570    pub(crate) fn with_dataset(mut self, dataset: QueryDataset) -> Self {
1571        self.dataset = dataset;
1572        self
1573    }
1574
1575    /// SPARQL Protocol dataset IRIs (override query-text FROM when non-empty).
1576    pub fn with_protocol_dataset(
1577        mut self,
1578        default_graphs: Vec<String>,
1579        named_graphs: Vec<String>,
1580    ) -> Self {
1581        self.protocol_default_graphs = default_graphs;
1582        self.protocol_named_graphs = named_graphs;
1583        self
1584    }
1585
1586    /// Set the base IRI used when parsing the query text.
1587    ///
1588    /// Relative IRIs in the query (`FROM <data.ttl>`, `GRAPH <g.ttl>`, IRI
1589    /// template terms) resolve against this. Callers that already know their
1590    /// queries are absolute-IRI-only (HTTP API, CLI) leave it unset.
1591    pub fn with_base_iri(mut self, base_iri: Option<String>) -> Self {
1592        self.base_iri = base_iri.clone();
1593        self.eval_env = Arc::new(ExprEvalEnv::new(self.eval_env.now(), base_iri));
1594        self
1595    }
1596
1597    /// Replace the operational log sink.
1598    pub fn with_log(mut self, log: LogSink) -> Self {
1599        self.log = log;
1600        self
1601    }
1602
1603    /// Replace the execution trace sink.
1604    pub fn with_trace(mut self, trace: TraceSink) -> Self {
1605        self.trace = trace;
1606        self
1607    }
1608
1609    /// Wall-clock deadline checked before hexastore RPCs and materialize.
1610    pub fn with_deadline(mut self, deadline: Option<Instant>) -> Self {
1611        self.deadline = deadline;
1612        self
1613    }
1614
1615    /// Cooperative cancellation checked before hexastore RPCs, materialize, and return.
1616    pub fn with_cancel(mut self, cancel: Option<Arc<AtomicBool>>) -> Self {
1617        self.cancel = cancel;
1618        self
1619    }
1620
1621    /// Replace the security stub (still unused).
1622    pub fn with_security(mut self, security: SecurityContext) -> Self {
1623        self.security = security;
1624        self
1625    }
1626
1627    /// S-axis Present named graphs for this execute, listing at most once.
1628    pub(crate) async fn get_or_load_named_graphs<F, Fut>(
1629        &self,
1630        load: F,
1631    ) -> Result<Arc<[EncodedTerm]>, ComputeError>
1632    where
1633        F: FnOnce() -> Fut,
1634        Fut: Future<Output = Result<Vec<EncodedTerm>, ComputeError>>,
1635    {
1636        if let Some(graphs) = self.named_graphs.slot.get() {
1637            return Ok(Arc::clone(graphs));
1638        }
1639        let graphs: Arc<[EncodedTerm]> = Arc::from(load().await?);
1640        let _ = self.named_graphs.slot.set(Arc::clone(&graphs));
1641        Ok(graphs)
1642    }
1643
1644    /// Try to reserve one slot of this query's parallel-arm budget.
1645    ///
1646    /// Returns `None` when all of the query's arm permits
1647    /// ([`arm_pool_permits`]) are held;
1648    /// the caller must then evaluate the arm on the sequential path instead of
1649    /// waiting. The `OwnedSemaphorePermit` releases when dropped, so a dropped
1650    /// (cancelled) arm returns its permit automatically.
1651    pub(crate) fn try_acquire_arm_permit(&self) -> Option<tokio::sync::OwnedSemaphorePermit> {
1652        Arc::clone(&self.parallel_arm_permits)
1653            .try_acquire_owned()
1654            .ok()
1655    }
1656
1657    /// Try to reserve up to `want` Grace join worker tokens from this
1658    /// query's pool. Returns a lease with however many were free — check
1659    /// [`GraceWorkerLease::count`]; a count under 2 means the caller runs
1660    /// the serial bucket loop. Never blocks: a nested or sibling join that
1661    /// finds the pool spent degrades to serial instead of waiting.
1662    pub(crate) fn try_acquire_grace_workers(&self, want: usize) -> GraceWorkerLease<'_> {
1663        self.grace_workers.try_acquire(want)
1664    }
1665
1666    /// Reserve one slot of the parallel-arm budget, waiting if needed.
1667    ///
1668    /// Used for the query root: holding a slot for the whole execution makes
1669    /// the budget exact — every concurrently evaluating arm either holds its
1670    /// own permit or descends from the one root permit, so outstanding arm
1671    /// evaluations never exceed the pool ([`arm_pool_permits`]). The pool
1672    /// always holds at least this one permit ([`arm_pool_permits_for`]
1673    /// guarantees a minimum of 1), and holders always
1674    /// finish (their scans are finite), so a wait here cannot deadlock.
1675    pub(crate) async fn acquire_arm_permit(&self) -> tokio::sync::OwnedSemaphorePermit {
1676        Arc::clone(&self.parallel_arm_permits)
1677            .acquire_owned()
1678            .await
1679            .expect("query permit pool is never closed")
1680    }
1681}
1682
1683#[cfg(test)]
1684mod tests {
1685    use super::*;
1686    use waratah_storage::SnapshotId;
1687
1688    #[test]
1689    fn arm_pool_permits_follow_the_fetch_concurrency() {
1690        // Fetch concurrency 0 and 1 both mean "engine off": the root's permit only.
1691        assert_eq!(arm_pool_permits_for(0), 1);
1692        assert_eq!(arm_pool_permits_for(1), 1);
1693        // Fetch concurrency 2 and up: that many permits plus the root's
1694        // whole-execution hold.
1695        assert_eq!(arm_pool_permits_for(2), 3);
1696        assert_eq!(arm_pool_permits_for(3), 4);
1697        assert_eq!(arm_pool_permits_for(16), 17);
1698        // Above the documented ceiling (64): clamped before the pool
1699        // arithmetic, so the pool stays at 65 permits and no input can
1700        // overflow the addition — the zero-permit-pool deadlock a raw
1701        // `usize::MAX + 1` wrap would build in release builds.
1702        assert_eq!(arm_pool_permits_for(MAX_QUERY_FETCH_CONCURRENCY), 65);
1703        assert_eq!(arm_pool_permits_for(MAX_QUERY_FETCH_CONCURRENCY + 1), 65);
1704        assert_eq!(arm_pool_permits_for(usize::MAX), 65);
1705    }
1706
1707    #[test]
1708    fn parallel_probe_engine_off_below_fetch_concurrency_two() {
1709        assert!(!parallel_probe_engine_on(0));
1710        assert!(!parallel_probe_engine_on(1));
1711        assert!(parallel_probe_engine_on(2));
1712        assert!(parallel_probe_engine_on(3));
1713    }
1714
1715    #[test]
1716    fn default_pool_preserves_the_historical_four_permits() {
1717        // Fetch concurrency 3 (pool 4, three free after the root hold) is exactly the
1718        // behavior the pre-redefinition value 4 delivered, so the default
1719        // move is a renaming, not a behavior change.
1720        assert_eq!(QUERY_FETCH_CONCURRENCY, 3);
1721        assert_eq!(arm_pool_permits_for(QUERY_FETCH_CONCURRENCY), 4);
1722    }
1723
1724    #[test]
1725    fn from_snapshot_defaults() {
1726        let ctx = QueryContext::from_snapshot(SnapshotId::latest());
1727        assert_eq!(ctx.query_id(), 0);
1728        assert!(!ctx.default_union());
1729        assert!(!ctx.trace().is_enabled());
1730        assert!(!ctx.log_sink().enabled_at(LogLevel::Error));
1731        assert!(ctx.deadline().is_none());
1732        assert!(ctx.cancel().is_none());
1733    }
1734
1735    #[test]
1736    fn with_cancel_stores_flag() {
1737        let flag = Arc::new(AtomicBool::new(true));
1738        let ctx = QueryContext::from_snapshot(SnapshotId::latest()).with_cancel(Some(flag.clone()));
1739        assert!(
1740            ctx.cancel()
1741                .is_some_and(|stored| stored.load(Ordering::Relaxed))
1742        );
1743    }
1744
1745    #[test]
1746    fn check_abort_cancelled() {
1747        let flag = Arc::new(AtomicBool::new(true));
1748        let ctx = QueryContext::from_snapshot(SnapshotId::latest()).with_cancel(Some(flag));
1749        assert!(matches!(ctx.check_abort(), Err(ComputeError::Cancelled)));
1750    }
1751
1752    #[test]
1753    fn check_cancelled_ignores_deadline() {
1754        let ctx = QueryContext::from_snapshot(SnapshotId::latest())
1755            .with_deadline(Some(Instant::now() - std::time::Duration::from_secs(1)));
1756        assert!(ctx.check_cancelled().is_ok());
1757        assert!(matches!(
1758            ctx.check_abort(),
1759            Err(ComputeError::DeadlineExceeded)
1760        ));
1761    }
1762
1763    #[test]
1764    fn from_engine_copies_default_union() {
1765        let ctx = QueryContext::from_engine(SnapshotId::latest(), true, None);
1766        assert!(ctx.default_union());
1767        assert_eq!(ctx.geo_index_epoch(), None);
1768        let ctx = QueryContext::from_engine(SnapshotId::latest(), false, Some(7));
1769        assert_eq!(ctx.geo_index_epoch(), Some(7));
1770    }
1771
1772    #[test]
1773    fn grace_worker_pool_acquires_exhausts_and_returns() {
1774        let pool = GraceWorkerPool::new(8);
1775        // Under budget: full ask granted.
1776        let lease = pool.try_acquire(5);
1777        assert_eq!(lease.count(), 5);
1778        // Partly spent pool: the next acquire gets only the remainder.
1779        let lease2 = pool.try_acquire(5);
1780        assert_eq!(lease2.count(), 3);
1781        // Exhausted: zero tokens without blocking (the nested/sibling case).
1782        let lease3 = pool.try_acquire(4);
1783        assert_eq!(lease3.count(), 0);
1784        // Dropping a lease returns exactly its tokens.
1785        drop(lease2);
1786        let lease4 = pool.try_acquire(4);
1787        assert_eq!(lease4.count(), 3);
1788        // Panic unwind drops the lease too — tokens return on unwind.
1789        let payload = std::panic::AssertUnwindSafe(lease4);
1790        let _ = std::panic::catch_unwind(move || {
1791            let _lease = payload;
1792            panic!("unwind must still return the lease");
1793        });
1794        let lease5 = pool.try_acquire(8);
1795        assert_eq!(
1796            lease5.count(),
1797            3,
1798            "only the panicked lease's tokens returned"
1799        );
1800        drop(lease);
1801        drop(lease3);
1802        drop(lease5);
1803        // Fully drained pool restores to the full budget.
1804        let full = pool.try_acquire(8);
1805        assert_eq!(full.count(), 8);
1806    }
1807
1808    #[test]
1809    fn base_iri_defaults_to_none_and_builder_stores() {
1810        let ctx = QueryContext::from_snapshot(SnapshotId::latest());
1811        assert!(ctx.base_iri().is_none());
1812        let ctx = ctx.with_base_iri(Some("file:///tmp/repo/q.rq".into()));
1813        assert_eq!(ctx.base_iri(), Some("file:///tmp/repo/q.rq"));
1814    }
1815
1816    #[test]
1817    fn now_frozen_across_clones() {
1818        let ctx = QueryContext::from_snapshot(SnapshotId::latest());
1819        let now = ctx.now();
1820        let clone = ctx.clone();
1821        assert_eq!(clone.now(), now);
1822    }
1823
1824    #[test]
1825    fn log_capture_includes_query_id() {
1826        let lines = Arc::new(Mutex::new(Vec::new()));
1827        let ctx = QueryContext::from_snapshot(SnapshotId::latest())
1828            .with_query_id(7)
1829            .with_log(LogSink::capture(LogLevel::Info, lines.clone()));
1830        ctx.log(LogLevel::Info, "hello");
1831        ctx.log(LogLevel::Debug, "skipped");
1832        let logged = lines.lock().unwrap();
1833        assert_eq!(logged.len(), 1);
1834        assert!(
1835            logged[0].starts_with("q#7 INFO hello at=+"),
1836            "line carries the query id and the elapsed-clock suffix: {}",
1837            logged[0]
1838        );
1839    }
1840
1841    #[test]
1842    fn log_off_does_not_emit() {
1843        let ctx = QueryContext::from_snapshot(SnapshotId::latest()).with_query_id(1);
1844        ctx.log(LogLevel::Error, "silent");
1845    }
1846
1847    #[test]
1848    fn trace_off_is_disabled() {
1849        let ctx = QueryContext::from_snapshot(SnapshotId::latest());
1850        crate::query_trace!(&ctx, TraceEvent::ScanStart { limit: 10 });
1851        assert!(!ctx.trace().is_enabled());
1852    }
1853
1854    #[test]
1855    fn next_spill_name_is_unique_across_clones() {
1856        let ctx = QueryContext::from_snapshot(SnapshotId::latest());
1857        let other = ctx.clone();
1858        let a = ctx.next_spill_name("run");
1859        let b = other.next_spill_name("run");
1860        let c = ctx.next_spill_name("grace-l-0-0");
1861        assert_ne!(a, b);
1862        assert_ne!(b, c);
1863        assert!(a.starts_with("run-") && a.ends_with(".page"));
1864        assert!(c.starts_with("grace-l-0-0-") && c.ends_with(".page"));
1865    }
1866
1867    #[test]
1868    fn spill_workdirs_differ_even_with_the_same_query_id() {
1869        // Both contexts use the test-default `query_id = 0`; the process
1870        // counter + nanos in the name must still keep them apart (the old
1871        // Arc-pointer scheme relied on allocator addresses).
1872        let a = QueryContext::from_snapshot(SnapshotId::latest());
1873        let b = QueryContext::from_snapshot(SnapshotId::latest());
1874        let dir_a = a.spill_workdir().unwrap();
1875        let dir_b = b.spill_workdir().unwrap();
1876        assert_ne!(dir_a, dir_b);
1877        assert!(dir_a.is_dir());
1878        assert!(dir_b.is_dir());
1879        // Clones of one context share the workdir (same spill session).
1880        let clone = a.clone();
1881        assert_eq!(clone.spill_workdir().unwrap(), dir_a);
1882    }
1883
1884    #[test]
1885    fn with_spill_dir_places_the_workdir_under_the_configured_root() {
1886        let root = std::env::temp_dir().join(format!(
1887            "waratah-spill-root-{}-{}",
1888            std::process::id(),
1889            QueryContext::from_snapshot(SnapshotId::latest())
1890                .spill_workdir()
1891                .unwrap()
1892                .file_name()
1893                .unwrap()
1894                .to_string_lossy()
1895        ));
1896        let ctx = QueryContext::from_snapshot(SnapshotId::latest()).with_spill_dir(root.clone());
1897        let dir = ctx.spill_workdir().unwrap();
1898        assert!(dir.starts_with(&root));
1899        assert_eq!(ctx.spill_dir(), Some(&root));
1900    }
1901}