1use 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
90const ROUTER_VNODES: u32 = 16;
92
93#[derive(Debug, Clone)]
95pub struct QueryEngine<H, R> {
96 hexastore: H,
97 registry: R,
98 router: Router,
99 retry: RetryPolicy,
100 profile: Arc<RwLock<Arc<EngineProfile>>>,
112 describe_mode: DescribeMode,
113 path_pair_budget: u64,
115 open_star_pair_budget: u64,
117 default_union: bool,
123 seat_by_total_cost: bool,
127 force_semi: bool,
130 eager_scan_filter: bool,
135 geo_index_epoch: Option<u64>,
140 temporal_index_epoch: Option<u64>,
145 text_index_epoch: Option<u64>,
149 text_index_fingerprint: std::sync::Arc<str>,
153 spill_root: Option<std::path::PathBuf>,
159 resolve_cache: Arc<ResolveCache>,
163}
164
165impl<H, R> QueryEngine<H, R> {
166 pub fn new(hexastore: H, registry: R, router: Router, retry: RetryPolicy) -> Self {
168 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 pub fn default_union(&self) -> bool {
196 self.default_union
197 }
198
199 pub fn set_default_union(&mut self, default_union: bool) {
201 self.default_union = default_union;
202 }
203
204 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 pub fn seat_by_total_cost(&self) -> bool {
212 self.seat_by_total_cost
213 }
214
215 pub fn set_force_semi(&mut self, force_semi: bool) {
217 self.force_semi = force_semi;
218 }
219
220 pub fn eager_scan_filter(&self) -> bool {
222 self.eager_scan_filter
223 }
224
225 pub fn set_eager_scan_filter(&mut self, enabled: bool) {
231 self.eager_scan_filter = enabled;
232 }
233
234 pub fn with_default_union(mut self, default_union: bool) -> Self {
236 self.default_union = default_union;
237 self
238 }
239
240 pub fn geo_index_epoch(&self) -> Option<u64> {
242 self.geo_index_epoch
243 }
244
245 pub fn set_geo_index_epoch(&mut self, geo_index_epoch: Option<u64>) {
247 self.geo_index_epoch = geo_index_epoch;
248 }
249
250 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 pub fn temporal_index_epoch(&self) -> Option<u64> {
258 self.temporal_index_epoch
259 }
260
261 pub fn set_temporal_index_epoch(&mut self, temporal_index_epoch: Option<u64>) {
263 self.temporal_index_epoch = temporal_index_epoch;
264 }
265
266 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 pub fn text_index_epoch(&self) -> Option<u64> {
274 self.text_index_epoch
275 }
276
277 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 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 pub fn spill_root(&self) -> Option<&std::path::Path> {
299 self.spill_root.as_deref()
300 }
301
302 pub fn set_spill_root(&mut self, spill_root: Option<std::path::PathBuf>) {
304 self.spill_root = spill_root;
305 }
306
307 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 pub fn context(&self, snapshot: SnapshotId) -> QueryContext {
316 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 pub fn path_pair_budget(&self) -> u64 {
349 self.path_pair_budget
350 }
351
352 pub fn set_path_pair_budget(&mut self, budget: u64) {
354 self.path_pair_budget = budget.max(1);
355 }
356
357 pub fn open_star_pair_budget(&self) -> u64 {
359 self.open_star_pair_budget
360 }
361
362 pub fn set_open_star_pair_budget(&mut self, budget: u64) {
364 self.open_star_pair_budget = budget.max(1);
365 }
366
367 pub fn describe_mode(&self) -> DescribeMode {
369 self.describe_mode
370 }
371
372 pub fn set_describe_mode(&mut self, mode: DescribeMode) {
374 self.describe_mode = mode;
375 }
376
377 pub fn with_describe_mode(mut self, mode: DescribeMode) -> Self {
379 self.describe_mode = mode;
380 self
381 }
382
383 pub fn router(&self) -> &Router {
385 &self.router
386 }
387
388 pub fn hexastore(&self) -> &H {
390 &self.hexastore
391 }
392
393 pub fn registry(&self) -> &R {
395 &self.registry
396 }
397
398 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 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 pub fn profile(&self) -> StatsProfile {
423 self.engine_profile().profile.clone()
424 }
425}
426
427#[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 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 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 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 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 let mut rolled = rollup_cluster(&shards);
573 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 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 pub async fn query_output(
623 &self,
624 sparql: &str,
625 ctx: &QueryContext,
626 ) -> Result<QueryOutput, ComputeError> {
627 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 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 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 perf.geo_drain_memo_hits(),
772 perf.text_drain_memo_hits(),
778 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 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 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 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 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 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 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 let _root_permit = ctx.acquire_arm_permit().await;
933 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 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 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 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 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 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 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 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 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 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 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 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 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
1240fn 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 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
1281async 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 if strings.contains_key(&key) {
1330 continue;
1331 }
1332 fetch_terms.push(term);
1333 }
1334 if !fetch_terms.is_empty() {
1335 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 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 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#[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 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 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 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 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 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 geo_fine: Vec<u8>,
1644 geo_coarse: Vec<u8>,
1646 temporal: Vec<u8>,
1648 seed_frame: Option<(PartitionAxis, Vec<u8>)>,
1652 }
1653
1654 impl StatsHexastore {
1655 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 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 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 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 #[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 #[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 *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 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}