Skip to main content

waratah_stats/
shard.rs

1//! In-memory shard stats: write-path `open` overlay plus cached SST merge.
2
3use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
5
6use crate::GeoCellHistogram;
7use crate::LiveQuadsProfile;
8use crate::StatsError;
9use crate::StatsProfile;
10use crate::TickHistogram;
11use crate::serde_bin::from_bytes;
12use waratah_storage::StrHash;
13
14/// SST `user_collected_properties` key for a serialized [`StatsProfile`].
15pub const STATS_USER_PROPERTY_KEY: &[u8] = b"waratah.stats";
16
17/// Flags set from RocksDB flush/compaction callbacks without taking a mutex.
18#[derive(Debug)]
19pub struct SstInvalidationFlags {
20    sealed_stale: AtomicBool,
21    open_absorbed: AtomicBool,
22    catalog_absorbed: AtomicBool,
23    temporal_absorbed: AtomicBool,
24    geo_absorbed: AtomicBool,
25    flush_events: AtomicU64,
26    compaction_events: AtomicU64,
27}
28
29impl Default for SstInvalidationFlags {
30    fn default() -> Self {
31        Self::new()
32    }
33}
34
35impl SstInvalidationFlags {
36    /// Both flags clear (`sealed` is considered valid / empty).
37    pub fn new() -> Self {
38        Self {
39            sealed_stale: AtomicBool::new(false),
40            open_absorbed: AtomicBool::new(false),
41            catalog_absorbed: AtomicBool::new(false),
42            temporal_absorbed: AtomicBool::new(false),
43            geo_absorbed: AtomicBool::new(false),
44            flush_events: AtomicU64::new(0),
45            compaction_events: AtomicU64::new(0),
46        }
47    }
48
49    /// Flush completed: live SST set changed and the aside (`flushing`) is in those SSTs.
50    pub fn mark_flush(&self) {
51        self.sealed_stale.store(true, Ordering::SeqCst);
52        self.open_absorbed.store(true, Ordering::SeqCst);
53        self.flush_events.fetch_add(1, Ordering::SeqCst);
54    }
55
56    /// Compaction completed: live SST set changed; memtable is unrelated.
57    pub fn mark_compaction(&self) {
58        self.sealed_stale.store(true, Ordering::SeqCst);
59        self.compaction_events.fetch_add(1, Ordering::SeqCst);
60    }
61
62    /// `true` from open until the first sealed-profile reload: the live
63    /// SST set changed (or was never read), so the sealed contribution is
64    /// unknown. Read-side consumers that must not under-estimate (the
65    /// scan-dispatch gate) dispatch while this is set.
66    pub fn sealed_stale(&self) -> bool {
67        self.sealed_stale.load(Ordering::SeqCst)
68    }
69
70    /// Catalog CF flush completed: live SST set changed and the catalog aside is in those SSTs.
71    pub fn mark_catalog_flush(&self) {
72        self.sealed_stale.store(true, Ordering::SeqCst);
73        self.catalog_absorbed.store(true, Ordering::SeqCst);
74        self.flush_events.fetch_add(1, Ordering::SeqCst);
75    }
76
77    /// Temporal CF flush completed: live SST set changed and the temporal aside is in those SSTs.
78    pub fn mark_temporal_flush(&self) {
79        self.sealed_stale.store(true, Ordering::SeqCst);
80        self.temporal_absorbed.store(true, Ordering::SeqCst);
81        self.flush_events.fetch_add(1, Ordering::SeqCst);
82    }
83
84    /// Geo CF flush completed: live SST set changed and the geo aside is in those SSTs.
85    pub fn mark_geo_flush(&self) {
86        self.sealed_stale.store(true, Ordering::SeqCst);
87        self.geo_absorbed.store(true, Ordering::SeqCst);
88        self.flush_events.fetch_add(1, Ordering::SeqCst);
89    }
90
91    /// Mark `sealed` stale (RocksDB open: first stats RPC must reload live SST blobs).
92    pub fn mark_sealed_stale(&self) {
93        self.sealed_stale.store(true, Ordering::SeqCst);
94    }
95
96    /// Take the stale bit. `true` means the next stats RPC must reload SST blobs.
97    pub fn take_sealed_stale(&self) -> bool {
98        self.sealed_stale.swap(false, Ordering::SeqCst)
99    }
100
101    /// Take the absorbed bit. `true` means `flushing` must be dropped after reload.
102    pub fn take_open_absorbed(&self) -> bool {
103        self.open_absorbed.swap(false, Ordering::SeqCst)
104    }
105
106    /// Take the catalog absorbed bit. `true` means `catalog_flushing` must be dropped after reload.
107    pub fn take_catalog_absorbed(&self) -> bool {
108        self.catalog_absorbed.swap(false, Ordering::SeqCst)
109    }
110
111    /// Take the temporal absorbed bit. `true` means `temporal_flushing` must be dropped after reload.
112    pub fn take_temporal_absorbed(&self) -> bool {
113        self.temporal_absorbed.swap(false, Ordering::SeqCst)
114    }
115
116    /// Take the geo absorbed bit. `true` means `geo_flushing` must be dropped after reload.
117    pub fn take_geo_absorbed(&self) -> bool {
118        self.geo_absorbed.swap(false, Ordering::SeqCst)
119    }
120
121    /// Completed flush jobs observed by the event listener.
122    pub fn flush_event_count(&self) -> u64 {
123        self.flush_events.load(Ordering::SeqCst)
124    }
125
126    /// Completed compaction jobs observed by the event listener.
127    pub fn compaction_event_count(&self) -> u64 {
128        self.compaction_events.load(Ordering::SeqCst)
129    }
130}
131
132/// Write-path estimate plus cached merge of live SST `waratah.stats` blobs.
133///
134/// `open` tracks the current MemTable. `OnFlushBegin` moves it to `flushing`
135/// (the frozen MemTable still being written to SST) and zeros `open`. Stats
136/// RPCs during the flush use `sealed ⊕ flushing ⊕ open`. `OnFlushCompleted`
137/// sets [`SstInvalidationFlags::open_absorbed`]; the next reload drops
138/// `flushing`, not `open`.
139///
140/// Two counts are **not** stored on the write-path [`LiveQuadsProfile`] at all;
141/// each rides its own CF-keyed overlay instead, because their SST blobs are
142/// produced by a different CF than the canonical hexastore flush the generic
143/// rotation listens to:
144///
145/// - [`StatsProfile::named_graph_count`]: catalog adds/drops update
146///   `catalog_open`; catalog-CF `OnFlushBegin` moves that aside to
147///   `catalog_flushing`.
148/// - [`StatsProfile::temporal_histogram`]: posting applies/rebuilds update
149///   `temporal_open` (`observe_temporal_posting`); temporal-CF
150///   `OnFlushBegin` moves it aside to `temporal_flushing`. Without its own
151///   rotation, a postings-only stretch between canonical flushes counted
152///   every posting in both `open` and the SST blob (transient 2×).
153#[derive(Debug)]
154pub struct ShardStats {
155    open: LiveQuadsProfile,
156    flushing: LiveQuadsProfile,
157    sealed: StatsProfile,
158    catalog_open: u64,
159    catalog_flushing: u64,
160    temporal_open: TickHistogram,
161    temporal_flushing: TickHistogram,
162    geo_open: GeoCellHistogram,
163    geo_flushing: GeoCellHistogram,
164    flags: Arc<SstInvalidationFlags>,
165}
166
167impl Default for ShardStats {
168    fn default() -> Self {
169        Self::memory()
170    }
171}
172
173impl ShardStats {
174    /// Memory backend: `open` is the whole profile; SST flags stay clear.
175    pub fn memory() -> Self {
176        Self {
177            open: LiveQuadsProfile::default(),
178            flushing: LiveQuadsProfile::default(),
179            sealed: StatsProfile::default(),
180            catalog_open: 0,
181            catalog_flushing: 0,
182            temporal_open: TickHistogram::default(),
183            temporal_flushing: TickHistogram::default(),
184            geo_open: GeoCellHistogram::default(),
185            geo_flushing: GeoCellHistogram::default(),
186            flags: Arc::new(SstInvalidationFlags::new()),
187        }
188    }
189
190    /// RocksDB backend: first `GetStatsProfile` reloads live SST blobs.
191    pub fn rocksdb(flags: Arc<SstInvalidationFlags>) -> Self {
192        flags.mark_sealed_stale();
193        Self {
194            open: LiveQuadsProfile::default(),
195            flushing: LiveQuadsProfile::default(),
196            sealed: StatsProfile::default(),
197            catalog_open: 0,
198            catalog_flushing: 0,
199            temporal_open: TickHistogram::default(),
200            temporal_flushing: TickHistogram::default(),
201            geo_open: GeoCellHistogram::default(),
202            geo_flushing: GeoCellHistogram::default(),
203            flags,
204        }
205    }
206
207    /// Shared invalidation flags (cloned into the RocksDB event listener).
208    pub fn flags(&self) -> &Arc<SstInvalidationFlags> {
209        &self.flags
210    }
211
212    /// Mutable write-path (memtable) profile.
213    pub fn open_profile_mut(&mut self) -> &mut LiveQuadsProfile {
214        &mut self.open
215    }
216
217    /// Borrow the write-path profile.
218    pub fn open_profile(&self) -> &LiveQuadsProfile {
219        &self.open
220    }
221
222    /// Frozen-MemTable aside used for stats RPCs while a flush is in progress.
223    pub fn flushing_profile(&self) -> &LiveQuadsProfile {
224        &self.flushing
225    }
226
227    /// Exact (or safely over-estimating) row count for a pattern with a
228    /// bound named predicate — the estimate behind the scan-dispatch gate
229    /// (`SCAN_DISPATCH_ROW_THRESHOLD`, see `PartitionService::
230    /// scan_runs_on_caller`).
231    ///
232    /// Sources are exact maps only: `predicate_counts` for the bound
233    /// predicate, and — when the predicate is `rdf:type` — `class_counts`
234    /// for one bound named class (`class_bound`) or an object allow-list
235    /// (`class_filter`, a broadcast filter's terms). Estimates sum the
236    /// live, flushing, and sealed contributions. The maps count net
237    /// observed rows (puts minus deletes, per logical quad, across
238    /// graphs), so re-puts and un-compacted history over-count: the
239    /// result is an upper bound on the rows a scan RETURNS, not the
240    /// version keys it VISITS — a delete-heavy uncompacted prefix can
241    /// still walk far more keys than the estimate admits.
242    ///
243    /// `Some(n)` is the tight value for `?s :p ?o` shapes and an upper
244    /// bound for narrower ones (a bound S or O can only shrink the scan);
245    /// over-estimates merely keep a scan on the blocking pool, which is
246    /// the safe direction for the gate. `None` means no statistical basis
247    /// (nothing ever observed) — the caller always dispatches.
248    ///
249    /// Absent-vs-empty semantics: with a basis present, a key absent from
250    /// a NON-EMPTY exact map is an observed zero. When every source map of
251    /// a kind is empty there is no basis of that kind and the coarser
252    /// bound stands.
253    ///
254    /// `early_exit` bounds the allow-list verdict, not the work: the sum
255    /// stops as soon as it exceeds `early_exit` (past the boundary the
256    /// verdict can no longer become "runs on the caller"), but a list
257    /// whose terms are all absent sums the whole list — up to
258    /// `terms.len()` × 3 BTreeMap lookups under the stats mutex.
259    pub fn exact_scan_rows(
260        &self,
261        predicate: StrHash,
262        class_bound: Option<StrHash>,
263        class_filter: Option<&[StrHash]>,
264        early_exit: u64,
265    ) -> Option<u64> {
266        // Basis: any observation at all. A store with zero observations
267        // has no data AND no stats, so an absent key there means "not
268        // observed", not "zero rows" — the gate must not open on it.
269        let basis =
270            self.open.total_puts > 0 || self.flushing.total_puts > 0 || self.sealed.total_puts > 0;
271        if !basis {
272            return None;
273        }
274        let rows = self.sum_predicate_rows(&predicate);
275        if class_bound.is_none() && class_filter.is_none() {
276            return Some(rows);
277        }
278        // Tighten with exact class counts when they exist. `rdf:type`
279        // rows counted per named class are exactly what a class-bound or
280        // class-filtered type scan returns (per-row counting, so multiple
281        // graphs of one subject over-count only in the safe direction).
282        let class_basis = !self.open.class_counts.is_empty()
283            || !self.flushing.class_counts.is_empty()
284            || !self.sealed.class_counts.is_empty();
285        if !class_basis {
286            return Some(rows);
287        }
288        let mut sum = 0u64;
289        if let Some(class) = class_bound {
290            sum = self.sum_class_rows(&class);
291        } else if let Some(terms) = class_filter {
292            for class in terms {
293                sum = sum.saturating_add(self.sum_class_rows(class));
294                // Stop once the verdict can no longer be "runs on the
295                // caller" (final_sum <= early_exit): past the boundary the
296                // remaining terms cannot flip it back.
297                if sum > early_exit {
298                    return Some(sum);
299                }
300            }
301        }
302        Some(sum)
303    }
304
305    /// `predicate_counts` summed across live, flushing, and sealed.
306    fn sum_predicate_rows(&self, predicate: &StrHash) -> u64 {
307        self.open
308            .predicate_counts
309            .get(predicate)
310            .copied()
311            .unwrap_or(0)
312            + self
313                .flushing
314                .predicate_counts
315                .get(predicate)
316                .copied()
317                .unwrap_or(0)
318            + self
319                .sealed
320                .predicate_counts
321                .get(predicate)
322                .copied()
323                .unwrap_or(0)
324    }
325
326    /// `class_counts` summed across live, flushing, and sealed.
327    fn sum_class_rows(&self, class: &StrHash) -> u64 {
328        self.open.class_counts.get(class).copied().unwrap_or(0)
329            + self.flushing.class_counts.get(class).copied().unwrap_or(0)
330            + self.sealed.class_counts.get(class).copied().unwrap_or(0)
331    }
332
333    /// Cached SST merge (tests).
334    pub fn sealed_profile(&self) -> &StatsProfile {
335        &self.sealed
336    }
337
338    /// Increment the in-memory Present named-graph count (new catalog put).
339    pub fn add_named_graphs(&mut self, n: u64) {
340        self.catalog_open = self.catalog_open.saturating_add(n);
341    }
342
343    /// Decrement the in-memory Present named-graph count (Dropped catalog put).
344    pub fn drop_named_graphs(&mut self, n: u64) {
345        self.catalog_open = self.catalog_open.saturating_sub(n);
346    }
347
348    /// Observe one temporal posting into the live overlay (Put-only by
349    /// contract, like `total_puts`; the collector observes only Put keys).
350    pub fn observe_temporal_posting(&mut self, node_key: u128) {
351        self.temporal_open.observe(node_key);
352    }
353
354    /// Replace the live temporal overlay with an empty cut (the rebuild's
355    /// REPLACE semantics: the walk re-derives every posting, so stale
356    /// observations must not survive alongside the re-applied ones).
357    pub fn reset_temporal_open(&mut self) {
358        self.temporal_open = TickHistogram::default();
359    }
360
361    /// Observe one geo posting (cell id) into the live overlay. Put-only by
362    /// contract — the caller filters on the op like `total_puts`.
363    pub fn observe_geo_posting(&mut self, cell_id: u64) {
364        self.geo_open.observe_posting(cell_id);
365    }
366
367    /// Replace the live geo overlay with an empty map (the geo rebuild wipes
368    /// the index CF and re-applies every posting; stale bucket counts must
369    /// not survive alongside the re-applied ones).
370    pub fn reset_geo_open(&mut self) {
371        self.geo_open = GeoCellHistogram::default();
372    }
373
374    /// `OnFlushBegin`: move `open` into `flushing` and reset `open` for the new MemTable.
375    ///
376    /// Overlapping canonical flushes merge into `flushing` rather than dropping the first aside.
377    /// Does not touch the catalog or temporal overlays — a hexastore flush must not drop
378    /// counts whose SSTs are produced by their own CFs. The rotated profiles are
379    /// [`LiveQuadsProfile`]s precisely because a canonical flush must never carry
380    /// CF-keyed counts.
381    pub fn rotate_on_flush_begin(&mut self) {
382        let taken = std::mem::take(&mut self.open);
383        if self.flushing.is_empty() {
384            self.flushing = taken;
385        } else {
386            let _ = self.flushing.merge(&taken);
387        }
388    }
389
390    /// Catalog-CF `OnFlushBegin`: move `catalog_open` into `catalog_flushing`.
391    pub fn rotate_catalog_on_flush_begin(&mut self) {
392        let taken = std::mem::take(&mut self.catalog_open);
393        self.catalog_flushing = self.catalog_flushing.saturating_add(taken);
394    }
395
396    /// Temporal-CF `OnFlushBegin`: move `temporal_open` into `temporal_flushing`.
397    pub fn rotate_temporal_on_flush_begin(&mut self) {
398        let taken = std::mem::take(&mut self.temporal_open);
399        self.temporal_flushing.merge(&taken);
400    }
401
402    /// Geo-CF `OnFlushBegin`: move `geo_open` into `geo_flushing`.
403    pub fn rotate_geo_on_flush_begin(&mut self) {
404        let taken = std::mem::take(&mut self.geo_open);
405        self.geo_flushing.merge(&taken);
406    }
407
408    /// Install a freshly merged SST profile; drop overlays only if that CF's flush absorbed them.
409    pub fn apply_sealed_reload(&mut self, sealed: StatsProfile) {
410        self.sealed = sealed;
411        if self.flags.take_open_absorbed() {
412            self.flushing = LiveQuadsProfile::default();
413        }
414        if self.flags.take_catalog_absorbed() {
415            self.catalog_flushing = 0;
416        }
417        if self.flags.take_temporal_absorbed() {
418            self.temporal_flushing = TickHistogram::default();
419        }
420        if self.flags.take_geo_absorbed() {
421            self.geo_flushing = GeoCellHistogram::default();
422        }
423    }
424
425    /// `sealed ⊕ flushing ⊕ open`, with the catalog count from SST blobs plus
426    /// catalog overlays and the temporal histogram from SST blobs plus
427    /// temporal overlays. The live layers convert into the full profile at
428    /// their overlay-identity values, which the overlay folds then replace.
429    pub fn merged(&self) -> Result<StatsProfile, StatsError> {
430        let mut out = self.sealed.clone();
431        out.merge(&StatsProfile::from(&self.flushing))?;
432        out.merge(&StatsProfile::from(&self.open))?;
433        out.temporal_histogram.merge(&self.temporal_flushing);
434        out.temporal_histogram.merge(&self.temporal_open);
435        out.geo_cell_histogram.merge(&self.geo_flushing);
436        out.geo_cell_histogram.merge(&self.geo_open);
437        out.named_graph_count = self
438            .sealed
439            .named_graph_count
440            .saturating_add(self.catalog_flushing)
441            .saturating_add(self.catalog_open);
442        Ok(out)
443    }
444}
445
446/// Merge `waratah.stats` blobs from live SSTs into one profile.
447pub fn merge_sst_property_blobs(blobs: &[Vec<u8>]) -> Result<StatsProfile, StatsError> {
448    let mut sealed = StatsProfile::default();
449    for blob in blobs {
450        sealed.merge(&from_bytes(blob)?)?;
451    }
452    Ok(sealed)
453}
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458    use crate::observe::observe_quad;
459    use waratah_storage::{NamedNode, StorageOp, encode_quad};
460
461    fn sample_put(profile: &mut LiveQuadsProfile, i: u32) {
462        let q = encode_quad(&waratah_storage::Quad::new(
463            NamedNode::new(format!("http://ex/s{i}")).unwrap(),
464            NamedNode::new("http://ex/p").unwrap(),
465            NamedNode::new(format!("http://ex/o{i}")).unwrap(),
466            waratah_storage::GraphName::DefaultGraph,
467        ))
468        .unwrap();
469        observe_quad(profile, &q, StorageOp::Put);
470    }
471
472    /// A sealed-style full profile carrying one sampled put.
473    fn sealed_with_put(i: u32) -> StatsProfile {
474        let mut live = LiveQuadsProfile::default();
475        sample_put(&mut live, i);
476        StatsProfile::from(live)
477    }
478
479    fn type_put(profile: &mut LiveQuadsProfile, class: &str) {
480        let q = encode_quad(&waratah_storage::Quad::new(
481            NamedNode::new(format!("http://ex/s{class}")).unwrap(),
482            NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
483            NamedNode::new(format!("http://ex/{class}")).unwrap(),
484            waratah_storage::GraphName::DefaultGraph,
485        ))
486        .unwrap();
487        observe_quad(profile, &q, StorageOp::Put);
488    }
489
490    fn hash_of(iri: &str) -> StrHash {
491        StrHash::new(iri)
492    }
493
494    #[test]
495    fn exact_scan_rows_without_basis_is_none() {
496        // Nothing ever observed: absent keys mean "not observed", not
497        // zero — the gate must not open.
498        let stats = ShardStats::memory();
499        assert_eq!(
500            stats.exact_scan_rows(hash_of("http://ex/p"), None, None, 1024),
501            None
502        );
503    }
504
505    #[test]
506    fn exact_scan_rows_absent_predicate_with_basis_is_zero() {
507        let mut stats = ShardStats::memory();
508        sample_put(stats.open_profile_mut(), 1);
509        // http://ex/q exists nowhere: an observed zero.
510        assert_eq!(
511            stats.exact_scan_rows(hash_of("http://ex/q"), None, None, 1024),
512            Some(0)
513        );
514        assert_eq!(
515            stats.exact_scan_rows(hash_of("http://ex/p"), None, None, 1024),
516            Some(1)
517        );
518    }
519
520    #[test]
521    fn exact_scan_rows_sums_live_and_sealed() {
522        let mut stats = ShardStats::memory();
523        sample_put(stats.open_profile_mut(), 1);
524        stats.sealed = sealed_with_put(2);
525        assert_eq!(
526            stats.exact_scan_rows(hash_of("http://ex/p"), None, None, 1024),
527            Some(2)
528        );
529    }
530
531    #[test]
532    fn exact_scan_rows_class_bound_exact_and_observed_zero() {
533        let mut stats = ShardStats::memory();
534        type_put(stats.open_profile_mut(), "Person");
535        type_put(stats.open_profile_mut(), "Person");
536        type_put(stats.open_profile_mut(), "Dog");
537        let type_hash = hash_of("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
538        assert_eq!(
539            stats.exact_scan_rows(type_hash, Some(hash_of("http://ex/Person")), None, 1024),
540            Some(2)
541        );
542        // Absent from a NON-EMPTY class map: an observed zero.
543        assert_eq!(
544            stats.exact_scan_rows(type_hash, Some(hash_of("http://ex/Ghost")), None, 1024),
545            Some(0)
546        );
547    }
548
549    #[test]
550    fn exact_scan_rows_class_filter_sums_with_early_exit() {
551        let mut stats = ShardStats::memory();
552        type_put(stats.open_profile_mut(), "A");
553        type_put(stats.open_profile_mut(), "B");
554        type_put(stats.open_profile_mut(), "C");
555        let type_hash = hash_of("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
556        let terms = [
557            hash_of("http://ex/A"),
558            hash_of("http://ex/B"),
559            hash_of("http://ex/C"),
560        ];
561        // Full sum below the exit: exact.
562        assert_eq!(
563            stats.exact_scan_rows(type_hash, None, Some(&terms), 4),
564            Some(3)
565        );
566        // Exit at 1: after two terms the sum is 2 > 1, so the third term
567        // is never consulted — a full sum would be 3, so Some(2) proves
568        // the early return fired.
569        assert_eq!(
570            stats.exact_scan_rows(type_hash, None, Some(&terms), 1),
571            Some(2)
572        );
573        // A term absent mid-list contributes an observed zero and the
574        // sum keeps going.
575        let with_hole = [
576            hash_of("http://ex/Ghost"),
577            hash_of("http://ex/A"),
578            hash_of("http://ex/B"),
579        ];
580        assert_eq!(
581            stats.exact_scan_rows(type_hash, None, Some(&with_hole), 4),
582            Some(2)
583        );
584    }
585
586    #[test]
587    fn exact_scan_rows_without_class_basis_keeps_predicate_bound() {
588        // rdf:type rows with LITERAL objects: predicate_counts carries
589        // them, the named-class map does not. The class bound cannot
590        // tighten (no class basis), so the predicate bound must come
591        // back — not the class lookup's 0.
592        let mut stats = ShardStats::memory();
593        for i in 0..3 {
594            let q = encode_quad(&waratah_storage::Quad::new(
595                NamedNode::new(format!("http://ex/s{i}")).unwrap(),
596                NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type").unwrap(),
597                waratah_storage::Literal::from(format!("lit{i}").as_str()),
598                waratah_storage::GraphName::DefaultGraph,
599            ))
600            .unwrap();
601            observe_quad(stats.open_profile_mut(), &q, StorageOp::Put);
602        }
603        let type_hash = hash_of("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
604        assert_eq!(
605            stats.exact_scan_rows(type_hash, Some(hash_of("http://ex/Person")), None, 1024),
606            Some(3)
607        );
608    }
609
610    #[test]
611    fn memory_merged_is_open_only() {
612        let mut stats = ShardStats::memory();
613        sample_put(stats.open_profile_mut(), 1);
614        assert_eq!(stats.merged().unwrap().total_puts, 1);
615        assert!(stats.sealed_profile().is_empty());
616        assert!(stats.flushing_profile().is_empty());
617    }
618
619    #[test]
620    fn flush_begin_moves_open_to_flushing() {
621        let mut stats = ShardStats::memory();
622        sample_put(stats.open_profile_mut(), 1);
623        stats.rotate_on_flush_begin();
624        assert!(stats.open_profile().is_empty());
625        assert_eq!(stats.flushing_profile().total_puts, 1);
626        assert_eq!(stats.merged().unwrap().total_puts, 1);
627        sample_put(stats.open_profile_mut(), 2);
628        assert_eq!(stats.merged().unwrap().total_puts, 2);
629    }
630
631    #[test]
632    fn reload_after_flush_listener_drops_flushing_keeps_open() {
633        let flags = Arc::new(SstInvalidationFlags::new());
634        let mut stats = ShardStats::rocksdb(Arc::clone(&flags));
635        assert!(flags.take_sealed_stale());
636        sample_put(stats.open_profile_mut(), 1);
637        stats.rotate_on_flush_begin();
638        sample_put(stats.open_profile_mut(), 2);
639        flags.mark_flush();
640        stats.apply_sealed_reload(sealed_with_put(1));
641        assert!(stats.flushing_profile().is_empty());
642        assert_eq!(stats.open_profile().total_puts, 1);
643        assert_eq!(stats.merged().unwrap().total_puts, 2);
644    }
645
646    #[test]
647    fn reload_after_compaction_keeps_open_and_flushing() {
648        let flags = Arc::new(SstInvalidationFlags::new());
649        let mut stats = ShardStats::rocksdb(Arc::clone(&flags));
650        let _ = flags.take_sealed_stale();
651        sample_put(stats.open_profile_mut(), 1);
652        stats.rotate_on_flush_begin();
653        sample_put(stats.open_profile_mut(), 2);
654        flags.mark_compaction();
655        stats.apply_sealed_reload(StatsProfile::default());
656        assert_eq!(stats.flushing_profile().total_puts, 1);
657        assert_eq!(stats.open_profile().total_puts, 1);
658        assert_eq!(stats.merged().unwrap().total_puts, 2);
659    }
660
661    #[test]
662    fn catalog_count_survives_hexastore_flush_rotate() {
663        let mut stats = ShardStats::memory();
664        stats.add_named_graphs(3);
665        sample_put(stats.open_profile_mut(), 1);
666        stats.rotate_on_flush_begin();
667        assert_eq!(stats.merged().unwrap().named_graph_count, 3);
668        assert_eq!(stats.merged().unwrap().total_puts, 1);
669    }
670
671    #[test]
672    fn catalog_flush_reload_drops_flushing_keeps_open() {
673        let flags = Arc::new(SstInvalidationFlags::new());
674        let mut stats = ShardStats::rocksdb(Arc::clone(&flags));
675        let _ = flags.take_sealed_stale();
676        stats.add_named_graphs(2);
677        stats.rotate_catalog_on_flush_begin();
678        stats.add_named_graphs(1);
679        flags.mark_catalog_flush();
680        let sealed = StatsProfile {
681            named_graph_count: 2,
682            ..StatsProfile::default()
683        };
684        stats.apply_sealed_reload(sealed);
685        assert_eq!(stats.merged().unwrap().named_graph_count, 3);
686        stats.drop_named_graphs(1);
687        assert_eq!(stats.merged().unwrap().named_graph_count, 2);
688    }
689
690    #[test]
691    fn temporal_histogram_survives_hexastore_flush_rotate() {
692        // The wrinkle this overlay exists for: a hexastore flush must not
693        // drop or keep temporal counts — they move only on their own CF's
694        // rotation, and merged() counts each posting exactly once.
695        let mut stats = ShardStats::memory();
696        stats.observe_temporal_posting(42);
697        sample_put(stats.open_profile_mut(), 1);
698        stats.rotate_on_flush_begin(); // canonical flush: ignores temporal
699        assert_eq!(
700            stats.merged().unwrap().temporal_histogram.total_postings(),
701            1,
702            "hexastore rotate must not drop the temporal overlay"
703        );
704        stats.rotate_temporal_on_flush_begin(); // temporal flush: moves its own overlay
705        stats.observe_temporal_posting(43);
706        let merged = stats.merged().unwrap();
707        assert_eq!(merged.temporal_histogram.total_postings(), 2);
708        assert_eq!(merged.total_puts, 1);
709    }
710
711    #[test]
712    fn temporal_flush_reload_drops_temporal_flushing() {
713        let flags = Arc::new(SstInvalidationFlags::new());
714        let mut stats = ShardStats::rocksdb(Arc::clone(&flags));
715        let _ = flags.take_sealed_stale();
716        stats.observe_temporal_posting(1);
717        stats.observe_temporal_posting(2);
718        stats.rotate_temporal_on_flush_begin();
719        stats.observe_temporal_posting(3);
720        flags.mark_temporal_flush();
721        let sealed = StatsProfile {
722            temporal_histogram: {
723                let mut histogram = TickHistogram::default();
724                histogram.observe(1);
725                histogram.observe(2);
726                histogram
727            },
728            ..StatsProfile::default()
729        };
730        stats.apply_sealed_reload(sealed);
731        // The blob's 2 absorbed the flushed aside; the live 3 stays.
732        assert_eq!(
733            stats.merged().unwrap().temporal_histogram.total_postings(),
734            3
735        );
736    }
737}