1use 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
14pub const STATS_USER_PROPERTY_KEY: &[u8] = b"waratah.stats";
16
17#[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 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 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 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 pub fn sealed_stale(&self) -> bool {
67 self.sealed_stale.load(Ordering::SeqCst)
68 }
69
70 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 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 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 pub fn mark_sealed_stale(&self) {
93 self.sealed_stale.store(true, Ordering::SeqCst);
94 }
95
96 pub fn take_sealed_stale(&self) -> bool {
98 self.sealed_stale.swap(false, Ordering::SeqCst)
99 }
100
101 pub fn take_open_absorbed(&self) -> bool {
103 self.open_absorbed.swap(false, Ordering::SeqCst)
104 }
105
106 pub fn take_catalog_absorbed(&self) -> bool {
108 self.catalog_absorbed.swap(false, Ordering::SeqCst)
109 }
110
111 pub fn take_temporal_absorbed(&self) -> bool {
113 self.temporal_absorbed.swap(false, Ordering::SeqCst)
114 }
115
116 pub fn take_geo_absorbed(&self) -> bool {
118 self.geo_absorbed.swap(false, Ordering::SeqCst)
119 }
120
121 pub fn flush_event_count(&self) -> u64 {
123 self.flush_events.load(Ordering::SeqCst)
124 }
125
126 pub fn compaction_event_count(&self) -> u64 {
128 self.compaction_events.load(Ordering::SeqCst)
129 }
130}
131
132#[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 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 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 pub fn flags(&self) -> &Arc<SstInvalidationFlags> {
209 &self.flags
210 }
211
212 pub fn open_profile_mut(&mut self) -> &mut LiveQuadsProfile {
214 &mut self.open
215 }
216
217 pub fn open_profile(&self) -> &LiveQuadsProfile {
219 &self.open
220 }
221
222 pub fn flushing_profile(&self) -> &LiveQuadsProfile {
224 &self.flushing
225 }
226
227 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 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 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 if sum > early_exit {
298 return Some(sum);
299 }
300 }
301 }
302 Some(sum)
303 }
304
305 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 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 pub fn sealed_profile(&self) -> &StatsProfile {
335 &self.sealed
336 }
337
338 pub fn add_named_graphs(&mut self, n: u64) {
340 self.catalog_open = self.catalog_open.saturating_add(n);
341 }
342
343 pub fn drop_named_graphs(&mut self, n: u64) {
345 self.catalog_open = self.catalog_open.saturating_sub(n);
346 }
347
348 pub fn observe_temporal_posting(&mut self, node_key: u128) {
351 self.temporal_open.observe(node_key);
352 }
353
354 pub fn reset_temporal_open(&mut self) {
358 self.temporal_open = TickHistogram::default();
359 }
360
361 pub fn observe_geo_posting(&mut self, cell_id: u64) {
364 self.geo_open.observe_posting(cell_id);
365 }
366
367 pub fn reset_geo_open(&mut self) {
371 self.geo_open = GeoCellHistogram::default();
372 }
373
374 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 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 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 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 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 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
446pub 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 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 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 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 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 assert_eq!(
563 stats.exact_scan_rows(type_hash, None, Some(&terms), 4),
564 Some(3)
565 );
566 assert_eq!(
570 stats.exact_scan_rows(type_hash, None, Some(&terms), 1),
571 Some(2)
572 );
573 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 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 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(); 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(); 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 assert_eq!(
733 stats.merged().unwrap().temporal_histogram.total_postings(),
734 3
735 );
736 }
737}