Skip to main content

waratah_stats/
profile.rs

1//! Cluster/shard statistical profile and selectivity helpers.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use waratah_storage::{EncodedTriplePattern, PartitionAxis, RDF_TYPE, StrHash};
6
7use crate::cms::CountMinSketch;
8use crate::hll::HyperLogLog;
9use crate::observe::{named_node_hash, term_key};
10
11/// The **wire/terms limit** of the pushdown family: the maximum number of
12/// distinct terms one broadcast allow-list may carry in a single request
13/// or admission decision. Historically this doubled as the **driver page
14/// cut** (the eager left-chunk size `driver_chunk_rows` clamps to, the
15/// driver's rows-per-page pacing), which is why the name still reads as a
16/// row bound — see the coupling note at `JoinStrategy` and the sites that
17/// share the value.
18///
19/// Modern consumers of the limit as terms (the reason the name gained
20/// its current form — this number used to be called
21/// `BROADCAST_ROW_THRESHOLD` and that name read rows where the semantics
22/// are terms): the `Threshold` push gate's over-threshold drop
23/// (`PushedKeyVals::combine` / `join_keys_scan_filter`), the per-chunk
24/// term slices of the parallel pushdown transport, the subtree push
25/// gate's `Hostable` verdicts, `slice_chunk_filters` chunk sizing, and
26/// the wire-budget boundary guard (`assert_wire_budget` in the compute
27/// request builders — a detector, not a delivery mechanism: the plain
28/// whole-read road delivers an over-threshold list through the chunked
29/// transport, while the roads that bypass that hook ship their lists
30/// as-is today, so clustered-safe delivery there is follow-up work).
31/// One number serves
32/// both roles **by design**: a driver page cut at N rows holds at most N
33/// distinct terms, so single-page lists satisfy the terms limit by
34/// construction — that is the coupling the strategy stamp and the page
35/// cuts rely on ("over-threshold lists arise from join products", not
36/// from driver pages).
37pub const PUSHDOWN_TERMS_LIMIT: u64 = 24_576;
38
39/// Maximum encoded graphs in a scan `graph_filter` allow-list.
40pub const GRAPH_FILTER_TERM_CAP: u64 = 10_000;
41
42/// Serialized-size ceiling for one profile crossing the wire
43/// (`GetStatsProfile`), with headroom under the 4 MiB gRPC message limit
44/// for response framing.
45///
46/// Core budget: fixed parts + CMS + exact maps + the per-predicate HLL
47/// pairs, ranked largest-exact-count first. The geo cell-count histogram
48/// and temporal histogram no longer carve into this budget — each rides
49/// its own transport frame with its own budget (`GetGeoHistogram`
50/// fine/coarse, `GetTemporalHistogram`), so the core budget spends
51/// entirely on the hexastore sketches.
52///
53/// The exact predicate/class maps and the per-predicate HLL pairs both
54/// grow with the predicate namespace, but at very different rates: 24
55/// B/entry for the exact maps versus ~8.2 KB/predicate for HLL pairs at
56/// precision 12 — ~340× faster. The HLL pairs cross this wire budget at
57/// a few hundred predicates and the gRPC message ceiling itself at ~500;
58/// the exact maps alone would need ~170k predicates to reach the
59/// ceiling, far past the architecture's bounded-predicate-namespace
60/// assumption (a dataset that pathological also breaks
61/// [`StatsProfile::capped_for_wire`], which never trims the fixed
62/// parts). The exact counts are load-bearing regardless: they rank the
63/// HLL retention, and the estimator's HLL fan-out path requires a
64/// present exact count, so dropping them would neuter the sketches that
65/// are kept.
66pub const STATS_WIRE_BUDGET_BYTES: usize = 3 * 1024 * 1024;
67
68/// The geo histogram FINE frame's budget for its fine map (`GetGeoHistogram`
69/// section FINE). At 8 bytes per kept entry this buys ~229k buckets; heavier
70/// occupancy degrades through the remainder summary (parent averages), not
71/// through missing estimates. The remainder summary rides the SAME message
72/// under its OWN budget ([`GEO_REMAINDER_WIRE_BUDGET_BYTES`]) — the two
73/// budgets are INDEPENDENT and ADDITIVE, so a saturated FINE message is
74/// 1.75 MiB + 512 KiB = 2.25 MiB (an earlier
75/// "remainder carved inside / 3.5 MiB total" reading was wrong;
76/// `geo_frames_at_saturation_stay_under_the_message_ceiling` pins the real
77/// bound). Every message stays individually under the shared 4 MiB gRPC
78/// ceiling: worst case across the stat messages is FINE 2.25 MiB, COARSE
79/// 1.75 MiB, core 3 MiB, temporal ~100 KiB.
80pub const GEO_FINE_FRAME_BUDGET_BYTES: usize = 1792 * 1024;
81
82/// The geo histogram COARSE frame's own budget (`GetGeoHistogram` section
83/// COARSE: the native-id count-once map, levels 0–8 post-2026-10). At 12
84/// bytes per kept entry this buys ~149k coarse postings — an order of
85/// headroom over the census-measured population (~40k entries on
86/// bellendena-geo-10m, levels 0–8 inclusive). Over budget the map
87/// rank-keeps (count descending, id ascending) and the dropped tail reads
88/// EMPTY — the ONE down-biased trim in the package; see
89/// [`GeoCellHistogram::capped_coarse_map`] for the caveat and the
90/// coarse-side-summary escape hatch if a corpus ever saturates this.
91pub const GEO_COARSE_FRAME_BUDGET_BYTES: usize = 1792 * 1024;
92
93/// Budget for the geo histogram's remainder summary — the per-L8-parent
94/// dropped-mass entries. INDEPENDENT of and ADDITIVE to the fine-map
95/// budget: `capped_for_wire(fine, remainder)` enforces each separately, so
96/// a saturated FINE frame carries 1.75 MiB of fine map PLUS up to 512 KiB
97/// of remainder (2.25 MiB total, still under the 4 MiB per-message gRPC
98/// ceiling). The remainder's key space is the FULL L8 parent grid
99/// (6 × 4^8 = 393,216 ≈ 6.3 MB untrimmed at global density), so it obeys
100/// the same rank-and-keep discipline as the fine map: largest-total
101/// parents first, and beyond this budget the smallest-mass parents are
102/// dropped and read EMPTY — a bounded under-estimate on the advisory path
103/// (§10: estimates order plans, never prune; SPARQL results are unaffected).
104pub const GEO_REMAINDER_WIRE_BUDGET_BYTES: usize = 512 * 1024;
105
106/// Which unbound term slot carries a join key for HLL domain lookup.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum JoinKeySlot {
109    /// Join variable is the subject of the pattern.
110    Subject,
111    /// Join variable is the object of the pattern.
112    Object,
113}
114
115/// S/P/O slots treated as bound for costing without a ground term.
116///
117/// LeftJoin incoming join keys occupy a variable slot that execution will
118/// allow-list. Do not invent a CMS key; use HLL fan-out under the bound
119/// predicate instead. Incoming-bound `?p` (no IRI) uses mean `|P|`
120/// (`total_puts / |predicate_counts|`).
121#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
122pub struct ExtraBoundSlots {
123    /// Subject variable is bound by an outer join key.
124    pub subject: bool,
125    /// Predicate variable is bound by an outer join key.
126    pub predicate: bool,
127    /// Object variable is bound by an outer join key.
128    pub object: bool,
129    /// Graph variable is bound by an outer join key (`GRAPH ?g` / VALUES).
130    pub graph: bool,
131}
132
133impl ExtraBoundSlots {
134    /// Number of extra bound slots (0–4).
135    pub fn count(self) -> usize {
136        usize::from(self.subject)
137            + usize::from(self.predicate)
138            + usize::from(self.object)
139            + usize::from(self.graph)
140    }
141}
142
143/// Physical join hint chosen at plan time (Phase 9b executes broadcast/shuffle).
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum JoinStrategy {
146    /// Compute-side hash join (Phase 6 default).
147    Hash,
148    /// Small build side → broadcast allow-list to storage (Phase 9b).
149    Broadcast,
150    /// Both sides large → shuffle by join key (Phase 9b).
151    Shuffle,
152    /// General semi join: build one key set from the right side — a scan or
153    /// a subtree — and keep only the left rows whose key is present, emitting
154    /// the left columns. This is the umbrella strategy: the [`Self::SemiScan`]
155    /// special case claims a key-unique scan whose fetch-once verdict chose
156    /// the whole read, and the general road builds from whatever the
157    /// promotion left, scan or subtree.
158    /// Never returned by [`JoinStrategy::from_cardinalities_and_domains`].
159    Semi,
160    /// Scan-source semi join: the right is a single scan whose `fetch_once`
161    /// verdict already chose the whole read, and the scan is key-unique with
162    /// no payload beyond the key. The kernel is
163    /// [`waratah_exec::SemiJoinSet`], the one `FILTER EXISTS` already uses.
164    /// Key-uniqueness is the row-multiplicity proof: a repeated right key
165    /// multiplies every left column, and a plain `COUNT` of a left column
166    /// observes that multiplication, so a bag mark on the key alone is not
167    /// enough. The cost is the verdict's build side, never a cardinality
168    /// choice. Never returned by
169    /// [`JoinStrategy::from_cardinalities_and_domains`].
170    SemiScan,
171}
172
173impl JoinStrategy {
174    /// Pick a strategy from estimated left/right row counts (no HLL domain).
175    pub fn from_cardinalities(left: u64, right: u64) -> Self {
176        Self::from_estimated_sizes(left, right)
177    }
178
179    /// Prefer distinct join-key domains when known; broadcast pushes the key set.
180    ///
181    /// Domain estimates are capped by row counts (`min(domain, rows)`) so a
182    /// selective prior scan cannot be inflated by a global predicate HLL.
183    pub fn from_cardinalities_and_domains(
184        left_rows: u64,
185        right_rows: u64,
186        left_domain: Option<u64>,
187        right_domain: Option<u64>,
188    ) -> Self {
189        let left = match left_domain {
190            Some(d) => d.min(left_rows).max(1),
191            None => left_rows,
192        };
193        let right = match right_domain {
194            Some(d) => d.min(right_rows).max(1),
195            None => right_rows,
196        };
197        Self::from_estimated_sizes(left, right)
198    }
199
200    fn from_estimated_sizes(left: u64, right: u64) -> Self {
201        // [`PUSHDOWN_TERMS_LIMIT`] doubles as the driver-rows bound by the
202        // shared-value design (a page cut at ≤ N rows satisfies the
203        // terms limit by construction).
204        //
205        // `Semi` is deliberately absent from this choice: it is not a size
206        // verdict. The planner promotes a join to `Semi` only after the
207        // fetch-once price (`fetch_once_verdict`) has chosen the whole
208        // right-side read and liveness has proved the right contributes no
209        // live column, so the row counts alone cannot decide it.
210        if left > 0 && left <= PUSHDOWN_TERMS_LIMIT {
211            Self::Broadcast
212        } else if right > 0 && right <= PUSHDOWN_TERMS_LIMIT {
213            // Probe-side small: keep Hash (broadcast expects a small *left* build).
214            Self::Hash
215        } else if left > PUSHDOWN_TERMS_LIMIT && right > PUSHDOWN_TERMS_LIMIT {
216            Self::Shuffle
217        } else {
218            Self::Hash
219        }
220    }
221}
222
223/// Mergeable statistical profile for one shard or the whole cluster.
224///
225/// # Equality caveat
226///
227/// The derived [`PartialEq`] / [`Eq`] compares the HLL cardinality cache maps
228/// too. Those maps are derived state (see [`Self::derive_hll_domains`]), so two
229/// profiles with identical sketches but different cache states compare
230/// unequal — for example, a `serde_bin` round trip (empty caches) versus a
231/// `refresh_stats` profile (derived caches). For "same statistics" checks,
232/// compare the sketch/count fields or derive both sides first; do not treat a
233/// whole-profile `==` across a decode/derive boundary as statistical equality.
234#[derive(Debug, Clone, PartialEq, Eq)]
235pub struct StatsProfile {
236    /// Approximate total `Put` observations in this profile.
237    pub total_puts: u64,
238    /// Exact predicate frequencies (named-node predicates).
239    pub predicate_counts: BTreeMap<StrHash, u64>,
240    /// Exact `rdf:type` class instance counts (named-node classes only).
241    pub class_counts: BTreeMap<StrHash, u64>,
242    /// Subject frequency CMS.
243    pub subject_cms: CountMinSketch,
244    /// Object frequency CMS.
245    pub object_cms: CountMinSketch,
246    /// Distinct subjects per predicate (joint S–P cardinality).
247    pub subjects_per_predicate: BTreeMap<StrHash, HyperLogLog>,
248    /// Distinct objects per predicate (joint P–O cardinality).
249    pub objects_per_predicate: BTreeMap<StrHash, HyperLogLog>,
250    /// HLL cardinality cache for [`Self::subjects_per_predicate`]:
251    /// `cardinality().max(1)` per sketch, materialized by
252    /// [`Self::derive_hll_domains`] at the compute boundary
253    /// (`waratah_compute`'s stats rollup). NOT serialized: profiles decoded
254    /// from bytes or built by hand carry empty maps, and the
255    /// [`Self::subject_domain`] / [`Self::object_domain`] helpers fall back
256    /// to computing on the fly (correct, just uncached). Cleared by
257    /// [`Self::merge`], [`rollup_cluster`], and
258    /// [`Self::capped_for_wire_with_budget`] — a merged or trimmed sketch is
259    /// not the sketch the cached number came from, so an inherited value
260    /// would be silently wrong. Direct mutation of
261    /// [`Self::subjects_per_predicate`] or [`Self::objects_per_predicate`]
262    /// likewise invalidates these maps; call [`Self::derive_hll_domains`]
263    /// after such edits.
264    pub subject_domains_per_predicate: BTreeMap<StrHash, u64>,
265    /// Precomputed distinct counts for [`Self::objects_per_predicate`] —
266    /// see [`Self::subject_domains_per_predicate`].
267    pub object_domains_per_predicate: BTreeMap<StrHash, u64>,
268    /// Exact count of named graphs whose newest catalog version is `Present`.
269    ///
270    /// S-axis only (`named_graphs_catalog` CF). P/O profiles leave this at 0.
271    /// [`rollup_cluster`] copies the S value onto the preferred axis profile.
272    pub named_graph_count: u64,
273    /// Sparse dyadic histogram over the temporal tick axis (postings of the
274    /// O-axis `temporal_index` CF). Collected on the O partition only; the
275    /// estimator consumes it for `temporal_scan` window row counts —
276    /// advisory, never pruning (see [`crate::tick_histogram`]).
277    pub temporal_histogram: crate::tick_histogram::TickHistogram,
278    /// Sparse level-11 cell-count histogram over the geo index (postings of
279    /// the O-axis `geo_index` CF). Collected on the O partition only; the
280    /// estimator consumes it for `GeoCandidateScan` covering row counts —
281    /// advisory, never pruning (see [`crate::geo_cell_histogram`]).
282    pub geo_cell_histogram: crate::geo_cell_histogram::GeoCellHistogram,
283    /// Pruned count tries over the text index's seed fields (posting
284    /// counts of first-`seed_chars` and reversed last-`seed_chars`
285    /// characters per indexed literal). Collected on the O partition only,
286    /// at text rebuild finish, stamped with the index's build epoch; the
287    /// text planner consumes it for candidate-drain estimates — advisory,
288    /// never pruning (see [`crate::text_seed_sketch::TextSeedSketch`]).
289    pub text_seed_sketch: crate::text_seed_sketch::TextSeedSketch,
290}
291
292impl Default for StatsProfile {
293    fn default() -> Self {
294        Self {
295            total_puts: 0,
296            predicate_counts: BTreeMap::new(),
297            class_counts: BTreeMap::new(),
298            subject_cms: CountMinSketch::default_params(),
299            object_cms: CountMinSketch::default_params(),
300            subjects_per_predicate: BTreeMap::new(),
301            objects_per_predicate: BTreeMap::new(),
302            subject_domains_per_predicate: BTreeMap::new(),
303            object_domains_per_predicate: BTreeMap::new(),
304            named_graph_count: 0,
305            temporal_histogram: crate::tick_histogram::TickHistogram::default(),
306            geo_cell_histogram: crate::geo_cell_histogram::GeoCellHistogram::default(),
307            text_seed_sketch: crate::text_seed_sketch::TextSeedSketch::empty(),
308        }
309    }
310}
311
312impl StatsProfile {
313    /// Whether the profile carries a row sketch for `pattern`'s bound named
314    /// predicate — the evidence [`estimate_pattern`] consults for such a
315    /// pattern. A never-observed predicate estimates as **1** (see that
316    /// function's doc), not unknown, so fetch-once pricing must not treat a
317    /// non-empty profile that lacks this key as evidence for the arm's size.
318    /// A pattern without a bound named predicate prices from the store-level
319    /// uniform model ([`StatsProfile::total_puts`]), which any non-empty
320    /// profile carries.
321    pub fn has_predicate_sketch(&self, pattern: &EncodedTriplePattern) -> bool {
322        match pattern.predicate.as_ref().and_then(named_node_hash) {
323            Some(pred) => self.predicate_counts.contains_key(&pred),
324            None => true,
325        }
326    }
327
328    /// Whether this profile has observed any puts or named graphs.
329    pub fn is_empty(&self) -> bool {
330        self.total_puts == 0
331            && self.predicate_counts.is_empty()
332            && self.class_counts.is_empty()
333            && self.named_graph_count == 0
334    }
335    /// Copy truncated to serialize within [`STATS_WIRE_BUDGET_BYTES`].
336    ///
337    /// CORE-ONLY since the frame split: the geo cell-count histogram and
338    /// the temporal histogram sections arrive EMPTY (they travel in their
339    /// own frames — see [`Self::capped_geo_histogram_for_wire`]), and the
340    /// per-predicate HLL pairs are ranked-trimmed: the LARGEST predicates
341    /// by exact count are kept first (the ranking is free —
342    /// `predicate_counts` is in the same profile) until the budget, and the
343    /// smallest are dropped. The estimator's absent-entry contract makes
344    /// this safe: a dropped HLL skips the fan-out candidate and degrades the
345    /// join domain to the existing fallbacks, and because distinct counts
346    /// never exceed row counts, the single-pattern estimate can only
347    /// overestimate — bounded by the predicate's own (small) count. Fixed
348    /// parts are always kept; SST blobs and shard merges stay
349    /// full-fidelity, so nothing here is lossy for merging — trim only at
350    /// transport boundaries.
351    pub fn capped_for_wire(&self) -> Self {
352        self.capped_for_wire_with_budget(STATS_WIRE_BUDGET_BYTES)
353    }
354
355    /// The geo cell-count histogram trimmed for its TWO transport frames
356    /// (`GetGeoHistogram`): the fine map under
357    /// [`GEO_FINE_FRAME_BUDGET_BYTES`] PLUS the remainder summary under its
358    /// own [`GEO_REMAINDER_WIRE_BUDGET_BYTES`] — independent, ADDITIVE
359    /// budgets, so a saturated FINE message is 2.25 MiB (1.75 fine + 0.5
360    /// remainder); coarse under [`GEO_COARSE_FRAME_BUDGET_BYTES`]
361    /// (rank-and-keep, drop-tail reads empty — the package's one
362    /// down-biased trim; see [`GeoCellHistogram::capped_coarse_map`]).
363    /// Every message stays individually under the shared 4 MiB gRPC
364    /// ceiling.
365    ///
366    /// ONE canonical trim both transport sides share: the partition
367    /// handlers slice the FINE / COARSE frames out of this, and the
368    /// compute rollup re-trims the merged frames with the same budgets —
369    /// the same double-trim discipline the core profile has always had.
370    pub fn capped_geo_histogram_for_wire(&self) -> crate::geo_cell_histogram::GeoCellHistogram {
371        let mut trimmed = self.geo_cell_histogram.capped_for_wire(
372            crate::GEO_FINE_FRAME_BUDGET_BYTES,
373            crate::GEO_REMAINDER_WIRE_BUDGET_BYTES,
374        );
375        trimmed.coarse = self
376            .geo_cell_histogram
377            .capped_coarse_map(crate::GEO_COARSE_FRAME_BUDGET_BYTES);
378        trimmed
379    }
380
381    /// [`Self::capped_for_wire`] under an explicit byte budget (tests).
382    ///
383    /// CORE-ONLY since the frame split: the geo cell-count histogram and
384    /// the temporal histogram arrive EMPTY — they travel in their own
385    /// frames with their own budgets (see
386    /// [`Self::capped_geo_histogram_for_wire`]); the whole core budget
387    /// spends on fixed parts + CMS + exact maps + the HLL pairs.
388    pub fn capped_for_wire_with_budget(&self, budget: usize) -> Self {
389        let mut capped = self.clone();
390        capped.subjects_per_predicate.clear();
391        capped.objects_per_predicate.clear();
392        capped.geo_cell_histogram = crate::geo_cell_histogram::GeoCellHistogram::default();
393        capped.text_seed_sketch = crate::text_seed_sketch::TextSeedSketch::empty();
394        capped.temporal_histogram = crate::tick_histogram::TickHistogram::default();
395        // `capped` no longer carries geo or temporal sections, so the
396        // measured blob is fixed-parts alone.
397        let fixed_bytes = crate::serde_bin::to_bytes(&capped).len();
398        let mut remaining = budget.saturating_sub(fixed_bytes);
399
400        // Rank predicates present in either HLL map: exact count descending
401        // (predicates deleted to zero rank last), hash ascending so the
402        // truncation point is deterministic.
403        let mut ranked: Vec<(StrHash, u64)> = self
404            .subjects_per_predicate
405            .keys()
406            .chain(self.objects_per_predicate.keys())
407            .collect::<BTreeSet<_>>()
408            .into_iter()
409            .map(|hash| (*hash, self.predicate_counts.get(hash).copied().unwrap_or(0)))
410            .collect();
411        ranked.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
412
413        for (hash, _) in ranked {
414            let cost = hll_wire_entry_bytes(self.subjects_per_predicate.get(&hash))
415                + hll_wire_entry_bytes(self.objects_per_predicate.get(&hash));
416            if cost > remaining {
417                // Largest first: once a pair no longer fits, stop.
418                break;
419            }
420            if let Some(hll) = self.subjects_per_predicate.get(&hash) {
421                capped.subjects_per_predicate.insert(hash, hll.clone());
422            }
423            if let Some(hll) = self.objects_per_predicate.get(&hash) {
424                capped.objects_per_predicate.insert(hash, hll.clone());
425            }
426            remaining -= cost;
427        }
428        // The clone carried any caller-populated HLL cardinality cache, but
429        // the cap just changed which sketches survive — drop it; the compute
430        // boundary re-derives over exactly this trimmed set
431        // (`derive_hll_domains`).
432        capped.subject_domains_per_predicate.clear();
433        capped.object_domains_per_predicate.clear();
434        capped
435    }
436
437    /// Materialize the HLL cardinality cache from the sketch maps.
438    ///
439    /// Cost: one [`HyperLogLog::cardinality`] per surviving sketch — bounded
440    /// by the wire cap (~3 MiB / ~8.5 KB per subject+object pair ≈ 370
441    /// predicates) regardless of dataset size, i.e. low single-digit
442    /// milliseconds once per refresh. Callers: compute's stats rollup
443    /// (`waratah_compute::query::refresh_stats`), right after
444    /// [`Self::capped_for_wire`], before the profile becomes visible to any
445    /// query — never on the query path. [`Self::merge`], [`rollup_cluster`],
446    /// and the cap clear the maps so a stale cardinality can never survive a
447    /// merge or trim.
448    pub fn derive_hll_domains(&mut self) {
449        self.subject_domains_per_predicate = self
450            .subjects_per_predicate
451            .iter()
452            .map(|(hash, hll)| (*hash, hll.cardinality().max(1)))
453            .collect();
454        self.object_domains_per_predicate = self
455            .objects_per_predicate
456            .iter()
457            .map(|(hash, hll)| (*hash, hll.cardinality().max(1)))
458            .collect();
459    }
460
461    /// Distinct subjects of the predicate `hash`, from the HLL cardinality
462    /// cache when the profile carries one, else computed on the fly.
463    ///
464    /// The fallback keeps hand-built and decoded profiles (empty caches —
465    /// the maps are not serialized) correct at today's per-call cost;
466    /// refresh-derived profiles answer from a `u64` map hit. `None` when
467    /// the profile has no subject sketch for this predicate — identical to
468    /// the sketch maps' own missing-entry contract.
469    pub fn subject_domain(&self, hash: &StrHash) -> Option<u64> {
470        if let Some(domain) = self.subject_domains_per_predicate.get(hash) {
471            return Some(*domain);
472        }
473        Some(self.subjects_per_predicate.get(hash)?.cardinality().max(1))
474    }
475
476    /// [`Self::subject_domain`] for the objects-per-predicate sketch.
477    pub fn object_domain(&self, hash: &StrHash) -> Option<u64> {
478        if let Some(domain) = self.object_domains_per_predicate.get(hash) {
479            return Some(*domain);
480        }
481        Some(self.objects_per_predicate.get(hash)?.cardinality().max(1))
482    }
483
484    /// Algebraic merge (CMS add, HLL register-max, exact maps sum).
485    pub fn merge(&mut self, other: &Self) -> Result<(), crate::StatsError> {
486        // Any merge changes HLL registers (`register-max`), so cardinalities
487        // cached from either input no longer describe this profile. Clear
488        // both maps before touching the sketches; a caller that wants the
489        // cache back re-derives it with `derive_hll_domains`. Without this,
490        // a clone-then-merge would freeze the pre-merge domains.
491        self.subject_domains_per_predicate.clear();
492        self.object_domains_per_predicate.clear();
493        self.total_puts = self.total_puts.saturating_add(other.total_puts);
494        for (k, v) in &other.predicate_counts {
495            *self.predicate_counts.entry(*k).or_insert(0) = self
496                .predicate_counts
497                .get(k)
498                .copied()
499                .unwrap_or(0)
500                .saturating_add(*v);
501        }
502        for (k, v) in &other.class_counts {
503            *self.class_counts.entry(*k).or_insert(0) = self
504                .class_counts
505                .get(k)
506                .copied()
507                .unwrap_or(0)
508                .saturating_add(*v);
509        }
510        self.subject_cms.merge(&other.subject_cms)?;
511        self.object_cms.merge(&other.object_cms)?;
512        for (k, hll) in &other.subjects_per_predicate {
513            self.subjects_per_predicate
514                .entry(*k)
515                .or_insert_with(HyperLogLog::default_params)
516                .merge(hll)?;
517        }
518        for (k, hll) in &other.objects_per_predicate {
519            self.objects_per_predicate
520                .entry(*k)
521                .or_insert_with(HyperLogLog::default_params)
522                .merge(hll)?;
523        }
524        self.named_graph_count = self
525            .named_graph_count
526            .saturating_add(other.named_graph_count);
527        self.temporal_histogram.merge(&other.temporal_histogram);
528        self.geo_cell_histogram.merge(&other.geo_cell_histogram);
529        self.text_seed_sketch.merge(&other.text_seed_sketch);
530        Ok(())
531    }
532
533    /// Estimated matches for an encoded triple pattern.
534    pub fn estimate(&self, pattern: &EncodedTriplePattern) -> u64 {
535        estimate_pattern(self, pattern)
536    }
537
538    /// [`Self::estimate`] with extra S/P/O slots treated as bound (no ground term).
539    pub fn estimate_with_bound_slots(
540        &self,
541        pattern: &EncodedTriplePattern,
542        extra: ExtraBoundSlots,
543    ) -> u64 {
544        estimate_pattern_with_bound_slots(self, pattern, extra)
545    }
546
547    /// Distinct join-key domain for `slot` under a bound named-node predicate.
548    ///
549    /// Uses `subjects_per_predicate` / `objects_per_predicate` HLL cardinality.
550    pub fn join_key_domain(
551        &self,
552        pattern: &EncodedTriplePattern,
553        slot: JoinKeySlot,
554    ) -> Option<u64> {
555        estimate_join_key_domain(self, pattern, slot)
556    }
557}
558
559/// The write-path (`open`/`flushing`) profile of one shard: exactly the stats
560/// the canonical hexastore write stream produces.
561///
562/// The two CF-keyed counts are deliberately ABSENT. The named-graph count and
563/// the temporal tick histogram are produced by their own CFs' collectors, so
564/// they live in [`ShardStats`](crate::ShardStats) overlays rotated by those
565/// CFs' own flushes; carrying them here would let a canonical flush sweep
566/// counts into an aside that no canonical SST contains and drop them at
567/// reload. This is also the ONLY type [`observe_quad`](crate::observe_quad)
568/// accumulates into — a sealed [`StatsProfile`] is a derived artifact (blob
569/// decode, `merged()`, the collectors' `From` conversion), so quad stats can
570/// never enter the system around the write path.
571#[derive(Debug, Clone, PartialEq, Eq)]
572pub struct LiveQuadsProfile {
573    /// Approximate total `Put` observations in this profile.
574    pub total_puts: u64,
575    /// Exact predicate frequencies (named-node predicates).
576    pub predicate_counts: BTreeMap<StrHash, u64>,
577    /// Exact `rdf:type` class instance counts (named-node classes only).
578    pub class_counts: BTreeMap<StrHash, u64>,
579    /// Subject frequency CMS.
580    pub subject_cms: CountMinSketch,
581    /// Object frequency CMS.
582    pub object_cms: CountMinSketch,
583    /// Distinct subjects per predicate (joint S–P cardinality).
584    pub subjects_per_predicate: BTreeMap<StrHash, HyperLogLog>,
585    /// Distinct objects per predicate (joint P–O cardinality).
586    pub objects_per_predicate: BTreeMap<StrHash, HyperLogLog>,
587}
588
589impl Default for LiveQuadsProfile {
590    fn default() -> Self {
591        Self {
592            total_puts: 0,
593            predicate_counts: BTreeMap::new(),
594            class_counts: BTreeMap::new(),
595            subject_cms: CountMinSketch::default_params(),
596            object_cms: CountMinSketch::default_params(),
597            subjects_per_predicate: BTreeMap::new(),
598            objects_per_predicate: BTreeMap::new(),
599        }
600    }
601}
602
603impl LiveQuadsProfile {
604    /// Whether this profile has observed any puts.
605    pub fn is_empty(&self) -> bool {
606        self.total_puts == 0 && self.predicate_counts.is_empty() && self.class_counts.is_empty()
607    }
608
609    /// Algebraic merge (CMS add, HLL register-max, exact maps sum) — the
610    /// [`StatsProfile::merge`] field set minus the CF-keyed overlays.
611    pub fn merge(&mut self, other: &Self) -> Result<(), crate::StatsError> {
612        self.total_puts = self.total_puts.saturating_add(other.total_puts);
613        for (k, v) in &other.predicate_counts {
614            *self.predicate_counts.entry(*k).or_insert(0) = self
615                .predicate_counts
616                .get(k)
617                .copied()
618                .unwrap_or(0)
619                .saturating_add(*v);
620        }
621        for (k, v) in &other.class_counts {
622            *self.class_counts.entry(*k).or_insert(0) = self
623                .class_counts
624                .get(k)
625                .copied()
626                .unwrap_or(0)
627                .saturating_add(*v);
628        }
629        self.subject_cms.merge(&other.subject_cms)?;
630        self.object_cms.merge(&other.object_cms)?;
631        for (k, hll) in &other.subjects_per_predicate {
632            self.subjects_per_predicate
633                .entry(*k)
634                .or_insert_with(HyperLogLog::default_params)
635                .merge(hll)?;
636        }
637        for (k, hll) in &other.objects_per_predicate {
638            self.objects_per_predicate
639                .entry(*k)
640                .or_insert_with(HyperLogLog::default_params)
641                .merge(hll)?;
642        }
643        Ok(())
644    }
645}
646
647impl From<&LiveQuadsProfile> for StatsProfile {
648    fn from(live: &LiveQuadsProfile) -> Self {
649        Self {
650            total_puts: live.total_puts,
651            predicate_counts: live.predicate_counts.clone(),
652            class_counts: live.class_counts.clone(),
653            subject_cms: live.subject_cms.clone(),
654            object_cms: live.object_cms.clone(),
655            subjects_per_predicate: live.subjects_per_predicate.clone(),
656            objects_per_predicate: live.objects_per_predicate.clone(),
657            // HLL cardinality caches are materialized at the compute
658            // boundary (`derive_hll_domains`), never on the observation path.
659            subject_domains_per_predicate: BTreeMap::new(),
660            object_domains_per_predicate: BTreeMap::new(),
661            // CF-keyed overlays are shard-level, not live-profile fields; a
662            // converted live profile carries their merge identity.
663            named_graph_count: 0,
664            temporal_histogram: crate::tick_histogram::TickHistogram::default(),
665            geo_cell_histogram: crate::geo_cell_histogram::GeoCellHistogram::default(),
666            text_seed_sketch: crate::text_seed_sketch::TextSeedSketch::empty(),
667        }
668    }
669}
670
671impl From<LiveQuadsProfile> for StatsProfile {
672    fn from(live: LiveQuadsProfile) -> Self {
673        Self::from(&live)
674    }
675}
676
677/// Selectivity estimate for `pattern` from `profile`.
678///
679/// Combines exact maps, CMS frequencies, and HLL-derived average fan-out under
680/// a bound predicate.
681///
682/// A bound named predicate that was never observed has no `predicate_counts`
683/// key and no `subjects_per_predicate` HLL. That is **zero** (reported as 1 so
684/// join order still has a positive number), not “unknown”: do not fall through
685/// to [`StatsProfile::total_puts`]. Unbound `?p` still uses `total_puts` / CMS.
686pub fn estimate_pattern(profile: &StatsProfile, pattern: &EncodedTriplePattern) -> u64 {
687    estimate_pattern_with_bound_slots(profile, pattern, ExtraBoundSlots::default())
688}
689
690/// [`estimate_pattern`] with extra S/P/O slots treated as bound without a term.
691///
692/// Incoming LeftJoin keys use this: no CMS probe (no concrete IRI), but HLL
693/// fan-out under bound P still applies. Incoming-bound `?p` with no ground
694/// predicate uses mean `|P|`. `rdf:type` + a named class still uses the exact
695/// class map only when the object slot holds a ground term.
696pub fn estimate_pattern_with_bound_slots(
697    profile: &StatsProfile,
698    pattern: &EncodedTriplePattern,
699    extra: ExtraBoundSlots,
700) -> u64 {
701    let s = pattern.subject.as_ref();
702    let p = pattern.predicate.as_ref();
703    let o = pattern.object.as_ref();
704    let s_bound = s.is_some() || extra.subject;
705    let o_bound = o.is_some() || extra.object;
706
707    // Point lookup: S, P, and O are populated terms. Sketches cannot tell
708    // whether that exact triple exists, so report 1 (0 or 1, max 1).
709    // Incoming-only extras do not count — there is no concrete IRI to probe.
710    if s.is_some() && p.is_some() && o.is_some() {
711        return 1;
712    }
713
714    // rdf:type + bound named class → exact class map (TSG-aligned).
715    // Incoming-only object (no class IRI) must not take this path.
716    if p.is_some_and(|pred| pred == &RDF_TYPE)
717        && let Some(obj) = o
718        && let Some(class) = named_node_hash(obj)
719    {
720        return profile
721            .class_counts
722            .get(&class)
723            .copied()
724            .unwrap_or(0)
725            .max(1);
726    }
727
728    let mut candidates = Vec::new();
729
730    let pred_hash = p.and_then(named_node_hash);
731    let pred_count = pred_hash.and_then(|h| profile.predicate_counts.get(&h).copied());
732
733    // Bound named P: exact count, or 0.max(1) if the IRI was never ingested.
734    // `observe_quad` inserts `predicate_counts` and `subjects_per_predicate`
735    // together on Put, and `bump_exact` drops the count key at 0, so a miss
736    // here is “this predicate is not in the store,” not “we have no sketches.”
737    if pred_hash.is_some() {
738        candidates.push(pred_count.unwrap_or(0).max(1));
739    }
740    // Incoming-bound ?p, no IRI: mean predicate frequency. Sketches are
741    // keyed by a named P, so HLL fan-out cannot run.
742    if extra.predicate && pred_hash.is_none() {
743        let n_preds = profile.predicate_counts.len().max(1) as u64;
744        candidates.push((profile.total_puts / n_preds).max(1));
745    }
746    if let Some(obj) = o {
747        candidates.push(profile.object_cms.estimate(term_key(obj)).max(1));
748    }
749    if let Some(sub) = s {
750        candidates.push(profile.subject_cms.estimate(term_key(sub)).max(1));
751    }
752
753    // HLL fan-out: avg triples per subject (or object) under bound P.
754    // Improves join-key patterns where one end is ground and CMS alone is coarse.
755    // Incoming-bound slots (no term) take the same fan-out, not a dummy CMS key.
756    if let (Some(hash), Some(pc)) = (pred_hash, pred_count) {
757        if s_bound && !o_bound {
758            // (S, :p, ?o) → expected objects ≈ |P| / distinct subjects of P
759            if let Some(distinct_s) = profile.subject_domain(&hash) {
760                candidates.push((pc / distinct_s).max(1));
761            }
762        }
763        if o_bound && !s_bound {
764            // (?s, :p, O) → expected subjects ≈ |P| / distinct objects of P
765            if let Some(distinct_o) = profile.object_domain(&hash) {
766                candidates.push((pc / distinct_o).max(1));
767            }
768        }
769    }
770
771    if candidates.is_empty() {
772        return profile.total_puts.max(1);
773    }
774    let mut estimate = candidates.into_iter().min().unwrap_or(1);
775    // Invariant clamp, full-extent patterns only (S and O both open, named
776    // P): a predicate with D distinct subjects — or objects — has at least
777    // D rows, because every distinct value owns at least one row. The
778    // exact count map and the HLLs are independent observations, so a count
779    // below an HLL is a violated invariant, not a smaller truth: whatever
780    // lost exact-count observations (a partially observed sealed reload, a
781    // merge gap) cannot have un-written the rows the HLL registers still
782    // remember. Clamp the estimate up to the HLL floor rather than pricing
783    // a fiction.
784    // Bound-slot patterns are exempt on purpose: `?s :p <o>` may
785    // legitimately return 3 rows under a predicate with 30k distinct
786    // subjects. Exemptions also cover the wire-cap corner: a trimmed HLL
787    // map entry is simply absent, and the clamp silently does nothing.
788    if !s_bound
789        && !o_bound
790        && let Some(hash) = pred_hash
791    {
792        if let Some(domain) = profile.subject_domain(&hash) {
793            estimate = estimate.max(domain);
794        }
795        if let Some(domain) = profile.object_domain(&hash) {
796            estimate = estimate.max(domain);
797        }
798    }
799    estimate.max(1)
800}
801
802/// Distinct-value domain for a join variable in `slot`, from predicate HLLs.
803///
804/// `rdf:type` exception: for the **subject** slot of a `?s rdf:type Class`
805/// pattern with a bound named class, the exact `class_counts` entry IS the
806/// domain — the per-predicate HLL cannot condition on the bound object and
807/// would answer "distinct subjects with *any* type", routinely overstating
808/// a 5-instance class by the whole typed-subject population. A missing or
809/// zero class count falls back to the HLL rather than reporting 0 (a
810/// never-observed class arguably proves an empty join, but turning that
811/// into zero-row plan substitutions is a separate, deliberate rewrite).
812/// Note `class_counts` counts visible type-triples (rows), which overstates
813/// distinct subjects only when one subject carries the class in several
814/// graphs; callers cap with `min(domain, rows)` so the skew degrades
815/// gracefully.
816///
817/// `rdf:type` object exception: for the **object** slot of an open
818/// `?s rdf:type ?cls` pattern, `class_counts.len()` IS the distinct-class
819/// domain when the exact map is non-empty. The objects HLL answers the same
820/// question approximately (± sketch error, insert-biased after deletes,
821/// admits non-named objects) and can be trimmed by the wire cap
822/// (`class_counts` never is), so exact wins whenever it exists.
823///
824/// Returns [`None`] when the predicate is unbound or has no HLL sketch yet
825/// (and no exact class count applied).
826pub fn estimate_join_key_domain(
827    profile: &StatsProfile,
828    pattern: &EncodedTriplePattern,
829    slot: JoinKeySlot,
830) -> Option<u64> {
831    let pred = pattern.predicate.as_ref()?;
832    if pred == &RDF_TYPE
833        && slot == JoinKeySlot::Subject
834        && let Some(obj) = &pattern.object
835        && let Some(class) = named_node_hash(obj)
836        && let Some(&count) = profile.class_counts.get(&class)
837        && count > 0
838    {
839        return Some(count);
840    }
841    if pred == &RDF_TYPE && slot == JoinKeySlot::Object && !profile.class_counts.is_empty() {
842        return Some(profile.class_counts.len() as u64);
843    }
844    let pred_hash = named_node_hash(pred)?;
845    match slot {
846        JoinKeySlot::Subject => profile.subject_domain(&pred_hash),
847        JoinKeySlot::Object => profile.object_domain(&pred_hash),
848    }
849}
850
851/// The milli scale for vocabulary containment: 1000 = full overlap, so a
852/// consumer passing this constant reduces every containment-aware formula
853/// to its pre-containment (count-only) form. `estimate_vocabulary_overlap`
854/// degrades to exactly this value on every unknown — missing sketches,
855/// unbound predicates, the `rdf:type` family — which is what makes the
856/// feature regression-free by construction.
857pub const VOCABULARY_OVERLAP_FULL_MILLI: u64 = 1_000;
858
859/// Vocabulary containment between the two arms of one join key, milli-scaled
860/// `|A ∩ B| / |A|` (A = the driver arm's key vocabulary, B = the probe arm's).
861///
862/// The per-predicate HLL pairs (`subjects_per_predicate` /
863/// `objects_per_predicate`) summarize each arm's distinct key values.
864/// Cardinalities alone cannot answer containment — |A| = 300 and |B| = 3 are
865/// consistent with any intersection in 0..=3 — but the sketches themselves
866/// support union: a register-max merge gives |A ∪ B|, and inclusion–exclusion
867/// gives the overlap. That merge is the one operation the seating model never
868/// performed; this function is its single definition.
869///
870/// Consumers:
871/// - the coverage verdict (`push_list_covers_domain`): a pushed list covers
872///   the probe's key space when `list × r` reaches the probe domain — at
873///   r = full this reduces to the historical count comparison;
874/// - the probe broadcast price (`probe_broadcast_price`): the matched-rows
875///   fraction scales by the same r.
876///
877/// Error contract: inclusion–exclusion carries roughly twice a single HLL's
878/// relative error (σ ≈ 1.6% at p=12, so ±3–4% typical), coarser on tiny
879/// domains. Verdicts stay advisory-only (§10): a wrong overlap changes plan
880/// choice and fetch selectivity, never results — the join applies the same
881/// predicate downstream regardless of what the push carried.
882///
883/// Returns `None` (→ the consumer degrades to
884/// [`VOCABULARY_OVERLAP_FULL_MILLI`]) when either arm presents no vocabulary:
885/// an unbound predicate, a missing or wire-trimmed sketch, a precision
886/// mismatch, an empty driver cardinality, the `rdf:type` family (its domains
887/// short-circuit through the exact class map — kept byte-identical on the
888/// count rule), or an unknown hash. The same-predicate/same-slot pair is the
889/// one *positive* short-circuit: both arms read the same sketch, so
890/// containment is full by identity (the self-merge is a register no-op) and
891/// the merge work is skipped.
892///
893/// Slots must be resolved for UNBOUND positions only (a ground key is a
894/// constant — no vocabulary question; callers mirror
895/// `estimate_join_key_domain`'s ground check before calling).
896pub fn estimate_vocabulary_overlap(
897    profile: &StatsProfile,
898    driver_pattern: &EncodedTriplePattern,
899    driver_slot: JoinKeySlot,
900    probe_pattern: &EncodedTriplePattern,
901    probe_slot: JoinKeySlot,
902) -> Option<u64> {
903    // Identity containment: one predicate, one slot — one vocabulary. The
904    // count rule's sound home (the pushed list is drawn from the probe's
905    // own population), and the general formula below would return exactly
906    // this.
907    if driver_slot == probe_slot
908        && driver_pattern.predicate.is_some()
909        && driver_pattern.predicate == probe_pattern.predicate
910    {
911        return Some(VOCABULARY_OVERLAP_FULL_MILLI);
912    }
913    // The rdf:type family keeps the count rule: its key domains
914    // short-circuit through the exact class map (see
915    // `estimate_join_key_domain`), the type-join shapes carry the deepest
916    // tuning history, and a cross-family type join (type on one side,
917    // another predicate on the other) is not a shape with measured
918    // behavior to improve.
919    if driver_pattern.predicate.as_ref() == Some(&RDF_TYPE)
920        || probe_pattern.predicate.as_ref() == Some(&RDF_TYPE)
921    {
922        return None;
923    }
924    let driver_pred = named_node_hash(driver_pattern.predicate.as_ref()?)?;
925    let probe_pred = named_node_hash(probe_pattern.predicate.as_ref()?)?;
926    let sketch = |pred: &StrHash, slot: JoinKeySlot| -> Option<&HyperLogLog> {
927        match slot {
928            JoinKeySlot::Subject => profile.subjects_per_predicate.get(pred),
929            JoinKeySlot::Object => profile.objects_per_predicate.get(pred),
930        }
931    };
932    let driver_hll = sketch(&driver_pred, driver_slot)?;
933    let probe_hll = sketch(&probe_pred, probe_slot)?;
934    if driver_hll.precision() != probe_hll.precision() {
935        return None;
936    }
937    // The two arm cardinalities read the derived domain caches when they
938    // exist (refresh derives them once per rollup — see
939    // `derive_hll_domains`), falling back to a fold for hand-built or
940    // decoded profiles. Only the UNION genuinely needs fresh registers.
941    let domain = |pred: &StrHash, slot: JoinKeySlot| -> Option<u64> {
942        match slot {
943            JoinKeySlot::Subject => profile.subject_domain(pred),
944            JoinKeySlot::Object => profile.object_domain(pred),
945        }
946    };
947    // |A ∪ B| by register-max merge, then inclusion–exclusion. Both
948    // saturating clamps guard the estimate: subtraction can dip below zero
949    // on sketch noise (clamped to 0), and the sum can exceed the smaller
950    // cardinality (clamped to it — the intersection's structural bound).
951    // `subject_domain`/`object_domain` floor at 1, so the divisor here is
952    // never zero.
953    let mut union_hll = driver_hll.clone();
954    union_hll.merge(probe_hll).ok()?;
955    let card_a = domain(&driver_pred, driver_slot)?;
956    let card_b = domain(&probe_pred, probe_slot)?;
957    let card_union = union_hll.cardinality();
958    let intersection = card_a
959        .saturating_add(card_b)
960        .saturating_sub(card_union)
961        .min(card_a.min(card_b));
962    Some(intersection.saturating_mul(1000) / card_a)
963}
964
965/// Multi-key equijoin intermediate cardinality:
966/// `|L| · |R| / Π_v max(dom_L(v), dom_R(v))` over the join keys, assuming
967/// key independence.
968///
969/// Per key, the divisor factor is the KNOWN side's domain, capped by its
970/// own side's row count (distinct values never exceed own rows). When one
971/// side's domain is unknown (missing HLL, `Path`, `SubSelect` boundary)
972/// the known side alone is used: the structural bound `dom ≤ own rows`
973/// means a known domain already at/above the other side's rows pins
974/// `max(...)` exactly, and below that the known domain is the smallest
975/// plausible max — both over-estimate relative to the uniform assumption,
976/// the safe direction for advisory stats. A key unknown on both sides
977/// contributes no factor; when no key carries any domain the Phase 7
978/// `min(|L|, |R|)` heuristic stands. Both-sides-ground-unique keys need
979/// no special case (their factor is 1 — multiplying by 1 is identity,
980/// unlike the min-aggregation in the planner's allow-list channel, which
981/// must exclude no-op keys so a domain-1 key cannot drag the minimum
982/// down).
983///
984/// Independence is the known hazard: correlated keys (e.g. one functionally
985/// determined by the other in the data) over-divide and under-estimate
986/// within this formula; estimates stay advisory-only.
987pub fn estimate_join_rows_multi(
988    left_rows: u64,
989    right_rows: u64,
990    key_domains: &[(Option<u64>, Option<u64>)],
991) -> u64 {
992    let left = left_rows.max(1);
993    let right = right_rows.max(1);
994    let mut divisor: u128 = 1;
995    let mut any_known = false;
996    for (left_domain, right_domain) in key_domains {
997        let left_domain = left_domain.map(|d| d.min(left));
998        let right_domain = right_domain.map(|d| d.min(right));
999        let factor = match (left_domain, right_domain) {
1000            (None, None) => continue,
1001            (Some(l), Some(r)) => l.max(r),
1002            (Some(l), None) | (None, Some(l)) => l,
1003        }
1004        .max(1);
1005        any_known = true;
1006        divisor = divisor.saturating_mul(u128::from(factor));
1007    }
1008    if !any_known {
1009        return left.min(right);
1010    }
1011    let product = (u128::from(left)).saturating_mul(u128::from(right));
1012    u64::try_from(product / divisor).unwrap_or(u64::MAX).max(1)
1013}
1014
1015/// Equijoin intermediate cardinality from row counts and optional key domains.
1016///
1017/// Uses `|L| * |R| / max(dom_L, dom_R)` when domains are known; otherwise
1018/// falls back to `min(|L|, |R|)` (Phase 7 heuristic).
1019pub fn estimate_join_rows(
1020    left_rows: u64,
1021    right_rows: u64,
1022    left_domain: Option<u64>,
1023    right_domain: Option<u64>,
1024) -> u64 {
1025    estimate_join_rows_multi(left_rows, right_rows, &[(left_domain, right_domain)])
1026}
1027
1028/// Bound-slot count — fallback when the profile is empty.
1029///
1030/// Counts S, P, O, and G. `Some(DefaultGraph)` is bound (RDF unnamed graph);
1031/// `None` is unbound (any graph).
1032pub fn bound_slots(pattern: &EncodedTriplePattern) -> usize {
1033    [
1034        pattern.subject.is_some(),
1035        pattern.predicate.is_some(),
1036        pattern.object.is_some(),
1037        pattern.graph_name.is_some(),
1038    ]
1039    .into_iter()
1040    .filter(|b| *b)
1041    .count()
1042}
1043
1044/// Whether S, P, O, and G are all ground (at most one visible quad).
1045pub fn pattern_is_point_lookup(pattern: &EncodedTriplePattern) -> bool {
1046    bound_slots(pattern) == 4
1047}
1048
1049/// Roll shard profiles into one cluster profile.
1050///
1051/// S/P/O each see the full write stream under 3-way fan-out, so summing them
1052/// would triple counts. Prefer the **O** axis profile (class counts + object
1053/// CMS), then P, then S. Multiple profiles on the same axis are merged.
1054///
1055/// [`StatsProfile::named_graph_count`] lives only on S (`named_graphs_catalog`).
1056/// After picking O/P sketches, copy that count from the S profile so GRAPH
1057/// costing still sees the catalog size.
1058pub fn rollup_cluster(shards: &[(PartitionAxis, StatsProfile)]) -> StatsProfile {
1059    let mut by_axis: BTreeMap<PartitionAxis, StatsProfile> = BTreeMap::new();
1060    for (axis, profile) in shards {
1061        by_axis
1062            .entry(*axis)
1063            .and_modify(|existing| {
1064                let _ = existing.merge(profile);
1065            })
1066            .or_insert_with(|| profile.clone());
1067    }
1068    let named_graph_count = by_axis
1069        .get(&PartitionAxis::S)
1070        .map(|profile| profile.named_graph_count)
1071        .unwrap_or(0);
1072    for axis in [PartitionAxis::O, PartitionAxis::P, PartitionAxis::S] {
1073        if let Some(mut profile) = by_axis.remove(&axis) {
1074            profile.named_graph_count = named_graph_count;
1075            // Merged HLL registers differ from every shard's, so any domain
1076            // cache inherited from a shard profile would be silently wrong.
1077            // The compute boundary re-derives after its final cap
1078            // (`derive_hll_domains`).
1079            profile.subject_domains_per_predicate.clear();
1080            profile.object_domains_per_predicate.clear();
1081            return profile;
1082        }
1083    }
1084    StatsProfile::default()
1085}
1086
1087/// Serialized size of one HLL-map entry: the 16-byte key plus the HLL body
1088/// (precision byte, register-count `u32`, and `2^precision` one-byte
1089/// registers). `None` (map lacks this predicate) costs nothing.
1090fn hll_wire_entry_bytes(hll: Option<&HyperLogLog>) -> usize {
1091    match hll {
1092        Some(hll) => 16 + 5 + (1usize << hll.precision()),
1093        None => 0,
1094    }
1095}
1096
1097#[cfg(test)]
1098mod tests {
1099    use super::*;
1100    use crate::LiveQuadsProfile;
1101    use crate::observe::{observe_quad, term_key};
1102    use waratah_storage::{EncodedTerm, Literal, NamedNode, StorageOp, encode_quad};
1103
1104    #[test]
1105    fn full_extent_estimate_clamps_to_hll_floor() {
1106        // A predicate with 2,000 distinct subjects and 50 distinct objects.
1107        // The exact count map is then corrupted down to 7 — simulating
1108        // whatever loses exact-count observations without touching the
1109        // sketches — and the full-extent estimate must refuse to price
1110        // 7 rows under a predicate the HLLs remember 2,000 subjects for.
1111        let mut live = LiveQuadsProfile::default();
1112        let pred = NamedNode::new("http://ex/worksAt").unwrap();
1113        let objects: Vec<_> = (0..50)
1114            .map(|i| NamedNode::new(format!("http://ex/org{i}")).unwrap())
1115            .collect();
1116        for i in 0..2000u64 {
1117            let subject = NamedNode::new(format!("http://ex/p{i}")).unwrap();
1118            let q = encode_quad(&waratah_storage::Quad::new(
1119                subject,
1120                pred.clone(),
1121                objects[(i % 50) as usize].clone(),
1122                waratah_storage::GraphName::DefaultGraph,
1123            ))
1124            .unwrap();
1125            observe_quad(&mut live, &q, StorageOp::Put);
1126        }
1127        let mut profile = StatsProfile::from(live);
1128        let pred_hash = named_node_hash(&EncodedTerm::from(&pred)).unwrap();
1129        let subj_floor = profile
1130            .subjects_per_predicate
1131            .get(&pred_hash)
1132            .expect("subject HLL observed")
1133            .cardinality();
1134        let obj_floor = profile
1135            .objects_per_predicate
1136            .get(&pred_hash)
1137            .expect("object HLL observed")
1138            .cardinality();
1139        assert!(
1140            subj_floor > 1_900 && subj_floor < 2_100,
1141            "subj HLL ≈ 2000, got {subj_floor}"
1142        );
1143        assert!(
1144            obj_floor > 45 && obj_floor < 55,
1145            "obj HLL ≈ 50, got {obj_floor}"
1146        );
1147        profile.predicate_counts.insert(pred_hash, 7);
1148
1149        let var_var = EncodedTriplePattern {
1150            subject: None,
1151            predicate: Some(EncodedTerm::from(&pred)),
1152            object: None,
1153            graph_name: None,
1154        };
1155        let estimate = estimate_pattern(&profile, &var_var);
1156        assert_eq!(
1157            estimate,
1158            subj_floor.max(obj_floor),
1159            "full-extent estimate must clamp to the HLL floor, not the corrupted exact count"
1160        );
1161
1162        // Bound-object pattern: exempt from the clamp — `?s :p <org3>` may
1163        // legitimately return ~40 rows under a 2,000-subject predicate.
1164        let bound = EncodedTriplePattern {
1165            subject: None,
1166            predicate: Some(EncodedTerm::from(&pred)),
1167            object: Some(EncodedTerm::from(&objects[3])),
1168            graph_name: None,
1169        };
1170        let bound_estimate = estimate_pattern(&profile, &bound);
1171        assert!(
1172            bound_estimate < subj_floor,
1173            "bound-slot estimate stays small ({bound_estimate}), no full-extent clamp"
1174        );
1175    }
1176
1177    #[test]
1178    fn selective_object_beats_broad_type() {
1179        let mut live = LiveQuadsProfile::default();
1180        let person = NamedNode::new("http://ex/Person").unwrap();
1181        let type_pred = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
1182        let hometown = NamedNode::new("http://ex/hasHometown").unwrap();
1183        let brisbane = NamedNode::new("http://ex/Brisbane").unwrap();
1184
1185        for i in 0..100 {
1186            let s = NamedNode::new(format!("http://ex/p{i}")).unwrap();
1187            let q = encode_quad(&waratah_storage::Quad::new(
1188                s.clone(),
1189                type_pred.clone(),
1190                person.clone(),
1191                waratah_storage::GraphName::DefaultGraph,
1192            ))
1193            .unwrap();
1194            observe_quad(&mut live, &q, StorageOp::Put);
1195            if i < 5 {
1196                let q2 = encode_quad(&waratah_storage::Quad::new(
1197                    s,
1198                    hometown.clone(),
1199                    brisbane.clone(),
1200                    waratah_storage::GraphName::DefaultGraph,
1201                ))
1202                .unwrap();
1203                observe_quad(&mut live, &q2, StorageOp::Put);
1204            }
1205        }
1206        let profile = StatsProfile::from(live);
1207
1208        let pattern_a = EncodedTriplePattern {
1209            subject: None,
1210            predicate: Some(EncodedTerm::from(&type_pred)),
1211            object: Some(EncodedTerm::from(&person)),
1212            graph_name: Some(EncodedTerm::DefaultGraph),
1213        };
1214        let pattern_b = EncodedTriplePattern {
1215            subject: None,
1216            predicate: Some(EncodedTerm::from(&hometown)),
1217            object: Some(EncodedTerm::from(&brisbane)),
1218            graph_name: Some(EncodedTerm::DefaultGraph),
1219        };
1220        let est_a = profile.estimate(&pattern_a);
1221        let est_b = profile.estimate(&pattern_b);
1222        assert!(est_b < est_a, "est_b={est_b} est_a={est_a}");
1223        assert_eq!(est_a, 100);
1224        assert_eq!(est_b, 5);
1225    }
1226
1227    /// Profile with `counts.len()` predicates, each carrying both HLL maps.
1228    fn profile_with_predicate_pairs(counts: &[(StrHash, u64)]) -> StatsProfile {
1229        let mut profile = StatsProfile::default();
1230        for (hash, count) in counts {
1231            profile.predicate_counts.insert(*hash, *count);
1232            profile
1233                .subjects_per_predicate
1234                .insert(*hash, HyperLogLog::default_params());
1235            profile
1236                .objects_per_predicate
1237                .insert(*hash, HyperLogLog::default_params());
1238        }
1239        profile
1240    }
1241
1242    /// One subject-side HLL map entry costs 16 + 5 + 2^12 bytes serialized.
1243    const PAIR_BYTES: usize = 2 * (16 + 5 + (1 << 12));
1244
1245    #[test]
1246    fn cap_keeps_heaviest_pairs_first_and_respects_budget() {
1247        let heavy = StrHash::new("http://ex/heavy");
1248        let mid = StrHash::new("http://ex/mid");
1249        let light = StrHash::new("http://ex/light");
1250        let profile = profile_with_predicate_pairs(&[(heavy, 1000), (mid, 50), (light, 3)]);
1251
1252        let mut skeleton = profile.clone();
1253        skeleton.subjects_per_predicate.clear();
1254        skeleton.objects_per_predicate.clear();
1255        let base = crate::serde_bin::to_bytes(&skeleton).len();
1256        // Budget for exactly two pairs: heavy and mid stay, light drops.
1257        let budget = base + 2 * PAIR_BYTES;
1258        let capped = profile.capped_for_wire_with_budget(budget);
1259
1260        assert!(crate::serde_bin::to_bytes(&capped).len() <= budget);
1261        assert!(capped.subjects_per_predicate.contains_key(&heavy));
1262        assert!(capped.objects_per_predicate.contains_key(&heavy));
1263        assert!(capped.subjects_per_predicate.contains_key(&mid));
1264        assert!(
1265            !capped.subjects_per_predicate.contains_key(&light),
1266            "the smallest-count pair must be the first dropped"
1267        );
1268        // Fixed parts survive untouched.
1269        assert_eq!(capped.predicate_counts, profile.predicate_counts);
1270        assert_eq!(capped.subject_cms, profile.subject_cms);
1271        assert_eq!(capped.total_puts, profile.total_puts);
1272    }
1273
1274    #[test]
1275    fn cap_with_room_for_everything_is_identity() {
1276        let profile = profile_with_predicate_pairs(&[
1277            (StrHash::new("http://ex/a"), 7),
1278            (StrHash::new("http://ex/b"), 9),
1279        ]);
1280        let budget = crate::serde_bin::to_bytes(&profile).len();
1281        let capped = profile.capped_for_wire_with_budget(budget);
1282        assert_eq!(capped, profile);
1283    }
1284
1285    #[test]
1286    fn cap_beyond_fixed_parts_keeps_maps_empty() {
1287        let profile = profile_with_predicate_pairs(&[(StrHash::new("http://ex/a"), 7)]);
1288        let mut skeleton = profile.clone();
1289        skeleton.subjects_per_predicate.clear();
1290        skeleton.objects_per_predicate.clear();
1291        let budget = crate::serde_bin::to_bytes(&skeleton).len();
1292        let capped = profile.capped_for_wire_with_budget(budget);
1293        assert!(capped.subjects_per_predicate.is_empty());
1294        assert!(capped.objects_per_predicate.is_empty());
1295    }
1296
1297    #[test]
1298    fn asymmetric_pairs_cost_one_side_only() {
1299        // A predicate with only a subject-side HLL costs half a pair, so a
1300        // budget that fits one full pair also fits it.
1301        let hash = StrHash::new("http://ex/a");
1302        let mut profile = StatsProfile::default();
1303        profile.predicate_counts.insert(hash, 10);
1304        profile
1305            .subjects_per_predicate
1306            .insert(hash, HyperLogLog::default_params());
1307
1308        let mut skeleton = profile.clone();
1309        skeleton.subjects_per_predicate.clear();
1310        let base = crate::serde_bin::to_bytes(&skeleton).len();
1311        let capped = profile.capped_for_wire_with_budget(base + PAIR_BYTES);
1312        assert!(capped.subjects_per_predicate.contains_key(&hash));
1313    }
1314
1315    #[test]
1316    fn rollup_prefers_o_axis() {
1317        let mut o = StatsProfile::default();
1318        let mut s = StatsProfile::default();
1319        o.total_puts = 10;
1320        s.total_puts = 99;
1321        let rolled = rollup_cluster(&[(PartitionAxis::S, s), (PartitionAxis::O, o.clone())]);
1322        assert_eq!(rolled.total_puts, 10);
1323    }
1324
1325    #[test]
1326    fn rollup_copies_named_graph_count_from_s() {
1327        let mut o = StatsProfile::default();
1328        let mut s = StatsProfile::default();
1329        o.total_puts = 10;
1330        s.named_graph_count = 42;
1331        let rolled = rollup_cluster(&[(PartitionAxis::S, s), (PartitionAxis::O, o)]);
1332        assert_eq!(rolled.total_puts, 10);
1333        assert_eq!(rolled.named_graph_count, 42);
1334    }
1335
1336    #[test]
1337    fn join_strategy_broadcast_when_left_small() {
1338        assert_eq!(
1339            JoinStrategy::from_cardinalities(5, 1_000_000),
1340            JoinStrategy::Broadcast
1341        );
1342        assert_eq!(
1343            JoinStrategy::from_cardinalities(50_000, 80_000),
1344            JoinStrategy::Shuffle
1345        );
1346    }
1347
1348    #[test]
1349    fn join_strategy_uses_hll_domain_for_broadcast_vs_shuffle() {
1350        // Many rows but few distinct join keys → broadcast the key set.
1351        assert_eq!(
1352            JoinStrategy::from_cardinalities_and_domains(100_000, 200_000, Some(50), Some(80_000),),
1353            JoinStrategy::Broadcast
1354        );
1355        // Both key domains large → shuffle.
1356        assert_eq!(
1357            JoinStrategy::from_cardinalities_and_domains(
1358                100_000,
1359                200_000,
1360                Some(50_000),
1361                Some(80_000),
1362            ),
1363            JoinStrategy::Shuffle
1364        );
1365        // Domain capped by rows: 5 result rows cannot inflate past broadcast.
1366        assert_eq!(
1367            JoinStrategy::from_cardinalities_and_domains(5, 1_000_000, Some(50_000), None),
1368            JoinStrategy::Broadcast
1369        );
1370    }
1371
1372    #[test]
1373    fn hll_fanout_tightens_bound_object_estimate() {
1374        // Object CMS is hot (Brisbane appears often under other predicates), so
1375        // exact+CMS alone overestimates `(?s, livesIn, Brisbane)`. HLL avg
1376        // fan-out under livesIn (~1000 triples / 10 cities) tightens it.
1377        let mut profile = StatsProfile::default();
1378        let lives_in = NamedNode::new("http://ex/livesIn").unwrap();
1379        let brisbane = NamedNode::new("http://ex/Brisbane").unwrap();
1380        let pred = StrHash::new("http://ex/livesIn");
1381        let brisbane_term = EncodedTerm::from(&brisbane);
1382
1383        profile.total_puts = 1000;
1384        profile.predicate_counts.insert(pred, 1000);
1385        profile.object_cms.add(term_key(&brisbane_term), 800);
1386
1387        let mut objects = HyperLogLog::default_params();
1388        for i in 0..10u128 {
1389            objects.add(i);
1390        }
1391        profile.objects_per_predicate.insert(pred, objects);
1392
1393        let pattern = EncodedTriplePattern {
1394            subject: None,
1395            predicate: Some(EncodedTerm::from(&lives_in)),
1396            object: Some(brisbane_term),
1397            graph_name: Some(EncodedTerm::DefaultGraph),
1398        };
1399
1400        let with_hll = estimate_pattern(&profile, &pattern);
1401        let mut no_hll = profile.clone();
1402        no_hll.objects_per_predicate.clear();
1403        no_hll.subjects_per_predicate.clear();
1404        let without_hll = estimate_pattern(&no_hll, &pattern);
1405
1406        assert_eq!(without_hll, 800, "CMS/exact-only should take object CMS");
1407        assert!(
1408            with_hll < without_hll,
1409            "HLL fan-out should tighten: {with_hll} vs {without_hll}"
1410        );
1411        // ~1000/10 = 100; allow HLL error band.
1412        assert!(
1413            (50..=200).contains(&with_hll),
1414            "expected ~100 fan-out, got {with_hll}"
1415        );
1416
1417        let domain = estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Object).unwrap();
1418        assert!(
1419            (5..=20).contains(&domain),
1420            "object HLL domain should be ~10, got {domain}"
1421        );
1422    }
1423
1424    #[test]
1425    fn hll_join_rows_uses_domains() {
1426        // 10k × 10k / max(100, 100) = 1_000_000; without domains → min = 10k.
1427        assert_eq!(
1428            estimate_join_rows(10_000, 10_000, Some(100), Some(100)),
1429            1_000_000
1430        );
1431        assert_eq!(estimate_join_rows(10_000, 50_000, None, None), 10_000);
1432    }
1433
1434    /// The two-key shape from the slow-query diagnosis: 500 × 237,016
1435    /// divided by max(5,121) × max(100,114_739) ≈ 8 — where the old
1436    /// single-key formula divided by one key's domain only and answered
1437    /// 979,404.
1438    #[test]
1439    fn join_rows_multi_multiplies_per_key_factors() {
1440        assert_eq!(
1441            estimate_join_rows_multi(
1442                500,
1443                237_016,
1444                &[(Some(5), Some(121)), (Some(100), Some(114_739))]
1445            ),
1446            8
1447        );
1448    }
1449
1450    /// k=1 with both domains known reduces exactly to
1451    /// [`estimate_join_rows`]; a key with no domain on either side leaves
1452    /// the Phase 7 `min(|L|, |R|)` heuristic standing.
1453    #[test]
1454    fn join_rows_multi_reduces_to_single_key() {
1455        assert_eq!(
1456            estimate_join_rows_multi(10_000, 10_000, &[(Some(100), Some(100))]),
1457            estimate_join_rows(10_000, 10_000, Some(100), Some(100))
1458        );
1459        assert_eq!(
1460            estimate_join_rows_multi(10_000, 50_000, &[(None, None)]),
1461            10_000
1462        );
1463    }
1464
1465    /// Missing-side rule: the KNOWN side's domain is the factor — not the
1466    /// old rows-substitution, which would divide by max(1M, 100) = 1M here
1467    /// and price the join at |L|. The known domain already pins
1468    /// max(dom_L, dom_R) because dom_R ≤ 100 rows on the other side.
1469    #[test]
1470    fn join_rows_multi_known_side_only_for_missing_domains() {
1471        assert_eq!(
1472            estimate_join_rows_multi(2_000_000, 100, &[(Some(1_000_000), None)]),
1473            200
1474        );
1475        // A key unknown on both sides contributes nothing; the known key
1476        // still divides.
1477        assert_eq!(
1478            estimate_join_rows_multi(1_000, 2_000, &[(None, None), (Some(10), Some(10))]),
1479            200_000
1480        );
1481        // Integer division can reach 0 (2×2 over a 100 divisor); estimates
1482        // never stamp 0.
1483        assert_eq!(
1484            estimate_join_rows_multi(2, 2, &[(Some(10), Some(10)), (Some(10), Some(10))]),
1485            1
1486        );
1487    }
1488
1489    /// A `?s rdf:type Class` pattern with an exact class count: the subject
1490    /// domain is that count, even when the (class-blind) `rdf:type` subject
1491    /// HLL is present and wildly larger.
1492    #[test]
1493    fn type_scan_subject_domain_uses_exact_class_count() {
1494        let mut profile = StatsProfile::default();
1495        let dataset = EncodedTerm::from(&NamedNode::new("http://schema.org/Dataset").unwrap());
1496        let type_hash = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
1497        let mut typed_subjects = HyperLogLog::default_params();
1498        for i in 0..125_483u128 {
1499            typed_subjects.add(i);
1500        }
1501        profile
1502            .class_counts
1503            .insert(named_node_hash(&dataset).unwrap(), 5);
1504        profile
1505            .subjects_per_predicate
1506            .insert(type_hash, typed_subjects);
1507
1508        let pattern = EncodedTriplePattern {
1509            subject: None,
1510            predicate: Some(RDF_TYPE),
1511            object: Some(dataset),
1512            graph_name: Some(EncodedTerm::DefaultGraph),
1513        };
1514        assert_eq!(
1515            estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Subject),
1516            Some(5),
1517            "exact class count must beat the class-blind HLL"
1518        );
1519        // The object slot (a variable class `?s a ?class`) now takes the
1520        // exact distinct-class count `class_counts.len()` — with or without
1521        // an objects HLL.
1522        let open_class = EncodedTriplePattern {
1523            object: None,
1524            ..pattern.clone()
1525        };
1526        assert_eq!(
1527            estimate_join_key_domain(&profile, &open_class, JoinKeySlot::Object),
1528            Some(1),
1529            "one class in class_counts → object domain 1, even with no objects HLL"
1530        );
1531    }
1532
1533    /// Missing or zero class counts fall back to the HLL rather than
1534    /// reporting a zero domain.
1535    #[test]
1536    fn type_scan_subject_domain_falls_back_to_hll_without_exact_count() {
1537        let mut profile = StatsProfile::default();
1538        let dataset = EncodedTerm::from(&NamedNode::new("http://schema.org/Dataset").unwrap());
1539        let unseen = EncodedTerm::from(&NamedNode::new("http://ex/Unseen").unwrap());
1540        let type_hash = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
1541        let mut typed_subjects = HyperLogLog::default_params();
1542        for i in 0..9_000u128 {
1543            typed_subjects.add(i);
1544        }
1545        profile
1546            .subjects_per_predicate
1547            .insert(type_hash, typed_subjects);
1548        // Zero counts (a class whose instances were all deleted) are not a
1549        // usable domain either — fall back like a miss.
1550        profile
1551            .class_counts
1552            .insert(named_node_hash(&unseen).unwrap(), 0);
1553
1554        let pattern = |obj: &EncodedTerm| EncodedTriplePattern {
1555            subject: None,
1556            predicate: Some(RDF_TYPE),
1557            object: Some(obj.clone()),
1558            graph_name: Some(EncodedTerm::DefaultGraph),
1559        };
1560        for (label, obj) in [("missing", &dataset), ("zero", &unseen)] {
1561            let domain =
1562                estimate_join_key_domain(&profile, &pattern(obj), JoinKeySlot::Subject).unwrap();
1563            assert!(
1564                (8_000..=10_000).contains(&domain),
1565                "{label} class count must fall back to the HLL (~9k), got {domain}"
1566            );
1567        }
1568    }
1569
1570    /// The object slot of an open `?s a ?class`: `class_counts.len()` is the
1571    /// exact distinct-class domain and beats a present (approximate, wildly
1572    /// larger) objects HLL.
1573    #[test]
1574    fn type_scan_object_domain_uses_exact_class_count() {
1575        let mut profile = StatsProfile::default();
1576        for iri in ["http://ex/A", "http://ex/B", "http://ex/C"] {
1577            let class = EncodedTerm::from(&NamedNode::new(iri).unwrap());
1578            profile
1579                .class_counts
1580                .insert(named_node_hash(&class).unwrap(), 7);
1581        }
1582        let type_hash = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
1583        let mut objects = HyperLogLog::default_params();
1584        for i in 0..10_000u128 {
1585            objects.add(i);
1586        }
1587        profile.objects_per_predicate.insert(type_hash, objects);
1588
1589        let pattern = EncodedTriplePattern {
1590            subject: None,
1591            predicate: Some(RDF_TYPE),
1592            object: None,
1593            graph_name: Some(EncodedTerm::DefaultGraph),
1594        };
1595        assert_eq!(
1596            estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Object),
1597            Some(3),
1598            "exact class_counts.len() must beat the ~10k objects HLL"
1599        );
1600    }
1601
1602    /// Empty `class_counts` (no exact map): the object slot falls back to
1603    /// the objects HLL unchanged.
1604    #[test]
1605    fn type_scan_object_domain_falls_back_to_hll_without_class_counts() {
1606        let mut profile = StatsProfile::default();
1607        let type_hash = StrHash::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
1608        let mut objects = HyperLogLog::default_params();
1609        for i in 0..121u128 {
1610            objects.add(i);
1611        }
1612        profile.objects_per_predicate.insert(type_hash, objects);
1613
1614        let pattern = EncodedTriplePattern {
1615            subject: None,
1616            predicate: Some(RDF_TYPE),
1617            object: None,
1618            graph_name: Some(EncodedTerm::DefaultGraph),
1619        };
1620        let domain = estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Object).unwrap();
1621        assert!(
1622            (110..=130).contains(&domain),
1623            "empty class_counts → objects HLL (~121), got {domain}"
1624        );
1625    }
1626
1627    /// Non-type predicates are untouched by the exact-class path.
1628    #[test]
1629    fn non_type_predicate_domain_stays_hll() {
1630        let mut profile = StatsProfile::default();
1631        let is_part_of = EncodedTerm::from(&NamedNode::new("http://ex/isPartOf").unwrap());
1632        let dataset = EncodedTerm::from(&NamedNode::new("http://schema.org/Dataset").unwrap());
1633        let pred_hash = StrHash::new("http://ex/isPartOf");
1634        let mut objects = HyperLogLog::default_params();
1635        for i in 0..121u128 {
1636            objects.add(i);
1637        }
1638        profile.objects_per_predicate.insert(pred_hash, objects);
1639        profile
1640            .class_counts
1641            .insert(named_node_hash(&dataset).unwrap(), 5);
1642
1643        let pattern = EncodedTriplePattern {
1644            subject: None,
1645            predicate: Some(is_part_of),
1646            object: None,
1647            graph_name: Some(EncodedTerm::DefaultGraph),
1648        };
1649        let domain = estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Object).unwrap();
1650        assert!(
1651            (110..=130).contains(&domain),
1652            "isPartOf object domain stays the HLL (~121), got {domain}"
1653        );
1654    }
1655
1656    #[test]
1657    fn literal_object_uses_cms() {
1658        let mut live = LiveQuadsProfile::default();
1659        let q = encode_quad(&waratah_storage::Quad::new(
1660            NamedNode::new("http://ex/c").unwrap(),
1661            NamedNode::new("http://ex/hasWeather").unwrap(),
1662            Literal::from("Sunny"),
1663            waratah_storage::GraphName::DefaultGraph,
1664        ))
1665        .unwrap();
1666        observe_quad(&mut live, &q, StorageOp::Put);
1667        let profile = StatsProfile::from(live);
1668        let pattern = EncodedTriplePattern {
1669            subject: None,
1670            predicate: Some(EncodedTerm::from(
1671                &NamedNode::new("http://ex/hasWeather").unwrap(),
1672            )),
1673            object: Some(EncodedTerm::from(&Literal::from("Sunny"))),
1674            graph_name: Some(EncodedTerm::DefaultGraph),
1675        };
1676        assert_eq!(profile.estimate(&pattern), 1);
1677    }
1678
1679    #[test]
1680    fn unseen_bound_predicate_is_one_not_total_puts() {
1681        let mut live = LiveQuadsProfile::default();
1682        let known = NamedNode::new("http://ex/name").unwrap();
1683        let q = encode_quad(&waratah_storage::Quad::new(
1684            NamedNode::new("http://ex/alice").unwrap(),
1685            known.clone(),
1686            Literal::from("Alice"),
1687            waratah_storage::GraphName::DefaultGraph,
1688        ))
1689        .unwrap();
1690        observe_quad(&mut live, &q, StorageOp::Put);
1691        let mut profile = StatsProfile::from(live);
1692        profile.total_puts = 360_000_000;
1693
1694        let unknown_p = EncodedTriplePattern {
1695            subject: None,
1696            predicate: Some(EncodedTerm::from(
1697                &NamedNode::new("http://ex/livesIn").unwrap(),
1698            )),
1699            object: None,
1700            graph_name: Some(EncodedTerm::DefaultGraph),
1701        };
1702        assert_eq!(
1703            estimate_pattern(&profile, &unknown_p),
1704            1,
1705            "bound IRI with no predicate_counts / subjects_per_predicate entry"
1706        );
1707
1708        let unbound_p = EncodedTriplePattern {
1709            subject: None,
1710            predicate: None,
1711            object: None,
1712            graph_name: Some(EncodedTerm::DefaultGraph),
1713        };
1714        assert_eq!(
1715            estimate_pattern(&profile, &unbound_p),
1716            360_000_000,
1717            "unbound ?p still falls back to total_puts"
1718        );
1719
1720        let known_p = EncodedTriplePattern {
1721            subject: None,
1722            predicate: Some(EncodedTerm::from(&known)),
1723            object: None,
1724            graph_name: Some(EncodedTerm::DefaultGraph),
1725        };
1726        assert_eq!(estimate_pattern(&profile, &known_p), 1);
1727    }
1728
1729    #[test]
1730    fn incoming_bound_object_uses_hll_fanout_not_cms() {
1731        // `(?s, locatedIn, ?rack)` with ?rack incoming: no object term, so no
1732        // CMS. HLL |P|/distinct O should still apply (same as a ground object).
1733        let mut profile = StatsProfile::default();
1734        let located_in = NamedNode::new("http://ex/locatedIn").unwrap();
1735        let pred = StrHash::new("http://ex/locatedIn");
1736
1737        profile.total_puts = 10_000;
1738        profile.predicate_counts.insert(pred, 10_000);
1739
1740        let mut objects = HyperLogLog::default_params();
1741        for i in 0..100u128 {
1742            objects.add(i);
1743        }
1744        profile.objects_per_predicate.insert(pred, objects);
1745
1746        let pattern = EncodedTriplePattern {
1747            subject: None,
1748            predicate: Some(EncodedTerm::from(&located_in)),
1749            object: None,
1750            graph_name: Some(EncodedTerm::DefaultGraph),
1751        };
1752
1753        let unbound = estimate_pattern(&profile, &pattern);
1754        let incoming = estimate_pattern_with_bound_slots(
1755            &profile,
1756            &pattern,
1757            ExtraBoundSlots {
1758                object: true,
1759                ..ExtraBoundSlots::default()
1760            },
1761        );
1762
1763        assert_eq!(unbound, 10_000, "predicate-only should be |P|");
1764        assert!(
1765            incoming < unbound,
1766            "incoming-bound object should take HLL fan-out: {incoming} vs {unbound}"
1767        );
1768        assert!(
1769            (50..=200).contains(&incoming),
1770            "expected ~100 fan-out (10000/100), got {incoming}"
1771        );
1772    }
1773
1774    #[test]
1775    fn incoming_bound_predicate_uses_mean_predicate_count() {
1776        // `(?s, ?p, ?o)` with ?p incoming: no pred_hash, so no |P| or HLL.
1777        // Mean |P| = total_puts / |predicate_counts|.
1778        let mut profile = StatsProfile {
1779            total_puts: 10_000,
1780            ..StatsProfile::default()
1781        };
1782        profile
1783            .predicate_counts
1784            .insert(StrHash::new("http://ex/a"), 1_000);
1785        profile
1786            .predicate_counts
1787            .insert(StrHash::new("http://ex/b"), 9_000);
1788
1789        let pattern = EncodedTriplePattern {
1790            subject: None,
1791            predicate: None,
1792            object: None,
1793            graph_name: Some(EncodedTerm::DefaultGraph),
1794        };
1795
1796        let unbound = estimate_pattern(&profile, &pattern);
1797        let incoming = estimate_pattern_with_bound_slots(
1798            &profile,
1799            &pattern,
1800            ExtraBoundSlots {
1801                predicate: true,
1802                ..ExtraBoundSlots::default()
1803            },
1804        );
1805
1806        assert_eq!(unbound, 10_000, "unbound ?p should be total_puts");
1807        assert_eq!(incoming, 5_000, "incoming ?p should be mean |P| (10000/2)");
1808    }
1809
1810    #[test]
1811    fn incoming_type_object_without_class_iri_skips_class_map() {
1812        let mut profile = StatsProfile::default();
1813        let type_pred = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap();
1814        let person = NamedNode::new("http://ex/Person").unwrap();
1815        profile
1816            .class_counts
1817            .insert(StrHash::new("http://ex/Person"), 5_000);
1818        profile.total_puts = 5_000;
1819
1820        let with_class = EncodedTriplePattern {
1821            subject: None,
1822            predicate: Some(EncodedTerm::from(&type_pred)),
1823            object: Some(EncodedTerm::from(&person)),
1824            graph_name: Some(EncodedTerm::DefaultGraph),
1825        };
1826        assert_eq!(estimate_pattern(&profile, &with_class), 5_000);
1827
1828        let fully_bound = EncodedTriplePattern {
1829            subject: Some(EncodedTerm::from(
1830                &NamedNode::new("http://ex/alice").unwrap(),
1831            )),
1832            predicate: Some(EncodedTerm::from(&type_pred)),
1833            object: Some(EncodedTerm::from(&person)),
1834            graph_name: Some(EncodedTerm::DefaultGraph),
1835        };
1836        assert_eq!(
1837            estimate_pattern(&profile, &fully_bound),
1838            1,
1839            "ground S/P/O is a point lookup, not the class map"
1840        );
1841
1842        let incoming_class_var = EncodedTriplePattern {
1843            subject: None,
1844            predicate: Some(EncodedTerm::from(&type_pred)),
1845            object: None,
1846            graph_name: Some(EncodedTerm::DefaultGraph),
1847        };
1848        let incoming = estimate_pattern_with_bound_slots(
1849            &profile,
1850            &incoming_class_var,
1851            ExtraBoundSlots {
1852                object: true,
1853                ..ExtraBoundSlots::default()
1854            },
1855        );
1856        assert_ne!(
1857            incoming, 5_000,
1858            "incoming ?class on rdf:type must not use the Person class map"
1859        );
1860    }
1861
1862    /// Two observations per distinct value, several predicates — enough for
1863    /// cardinality to land near the true distinct count.
1864    fn derived_domains_fixture() -> (StatsProfile, Vec<(StrHash, u64, u64)>) {
1865        let mut live = LiveQuadsProfile::default();
1866        let mut expected: Vec<(StrHash, u64, u64)> = Vec::new();
1867        for p in 0..3u8 {
1868            let pred = NamedNode::new(format!("http://ex/pred{p}")).unwrap();
1869            let pred_hash = crate::named_node_hash(&EncodedTerm::from(&pred)).unwrap();
1870            let distinct = 100 * (p as u64 + 1);
1871            for i in 0..distinct {
1872                let subject = NamedNode::new(format!("http://ex/s{p}-{i}")).unwrap();
1873                let object = NamedNode::new(format!("http://ex/o{p}-{i}")).unwrap();
1874                for _ in 0..2 {
1875                    let q = encode_quad(&waratah_storage::Quad::new(
1876                        subject.clone(),
1877                        pred.clone(),
1878                        object.clone(),
1879                        waratah_storage::GraphName::DefaultGraph,
1880                    ))
1881                    .unwrap();
1882                    observe_quad(&mut live, &q, StorageOp::Put);
1883                }
1884            }
1885            let subject_domain = live.subjects_per_predicate[&pred_hash].cardinality().max(1);
1886            let object_domain = live.objects_per_predicate[&pred_hash].cardinality().max(1);
1887            expected.push((pred_hash, subject_domain, object_domain));
1888        }
1889        (StatsProfile::from(live), expected)
1890    }
1891
1892    #[test]
1893    fn derive_hll_domains_matches_manual_cardinality() {
1894        let (mut profile, expected) = derived_domains_fixture();
1895        assert!(profile.subject_domains_per_predicate.is_empty());
1896        profile.derive_hll_domains();
1897        for (hash, subject_domain, object_domain) in &expected {
1898            assert_eq!(
1899                profile.subject_domains_per_predicate.get(hash),
1900                Some(subject_domain)
1901            );
1902            assert_eq!(
1903                profile.object_domains_per_predicate.get(hash),
1904                Some(object_domain)
1905            );
1906            // The readers answer from the cache, byte-identical.
1907            assert_eq!(profile.subject_domain(hash), Some(*subject_domain));
1908            assert_eq!(profile.object_domain(hash), Some(*object_domain));
1909        }
1910    }
1911
1912    #[test]
1913    fn domain_readers_fall_back_to_on_the_fly_cardinality() {
1914        // Hand-built / decoded profiles carry empty caches; the readers must
1915        // compute per call and return exactly what the cached path would.
1916        let (profile, expected) = derived_domains_fixture();
1917        for (hash, subject_domain, object_domain) in &expected {
1918            assert_eq!(profile.subject_domain(hash), Some(*subject_domain));
1919            assert_eq!(profile.object_domain(hash), Some(*object_domain));
1920        }
1921        assert_eq!(profile.subject_domain(&absent_hash()), None);
1922        assert_eq!(profile.object_domain(&absent_hash()), None);
1923    }
1924
1925    fn absent_hash() -> StrHash {
1926        crate::named_node_hash(&EncodedTerm::from(
1927            &NamedNode::new("http://ex/absent").unwrap(),
1928        ))
1929        .unwrap()
1930    }
1931
1932    #[test]
1933    fn cap_and_rollup_clear_inherited_domain_caches() {
1934        let (mut profile, _) = derived_domains_fixture();
1935        profile.derive_hll_domains();
1936        assert!(!profile.subject_domains_per_predicate.is_empty());
1937
1938        let capped = profile.capped_for_wire();
1939        assert!(capped.subject_domains_per_predicate.is_empty());
1940        assert!(capped.object_domains_per_predicate.is_empty());
1941
1942        let rolled = rollup_cluster(&[(PartitionAxis::S, profile)]);
1943        assert!(rolled.subject_domains_per_predicate.is_empty());
1944        assert!(rolled.object_domains_per_predicate.is_empty());
1945    }
1946
1947    #[test]
1948    fn tight_wire_cap_clears_cache_when_predicates_are_dropped() {
1949        // The default 3 MiB budget keeps every fixture pair, so it never
1950        // exercises the trimmed set. Budget exactly the largest pair (plus
1951        // the fixed skeleton): p2 ranks first by exact count, p1/p0 drop.
1952        let (mut profile, expected) = derived_domains_fixture();
1953        profile.derive_hll_domains();
1954
1955        let mut skeleton = profile.clone();
1956        skeleton.subjects_per_predicate.clear();
1957        skeleton.objects_per_predicate.clear();
1958        let skeleton_bytes = crate::serde_bin::to_bytes(&skeleton).len();
1959        let top = expected[2].0;
1960        let top_cost = hll_wire_entry_bytes(profile.subjects_per_predicate.get(&top))
1961            + hll_wire_entry_bytes(profile.objects_per_predicate.get(&top));
1962
1963        let capped = profile.capped_for_wire_with_budget(skeleton_bytes + top_cost);
1964        assert_eq!(capped.subjects_per_predicate.len(), 1);
1965        assert!(capped.subjects_per_predicate.contains_key(&top));
1966        assert!(!capped.subjects_per_predicate.contains_key(&expected[0].0));
1967        // The trimmed set must not inherit cardinalities for dropped (or
1968        // kept) predicates.
1969        assert!(capped.subject_domains_per_predicate.is_empty());
1970        assert!(capped.object_domains_per_predicate.is_empty());
1971        assert_eq!(capped.subject_domain(&top), Some(expected[2].1));
1972    }
1973
1974    /// The frame split's load-bearing assembly: the canonical trim respects
1975    /// BOTH frame budgets, the core cap empties geo/temporal, and the two
1976    /// sliced frames (subset-populated sections) round-trip and merge back
1977    /// into exactly the trimmed histogram — the property the partition
1978    /// handlers and the compute rollup both rely on.
1979    #[test]
1980    fn geo_frames_round_trip_and_merge_into_the_canonical_trim() {
1981        let mut profile = StatsProfile::default();
1982        // Fine mass: three buckets, one large. Coarse mass: one level-8
1983        // posting (count-once side) and one level-4 posting.
1984        *profile.geo_cell_histogram.fine.entry(100).or_insert(0) += 7;
1985        *profile.geo_cell_histogram.fine.entry(101).or_insert(0) += 1;
1986        *profile.geo_cell_histogram.fine.entry(102).or_insert(0) += 1;
1987        profile
1988            .geo_cell_histogram
1989            .observe_posting(1u64 << (60 - 2 * 8));
1990        profile
1991            .geo_cell_histogram
1992            .observe_posting(1u64 << (60 - 2 * 4));
1993
1994        let canonical = profile.capped_geo_histogram_for_wire();
1995        // Budget behavior is NOT asserted on this tiny fixture — the
1996        // assertion here would be vacuous. Saturation-level budget pinning
1997        // lives in geo_frames_at_saturation_stay_under_the_message_ceiling.
1998
1999        // Slice the frames exactly as the partition handler does.
2000        let fine_frame = crate::geo_cell_histogram::GeoCellHistogram {
2001            coarse: std::collections::BTreeMap::new(),
2002            ..canonical.clone()
2003        };
2004        let coarse_frame = crate::geo_cell_histogram::GeoCellHistogram {
2005            fine: std::collections::BTreeMap::new(),
2006            remainder: std::collections::BTreeMap::new(),
2007            ..canonical.clone()
2008        };
2009        let mut fine_bytes = Vec::new();
2010        fine_frame.encode_body(&mut fine_bytes);
2011        let mut coarse_bytes = Vec::new();
2012        coarse_frame.encode_body(&mut coarse_bytes);
2013        let mut fine_cursor = fine_bytes.as_slice();
2014        let mut coarse_cursor = coarse_bytes.as_slice();
2015        let mut reassembled =
2016            crate::geo_cell_histogram::GeoCellHistogram::decode_body(&mut fine_cursor)
2017                .expect("fine frame decodes");
2018        reassembled.merge(
2019            &crate::geo_cell_histogram::GeoCellHistogram::decode_body(&mut coarse_cursor)
2020                .expect("coarse frame decodes"),
2021        );
2022        assert_eq!(reassembled, canonical, "frames merge back into the trim");
2023
2024        // The CORE cap empties geo (and temporal) — no double-count path
2025        // through the core blob.
2026        let core = profile.capped_for_wire();
2027        assert!(core.geo_cell_histogram.is_empty());
2028        assert_eq!(
2029            core.temporal_histogram,
2030            crate::TickHistogram::default(),
2031            "the core blob's temporal section is empty — its frame carries it"
2032        );
2033    }
2034
2035    /// The frame budgets' REAL contract, pinned at saturation: the
2036    /// fine-map and remainder budgets
2037    /// are INDEPENDENT and ADDITIVE — a saturated canonical keeps exactly
2038    /// 229,376 fine entries AND 32,768 remainder entries, so the FINE
2039    /// message is 2.25 MiB, not the 1.75 MiB a carve would give — and each
2040    /// sliced frame's encoded body stays under the 4 MiB gRPC message
2041    /// ceiling (`waratah_proto::GRPC_MAX_MESSAGE_SIZE`; stats cannot depend
2042    /// on proto, so the literal is pinned here with framing headroom). This
2043    /// is the test the tiny round-trip fixture cannot be: its budget
2044    /// assertions were vacuous.
2045    #[test]
2046    fn geo_frames_at_saturation_stay_under_the_message_ceiling() {
2047        const FRAME_HEADER_BYTES: usize = 2 + 3 * 4; // version u16 + three map length u32s
2048        // Message framing: proto tag byte + length varint (≤ 4 bytes at
2049        // these sizes).
2050        const MESSAGE_FRAMING_BYTES: usize = 5;
2051        const GRPC_MAX_MESSAGE_SIZE: usize = 4 * 1024 * 1024;
2052
2053        let fine_kept = crate::GEO_FINE_FRAME_BUDGET_BYTES / crate::GEO_FINE_WIRE_ENTRY_BYTES;
2054        let remainder_kept =
2055            crate::GEO_REMAINDER_WIRE_BUDGET_BYTES / crate::GEO_REMAINDER_WIRE_ENTRY_BYTES;
2056        let coarse_kept = crate::GEO_COARSE_FRAME_BUDGET_BYTES / crate::GEO_COARSE_WIRE_ENTRY_BYTES;
2057
2058        let mut big = crate::geo_cell_histogram::GeoCellHistogram::default();
2059        // Fine buckets spaced 64 apart so every bucket is its own L8 parent
2060        // (parent = bucket >> 6): the 40k dropped tail then produces 40k
2061        // single-parent remainder entries, saturating the remainder budget
2062        // from fine drops alone.
2063        for i in 0..(fine_kept + 40_000) {
2064            *big.fine.entry((i as u32) * 64).or_insert(0) += 1;
2065        }
2066        for i in 0..(coarse_kept + 8_000) {
2067            big.coarse.insert(0x8000_0000_0000_0000 + i as u64, 1);
2068        }
2069        let profile = StatsProfile {
2070            geo_cell_histogram: big,
2071            ..StatsProfile::default()
2072        };
2073
2074        let canonical = profile.capped_geo_histogram_for_wire();
2075        assert_eq!(
2076            canonical.fine.len(),
2077            fine_kept,
2078            "the fine map saturates exactly at its budget"
2079        );
2080        assert_eq!(
2081            canonical.remainder.len(),
2082            remainder_kept,
2083            "the remainder saturates INDEPENDENTLY — additive on top of the fine map"
2084        );
2085        assert_eq!(
2086            canonical.coarse.len(),
2087            coarse_kept,
2088            "the coarse map saturates exactly at its budget"
2089        );
2090
2091        // Slice exactly as the partition handler does, then encode.
2092        let fine_frame = crate::geo_cell_histogram::GeoCellHistogram {
2093            coarse: std::collections::BTreeMap::new(),
2094            ..canonical.clone()
2095        };
2096        let coarse_frame = crate::geo_cell_histogram::GeoCellHistogram {
2097            fine: std::collections::BTreeMap::new(),
2098            remainder: std::collections::BTreeMap::new(),
2099            ..canonical.clone()
2100        };
2101        let mut fine_body = Vec::new();
2102        fine_frame.encode_body(&mut fine_body);
2103        let mut coarse_body = Vec::new();
2104        coarse_frame.encode_body(&mut coarse_body);
2105
2106        // ADDITIVE acceptance: the FINE body EXCEEDS the fine budget alone —
2107        // the remainder rides on top (documented 2026-10-27). A future
2108        // change that reintroduces a carve must consciously flip this.
2109        assert!(
2110            fine_body.len() > crate::GEO_FINE_FRAME_BUDGET_BYTES,
2111            "the remainder budget is additive, not carved out"
2112        );
2113        let fine_bound = crate::GEO_FINE_FRAME_BUDGET_BYTES
2114            + crate::GEO_REMAINDER_WIRE_BUDGET_BYTES
2115            + FRAME_HEADER_BYTES;
2116        assert!(
2117            fine_body.len() <= fine_bound,
2118            "FINE body {} exceeds fine + remainder budgets + header {}",
2119            fine_body.len(),
2120            fine_bound
2121        );
2122        let coarse_bound = crate::GEO_COARSE_FRAME_BUDGET_BYTES + FRAME_HEADER_BYTES;
2123        assert!(
2124            coarse_body.len() <= coarse_bound,
2125            "COARSE body {} exceeds its budget + header {}",
2126            coarse_body.len(),
2127            coarse_bound
2128        );
2129        // The per-message contract that actually matters for the wire.
2130        assert!(
2131            fine_body.len() + MESSAGE_FRAMING_BYTES <= GRPC_MAX_MESSAGE_SIZE,
2132            "saturated FINE message must stay under the gRPC ceiling"
2133        );
2134        assert!(
2135            coarse_body.len() + MESSAGE_FRAMING_BYTES <= GRPC_MAX_MESSAGE_SIZE,
2136            "saturated COARSE message must stay under the gRPC ceiling"
2137        );
2138    }
2139
2140    #[test]
2141    fn merge_clears_hll_cardinality_cache() {
2142        let (mut profile, expected) = derived_domains_fixture();
2143        profile.derive_hll_domains();
2144        assert!(!profile.subject_domains_per_predicate.is_empty());
2145        assert!(!profile.object_domains_per_predicate.is_empty());
2146
2147        let (hash, cached_subject, _) = &expected[0];
2148        // A disjoint right-hand observation set for the same predicate grows
2149        // the merged HLL; the pre-merge cached count would be stale.
2150        let mut live = LiveQuadsProfile::default();
2151        let pred = NamedNode::new("http://ex/pred0").unwrap();
2152        for i in 0..50 {
2153            let q = encode_quad(&waratah_storage::Quad::new(
2154                NamedNode::new(format!("http://ex/merge-s{i}")).unwrap(),
2155                pred.clone(),
2156                NamedNode::new(format!("http://ex/merge-o{i}")).unwrap(),
2157                waratah_storage::GraphName::DefaultGraph,
2158            ))
2159            .unwrap();
2160            observe_quad(&mut live, &q, StorageOp::Put);
2161        }
2162        let right = StatsProfile::from(live);
2163
2164        profile.merge(&right).expect("merge succeeds");
2165        assert!(profile.subject_domains_per_predicate.is_empty());
2166        assert!(profile.object_domains_per_predicate.is_empty());
2167        let merged = profile.subject_domain(hash).expect("merged sketch answers");
2168        assert!(
2169            merged > *cached_subject,
2170            "live answer must reflect the merged sketch, got {merged} <= {cached_subject}"
2171        );
2172    }
2173
2174    #[test]
2175    fn derived_domains_are_not_serialized() {
2176        let (mut profile, expected) = derived_domains_fixture();
2177        profile.derive_hll_domains();
2178        let decoded = crate::from_bytes(&crate::to_bytes(&profile)).expect("round-trips");
2179        assert!(decoded.subject_domains_per_predicate.is_empty());
2180        assert!(decoded.object_domains_per_predicate.is_empty());
2181        // Wire format unchanged: encoded bytes identical to a never-derived
2182        // profile with the same sketches.
2183        let (plain, _) = derived_domains_fixture();
2184        assert_eq!(crate::to_bytes(&profile), crate::to_bytes(&plain));
2185        // And the decoded profile still answers, via the fallback.
2186        for (hash, subject_domain, object_domain) in &expected {
2187            assert_eq!(decoded.subject_domain(hash), Some(*subject_domain));
2188            assert_eq!(decoded.object_domain(hash), Some(*object_domain));
2189        }
2190    }
2191
2192    #[test]
2193    fn estimators_agree_with_and_without_derived_domains() {
2194        let (mut profile, _) = derived_domains_fixture();
2195        profile.derive_hll_domains();
2196        let (plain, _) = derived_domains_fixture();
2197        let pred = NamedNode::new("http://ex/pred1").unwrap();
2198        let pattern = EncodedTriplePattern {
2199            subject: None,
2200            predicate: Some(EncodedTerm::from(&pred)),
2201            object: None,
2202            graph_name: Some(EncodedTerm::DefaultGraph),
2203        };
2204        assert_eq!(
2205            estimate_pattern(&profile, &pattern),
2206            estimate_pattern(&plain, &pattern)
2207        );
2208        assert_eq!(
2209            estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Subject),
2210            estimate_join_key_domain(&plain, &pattern, JoinKeySlot::Subject)
2211        );
2212        assert_eq!(
2213            estimate_join_key_domain(&profile, &pattern, JoinKeySlot::Object),
2214            estimate_join_key_domain(&plain, &pattern, JoinKeySlot::Object)
2215        );
2216    }
2217    /// Pattern helper for the overlap tests. Only the predicate and the
2218    /// key slot affect the lookup; S/O take placeholder IRIs. `None` pred
2219    /// = unbound predicate (the `?mayor ?p ?o` shape).
2220    fn overlap_pattern(pred: Option<&str>) -> EncodedTriplePattern {
2221        EncodedTriplePattern {
2222            subject: Some(EncodedTerm::from(
2223                &NamedNode::new("http://ex/varS").unwrap(),
2224            )),
2225            predicate: pred.map(|p| EncodedTerm::from(&NamedNode::new(p).unwrap())),
2226            object: Some(EncodedTerm::from(
2227                &NamedNode::new("http://ex/varO").unwrap(),
2228            )),
2229            graph_name: None,
2230        }
2231    }
2232
2233    #[test]
2234    fn overlap_estimates_disjoint_vocabularies_near_zero() {
2235        // The spaceport shape: 300 university towns under :fromTown vs 3
2236        // spaceport towns under :hasSpacePort, disjoint value sets. The
2237        // containment fraction must come out ~0 where the count rule sees
2238        // 300 >= 0.9 x 3 and concludes "covered".
2239        let mut live = LiveQuadsProfile::default();
2240        let towns: Vec<_> = (0..300)
2241            .map(|i| NamedNode::new(format!("http://ex/town{i}")).unwrap())
2242            .collect();
2243        let ports: Vec<_> = (0..3)
2244            .map(|i| NamedNode::new(format!("http://ex/spaceport{i}")).unwrap())
2245            .collect();
2246        let from_town = NamedNode::new("http://ex/fromTown").unwrap();
2247        let has_port = NamedNode::new("http://ex/hasSpacePort").unwrap();
2248        for (i, town) in towns.iter().enumerate() {
2249            let q = encode_quad(&waratah_storage::Quad::new(
2250                NamedNode::new(format!("http://ex/person{i}")).unwrap(),
2251                from_town.clone(),
2252                town.clone(),
2253                waratah_storage::GraphName::DefaultGraph,
2254            ))
2255            .unwrap();
2256            observe_quad(&mut live, &q, StorageOp::Put);
2257        }
2258        for (i, port) in ports.iter().enumerate() {
2259            let q = encode_quad(&waratah_storage::Quad::new(
2260                NamedNode::new(format!("http://ex/sp{i}")).unwrap(),
2261                has_port.clone(),
2262                port.clone(),
2263                waratah_storage::GraphName::DefaultGraph,
2264            ))
2265            .unwrap();
2266            observe_quad(&mut live, &q, StorageOp::Put);
2267        }
2268        let profile = StatsProfile::from(live);
2269        let driver = overlap_pattern(Some("http://ex/fromTown"));
2270        let probe = overlap_pattern(Some("http://ex/hasSpacePort"));
2271        let overlap = estimate_vocabulary_overlap(
2272            &profile,
2273            &driver,
2274            JoinKeySlot::Object,
2275            &probe,
2276            JoinKeySlot::Object,
2277        )
2278        .expect("both sketches present");
2279        // Disjoint: the true fraction is 0; sketch noise must keep the
2280        // estimate far below the ~330 milli a cover verdict needs at a
2281        // 3-value probe (1/300 of driver card would be ~3 milli per
2282        // colliding value).
2283        assert!(overlap <= 30, "disjoint vocabularies, got {overlap} milli");
2284    }
2285
2286    #[test]
2287    fn overlap_estimates_nested_vocabularies_high() {
2288        // Containment: every :playsFor subject also appears under
2289        // :isCitizenOf (plus extra citizens). The driver (playsFor)
2290        // fraction inside the probe vocabulary should come out high.
2291        let mut live = LiveQuadsProfile::default();
2292        let plays = NamedNode::new("http://ex/playsFor").unwrap();
2293        let citizen = NamedNode::new("http://ex/isCitizenOf").unwrap();
2294        for i in 0..200u64 {
2295            let player = NamedNode::new(format!("http://ex/player{i}")).unwrap();
2296            let q = encode_quad(&waratah_storage::Quad::new(
2297                player.clone(),
2298                plays.clone(),
2299                NamedNode::new(format!("http://ex/team{i}")).unwrap(),
2300                waratah_storage::GraphName::DefaultGraph,
2301            ))
2302            .unwrap();
2303            observe_quad(&mut live, &q, StorageOp::Put);
2304            let q = encode_quad(&waratah_storage::Quad::new(
2305                player,
2306                citizen.clone(),
2307                NamedNode::new("http://ex/city").unwrap(),
2308                waratah_storage::GraphName::DefaultGraph,
2309            ))
2310            .unwrap();
2311            observe_quad(&mut live, &q, StorageOp::Put);
2312        }
2313        for i in 0..600u64 {
2314            let q = encode_quad(&waratah_storage::Quad::new(
2315                NamedNode::new(format!("http://ex/citizen{i}")).unwrap(),
2316                citizen.clone(),
2317                NamedNode::new("http://ex/city").unwrap(),
2318                waratah_storage::GraphName::DefaultGraph,
2319            ))
2320            .unwrap();
2321            observe_quad(&mut live, &q, StorageOp::Put);
2322        }
2323        let profile = StatsProfile::from(live);
2324        let driver = overlap_pattern(Some("http://ex/playsFor"));
2325        let probe = overlap_pattern(Some("http://ex/isCitizenOf"));
2326        let overlap = estimate_vocabulary_overlap(
2327            &profile,
2328            &driver,
2329            JoinKeySlot::Subject,
2330            &probe,
2331            JoinKeySlot::Subject,
2332        )
2333        .expect("both sketches present");
2334        // All 200 players are citizens of the same object; the SUBJECT
2335        // vocabularies overlap in ~200 of ~800 citizens (drivers inside
2336        // probes). Fractions: |A ∩ B| ≈ 200, |A| = 200 → r ≈ 1000.
2337        assert!(overlap >= 700, "nested vocabularies, got {overlap} milli");
2338    }
2339
2340    #[test]
2341    fn overlap_identity_same_predicate_same_slot_is_full() {
2342        let mut live = LiveQuadsProfile::default();
2343        let from_town = NamedNode::new("http://ex/fromTown").unwrap();
2344        for i in 0..50u64 {
2345            let q = encode_quad(&waratah_storage::Quad::new(
2346                NamedNode::new(format!("http://ex/me{i}")).unwrap(),
2347                from_town.clone(),
2348                NamedNode::new(format!("http://ex/town{i}")).unwrap(),
2349                waratah_storage::GraphName::DefaultGraph,
2350            ))
2351            .unwrap();
2352            observe_quad(&mut live, &q, StorageOp::Put);
2353        }
2354        let profile = StatsProfile::from(live);
2355        let me = overlap_pattern(Some("http://ex/fromTown"));
2356        let mayor = overlap_pattern(Some("http://ex/fromTown"));
2357        let overlap = estimate_vocabulary_overlap(
2358            &profile,
2359            &me,
2360            JoinKeySlot::Object,
2361            &mayor,
2362            JoinKeySlot::Object,
2363        )
2364        .expect("identity pair");
2365        assert_eq!(overlap, VOCABULARY_OVERLAP_FULL_MILLI, "same vocabulary");
2366        // Different slots of the same predicate do NOT take the
2367        // fast-path — the sketches genuinely differ.
2368        let flipped = overlap_pattern(Some("http://ex/fromTown"));
2369        let overlap = estimate_vocabulary_overlap(
2370            &profile,
2371            &me,
2372            JoinKeySlot::Object,
2373            &flipped,
2374            JoinKeySlot::Subject,
2375        )
2376        .expect("both sketches present");
2377        assert_ne!(
2378            overlap, VOCABULARY_OVERLAP_FULL_MILLI,
2379            "object vocabulary vs subject vocabulary: 50 towns, 50 people"
2380        );
2381    }
2382
2383    #[test]
2384    fn overlap_degrades_to_none_on_unknowns() {
2385        let mut live = LiveQuadsProfile::default();
2386        let pred = NamedNode::new("http://ex/known").unwrap();
2387        for i in 0..10u64 {
2388            let q = encode_quad(&waratah_storage::Quad::new(
2389                NamedNode::new(format!("http://ex/s{i}")).unwrap(),
2390                pred.clone(),
2391                NamedNode::new(format!("http://ex/o{i}")).unwrap(),
2392                waratah_storage::GraphName::DefaultGraph,
2393            ))
2394            .unwrap();
2395            observe_quad(&mut live, &q, StorageOp::Put);
2396        }
2397        let profile = StatsProfile::from(live);
2398        let known = overlap_pattern(Some("http://ex/known"));
2399        // Unbound predicate on one side.
2400        let unbound = overlap_pattern(None);
2401        assert_eq!(
2402            None,
2403            estimate_vocabulary_overlap(
2404                &profile,
2405                &known,
2406                JoinKeySlot::Object,
2407                &unbound,
2408                JoinKeySlot::Object,
2409            )
2410        );
2411        // rdf:type on either side keeps the count rule.
2412        let typed = overlap_pattern(Some("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"));
2413        assert_eq!(
2414            None,
2415            estimate_vocabulary_overlap(
2416                &profile,
2417                &typed,
2418                JoinKeySlot::Object,
2419                &known,
2420                JoinKeySlot::Object,
2421            )
2422        );
2423        // Missing sketch (predicate never observed).
2424        let missing = overlap_pattern(Some("http://ex/never-seen"));
2425        assert_eq!(
2426            None,
2427            estimate_vocabulary_overlap(
2428                &profile,
2429                &known,
2430                JoinKeySlot::Object,
2431                &missing,
2432                JoinKeySlot::Object,
2433            )
2434        );
2435        // Wire-trimmed maps: an empty profile still answers the identity
2436        // pair FULL (same predicate + slot = same vocabulary by
2437        // construction, no sketch needed), but a DIFFERENT-predicate pair
2438        // with no sketches has no vocabulary to merge — degrade.
2439        assert_eq!(
2440            Some(VOCABULARY_OVERLAP_FULL_MILLI),
2441            estimate_vocabulary_overlap(
2442                &StatsProfile::default(),
2443                &known,
2444                JoinKeySlot::Object,
2445                &known,
2446                JoinKeySlot::Object,
2447            )
2448        );
2449        assert_eq!(
2450            None,
2451            estimate_vocabulary_overlap(
2452                &StatsProfile::default(),
2453                &known,
2454                JoinKeySlot::Object,
2455                &missing,
2456                JoinKeySlot::Object,
2457            )
2458        );
2459    }
2460}