Skip to main content

waratah_compute/
query.rs

1//! Query execution: route → scan → join → late materialize.
2//!
3//! Scans go to exactly one hexastore axis chosen by [`waratah_router`], joins
4//! run in compute memory over encoded terms (hash / shuffle), broadcast joins
5//! push a key allow-list into the right-hand scan, and raw strings are fetched
6//! from the **string-registry** process once, for projected columns or result
7//! graph terms. `SELECT` materializes bindings; `ASK` returns a boolean without
8//! registry materialization; `CONSTRUCT` instantiates a template over solution
9//! columns; `DESCRIBE` runs mode-specific prefix scans.
10//!
11//! # Module map
12//!
13//! This file is the module root: the [`QueryEngine`] type, its config, the
14//! [`query`] / [`QueryEngine::query_output`] entry points, and the registry
15//! resolve + late-materialization helpers. The two evaluator codepaths and
16//! their shared substrate live in submodules:
17//!
18//! - [`eval_eager`] — the materializing evaluator: `execute_node` reduces a
19//!   whole plan subtree to an `EncodedSolutions` table (Slice shortcuts,
20//!   OPTIONAL/FILTER stages, projection, CONSTRUCT/DESCRIBE materialization).
21//! - [`open_node`] — the demand-driven pull producer: `open_node` builds a
22//!   cursor tree for a Slice and `next_batch` fills it batch by batch
23//!   (capped-join state, probe pushdown). Falls back to `execute_node` for
24//!   operators that must materialize.
25//! - [`exists`] — FILTER EXISTS / NOT EXISTS (ASK-once, key-only SemiJoin,
26//!   NestedProbe), shared by eager Filter and OpenNode Filter.
27//! - [`scan`] — the scan fetch service shared by both: hexastore page
28//!   fetches (unary + streaming), domain/head scans, overlay + filter
29//!   composition, detached GROUP BY prefetch.
30//! - [`join_kernels`] — solution-level kernels shared by both: encoded inner
31//!   joins, broadcast filter merging, pushdown probes, `VALUES` evaluation.
32//! - [`pushdown`] — ancestor pushdown vocabulary: `PushedKeyVals` stacks and the
33//!   cursor-local `GraphOverlay`.
34//! - [`tunables`] — page-size / transport-ceiling constants and their
35//!   override setters.
36
37use std::sync::{Arc, RwLock};
38
39use spargebra::Query;
40use waratah_router::{ClusterConfig, Router};
41use waratah_stats::{GRAPH_FILTER_TERM_CAP, StatsProfile, from_bytes, rollup_cluster};
42use waratah_storage::{
43    EncodedTerm, EncodedTriplePattern, IndexPermutation, NamedOrBlankNode, PartitionAxis,
44    SnapshotId, StrBlobMap, StrHash, StrHashMap, Term, Triple, Variable, decode_term,
45    geo_lexical_key, hashes_in_term, new_str_blob_map, new_str_hash_map, new_str_hash_set,
46    well_known_iri,
47};
48
49use crate::aggregate::Grouping;
50use crate::clients::{
51    BlobStoreClient, GrpcHexastoreClients, GrpcRegistryClients, HexastoreCatalog, HexastoreGeo,
52    HexastoreScan, HexastoreStats, StringResolve,
53};
54use crate::construct::{EncodedTriple, compile_template, emit_construct};
55use crate::context::{LogLevel, QueryContext};
56use crate::custom_fns::CustomFunctions;
57use crate::dataset::QueryDataset;
58use crate::describe::DescribeMode;
59use crate::error::{ComputeError, RetryPolicy, with_retry};
60use crate::fanout::RESOLVE_STRING_CHUNK;
61use crate::filter_residual::{merge_resolved, novel_hashes_for_rows};
62use crate::path::{OPEN_STAR_PAIR_BUDGET, PATH_PAIR_BUDGET};
63use crate::plan::{LogicalPlan, PlanNode};
64use crate::query::caches::{ConstSeeds, QueryCaches};
65use crate::resolve_cache::ResolveCache;
66use crate::solutions::{EncodedSolutions, ProjectedSolutions, QueryOutput, QueryResults};
67pub(crate) mod caches;
68mod concurrent_star_exec;
69mod custom_op;
70mod eval_eager;
71mod exists;
72mod join_kernels;
73pub(crate) mod open_node;
74pub(crate) mod parallel_probe;
75mod parallel_pushdown;
76pub(crate) mod pushdown;
77pub(crate) mod scan;
78mod scan_filters;
79pub(crate) mod tunables;
80
81pub(crate) use join_kernels::BuiltProbeArm;
82pub(crate) use scan::DriverScanStream;
83pub(crate) use scan::scan_memo_eligible;
84
85#[cfg(test)]
86pub(crate) mod fixtures;
87
88use tunables::residual_window;
89
90/// Virtual nodes per axis on the router ring for compute-side routing.
91const ROUTER_VNODES: u32 = 16;
92
93/// SPARQL coordinator over the hexastore and registry endpoints.
94#[derive(Debug, Clone)]
95pub struct QueryEngine<H, R> {
96    hexastore: H,
97    registry: R,
98    router: Router,
99    retry: RetryPolicy,
100    /// Local sketch cache — never consulted over the network at plan time.
101    /// The rolled-up stats profile, plus the three advisory frame sketches
102    /// as ARCS built once per rollup. The Arcs exist so per-query readers
103    /// hand out cheap handles instead of deep-copying sketches, and the
104    /// INNER Arc (this is `Arc<RwLock<Arc<EngineProfile>>>`) lets
105    /// [`Self::query_output`] snapshot the whole engine profile for
106    /// planning with one refcount bump — a `StatsProfile` clone there
107    /// would memcpy the seed sketch (a fixed 3,648,014-byte frame at ANY
108    /// corpus scale — 10M or 1B unique strings) on every query. Writers
109    /// REPLACE the inner Arc; a snapshot plans against its generation
110    /// without holding the lock.
111    profile: Arc<RwLock<Arc<EngineProfile>>>,
112    describe_mode: DescribeMode,
113    /// Hard cap on distinct `(start, end)` pairs for a bound or one-end path.
114    path_pair_budget: u64,
115    /// Tighter cap for `*` / `+` when there is no LIMIT (open or join-pushed).
116    open_star_pair_budget: u64,
117    /// SPARQL default-graph fallback when the query has no `FROM` list.
118    ///
119    /// `false` (default): bare BGP scans the RDF unnamed graph only.
120    /// `true`: bare BGP scans all graphs (named and unnamed). Copied onto each
121    /// [`QueryContext`] and used when the query has no `FROM` / protocol dataset.
122    default_union: bool,
123    /// Inner-join arm seating comparator: `true` seats by the total seating
124    /// cost (the `join-seat-shadow` comparator promoted to decision)
125    /// instead of the `driver_cost` pair. Copied onto each [`QueryContext`].
126    seat_by_total_cost: bool,
127    /// Benchmark/diagnostic: override a `PerPage` semi-admission cost
128    /// verdict and stamp `Semi`. Copied onto each [`QueryContext`].
129    force_semi: bool,
130    /// Compute-side eager scan filter (Levels 2/3): drop rows a pushed
131    /// comparison provably rejects before or after interning. `true` by
132    /// default; the equivalence battery runs with it off to compare against
133    /// the plan `FILTER` alone.
134    eager_scan_filter: bool,
135    /// Geo-index rebuild epoch reported by the O partition at startup
136    /// (`None` = never stamped / probe failed). Copied onto each
137    /// [`QueryContext`]; the geo planner rewrite skips its `geof:*` FILTER
138    /// → scan rewrite for snapshots below the epoch.
139    geo_index_epoch: Option<u64>,
140    /// Temporal-index rebuild epoch reported by the O partition at startup
141    /// (`None` = never stamped — UNTRUSTED for the temporal rewrite; the
142    /// auto-rebuild stamps it before queries serve). Copied onto each
143    /// [`QueryContext`].
144    temporal_index_epoch: Option<u64>,
145    /// Text-index rebuild epoch reported by the O partition at startup
146    /// (`None` = UNTRUSTED for both text rewrites). Copied onto each
147    /// [`QueryContext`].
148    text_index_epoch: Option<u64>,
149    /// Config fingerprint the text index was built with (empty when none).
150    /// Copied onto each [`QueryContext`] so the plugin can detect a
151    /// settings change without a network call.
152    text_index_fingerprint: std::sync::Arc<str>,
153    /// Root directory for per-query spill files (external `ORDER BY` runs,
154    /// parked pages, Grace join partitions). Copied onto each
155    /// [`QueryContext`]; `None` falls back to `std::env::temp_dir`, which is
156    /// RAM-backed (tmpfs) on many Linux systems. Operators point this at a
157    /// disk-backed path (`--spill-dir`, default `{data-dir}/spill`).
158    spill_root: Option<std::path::PathBuf>,
159    /// Compute-wide cache of registry-resolved strings, shared by all queries
160    /// (clones share the `Arc`). Entries never go stale — `StrHash` is a
161    /// content hash and registry strings are not rewritten.
162    resolve_cache: Arc<ResolveCache>,
163}
164
165impl<H, R> QueryEngine<H, R> {
166    /// Build over injected clients (mocks in unit tests; tonic in integration).
167    pub fn new(hexastore: H, registry: R, router: Router, retry: RetryPolicy) -> Self {
168        // Evaluation consults the process-lifetime registry, never a per-engine
169        // field (see `custom_fns` module docs): install the spec-defined XSD
170        // casts once — first install wins, later engines are no-ops.
171        crate::custom_fns::install_process_registry(Arc::new(CustomFunctions::with_builtins()));
172        Self {
173            hexastore,
174            registry,
175            router,
176            retry,
177            profile: Arc::new(RwLock::new(Arc::new(EngineProfile::default()))),
178            describe_mode: DescribeMode::Star,
179            path_pair_budget: PATH_PAIR_BUDGET,
180            open_star_pair_budget: OPEN_STAR_PAIR_BUDGET,
181            default_union: false,
182            seat_by_total_cost: false,
183            force_semi: false,
184            eager_scan_filter: true,
185            geo_index_epoch: None,
186            temporal_index_epoch: None,
187            text_index_epoch: None,
188            text_index_fingerprint: std::sync::Arc::from(""),
189            spill_root: None,
190            resolve_cache: ResolveCache::from_env(),
191        }
192    }
193
194    /// SPARQL default-graph fallback copied onto [`QueryContext`].
195    pub fn default_union(&self) -> bool {
196        self.default_union
197    }
198
199    /// Set the SPARQL default-graph fallback (`false` = RDF unnamed graph only).
200    pub fn set_default_union(&mut self, default_union: bool) {
201        self.default_union = default_union;
202    }
203
204    /// Seat inner joins by the total seating cost (`false` = legacy
205    /// `driver_cost` comparator; the shadow log is unaffected).
206    pub fn set_seat_by_total_cost(&mut self, seat_by_total_cost: bool) {
207        self.seat_by_total_cost = seat_by_total_cost;
208    }
209
210    /// Inner-join seating comparator currently configured.
211    pub fn seat_by_total_cost(&self) -> bool {
212        self.seat_by_total_cost
213    }
214
215    /// Benchmark switch: force `Semi` past a `PerPage` cost verdict.
216    pub fn set_force_semi(&mut self, force_semi: bool) {
217        self.force_semi = force_semi;
218    }
219
220    /// Whether scans stamp and apply slot comparisons.
221    pub fn eager_scan_filter(&self) -> bool {
222        self.eager_scan_filter
223    }
224
225    /// Test/benchmark switch for slot comparison pushdown and the eager scan
226    /// filter. Production leaves it on; the equivalence battery turns it off
227    /// to prove identical answers, and a benchmark uses it for the on/off
228    /// delta. Off is the pre-feature path: nothing is stamped, so no
229    /// comparison reaches the wire and every conjunct stays in the plan.
230    pub fn set_eager_scan_filter(&mut self, enabled: bool) {
231        self.eager_scan_filter = enabled;
232    }
233
234    /// Builder: SPARQL default-graph fallback.
235    pub fn with_default_union(mut self, default_union: bool) -> Self {
236        self.default_union = default_union;
237        self
238    }
239
240    /// Geo-index rebuild epoch copied onto [`QueryContext`].
241    pub fn geo_index_epoch(&self) -> Option<u64> {
242        self.geo_index_epoch
243    }
244
245    /// Set the geo-index rebuild epoch (`None` = trusted).
246    pub fn set_geo_index_epoch(&mut self, geo_index_epoch: Option<u64>) {
247        self.geo_index_epoch = geo_index_epoch;
248    }
249
250    /// Builder: geo-index rebuild epoch (`None` = trusted).
251    pub fn with_geo_index_epoch(mut self, geo_index_epoch: Option<u64>) -> Self {
252        self.geo_index_epoch = geo_index_epoch;
253        self
254    }
255
256    /// Temporal-index rebuild epoch copied onto [`QueryContext`].
257    pub fn temporal_index_epoch(&self) -> Option<u64> {
258        self.temporal_index_epoch
259    }
260
261    /// Set the temporal-index rebuild epoch (`None` = untrusted).
262    pub fn set_temporal_index_epoch(&mut self, temporal_index_epoch: Option<u64>) {
263        self.temporal_index_epoch = temporal_index_epoch;
264    }
265
266    /// Builder: temporal-index rebuild epoch (`None` = untrusted).
267    pub fn with_temporal_index_epoch(mut self, temporal_index_epoch: Option<u64>) -> Self {
268        self.temporal_index_epoch = temporal_index_epoch;
269        self
270    }
271
272    /// Text-index rebuild epoch copied onto [`QueryContext`] (`None` = untrusted).
273    pub fn text_index_epoch(&self) -> Option<u64> {
274        self.text_index_epoch
275    }
276
277    /// Set the text-index rebuild epoch and fingerprint.
278    pub fn set_text_index_state(
279        &mut self,
280        epoch: Option<u64>,
281        fingerprint: impl Into<std::sync::Arc<str>>,
282    ) {
283        self.text_index_epoch = epoch;
284        self.text_index_fingerprint = fingerprint.into();
285    }
286
287    /// Builder: text-index rebuild epoch + fingerprint (`None` = untrusted).
288    pub fn with_text_index_state(
289        mut self,
290        epoch: Option<u64>,
291        fingerprint: impl Into<std::sync::Arc<str>>,
292    ) -> Self {
293        self.set_text_index_state(epoch, fingerprint);
294        self
295    }
296
297    /// Spill root copied onto [`QueryContext`] (`None` = `std::env::temp_dir`).
298    pub fn spill_root(&self) -> Option<&std::path::Path> {
299        self.spill_root.as_deref()
300    }
301
302    /// Set the spill root copied onto each [`QueryContext`].
303    pub fn set_spill_root(&mut self, spill_root: Option<std::path::PathBuf>) {
304        self.spill_root = spill_root;
305    }
306
307    /// Builder: spill root copied onto each [`QueryContext`].
308    pub fn with_spill_root(mut self, spill_root: Option<std::path::PathBuf>) -> Self {
309        self.spill_root = spill_root;
310        self
311    }
312
313    /// Per-query context with this engine's `default_union`, spill root,
314    /// index epochs, and `snapshot`.
315    pub fn context(&self, snapshot: SnapshotId) -> QueryContext {
316        // Advisory snapshot of the rolled-up temporal histogram: the rewrite
317        // reads it for row estimates only (ordering, never pruning).
318        // Per-query snapshots are ARC CLONES of the rollup-time handles —
319        // never deep copies (the frame sketches are megabytes at real
320        // corpus scales; see the `profile` field doc).
321        let (histogram, geo_histogram, seed_sketch) = {
322            let state = self.profile.read().expect("stats profile lock");
323            (
324                state.temporal.clone(),
325                state.geo.clone(),
326                state.seed.clone(),
327            )
328        };
329        let mut ctx = QueryContext::from_engine(snapshot, self.default_union, self.geo_index_epoch)
330            .with_seat_by_total_cost(self.seat_by_total_cost)
331            .with_force_semi(self.force_semi)
332            .with_eager_scan_filter(self.eager_scan_filter)
333            .with_temporal_index_epoch(self.temporal_index_epoch)
334            .with_text_index_state(
335                self.text_index_epoch,
336                std::sync::Arc::clone(&self.text_index_fingerprint),
337            )
338            .with_temporal_histogram(histogram)
339            .with_geo_cell_histogram(geo_histogram)
340            .with_text_seed_sketch(seed_sketch);
341        if let Some(root) = self.spill_root.clone() {
342            ctx = ctx.with_spill_dir(root);
343        }
344        ctx
345    }
346
347    /// Distinct-pair circuit breaker for bound / one-end property paths.
348    pub fn path_pair_budget(&self) -> u64 {
349        self.path_pair_budget
350    }
351
352    /// Set the distinct-pair circuit breaker (default [`PATH_PAIR_BUDGET`]).
353    pub fn set_path_pair_budget(&mut self, budget: u64) {
354        self.path_pair_budget = budget.max(1);
355    }
356
357    /// Distinct-pair circuit breaker for `*` / `+` with no LIMIT.
358    pub fn open_star_pair_budget(&self) -> u64 {
359        self.open_star_pair_budget
360    }
361
362    /// Set the open-`*` / `+` pair budget (default [`OPEN_STAR_PAIR_BUDGET`]).
363    pub fn set_open_star_pair_budget(&mut self, budget: u64) {
364        self.open_star_pair_budget = budget.max(1);
365    }
366
367    /// DESCRIBE algorithm used by [`Self::query`].
368    pub fn describe_mode(&self) -> DescribeMode {
369        self.describe_mode
370    }
371
372    /// Set the DESCRIBE algorithm (`star` default).
373    pub fn set_describe_mode(&mut self, mode: DescribeMode) {
374        self.describe_mode = mode;
375    }
376
377    /// Builder: set the DESCRIBE algorithm.
378    pub fn with_describe_mode(mut self, mode: DescribeMode) -> Self {
379        self.describe_mode = mode;
380        self
381    }
382
383    /// Router used to pick an axis (and, later, a node) per scan.
384    pub fn router(&self) -> &Router {
385        &self.router
386    }
387
388    /// Hexastore clients.
389    pub fn hexastore(&self) -> &H {
390        &self.hexastore
391    }
392
393    /// Registry clients.
394    pub fn registry(&self) -> &R {
395        &self.registry
396    }
397
398    /// Replace the local sketch cache (tests / in-process push). The
399    /// whole [`EngineProfile`] is swapped as one new inner Arc — snapshots
400    /// taken by outstanding queries keep planning against the generation
401    /// they saw.
402    pub fn set_profile(&self, profile: StatsProfile) {
403        if let Ok(mut guard) = self.profile.write() {
404            *guard = Arc::new(EngineProfile::from(profile));
405        }
406    }
407
408    /// Cheap planning snapshot: one inner-Arc clone under the read lock.
409    /// The snapshot plans against its generation without holding the
410    /// lock — a concurrent rollup replaces the profile underneath, and
411    /// the outstanding query keeps advisory consistency (one rollup's
412    /// numbers for its whole plan, mixed with no other).
413    fn engine_profile(&self) -> Arc<EngineProfile> {
414        self.profile
415            .read()
416            .map(|guard| Arc::clone(&guard))
417            .unwrap_or_else(|_| Arc::new(EngineProfile::default()))
418    }
419
420    /// Snapshot of the local sketch cache (an owned deep copy — admin and
421    /// EXPLAIN paths, not the per-query hot path; see [`Self::engine_profile`]).
422    pub fn profile(&self) -> StatsProfile {
423        self.engine_profile().profile.clone()
424    }
425}
426
427/// One rollup's worth of profile state: the by-value `StatsProfile` every
428/// reader of the sketch cache expects, plus the frame sketches shared by
429/// ARCS so per-query contexts never deep-copy them (see the `profile`
430/// field doc on [`QueryEngine`]).
431#[derive(Debug, Default, Clone)]
432struct EngineProfile {
433    profile: StatsProfile,
434    temporal: Option<std::sync::Arc<waratah_stats::TickHistogram>>,
435    geo: Option<std::sync::Arc<waratah_stats::GeoCellHistogram>>,
436    seed: Option<std::sync::Arc<waratah_stats::TextSeedSketch>>,
437}
438
439impl From<StatsProfile> for EngineProfile {
440    fn from(profile: StatsProfile) -> Self {
441        let temporal = (profile.temporal_histogram.total_postings() > 0)
442            .then(|| std::sync::Arc::new(profile.temporal_histogram.clone()));
443        let geo = (!profile.geo_cell_histogram.is_empty())
444            .then(|| std::sync::Arc::new(profile.geo_cell_histogram.clone()));
445        let seed = (!profile.text_seed_sketch.is_empty())
446            .then(|| std::sync::Arc::new(profile.text_seed_sketch.clone()));
447        Self {
448            profile,
449            temporal,
450            geo,
451            seed,
452        }
453    }
454}
455
456impl QueryEngine<GrpcHexastoreClients, GrpcRegistryClients> {
457    /// Connect tonic clients for every address in `config`.
458    pub async fn connect(config: &ClusterConfig, retry: RetryPolicy) -> Result<Self, ComputeError> {
459        Ok(Self::new(
460            GrpcHexastoreClients::connect(config).await?,
461            GrpcRegistryClients::connect(config).await?,
462            config.router(ROUTER_VNODES)?,
463            retry,
464        ))
465    }
466}
467
468impl<H: HexastoreStats, R> QueryEngine<H, R> {
469    /// Pull shard profiles from S/P/O and roll up into the local cache.
470    ///
471    /// Because writes fan out to all three axes, roll-up prefers the O profile
472    /// rather than summing replicas. Named-graph count is taken from S.
473    /// The result is re-capped so a future with several same-axis shard
474    /// profiles (whose merge could union two capped HLL sets) still keeps
475    /// the planner cache bounded.
476    pub async fn refresh_stats(&self) -> Result<StatsProfile, ComputeError> {
477        let mut shards = Vec::with_capacity(3);
478        for axis in PartitionAxis::ALL {
479            let bytes = with_retry(
480                self.retry,
481                || self.hexastore.stats_profile(axis),
482                |attempts, message| ComputeError::HexastoreScan {
483                    axis,
484                    attempts,
485                    message,
486                },
487            )
488            .await?;
489            let mut profile = from_bytes(&bytes).map_err(|e| ComputeError::Stats(e.to_string()))?;
490            // The geo/temporal FRAMES arrive separately (one map per
491            // message, each under the gRPC ceiling with its own budget).
492            // Decode the section bytes and reassemble them INTO the axis
493            // profile in-memory, so `rollup_cluster` below merges them with
494            // its ordinary per-key algebra — a subset-populated section is
495            // a valid merge input by construction.
496            let fine = with_retry(
497                self.retry,
498                || {
499                    self.hexastore
500                        .geo_histogram(axis, waratah_proto::pb::GeoHistogramSection::Fine)
501                },
502                |attempts, message| ComputeError::HexastoreScan {
503                    axis,
504                    attempts,
505                    message,
506                },
507            )
508            .await?;
509            let coarse = with_retry(
510                self.retry,
511                || {
512                    self.hexastore
513                        .geo_histogram(axis, waratah_proto::pb::GeoHistogramSection::Coarse)
514                },
515                |attempts, message| ComputeError::HexastoreScan {
516                    axis,
517                    attempts,
518                    message,
519                },
520            )
521            .await?;
522            let temporal = with_retry(
523                self.retry,
524                || self.hexastore.temporal_histogram(axis),
525                |attempts, message| ComputeError::HexastoreScan {
526                    axis,
527                    attempts,
528                    message,
529                },
530            )
531            .await?;
532            let seed_sketch = with_retry(
533                self.retry,
534                || self.hexastore.text_seed_sketch(axis),
535                |attempts, message| ComputeError::HexastoreScan {
536                    axis,
537                    attempts,
538                    message,
539                },
540            )
541            .await?;
542            let mut fine_buf = fine.as_slice();
543            let mut coarse_buf = coarse.as_slice();
544            let mut temporal_buf = temporal.as_slice();
545            let mut seed_sketch_buf = seed_sketch.as_slice();
546            profile.geo_cell_histogram =
547                waratah_stats::GeoCellHistogram::decode_body(&mut fine_buf)
548                    .map_err(|e| ComputeError::Stats(e.to_string()))?;
549            profile.geo_cell_histogram.merge(
550                &waratah_stats::GeoCellHistogram::decode_body(&mut coarse_buf)
551                    .map_err(|e| ComputeError::Stats(e.to_string()))?,
552            );
553            profile.temporal_histogram =
554                waratah_stats::TickHistogram::decode_body(&mut temporal_buf)
555                    .map_err(|e| ComputeError::Stats(e.to_string()))?;
556            // Empty bytes = no trusted sketch; decode only non-empty frames
557            // so an absent sketch stays the merge identity.
558            if !seed_sketch_buf.is_empty() {
559                profile.text_seed_sketch =
560                    waratah_stats::TextSeedSketch::decode_body(&mut seed_sketch_buf)
561                        .map_err(|e| ComputeError::Stats(e.to_string()))?;
562            }
563            shards.push((axis, profile));
564        }
565        // Derive the per-predicate HLL domain caches here — the compute
566        // boundary, before the profile is visible to any query. Planning
567        // then reads u64 map entries instead of re-folding 4096-register
568        // sketches per estimate (hundreds of `cardinality()` calls per plan
569        // on the pre-cache LUBM cohort). Cost: one cardinality per surviving
570        // sketch per refresh — startup and post-ingest only, never per
571        // query.
572        let mut rolled = rollup_cluster(&shards);
573        // The rollup re-trims with the same double-trim discipline as the
574        // core: `capped_for_wire` empties geo/temporal (frame sections),
575        // so reattach the geo frames' own canonical trim and the temporal
576        // frame (bounded by construction, untrimmed) afterwards. The seed
577        // sketch rides the same treatment (own frame, trimmed at serve;
578        // the core cap empties it, reattach the fetched copy).
579        let geo = rolled.capped_geo_histogram_for_wire();
580        let temporal = std::mem::take(&mut rolled.temporal_histogram);
581        let seed_sketch = std::mem::take(&mut rolled.text_seed_sketch);
582        let mut profile = rolled.capped_for_wire();
583        profile.geo_cell_histogram = geo;
584        profile.temporal_histogram = temporal;
585        profile.text_seed_sketch = seed_sketch;
586        profile.derive_hll_domains();
587        self.set_profile(profile.clone());
588        Ok(profile)
589    }
590}
591
592impl<H: HexastoreScan + HexastoreCatalog + HexastoreGeo, R: StringResolve + BlobStoreClient>
593    QueryEngine<H, R>
594{
595    /// Parse, plan, execute, and materialize a SPARQL `SELECT`, `ASK`, `CONSTRUCT`, or `DESCRIBE`.
596    ///
597    /// The execution dataset is [`QueryDataset::resolve`] of `ctx` protocol
598    /// graph IRIs, the query's `FROM` / `FROM NAMED` clause, and
599    /// [`QueryContext::default_union`]. A dataset already stored on `ctx` is
600    /// replaced.
601    pub async fn query(
602        &self,
603        sparql: &str,
604        ctx: &QueryContext,
605    ) -> Result<QueryResults, ComputeError> {
606        match self.query_output(sparql, ctx).await? {
607            QueryOutput::Select(projected) => decode_projected(projected),
608            QueryOutput::Ready(results) => Ok(results),
609        }
610    }
611
612    /// Parse, plan, execute, and late-materialize SPARQL results.
613    ///
614    /// `SELECT` returns encoded projected columns plus the interned string map
615    /// from a registry resolve — not decoded `oxrdf` [`Term`]s. ASK / CONSTRUCT /
616    /// DESCRIBE return [`QueryOutput::Ready`].
617    ///
618    /// The execution dataset is [`QueryDataset::resolve`] of `ctx` protocol
619    /// graph IRIs, the query's `FROM` / `FROM NAMED` clause, and
620    /// [`QueryContext::default_union`]. A dataset already stored on `ctx` is
621    /// replaced.
622    pub async fn query_output(
623        &self,
624        sparql: &str,
625        ctx: &QueryContext,
626    ) -> Result<QueryOutput, ComputeError> {
627        // One refcount bump, not a StatsProfile deep copy: the snapshot
628        // carries the (fixed-size, but megabyte-scale) seed sketch that
629        // `profile()`'s owned clone would memcpy per query.
630        let engine_profile = self.engine_profile();
631        let profile = (!engine_profile.profile.is_empty()).then_some(&engine_profile.profile);
632        let parsed = crate::rephrase_error::parse_query_with_base(sparql, ctx.base_iri())?;
633        let dataset_clause = match &parsed {
634            Query::Ask { dataset, .. }
635            | Query::Select { dataset, .. }
636            | Query::Construct { dataset, .. }
637            | Query::Describe { dataset, .. } => dataset.as_ref(),
638        };
639        let dataset = QueryDataset::resolve(
640            ctx.protocol_default_graphs(),
641            ctx.protocol_named_graphs(),
642            dataset_clause,
643            ctx.default_union(),
644        )?;
645        let ctx_owned = ctx.clone().with_dataset(dataset);
646        let ctx = &ctx_owned;
647        let query_started = std::time::Instant::now();
648        // The engine-level ResolveCache counters accumulate for the process
649        // lifetime, but every other number on the `phases:` line describes
650        // THIS query — snapshot before execution and print the delta, so
651        // `cache=` reads as this query's own hits/misses. Exact only while
652        // queries do not overlap: concurrent queries share the one counter
653        // pair (as they share the cache itself).
654        let (rc_hits_before, rc_misses_before) = self.resolve_cache.stats();
655        let output = match parsed {
656            Query::Ask { pattern, .. } => {
657                let plan_started = std::time::Instant::now();
658                let plan = LogicalPlan::from_ask_algebra_with_ctx(pattern, profile, ctx)?;
659                ctx.perf().record_plan(plan_started.elapsed());
660                crate::plan::reserve_term_dict_from_plan(&plan, profile, ctx);
661                let mut cache = QueryCaches::new();
662                let execute_started = std::time::Instant::now();
663                let solutions = self.execute_with_cache(&plan, ctx, &mut cache).await?;
664                ctx.perf().record_execute(execute_started.elapsed());
665                ctx.check_abort()?;
666                QueryOutput::Ready(QueryResults::Boolean(!solutions.is_empty()))
667            }
668            Query::Select { pattern, .. } => {
669                let plan_started = std::time::Instant::now();
670                let plan = LogicalPlan::from_algebra_with_ctx(pattern, profile, ctx)?;
671                ctx.perf().record_plan(plan_started.elapsed());
672                crate::plan::reserve_term_dict_from_plan(&plan, profile, ctx);
673                let mut cache = QueryCaches::new();
674                let execute_started = std::time::Instant::now();
675                let solutions = self.execute_with_cache(&plan, ctx, &mut cache).await?;
676                ctx.perf().record_execute(execute_started.elapsed());
677                ctx.check_abort()?;
678                let materialize_started = std::time::Instant::now();
679                let output = self
680                    .resolve_projection(&plan.projection, &solutions, ctx, &cache)
681                    .await?;
682                ctx.perf().record_materialize(materialize_started.elapsed());
683                QueryOutput::Select(output)
684            }
685            Query::Construct {
686                template, pattern, ..
687            } => {
688                let compiled = compile_template(&template)?;
689                let plan_started = std::time::Instant::now();
690                let plan = LogicalPlan::from_algebra_with_ctx(pattern, profile, ctx)?;
691                ctx.perf().record_plan(plan_started.elapsed());
692                crate::plan::reserve_term_dict_from_plan(&plan, profile, ctx);
693                let mut cache = QueryCaches::new();
694                for (hash, raw) in compiled.strings() {
695                    cache.insert(*hash, raw.clone());
696                }
697                let execute_started = std::time::Instant::now();
698                let solutions = self.execute_with_cache(&plan, ctx, &mut cache).await?;
699                ctx.perf().record_execute(execute_started.elapsed());
700                let materialize_started = std::time::Instant::now();
701                let triples = emit_construct(&compiled, &solutions)?;
702                ctx.check_abort()?;
703                let graph = self.materialize_graph(&triples, ctx, &cache).await?;
704                ctx.perf().record_materialize(materialize_started.elapsed());
705                QueryOutput::Ready(graph)
706            }
707            Query::Describe { pattern, .. } => {
708                let plan_started = std::time::Instant::now();
709                let plan = LogicalPlan::from_algebra_with_ctx(pattern, profile, ctx)?;
710                ctx.perf().record_plan(plan_started.elapsed());
711                crate::plan::reserve_term_dict_from_plan(&plan, profile, ctx);
712                let mut cache = QueryCaches::new();
713                let execute_started = std::time::Instant::now();
714                let solutions = self.execute_with_cache(&plan, ctx, &mut cache).await?;
715                ctx.perf().record_execute(execute_started.elapsed());
716                let materialize_started = std::time::Instant::now();
717                let triples = self
718                    .describe_resources(&plan.projection, &solutions, ctx)
719                    .await?;
720                ctx.check_abort()?;
721                let graph = self.materialize_graph(&triples, ctx, &cache).await?;
722                ctx.perf().record_materialize(materialize_started.elapsed());
723                QueryOutput::Ready(graph)
724            }
725        };
726        ctx.check_cancelled()?;
727        let perf = ctx.perf();
728        let (rc_hits_now, rc_misses_now) = self.resolve_cache.stats();
729        let (cache_hits, cache_misses) = (
730            rc_hits_now.saturating_sub(rc_hits_before),
731            rc_misses_now.saturating_sub(rc_misses_before),
732        );
733        ctx.log(
734            LogLevel::Debug,
735            &format!(
736                "phases: total={:.3}s plan={:.3}s execute={:.3}s materialize={:.3}s \
737                 scans={:.3}s/{}rpcs scan_wall={:.3}s local={:.3}s \
738                 resolve={:.3}s/{}rpcs/{}hashes \
739                 custom_op={:.3}s/{}execs blobs={:.3}s/{}rpcs/{}payloads \
740                 geo_scan={:.3}s/{}drains/{}terms geo_memo={}hits \
741                 text_memo={}hits \
742                 text_subject={:.3}s/{}drains/{}rows/{}hits \
743                 cache={}/{}hits+misses",
744                query_started.elapsed().as_secs_f64(),
745                perf.plan_micros() as f64 / 1e6,
746                perf.execute_micros() as f64 / 1e6,
747                perf.materialize_micros() as f64 / 1e6,
748                perf.scan_micros() as f64 / 1e6,
749                perf.scan_rpcs(),
750                // Wall union of outstanding scan RPCs (overlaps counted once),
751                // then execute minus that union: the local join / group /
752                // parking time no scan RPC was pending.
753                perf.scan_wall_micros() as f64 / 1e6,
754                perf.execute_micros()
755                    .saturating_sub(perf.scan_wall_micros()) as f64
756                    / 1e6,
757                perf.resolve_micros() as f64 / 1e6,
758                perf.resolve_rpcs(),
759                perf.resolve_hashes(),
760                perf.custom_op_micros() as f64 / 1e6,
761                perf.custom_op_count(),
762                perf.blob_micros() as f64 / 1e6,
763                perf.blob_rpcs(),
764                perf.blob_payloads(),
765                perf.geo_scan_micros() as f64 / 1e6,
766                perf.geo_scan_count(),
767                perf.geo_scan_terms(),
768                // Windows the geo drain memo served without their RPC —
769                // with `geo_scan_count` above, a window's per-query drain
770                // count reads as drains + hits.
771                perf.geo_drain_memo_hits(),
772                // Candidate drains the text drain memo served without their
773                // RPC. The memo refuses a window larger than its per-entry
774                // term cap, so a drain above that cap re-fetches on every op
775                // execution; this counter is where that cost shows up (the
776                // gap between `custom_op` executions and these hits).
777                perf.text_drain_memo_hits(),
778                // Subject-form resolves and the windows their memo served
779                // without an RPC. A resolve above the memo's entry budget is
780                // refused and re-runs per execution; the gap between
781                // `custom_op` executions and these drains is where that
782                // shows up.
783                perf.text_subject_scan_micros() as f64 / 1e6,
784                perf.text_subject_scan_count(),
785                perf.text_subject_scan_rows(),
786                perf.text_subject_memo_hits(),
787                cache_hits,
788                cache_misses,
789            ),
790        );
791        Ok(output)
792    }
793
794    /// Count quads visible as of `snapshot` (unbound S/SPOG prefix count).
795    ///
796    /// Counts the default graph on the S axis. The partition walks SPOG locally
797    /// and returns a single integer; matching quads are not sent to compute.
798    pub async fn quad_count(&self, snapshot: SnapshotId) -> Result<u64, ComputeError> {
799        let pattern = EncodedTriplePattern {
800            subject: None,
801            predicate: None,
802            object: None,
803            graph_name: Some(EncodedTerm::DefaultGraph),
804        };
805        self.count_encoded_pattern(
806            &pattern,
807            snapshot,
808            PartitionAxis::S,
809            Some(IndexPermutation::Spog),
810        )
811        .await
812    }
813
814    /// Count quads matching `pattern` on `axis` without returning rows.
815    pub async fn count_encoded_pattern(
816        &self,
817        pattern: &EncodedTriplePattern,
818        snapshot: SnapshotId,
819        axis: PartitionAxis,
820        permutation: Option<IndexPermutation>,
821    ) -> Result<u64, ComputeError> {
822        with_retry(
823            self.retry,
824            || {
825                self.hexastore.count_pattern(
826                    axis,
827                    pattern,
828                    snapshot,
829                    0,
830                    permutation,
831                    None,
832                    None,
833                    false,
834                )
835            },
836            |attempts, message| ComputeError::HexastoreScan {
837                axis,
838                attempts,
839                message,
840            },
841        )
842        .await
843    }
844
845    /// Run a planned query, stopping before string materialization.
846    ///
847    /// The plan and `ctx` must agree on whether the eager scan filter runs:
848    /// planning deletes exact `FILTER` conjuncts into the scans' comparisons
849    /// when it runs, so a plan built that way cannot be executed with the
850    /// filter switched off. Plan under the executing context
851    /// (`LogicalPlan::parse_with_context`) when the filter setting differs
852    /// from the planner default.
853    pub async fn execute(
854        &self,
855        plan: &LogicalPlan,
856        ctx: &QueryContext,
857    ) -> Result<EncodedSolutions, ComputeError> {
858        let mut cache = QueryCaches::new();
859        self.execute_with_cache(plan, ctx, &mut cache).await
860    }
861
862    /// Diagnostic walker for the stamp-written-never-consumed probe: how
863    /// many `fetch_once` marks the tree about to execute carries. Coverage
864    /// mirrors `clear_fetch_once_marks` so the count and the stamp writer
865    /// see the same node set.
866    fn count_fetch_once_stamps(node: &PlanNode) -> usize {
867        match node {
868            PlanNode::Scan(scan) => usize::from(scan.fetch_once.is_some()),
869            PlanNode::Join { left, right, .. } | PlanNode::LeftJoin { left, right, .. } => {
870                Self::count_fetch_once_stamps(left) + Self::count_fetch_once_stamps(right)
871            }
872            PlanNode::Union { left, right } => {
873                Self::count_fetch_once_stamps(left) + Self::count_fetch_once_stamps(right)
874            }
875            PlanNode::CustomNode(op) => op.children.iter().map(Self::count_fetch_once_stamps).sum(),
876            PlanNode::Filter { inner, exists, .. } => {
877                Self::count_fetch_once_stamps(inner)
878                    + exists
879                        .iter()
880                        .map(|clause| Self::count_fetch_once_stamps(&clause.body))
881                        .sum::<usize>()
882            }
883            PlanNode::Extend { inner, .. }
884            | PlanNode::Slice { inner, .. }
885            | PlanNode::Distinct { inner, .. }
886            | PlanNode::Sort { inner, .. }
887            | PlanNode::Group { inner, .. }
888            | PlanNode::JoinGraphVar { inner, .. } => Self::count_fetch_once_stamps(inner),
889            PlanNode::SubSelect(sub) => Self::count_fetch_once_stamps(&sub.inner),
890            // Leaf nodes: DomainCounts/HeadCounts/PatternCount are count
891            // rewrites, NamedGraphs/NamedGraphExists are catalog leaves,
892            // Values/Unit carry no scans — stampable scans never hide
893            // below them.
894            PlanNode::DomainCounts { .. }
895            | PlanNode::HeadCounts { .. }
896            | PlanNode::PatternCount { .. }
897            | PlanNode::NamedGraphs { .. }
898            | PlanNode::NamedGraphExists { .. }
899            | PlanNode::Path(_)
900            | PlanNode::Values(_)
901            | PlanNode::Unit => 0,
902        }
903    }
904
905    async fn execute_with_cache(
906        &self,
907        plan: &LogicalPlan,
908        ctx: &QueryContext,
909        cache: &mut QueryCaches,
910    ) -> Result<EncodedSolutions, ComputeError> {
911        // A plan that deleted exact `FILTER` conjuncts into scan eager
912        // comparisons keeps those predicates only on the scans' `eager`
913        // lists. Running it with the eager filter off would return rows the
914        // deleted conjuncts rejected, so refuse the pairing rather than
915        // answer wrongly. `plan` and `ctx` agree whenever the same context
916        // planned and executes the query; only a caller pairing a plan with
917        // a different context can reach this.
918        if !ctx.eager_scan_filter() && plan.depends_on_eager_scan_filter() {
919            return Err(ComputeError::Internal(
920                "plan removed exact FILTER conjuncts into scan eager comparisons, but \
921                 execution disabled the eager scan filter; plan the query with the \
922                 context that executes it (LogicalPlan::parse_with_context)"
923                    .into(),
924            ));
925        }
926        // The root arm holds one slot of the per-query parallel-arm budget
927        // for the whole execution; each parallel fork holds its own extra
928        // slot. Concurrently evaluating plan arms therefore never exceed
929        // the pool ([`crate::context::arm_pool_permits`] — the engine's
930        // fetch concurrency plus this root hold). For a fresh per-query pool this
931        // permit is available immediately.
932        let _root_permit = ctx.acquire_arm_permit().await;
933        // Diagnostic (stamp-written-never-consumed): the planner wrote
934        // `fetch_once` marks that the executor's stamped branch did not
935        // consume on the bellendena-geo-100m q-control-three-way trace.
936        // Count what the EXECUTED tree actually carries so a lost mark
937        // (handoff) and a failed branch condition can be blamed
938        // separately: N=0 means the marks never reached execution;
939        // N>0 with `fetch-once-consume-skip` lines means they did and the
940        // branch declined.
941        let stamps = Self::count_fetch_once_stamps(&plan.root);
942        ctx.log(
943            LogLevel::Debug,
944            &format!("fetch-once-stamps in executed tree: {stamps}"),
945        );
946        self.execute_node(&plan.root, ctx, cache, None).await
947    }
948
949    /// Present named graphs at `ctx.snapshot` (S-axis catalog). Same cap as
950    /// [`PlanNode::NamedGraphs`]: refuse if the list exceeds
951    /// [`GRAPH_FILTER_TERM_CAP`]. Never includes the RDF default graph.
952    ///
953    /// Memoized on [`QueryContext`]: Collect `NamedGraphs` leaves and `*` / `?`
954    /// path identities share one RPC per query execute.
955    pub(crate) async fn list_catalog_named_graphs(
956        &self,
957        ctx: &QueryContext,
958    ) -> Result<Vec<EncodedTerm>, ComputeError> {
959        let graphs = ctx
960            .get_or_load_named_graphs(|| async {
961                let graphs = with_retry(
962                    self.retry,
963                    || self.hexastore.list_named_graphs(ctx.snapshot()),
964                    |attempts, message| ComputeError::NamedGraphCatalog { attempts, message },
965                )
966                .await?;
967                if graphs.len() > GRAPH_FILTER_TERM_CAP as usize {
968                    return Err(ComputeError::UnsupportedSparql(format!(
969                        "named graph catalog exceeds {GRAPH_FILTER_TERM_CAP} graphs"
970                    )));
971                }
972                Ok(graphs
973                    .into_iter()
974                    .filter(|graph| !matches!(graph, EncodedTerm::DefaultGraph))
975                    .collect())
976            })
977            .await?;
978        Ok(graphs.to_vec())
979    }
980    /// Resolve unique projected hashes, then drop unprojected join-key columns.
981    ///
982    /// This is the registry RPC half of late materialization. HTTP serializes
983    /// from the returned map; [`Self::materialize`] still decodes into owned
984    /// [`Term`]s for `query()` / CLI / compliance.
985    pub async fn resolve_projection(
986        &self,
987        projection: &[Variable],
988        solutions: &EncodedSolutions,
989        ctx: &QueryContext,
990        cache: &QueryCaches,
991    ) -> Result<ProjectedSolutions, ComputeError> {
992        let mut wanted: Vec<StrHash> = Vec::new();
993        let mut seen = new_str_hash_set();
994        let dict = solutions.dict();
995        for variable in projection {
996            let Some(column) = solutions.column(variable)? else {
997                continue;
998            };
999            for term in column.terms(&dict).into_iter().flatten() {
1000                for hash in hashes_in_term(&term) {
1001                    if cache.contains_key(&hash) {
1002                        continue;
1003                    }
1004                    if seen.insert(hash) {
1005                        wanted.push(hash);
1006                    }
1007                }
1008            }
1009        }
1010        wanted.sort_unstable();
1011
1012        let mut strings = self.resolve(&wanted, ctx).await?;
1013        for (hash, raw) in &cache.strings {
1014            strings.entry(*hash).or_insert_with(|| raw.clone());
1015        }
1016        // Render plugin-native geo terms into the same strings map (under
1017        // their deterministic keys) so HTTP serialization and owned decode
1018        // see one convention.
1019        let dict = solutions.dict();
1020        let mut geo_terms: Vec<EncodedTerm> = Vec::new();
1021        for variable in projection {
1022            if let Some(column) = solutions.column(variable)? {
1023                geo_terms.extend(column.terms(&dict).into_iter().flatten());
1024            }
1025        }
1026        // The projection's blob map starts empty: materialize files fetched
1027        // store payloads under the content address. Query-const payloads
1028        // are not copied here — nothing reads the projected map (output
1029        // decode uses strings; serialization reads strings), and the
1030        // query-local map remains the consts' only copy.
1031        let mut blobs = new_str_blob_map();
1032        materialize_geo_terms(self, geo_terms, &mut strings, &mut blobs, ctx).await?;
1033        let solutions = solutions.project_to(projection)?;
1034        Ok(ProjectedSolutions {
1035            variables: projection.to_vec(),
1036            solutions,
1037            strings,
1038            blobs,
1039        })
1040    }
1041
1042    /// Resolve the hashes of projected columns and rebuild `oxrdf` terms.
1043    ///
1044    /// Only projected variables reach the registry: intermediate join columns
1045    /// stay encoded for the whole query.
1046    pub async fn materialize(
1047        &self,
1048        projection: &[Variable],
1049        solutions: &EncodedSolutions,
1050        ctx: &QueryContext,
1051        cache: &QueryCaches,
1052    ) -> Result<QueryResults, ComputeError> {
1053        let projected = self
1054            .resolve_projection(projection, solutions, ctx, cache)
1055            .await?;
1056        decode_projected(projected)
1057    }
1058
1059    /// Resolve hashes in encoded triples and rebuild `oxrdf` [`Triple`]s.
1060    pub(super) async fn materialize_graph(
1061        &self,
1062        triples: &[EncodedTriple],
1063        ctx: &QueryContext,
1064        cache: &QueryCaches,
1065    ) -> Result<QueryResults, ComputeError> {
1066        let mut wanted: Vec<StrHash> = Vec::new();
1067        let mut seen = new_str_hash_set();
1068        for triple in triples {
1069            for term in [&triple.subject, &triple.predicate, &triple.object] {
1070                for hash in hashes_in_term(term) {
1071                    if cache.contains_key(&hash) {
1072                        continue;
1073                    }
1074                    if seen.insert(hash) {
1075                        wanted.push(hash);
1076                    }
1077                }
1078            }
1079        }
1080        wanted.sort_unstable();
1081
1082        let mut strings = self.resolve(&wanted, ctx).await?;
1083        for (hash, raw) in &cache.strings {
1084            strings.entry(*hash).or_insert_with(|| raw.clone());
1085        }
1086        let mut geo_terms: Vec<EncodedTerm> = Vec::new();
1087        for triple in triples {
1088            geo_terms.extend([
1089                triple.subject.clone(),
1090                triple.predicate.clone(),
1091                triple.object.clone(),
1092            ]);
1093        }
1094        // Same as the projection path: the CONSTRUCT blob map starts empty
1095        // and only carries materialize's fetched payloads (nothing reads
1096        // it — output decode uses strings).
1097        let mut blobs = new_str_blob_map();
1098        materialize_geo_terms(self, geo_terms, &mut strings, &mut blobs, ctx).await?;
1099
1100        let mut out = Vec::with_capacity(triples.len());
1101        for triple in triples {
1102            let subject = decode(&triple.subject, &strings)?;
1103            let predicate = decode(&triple.predicate, &strings)?;
1104            let object = decode(&triple.object, &strings)?;
1105            let Term::NamedNode(predicate) = predicate else {
1106                continue;
1107            };
1108            let subject = match subject {
1109                Term::NamedNode(node) => NamedOrBlankNode::from(node),
1110                Term::BlankNode(node) => NamedOrBlankNode::from(node),
1111                _ => continue,
1112            };
1113            out.push(Triple::new(subject, predicate, object));
1114        }
1115        Ok(QueryResults::Graph { triples: out })
1116    }
1117}
1118
1119impl<H, R: StringResolve> QueryEngine<H, R> {
1120    async fn resolve(
1121        &self,
1122        hashes: &[StrHash],
1123        ctx: &QueryContext,
1124    ) -> Result<StrHashMap, ComputeError> {
1125        if hashes.is_empty() {
1126            return Ok(new_str_hash_map());
1127        }
1128        let mut strings = new_str_hash_map();
1129        for chunk in hashes.chunks(RESOLVE_STRING_CHUNK) {
1130            // Resolve waterfall: compute-wide LRU first (hits refresh their
1131            // recency); only the misses go over the wire, still in sorted
1132            // order so the registry's seek walk stays forward-monotonic.
1133            let (mut hits, misses) = self.resolve_cache.probe(chunk);
1134            if misses.is_empty() {
1135                strings.extend(hits);
1136                continue;
1137            }
1138            let started = std::time::Instant::now();
1139            let resolved = with_retry(
1140                self.retry,
1141                || self.registry.resolve_strings(&misses),
1142                |attempts, message| ComputeError::ResolveStrings { attempts, message },
1143            )
1144            .await?;
1145            let elapsed = started.elapsed();
1146            ctx.perf().record_resolve(misses.len(), elapsed);
1147            ctx.log(
1148                LogLevel::Debug,
1149                &format!(
1150                    "resolve rpc: hashes={} elapsed={:.1}ms",
1151                    misses.len(),
1152                    elapsed.as_secs_f64() * 1e3
1153                ),
1154            );
1155            if resolved.len() != misses.len() {
1156                return Err(ComputeError::RegistryResponseLength {
1157                    got: resolved.len(),
1158                    want: misses.len(),
1159                });
1160            }
1161            // Cache only registered strings: unregistered hashes stay absent
1162            // so a later import remains visible to the next resolve.
1163            self.resolve_cache.insert(
1164                misses
1165                    .iter()
1166                    .zip(resolved.iter())
1167                    .filter_map(|(hash, raw)| raw.as_ref().map(|raw| (*hash, raw.clone()))),
1168            );
1169            for (hash, raw) in misses.into_iter().zip(resolved) {
1170                if let Some(raw) = raw {
1171                    hits.insert(hash, raw);
1172                }
1173            }
1174            strings.extend(hits);
1175        }
1176        Ok(strings)
1177    }
1178
1179    /// Resolve `hashes`, deduplicated and sorted (registry seek walks are
1180    /// forward-monotonic), returning one slot per input hash in input order.
1181    async fn resolve_values(
1182        &self,
1183        hashes: &[StrHash],
1184        ctx: &QueryContext,
1185    ) -> Result<Vec<Option<String>>, ComputeError> {
1186        if hashes.is_empty() {
1187            return Ok(Vec::new());
1188        }
1189        let mut unique = hashes.to_vec();
1190        unique.sort_unstable();
1191        unique.dedup();
1192        let map = self.resolve(&unique, ctx).await?;
1193        Ok(hashes.iter().map(|hash| map.get(hash).cloned()).collect())
1194    }
1195
1196    /// Aggregate argument variables are pre-resolved into the cache when the
1197    /// fold will decode them (`MIN`/`MAX` lexical comparison, `GROUP_CONCAT`
1198    /// concatenation, or a non-encodable argument expression). Purely encoded
1199    /// aggregates — `COUNT` over bound-ness and TermIds, `SUM`/`AVG` on
1200    /// native numerics — resolve nothing here, so a plain `COUNT(?o)` group
1201    /// query never touches the registry during aggregation.
1202    ///
1203    /// Geo lexicals are prefetched beside this (not here: this impl block is
1204    /// bounded only on `StringResolve`) by [`prefetch_aggregate_geo_lexicals`]
1205    /// in `eval_eager`, called next to this method before every folded batch.
1206    async fn resolve_aggregate_args(
1207        &self,
1208        solutions: &EncodedSolutions,
1209        aggregates: &[(Variable, spargebra::algebra::AggregateExpression)],
1210        seeds: ConstSeeds<'_>,
1211        ctx: &QueryContext,
1212        cache: &mut QueryCaches,
1213    ) -> Result<(), ComputeError> {
1214        // Plan-carried const seeds for the aggregate arguments (the same
1215        // contract as the Extend entry install): the fold evaluates
1216        // argument expressions on the encoded path and a const argument's
1217        // mint escapes into the group value. The install must precede the
1218        // variable-driven early return — a const-only argument has an
1219        // empty variable list and would otherwise skip its own seeding.
1220        // Repetition (per folded batch) is an idempotent flat merge.
1221        crate::query::caches::install_const_seeds(cache, seeds);
1222        let vars = Grouping::agg_arg_vars_maybe_need_resolve(aggregates);
1223        if vars.is_empty() || solutions.is_empty() {
1224            return Ok(());
1225        }
1226        let rows: Vec<usize> = (0..solutions.len()).collect();
1227        let window = residual_window();
1228        for chunk in rows.chunks(window) {
1229            let novel = novel_hashes_for_rows(solutions, chunk, &vars, cache)?;
1230            if novel.is_empty() {
1231                continue;
1232            }
1233            let values = self.resolve_values(&novel, ctx).await?;
1234            merge_resolved(cache, &novel, values);
1235        }
1236        Ok(())
1237    }
1238}
1239
1240/// Decode an encoded term to an owned [`Term`], resolving plugin-native
1241/// geo/blob literals through the strings map.
1242///
1243/// Geo terms carry their rendered lexical form under the deterministic key
1244/// from [`geo_lexical_key`] (see `materialize_geo_terms`); consumers recompute
1245/// the key from the term, so no geo identity leaks into the registry.
1246fn decode(term: &EncodedTerm, strings: &StrHashMap) -> Result<Term, ComputeError> {
1247    if matches!(
1248        term,
1249        EncodedTerm::LiteralPoint { .. }
1250            | EncodedTerm::LiteralGeometry { .. }
1251            | EncodedTerm::BlobLiteral { .. }
1252    ) {
1253        let key = geo_lexical_key(term).ok_or_else(|| {
1254            ComputeError::UnsupportedSparql("geo term without a lexical key".into())
1255        })?;
1256        let lexical = strings.get(&key).ok_or_else(|| {
1257            ComputeError::UnsupportedSparql(format!(
1258                "geo literal {} was not materialized (blob store or plugin missing?)",
1259                key
1260            ))
1261        })?;
1262        // The datatype rides the term itself.
1263        let datatype = crate::expr::encoded_datatype(term);
1264        let Some(EncodedTerm::NamedNode { iri_id }) = datatype else {
1265            return Err(ComputeError::UnsupportedSparql(
1266                "geo term datatype must be an IRI".into(),
1267            ));
1268        };
1269        let iri = well_known_iri(iri_id).unwrap_or("");
1270        let node = oxrdf::NamedNode::new(iri).map_err(|e| {
1271            ComputeError::UnsupportedSparql(format!("geo datatype IRI {iri:?}: {e}"))
1272        })?;
1273        return Ok(Term::Literal(oxrdf::Literal::new_typed_literal(
1274            lexical.as_str(),
1275            node.as_ref(),
1276        )));
1277    }
1278    Ok(decode_term(term, strings)?)
1279}
1280
1281/// Render every distinct plugin-native geo term of `terms` into `strings`
1282/// under its [`geo_lexical_key`], fetching blob payloads for blob-backed
1283/// terms through the process LRU over the registry. A strings hit skips
1284/// the fetch: query consts are seeded under the same key at mint, and
1285/// stored terms already materialized stay materialized. Fetched payloads
1286/// land in `blobs` under the term's `blob_id`, uniformly content-addressed
1287/// with the map's other inhabitants. Called
1288/// on projected columns before serialization.
1289async fn materialize_geo_terms(
1290    engine: &QueryEngine<impl crate::clients::HexastoreGeo, impl crate::clients::BlobStoreClient>,
1291    terms: impl IntoIterator<Item = EncodedTerm>,
1292    strings: &mut StrHashMap,
1293    blobs: &mut StrBlobMap,
1294    ctx: &QueryContext,
1295) -> Result<(), ComputeError> {
1296    let mut points: Vec<EncodedTerm> = Vec::new();
1297    let mut blob_terms: Vec<EncodedTerm> = Vec::new();
1298    for term in terms {
1299        match &term {
1300            EncodedTerm::LiteralPoint { .. } => points.push(term),
1301            EncodedTerm::LiteralGeometry { .. } | EncodedTerm::BlobLiteral { .. } => {
1302                blob_terms.push(term);
1303            }
1304            _ => {}
1305        }
1306    }
1307    let registry = crate::plugin::process_plugins();
1308    if registry.is_empty() {
1309        return Ok(());
1310    }
1311    for term in points {
1312        let key = geo_lexical_key(&term).expect("point key");
1313        if strings.contains_key(&key) {
1314            continue;
1315        }
1316        if let Some(lexical) = crate::plugin::decode_user_literal(&term, None) {
1317            strings.insert(key, lexical);
1318        }
1319    }
1320    let mut fetch_terms: Vec<EncodedTerm> = Vec::new();
1321    for term in blob_terms {
1322        let key = geo_lexical_key(&term).expect("blob key");
1323        // A strings hit covers query consts (seeded under this key at op
1324        // entry / template compile time) and already-materialized stored
1325        // terms; everything else takes the batched store fetch below.
1326        // Query-const payloads are content-addressed binary in the blob
1327        // map — they never carried lexical text, so there is no
1328        // payload-sniff fast path to consult here.
1329        if strings.contains_key(&key) {
1330            continue;
1331        }
1332        fetch_terms.push(term);
1333    }
1334    if !fetch_terms.is_empty() {
1335        // Fetch by the terms' actual blob ids (the registry's content
1336        // addresses) — NOT by the lexical key, which is derived from the
1337        // full term because distinct terms can share one blob.
1338        let ids: Vec<StrHash> = fetch_terms
1339            .iter()
1340            .map(|term| match term {
1341                EncodedTerm::LiteralGeometry { blob_id, .. }
1342                | EncodedTerm::BlobLiteral { blob_id, .. } => *blob_id,
1343                _ => unreachable!("only blob-backed terms are fetched"),
1344            })
1345            .collect();
1346        let payloads = engine.blob_payloads(&ids, ctx).await?;
1347        for (term, payload) in fetch_terms.iter().zip(payloads) {
1348            let key = geo_lexical_key(term).expect("blob key");
1349            let Some(payload) = payload else {
1350                return Err(ComputeError::UnsupportedSparql(format!(
1351                    "blob {term:?} missing from the registry blob store",
1352                )));
1353            };
1354            // Payloads file under the content address — uniform with the
1355            // const-payload copy that pre-seeded this map; lexicals under
1356            // the geo key.
1357            let blob_id = match term {
1358                EncodedTerm::LiteralGeometry { blob_id, .. }
1359                | EncodedTerm::BlobLiteral { blob_id, .. } => *blob_id,
1360                _ => unreachable!("only blob-backed terms are fetched"),
1361            };
1362            blobs.insert(blob_id, payload.clone());
1363            if let Some(lexical) = crate::plugin::decode_user_literal(term, Some(&payload)) {
1364                strings.insert(key, lexical);
1365            }
1366        }
1367    }
1368    Ok(())
1369}
1370
1371fn decode_projected(projected: ProjectedSolutions) -> Result<QueryResults, ComputeError> {
1372    let ProjectedSolutions {
1373        variables,
1374        solutions,
1375        strings,
1376        blobs: _,
1377    } = projected;
1378    let decoded = solutions
1379        .optional_rows()?
1380        .into_iter()
1381        .map(|row| {
1382            row.into_iter()
1383                .map(|term| term.map(|term| decode(&term, &strings)).transpose())
1384                .collect::<Result<Vec<Option<Term>>, ComputeError>>()
1385        })
1386        .collect::<Result<Vec<_>, ComputeError>>()?;
1387    Ok(QueryResults::Solutions {
1388        variables,
1389        solutions: decoded,
1390    })
1391}
1392
1393#[cfg(test)]
1394mod spill_root_tests {
1395    use super::*;
1396    use crate::query::fixtures::NullResolve;
1397
1398    fn engine() -> QueryEngine<(), NullResolve> {
1399        QueryEngine::new(
1400            (),
1401            NullResolve,
1402            ClusterConfig::local_dev().router(16).unwrap(),
1403            RetryPolicy::none(),
1404        )
1405    }
1406
1407    #[test]
1408    fn engine_spill_root_is_copied_onto_contexts() {
1409        let root =
1410            std::env::temp_dir().join(format!("waratah-engine-spill-{}", std::process::id()));
1411        let configured = engine().with_spill_root(Some(root.clone()));
1412        let ctx = configured.context(SnapshotId::latest());
1413        assert_eq!(ctx.spill_dir(), Some(&root));
1414
1415        // Without a root the context falls back to temp_dir at spill time and
1416        // reports no override.
1417        let plain = engine().context(SnapshotId::latest());
1418        assert!(plain.spill_dir().is_none());
1419    }
1420
1421    #[test]
1422    fn engine_spill_root_setter_round_trips() {
1423        let mut engine = engine();
1424        assert!(engine.spill_root().is_none());
1425        let root = std::env::temp_dir();
1426        engine.set_spill_root(Some(root.clone()));
1427        assert_eq!(engine.spill_root(), Some(root.as_path()));
1428        engine.set_spill_root(None);
1429        assert!(engine.spill_root().is_none());
1430    }
1431}
1432
1433#[cfg(test)]
1434mod resolve_chunk_tests {
1435    use super::*;
1436    use std::sync::{Arc, Mutex};
1437
1438    struct RecordingResolve {
1439        batches: Arc<Mutex<Vec<usize>>>,
1440    }
1441
1442    impl StringResolve for RecordingResolve {
1443        async fn resolve_strings(
1444            &self,
1445            hashes: &[StrHash],
1446        ) -> Result<Vec<Option<String>>, tonic::Status> {
1447            self.batches.lock().expect("batch log").push(hashes.len());
1448            Ok(hashes.iter().map(|_| None).collect())
1449        }
1450    }
1451
1452    #[tokio::test]
1453    async fn resolve_splits_hashes_above_chunk() {
1454        let batches = Arc::new(Mutex::new(Vec::new()));
1455        let engine = QueryEngine::new(
1456            (),
1457            RecordingResolve {
1458                batches: batches.clone(),
1459            },
1460            ClusterConfig::local_dev().router(16).unwrap(),
1461            RetryPolicy::none(),
1462        );
1463        let hashes: Vec<StrHash> = (0..=RESOLVE_STRING_CHUNK)
1464            .map(|i| StrHash::new(&format!("http://ex/chunk-test-iri-{i}")))
1465            .collect();
1466        let map = engine
1467            .resolve(
1468                &hashes,
1469                &QueryContext::from_snapshot(waratah_storage::SnapshotId::latest()),
1470            )
1471            .await
1472            .unwrap();
1473        assert!(map.is_empty());
1474        assert_eq!(
1475            batches.lock().expect("batch log").as_slice(),
1476            &[RESOLVE_STRING_CHUNK, 1]
1477        );
1478    }
1479}
1480
1481/// Engine-level tests for the compute-wide resolve LRU (waratah_compute's
1482/// cross-query string cache). The registry mock returns canned strings and
1483/// records every RPC, so hits/misses are observable end to end.
1484#[cfg(test)]
1485mod resolve_cache_engine_tests {
1486    use super::*;
1487    use spargebra::algebra::{AggregateExpression, AggregateFunction};
1488    use std::sync::{Arc, Mutex};
1489
1490    struct CannedResolve {
1491        calls: Arc<Mutex<Vec<usize>>>,
1492    }
1493
1494    impl StringResolve for CannedResolve {
1495        async fn resolve_strings(
1496            &self,
1497            hashes: &[StrHash],
1498        ) -> Result<Vec<Option<String>>, tonic::Status> {
1499            self.calls.lock().expect("call log").push(hashes.len());
1500            Ok(hashes
1501                .iter()
1502                .map(|hash| Some(format!("http://ex/resolved-{}", hash.as_u128())))
1503                .collect())
1504        }
1505    }
1506
1507    fn engine_with_call_log(calls: Arc<Mutex<Vec<usize>>>) -> QueryEngine<(), CannedResolve> {
1508        QueryEngine::new(
1509            (),
1510            CannedResolve { calls },
1511            ClusterConfig::local_dev().router(16).unwrap(),
1512            RetryPolicy::none(),
1513        )
1514    }
1515
1516    #[tokio::test]
1517    async fn repeat_resolve_is_served_from_the_cache_without_an_rpc() {
1518        let calls = Arc::new(Mutex::new(Vec::new()));
1519        let engine = engine_with_call_log(calls.clone());
1520        let ctx = QueryContext::from_snapshot(waratah_storage::SnapshotId::latest());
1521        let hashes: Vec<StrHash> = (0..3)
1522            .map(|i| StrHash::new(&format!("http://ex/cache-test-{i}")))
1523            .collect();
1524
1525        let first = engine.resolve(&hashes, &ctx).await.unwrap();
1526        let second = engine.resolve(&hashes, &ctx).await.unwrap();
1527
1528        // The registry saw exactly one RPC; the second resolve came from the
1529        // compute-wide LRU and returned identical strings.
1530        assert_eq!(calls.lock().expect("call log").as_slice(), &[3]);
1531        for hash in &hashes {
1532            assert_eq!(first.get(hash), second.get(hash));
1533            assert!(second.contains_key(hash));
1534        }
1535    }
1536
1537    #[tokio::test]
1538    async fn uncached_hashes_still_reach_the_registry() {
1539        let calls = Arc::new(Mutex::new(Vec::new()));
1540        let engine = engine_with_call_log(calls.clone());
1541        let ctx = QueryContext::from_snapshot(waratah_storage::SnapshotId::latest());
1542        let cached: Vec<StrHash> = (0..2)
1543            .map(|i| StrHash::new(&format!("http://ex/warm-{i}")))
1544            .collect();
1545        let _ = engine.resolve(&cached, &ctx).await.unwrap();
1546
1547        // One cached hash + one never-resolved hash: only the latter is sent.
1548        let mixed = vec![cached[0], StrHash::new("http://ex/never-seen")];
1549        let _ = engine.resolve(&mixed, &ctx).await.unwrap();
1550        assert_eq!(calls.lock().expect("call log").as_slice(), &[2, 1]);
1551
1552        // The unregistered hash is absent from the result (no negative
1553        // caching), and the cached one is served from the cache.
1554        let (hits, misses) = engine.resolve_cache.stats();
1555        assert_eq!(
1556            (hits, misses),
1557            (1, 3),
1558            "misses: 2 first resolve + never-seen; hits: cached[0] on the second resolve"
1559        );
1560    }
1561    #[tokio::test]
1562    async fn count_aggregation_resolves_no_argument_strings() {
1563        // GROUP BY ?p { COUNT(?o) }: the fold counts bound-ness of
1564        // encoded TermIds, so the aggregate arg (?o) is never
1565        // resolved — no matter how many distinct objects the scan carries.
1566        let calls = Arc::new(Mutex::new(Vec::new()));
1567        let engine = engine_with_call_log(calls.clone());
1568        let ctx = QueryContext::from_snapshot(waratah_storage::SnapshotId::latest());
1569        let rows: Vec<Vec<Option<EncodedTerm>>> = (0..5)
1570            .map(|i| {
1571                vec![
1572                    Some(EncodedTerm::from(
1573                        &waratah_storage::NamedNode::new(format!("http://ex/p{i}")).unwrap(),
1574                    )),
1575                    Some(EncodedTerm::from(
1576                        &waratah_storage::NamedNode::new(format!("http://ex/o{i}")).unwrap(),
1577                    )),
1578                ]
1579            })
1580            .collect();
1581        let solutions = EncodedSolutions::from_optional_rows(
1582            ctx.term_dict(),
1583            vec![Variable::new("p").unwrap(), Variable::new("o").unwrap()],
1584            rows,
1585        )
1586        .unwrap();
1587        let aggregates = vec![(
1588            Variable::new("count").unwrap(),
1589            AggregateExpression::FunctionCall {
1590                name: AggregateFunction::Count,
1591                expr: spargebra::algebra::Expression::Variable(Variable::new("o").unwrap()),
1592                distinct: false,
1593            },
1594        )];
1595        let mut cache = QueryCaches::new();
1596        engine
1597            .resolve_aggregate_args(
1598                &solutions,
1599                &aggregates,
1600                crate::query::caches::ConstSeeds::EMPTY,
1601                &ctx,
1602                &mut cache,
1603            )
1604            .await
1605            .unwrap();
1606        assert!(
1607            calls.lock().expect("call log").is_empty(),
1608            "COUNT never decodes its argument: zero registry RPCs"
1609        );
1610
1611        // MIN over the same column compares hash-encoded strings lexically:
1612        // that genuinely decodes, so the arg hashes are resolved.
1613        let min_agg = vec![(
1614            Variable::new("min").unwrap(),
1615            AggregateExpression::FunctionCall {
1616                name: AggregateFunction::Min,
1617                expr: spargebra::algebra::Expression::Variable(Variable::new("o").unwrap()),
1618                distinct: false,
1619            },
1620        )];
1621        engine
1622            .resolve_aggregate_args(
1623                &solutions,
1624                &min_agg,
1625                crate::query::caches::ConstSeeds::EMPTY,
1626                &ctx,
1627                &mut cache,
1628            )
1629            .await
1630            .unwrap();
1631        assert!(!calls.lock().expect("call log").is_empty());
1632    }
1633}
1634
1635#[cfg(test)]
1636mod refresh_stats_cache_tests {
1637    use super::*;
1638
1639    struct StatsHexastore {
1640        bytes: Vec<u8>,
1641        /// FINE-frame section bytes (subset-populated; empty sections mean
1642        /// "no geo mass", matching the memory-partition doubles).
1643        geo_fine: Vec<u8>,
1644        /// COARSE-frame section bytes.
1645        geo_coarse: Vec<u8>,
1646        /// Temporal-frame section bytes.
1647        temporal: Vec<u8>,
1648        /// Per-axis seed-sketch frame: served to this axis only, EMPTY
1649        /// bytes to the others (the partition convention: every axis
1650        /// answers, only O can carry a collected sidecar).
1651        seed_frame: Option<(PartitionAxis, Vec<u8>)>,
1652    }
1653
1654    impl StatsHexastore {
1655        /// Core bytes plus merge-identity frame sections (no geo/temporal
1656        /// mass) — the "stats collector absent" shape.
1657        fn core(bytes: Vec<u8>) -> Self {
1658            let mut fine = Vec::new();
1659            waratah_stats::GeoCellHistogram::default().encode_body(&mut fine);
1660            let mut coarse = Vec::new();
1661            waratah_stats::GeoCellHistogram::default().encode_body(&mut coarse);
1662            let mut temporal = Vec::new();
1663            waratah_stats::TickHistogram::default().encode_body(&mut temporal);
1664            StatsHexastore {
1665                bytes,
1666                geo_fine: fine,
1667                geo_coarse: coarse,
1668                temporal,
1669                seed_frame: None,
1670            }
1671        }
1672
1673        /// Core bytes plus a seed-sketch frame served to ONE axis (empty
1674        /// bytes to the others) — the real cluster's shape.
1675        fn seeded(bytes: Vec<u8>, axis: PartitionAxis, sketch: Vec<u8>) -> Self {
1676            let mut double = Self::core(bytes);
1677            double.seed_frame = Some((axis, sketch));
1678            double
1679        }
1680    }
1681
1682    impl HexastoreStats for StatsHexastore {
1683        async fn stats_profile(&self, _axis: PartitionAxis) -> Result<Vec<u8>, tonic::Status> {
1684            Ok(self.bytes.clone())
1685        }
1686
1687        // Frame bytes by section; refresh_stats never requests
1688        // UNSPECIFIED, so the double refuses it rather than guessing.
1689        async fn geo_histogram(
1690            &self,
1691            _axis: PartitionAxis,
1692            section: waratah_proto::pb::GeoHistogramSection,
1693        ) -> Result<Vec<u8>, tonic::Status> {
1694            Ok(match section {
1695                waratah_proto::pb::GeoHistogramSection::Fine => self.geo_fine.clone(),
1696                waratah_proto::pb::GeoHistogramSection::Coarse => self.geo_coarse.clone(),
1697                other => unreachable!("test double asked for {other:?}"),
1698            })
1699        }
1700
1701        async fn temporal_histogram(&self, _axis: PartitionAxis) -> Result<Vec<u8>, tonic::Status> {
1702            Ok(self.temporal.clone())
1703        }
1704
1705        async fn text_seed_sketch(&self, axis: PartitionAxis) -> Result<Vec<u8>, tonic::Status> {
1706            // Per-axis frames; default is the all-empty shape (no sketch —
1707            // the planner keeps its unpriced estimate).
1708            Ok(match &self.seed_frame {
1709                Some((frame_axis, bytes)) if *frame_axis == axis => bytes.clone(),
1710                _ => Vec::new(),
1711            })
1712        }
1713    }
1714
1715    #[tokio::test]
1716    async fn refresh_stats_derives_both_hll_domain_caches() {
1717        let pred = StrHash::new("http://ex/refresh-cache");
1718        let mut source = StatsProfile {
1719            total_puts: 100,
1720            ..StatsProfile::default()
1721        };
1722        source.predicate_counts.insert(pred, 100);
1723        let mut subjects = waratah_stats::HyperLogLog::default_params();
1724        for i in 0..64u128 {
1725            subjects.add(i);
1726        }
1727        let mut objects = waratah_stats::HyperLogLog::default_params();
1728        for i in 0..16u128 {
1729            objects.add(i);
1730        }
1731        source.subjects_per_predicate.insert(pred, subjects);
1732        source.objects_per_predicate.insert(pred, objects);
1733        let expected_subject = source.subjects_per_predicate[&pred].cardinality().max(1);
1734        let expected_object = source.objects_per_predicate[&pred].cardinality().max(1);
1735
1736        let engine = QueryEngine::new(
1737            StatsHexastore::core(waratah_stats::to_bytes(&source)),
1738            (),
1739            ClusterConfig::local_dev().router(16).unwrap(),
1740            RetryPolicy::none(),
1741        );
1742        let refreshed = engine.refresh_stats().await.unwrap();
1743        assert_eq!(
1744            refreshed.subject_domains_per_predicate.get(&pred).copied(),
1745            Some(expected_subject),
1746            "refresh_stats must derive the subject cardinality cache"
1747        );
1748        assert_eq!(
1749            refreshed.object_domains_per_predicate.get(&pred).copied(),
1750            Some(expected_object),
1751            "refresh_stats must derive the object cardinality cache"
1752        );
1753        let cached = engine.profile();
1754        assert_eq!(
1755            cached.subject_domains_per_predicate.get(&pred).copied(),
1756            Some(expected_subject),
1757            "the engine profile must carry the derived subject cache"
1758        );
1759        assert_eq!(
1760            cached.object_domains_per_predicate.get(&pred).copied(),
1761            Some(expected_object),
1762            "the engine profile must carry the derived object cache"
1763        );
1764    }
1765
1766    /// The per-axis sketch contract end-to-end: O carries the collected
1767    /// sidecar bytes, the other axes answer EMPTY bytes (the partition
1768    /// convention — an error on any axis aborts the whole refresh), and
1769    /// the rolled profile still carries the O sketch epoch-trusted for the
1770    /// planner (`rollup_cluster` prefers O; empty frames stay the merge
1771    /// identity).
1772    #[tokio::test]
1773    async fn refresh_stats_takes_the_seed_sketch_from_the_o_axis_alone() {
1774        let mut sketch = waratah_stats::TextSeedSketch::collector(16);
1775        for i in 0..50u64 {
1776            sketch.record(&format!("eco{i:04}"));
1777        }
1778        sketch.epoch = 7;
1779        let mut sketch_bytes = Vec::new();
1780        sketch.encode_body(&mut sketch_bytes);
1781        let source = StatsProfile {
1782            total_puts: 10,
1783            ..StatsProfile::default()
1784        };
1785        let engine = QueryEngine::new(
1786            StatsHexastore::seeded(
1787                waratah_stats::to_bytes(&source),
1788                PartitionAxis::O,
1789                sketch_bytes,
1790            ),
1791            (),
1792            ClusterConfig::local_dev().router(16).unwrap(),
1793            RetryPolicy::none(),
1794        );
1795        let refreshed = engine.refresh_stats().await.unwrap();
1796        assert_eq!(
1797            refreshed.text_seed_sketch.epoch, 7,
1798            "the O-axis sketch must survive the rollup"
1799        );
1800        assert!(
1801            refreshed.text_seed_sketch.prices_at(Some(7)),
1802            "planner-visible and epoch-trusted"
1803        );
1804    }
1805
1806    /// The frame transport's end-to-end assembly: geo mass travels ONLY in
1807    /// the fine/coarse frames (the core blob carries empty sections), and
1808    /// `refresh_stats` reassembles it into the rolled profile — no
1809    /// double-count through a core-embedded map, no lost mass through a
1810    /// dropped frame.
1811    #[tokio::test]
1812    async fn refresh_stats_reassembles_geo_frames_into_the_rolled_profile() {
1813        let mut source = StatsProfile {
1814            total_puts: 10,
1815            ..StatsProfile::default()
1816        };
1817        // Fine mass in two buckets; coarse mass as one level-8 count-once
1818        // posting. The double slices the canonical trim into the same
1819        // subset-populated frames the partition handler produces.
1820        *source.geo_cell_histogram.fine.entry(7).or_insert(0) += 3;
1821        *source.geo_cell_histogram.fine.entry(9).or_insert(0) += 1;
1822        source
1823            .geo_cell_histogram
1824            .observe_posting(1u64 << (60 - 2 * 8));
1825        let canonical = source.capped_geo_histogram_for_wire();
1826        let fine_frame = waratah_stats::GeoCellHistogram {
1827            coarse: std::collections::BTreeMap::new(),
1828            ..canonical.clone()
1829        };
1830        let coarse_frame = waratah_stats::GeoCellHistogram {
1831            fine: std::collections::BTreeMap::new(),
1832            remainder: std::collections::BTreeMap::new(),
1833            ..canonical.clone()
1834        };
1835        let mut fine_bytes = Vec::new();
1836        fine_frame.encode_body(&mut fine_bytes);
1837        let mut coarse_bytes = Vec::new();
1838        coarse_frame.encode_body(&mut coarse_bytes);
1839        let mut temporal_bytes = Vec::new();
1840        waratah_stats::TickHistogram::default().encode_body(&mut temporal_bytes);
1841
1842        // The CORE blob must not carry the geo mass (the double serves the
1843        // trimmed core, exactly like both real transports).
1844        let core = source.capped_for_wire();
1845        assert!(
1846            core.geo_cell_histogram.is_empty(),
1847            "the core blob's geo section is empty — frames carry it"
1848        );
1849
1850        let engine = QueryEngine::new(
1851            StatsHexastore {
1852                bytes: waratah_stats::to_bytes(&core),
1853                geo_fine: fine_bytes,
1854                geo_coarse: coarse_bytes,
1855                temporal: temporal_bytes,
1856                seed_frame: None,
1857            },
1858            (),
1859            ClusterConfig::local_dev().router(16).unwrap(),
1860            RetryPolicy::none(),
1861        );
1862        let refreshed = engine.refresh_stats().await.unwrap();
1863        assert_eq!(
1864            refreshed.geo_cell_histogram, canonical,
1865            "the rolled profile carries exactly the frames' canonical trim"
1866        );
1867    }
1868}