From 853e3938f0fa2ca5031cf51be610f5bd5ea141aa Mon Sep 17 00:00:00 2001 From: WenyXu Date: Mon, 9 Nov 2026 06:08:39 +0000 Subject: [PATCH] feat(storage): define in-process sketch reader contracts Signed-off-by: WenyXu --- src/mito2/src/sst/index.rs | 1 + src/mito2/src/sst/index/sketch_reader.rs | 272 +++++++++++++++++++++++ src/store-api/src/lib.rs | 1 + src/store-api/src/region_engine.rs | 6 + src/store-api/src/sketch.rs | 239 ++++++++++++++++++++ 5 files changed, 519 insertions(+) create mode 100644 src/mito2/src/sst/index/sketch_reader.rs create mode 100644 src/store-api/src/sketch.rs diff --git a/src/mito2/src/sst/index.rs b/src/mito2/src/sst/index.rs index cc4ffcbb8ad..c610b177dd8 100644 --- a/src/mito2/src/sst/index.rs +++ b/src/mito2/src/sst/index.rs @@ -26,6 +26,7 @@ pub mod kind; pub mod primary_key; pub mod puffin_manager; pub mod registry; +pub mod sketch_reader; #[cfg(test)] mod sparse_test; mod statistics; diff --git a/src/mito2/src/sst/index/sketch_reader.rs b/src/mito2/src/sst/index/sketch_reader.rs new file mode 100644 index 00000000000..317117f05a5 --- /dev/null +++ b/src/mito2/src/sst/index/sketch_reader.rs @@ -0,0 +1,272 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Injected statistics reads over a pinned selection of SST files. + +use std::fmt::Debug; +use std::sync::Arc; + +use async_trait::async_trait; +use common_error::ext::BoxedError; +use common_time::Timestamp; +use store_api::metadata::RegionMetadataRef; +use store_api::sketch::{SketchRequest, SketchResponse, SketchTimeRange}; + +use crate::sst::file::FileHandle; +use crate::sst::index::puffin_manager::SstPuffinManager; +use crate::sst::version::SstVersionRef; + +/// Lazy candidates from one immutable SST snapshot. Construction does not enumerate files. +/// Retaining this view pins the snapshot, including files outside the requested range. +pub struct SketchReadFiles { + snapshot: SstVersionRef, + time_range: SketchTimeRange, +} + +impl SketchReadFiles { + pub(crate) fn new(snapshot: SstVersionRef, time_range: SketchTimeRange) -> Self { + Self { + snapshot, + time_range, + } + } + + /// Visits intersecting files without cloning handles or allocating a selection. + /// Iteration scans snapshot metadata; it performs no file I/O and has no order guarantee. + pub fn iter(&self) -> impl Iterator { + let start = Timestamp::new_millisecond(self.time_range.start_ms); + let end = Timestamp::new_millisecond(self.time_range.end_ms); + self.snapshot + .levels() + .iter() + .flat_map(|level| level.files()) + .filter(move |file| { + file.meta_ref().time_range.0 < end && file.meta_ref().time_range.1 >= start + }) + } +} + +/// Borrowed inputs from one snapshot, enumerated only when the handler consumes them. +pub struct SketchReadContext<'a> { + /// Schema captured with the selected file snapshot. + pub metadata: &'a RegionMetadataRef, + /// Lazy time-filtered candidates; consumers validate requests before iterating. + pub files: &'a SketchReadFiles, + /// Existing Puffin I/O and metadata cache facilities for these files. + pub puffin_manager: &'a SstPuffinManager, +} + +/// Node-scoped implementation owns caches; the engine owns file selection and lifetimes. +#[async_trait] +pub trait SketchReadHandler: Send + Sync + Debug { + /// Reads coverage directories without decoding algorithm payloads. Missing files are gaps, not empty data. + async fn stat( + &self, + context: &SketchReadContext<'_>, + request: &SketchRequest, + ) -> Result; + + /// Reads and merges complete buckets, preserving coverage gaps alongside estimates. + /// Invalid or corrupt payloads return errors rather than being silently excluded. + async fn query( + &self, + context: &SketchReadContext<'_>, + request: &SketchRequest, + ) -> Result; +} + +/// Plugin registration type shared by engine bootstrap and the read entry point. +pub type SketchReadHandlerRef = Arc; + +#[cfg(test)] +mod tests { + use std::sync::{Arc, Mutex}; + + use common_time::Timestamp; + use store_api::sketch::SketchTimeRange; + use store_api::storage::FileId; + + use super::SketchReadFiles; + use crate::sst::file::FileMeta; + use crate::sst::file_purger::FilePurger; + use crate::sst::version::SstVersion; + use crate::test_util::memtable_util::metadata_for_test; + use crate::test_util::new_noop_file_purger; + + fn file(start: Timestamp, end: Timestamp) -> FileMeta { + FileMeta { + file_id: FileId::random(), + time_range: (start, end), + ..Default::default() + } + } + + #[test] + fn test_sketch_files_time_boundaries() { + let millis = Timestamp::new_millisecond; + let cases = [ + (millis(-1), millis(999), false), + (millis(999), millis(1000), true), + (millis(1000), millis(1000), true), + (millis(1999), millis(2000), true), + (millis(2000), millis(2001), false), + (Timestamp::new_second(1), Timestamp::new_second(1), true), + ( + Timestamp::new_microsecond(1_999_999), + Timestamp::new_microsecond(2_000_000), + true, + ), + ( + Timestamp::new_nanosecond(2_000_000_000), + Timestamp::new_nanosecond(2_000_000_001), + false, + ), + ]; + let mut version = SstVersion::new(metadata_for_test()); + let mut expected = Vec::new(); + version.add_files( + new_noop_file_purger(), + cases + .into_iter() + .enumerate() + .map(|(index, (start, end, included))| { + let mut meta = file(start, end); + meta.level = (index % 2) as u8; + if included { + expected.push(meta.file_id); + } + meta + }), + ); + let selection = SketchReadFiles::new( + Arc::new(version), + SketchTimeRange { + start_ms: 1000, + end_ms: 2000, + }, + ); + let mut actual: Vec<_> = selection + .iter() + .map(|handle| handle.file_id().file_id()) + .collect(); + actual.sort_unstable_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + expected.sort_unstable_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + assert_eq!(actual, expected); + } + + #[test] + fn test_sketch_files_borrowed_selection_matches_eager_filter() { + let mut version = SstVersion::new(metadata_for_test()); + version.add_files( + new_noop_file_purger(), + (0..16_384).map(|index| { + let start = Timestamp::new_millisecond(index - 8192); + let end = Timestamp::new_millisecond(index - 8192 + 100); + let mut meta = file(start, end); + meta.level = (index % 2) as u8; + meta + }), + ); + let snapshot = Arc::new(version); + for (start_ms, end_ms) in [(-10_000, -9_000), (-100, 100), (0, 20_000)] { + let range = SketchTimeRange { start_ms, end_ms }; + let expected: Vec<_> = snapshot + .levels() + .iter() + .flat_map(|level| level.files()) + .filter(|handle| { + let (start, end) = handle.meta_ref().time_range; + start < Timestamp::new_millisecond(end_ms) + && end >= Timestamp::new_millisecond(start_ms) + }) + .collect(); + let selection = SketchReadFiles::new(snapshot.clone(), range); + let first: Vec<_> = selection.iter().take(1).collect(); + assert_eq!(first.len(), expected.len().min(1)); + if let Some(first) = first.first() { + assert!(std::ptr::eq(*first, expected[0])); + } + assert_eq!( + selection + .iter() + .map(|handle| handle.file_id()) + .collect::>(), + expected + .iter() + .map(|handle| handle.file_id()) + .collect::>(), + ); + } + } + + #[derive(Debug, Default)] + struct RecordingPurger(Mutex>); + + impl FilePurger for RecordingPurger { + fn purge_file(&self, meta: FileMeta) { + self.0.lock().unwrap().push(meta.file_id); + } + } + + #[test] + fn test_sketch_files_pin_retired_snapshot_until_drop() { + let old = file( + Timestamp::new_millisecond(10), + Timestamp::new_millisecond(20), + ); + let outside = file( + Timestamp::new_millisecond(100), + Timestamp::new_millisecond(200), + ); + let replacement = file( + Timestamp::new_millisecond(15), + Timestamp::new_millisecond(25), + ); + let purger = Arc::new(RecordingPurger::default()); + let mut version = SstVersion::new(metadata_for_test()); + version.add_files(purger.clone(), [old.clone(), outside.clone()].into_iter()); + let mut latest = Arc::new(version); + let range = SketchTimeRange { + start_ms: 0, + end_ms: 30, + }; + let selected = SketchReadFiles::new(latest.clone(), range); + + Arc::make_mut(&mut latest).remove_files([old.clone(), outside.clone()].into_iter()); + Arc::make_mut(&mut latest).add_files(purger.clone(), [replacement.clone()].into_iter()); + + assert!(purger.0.lock().unwrap().is_empty()); + let old_handles: Vec<_> = selected.iter().collect(); + assert_eq!(old_handles.len(), 1); + assert_eq!(old_handles[0].file_id().file_id(), old.file_id); + assert!(old_handles[0].is_deleted()); + let current = SketchReadFiles::new(latest, range); + assert_eq!( + current + .iter() + .map(|handle| handle.file_id().file_id()) + .collect::>(), + vec![replacement.file_id], + ); + drop(old_handles); + drop(selected); + + // The lazy view pins the complete snapshot, including the out-of-range file. + let mut purged = purger.0.lock().unwrap().clone(); + let mut expected = vec![old.file_id, outside.file_id]; + purged.sort_unstable_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + expected.sort_unstable_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + assert_eq!(purged, expected); + } +} diff --git a/src/store-api/src/lib.rs b/src/store-api/src/lib.rs index 7d156388e98..af6afb9ba31 100644 --- a/src/store-api/src/lib.rs +++ b/src/store-api/src/lib.rs @@ -27,6 +27,7 @@ pub mod path_utils; pub mod region_engine; pub mod region_info; pub mod region_request; +pub mod sketch; pub mod sst_entry; pub mod storage; diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index 16f1edd3dfa..fdb41739666 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -41,6 +41,7 @@ use crate::metadata::RegionMetadataRef; use crate::region_request::{ BatchRegionDdlRequest, RegionCatchupRequest, RegionOpenRequest, RegionPutRequest, RegionRequest, }; +use crate::sketch::SketchReader; use crate::storage::{FileId, RegionId, ScanRequest, SequenceNumber}; /// The settable region role state. @@ -1069,6 +1070,11 @@ pub struct MitoCopyRegionFromResponse { #[async_trait] pub trait RegionEngine: Send + Sync { + /// Returns the optional sketch-reading capability without taking a snapshot or performing I/O. + fn sketch_reader(&self) -> Option<&dyn SketchReader> { + None + } + /// Name of this engine fn name(&self) -> &str; diff --git a/src/store-api/src/sketch.rs b/src/store-api/src/sketch.rs new file mode 100644 index 00000000000..37c674b20bc --- /dev/null +++ b/src/store-api/src/sketch.rs @@ -0,0 +1,239 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! In-process, SST-only statistics requests. No wire protocol is defined here. + +use async_trait::async_trait; +use common_error::ext::{BoxedError, PlainError}; +use common_error::status_code::StatusCode; +use common_time::Timestamp; +use datatypes::value::Value; + +use crate::storage::{ColumnId, FileId, IndexVersion, RegionId}; + +/// Bounded, half-open event-time range. Endpoints retain their timestamp precision. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SketchTimeRange { + /// Inclusive start. + pub start: Timestamp, + /// Exclusive end. + pub end: Timestamp, +} + +/// Statistics requested for each named column. +#[derive(Debug, Clone, PartialEq)] +pub enum SketchQuery { + /// Estimates the number of distinct non-null values. + DistinctCount, + /// Finds a non-null value at a fraction in the inclusive range [0, 1]. + Quantile { fraction: f64 }, + /// Bounds the occurrence count of a value, including NULL. + Frequency { value: Value }, +} + +/// Selects whole time buckets inside a required range. The implementation validates request limits. +/// A whole bucket may still have missing file statistics, reported separately in its coverage. +#[derive(Debug, Clone, PartialEq)] +pub struct SketchRequest { + pub time_range: SketchTimeRange, + /// Column names resolved against the selected Region schema. + pub columns: Vec, + /// Operations applied to each selected column. + pub queries: Vec, +} + +impl SketchRequest { + /// Validates algorithm-independent inputs before file selection or I/O. + /// Implementations separately enforce resource limits and column/type compatibility. + pub fn validate(&self) -> Result<(), BoxedError> { + let reason = if self.time_range.start >= self.time_range.end { + Some("sketch time range must have start before end") + } else if self.columns.is_empty() { + Some("sketch request must select at least one column") + } else if self.queries.is_empty() { + Some("sketch request must select at least one query") + } else if self.queries.iter().any(|query| { + matches!(query, SketchQuery::Quantile { fraction } if !fraction.is_finite() || !(0.0..=1.0).contains(fraction)) + }) { + Some("sketch quantile fraction must be finite and in [0, 1]") + } else { + None + }; + match reason { + Some(reason) => Err(BoxedError::new(PlainError::new( + reason.to_string(), + StatusCode::InvalidArguments, + ))), + None => Ok(()), + } + } +} + +/// Coverage of one whole time bucket and one query across the selected physical files. +/// Whole means contained in the requested range, not that every file has statistics. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SketchBucket { + pub time_range: SketchTimeRange, + /// Number of compatible physical indexes contributing to this nonempty bucket. + pub covered_files: u64, + /// Unavailable or incompatible files whose SST time ranges intersect this bucket. + pub missing_files: u64, + /// Rows represented by contributing sketches, including NULLs, without cross-file deduplication. + pub represented_rows: u64, +} + +/// Explicitly unavailable file statistics; unavailable files never count as empty. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SketchGapReason { + /// The requested algorithm is not enabled for this column in the current Region schema. + /// This takes precedence over missing persisted descriptors. + NotConfigured, + /// No descriptor exists for this column and algorithm. + MissingIndex, + /// The index has no time-bucket directory. + LegacyFormat, + /// The persisted scope does not match the current Region scope. + ScopeMismatch, + /// Type, encoding, algorithm parameters or bucket width cannot be combined. + Incompatible, +} + +/// File-level coverage gap intersecting the request. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SketchGap { + /// Region that owns the physical source file, which may differ from the queried Region. + pub source_region_id: RegionId, + pub file_id: FileId, + /// Immutable generation of the physical index file. + pub index_version: IndexVersion, + /// Why this file cannot contribute to the requested operation. + pub reason: SketchGapReason, +} + +/// Results preserve the different error semantics of the algorithms. +#[derive(Debug, Clone, PartialEq)] +pub enum SketchValue { + DistinctCount { + /// Estimated distinct count, excluding NULLs. + estimate: f64, + /// Relative standard error as a fraction, not a maximum-error bound. + relative_standard_error: f64, + }, + Quantile { + value: Value, + }, + Frequency { + /// Inclusive lower bound on occurrences among represented rows. + lower: u64, + /// Inclusive upper bound on occurrences among represented rows. + upper: u64, + }, +} + +/// One column/query result. Partial coverage remains explicit even when a value exists. +#[derive(Debug, Clone, PartialEq)] +pub struct ColumnSketchResult { + pub column_name: String, + pub column_id: ColumnId, + pub query: SketchQuery, + /// Nonempty buckets wholly inside the requested range; `missing_files` may be nonzero. + pub buckets: Vec, + /// Unusable files intersecting the requested range; absence is not treated as zero rows. + pub gaps: Vec, + /// Absent for stat-only requests or when no usable value is available. + pub value: Option, +} + +/// SST-only response. Memtables and logical deduplication are not included. +#[derive(Debug, Clone, PartialEq)] +pub struct SketchResponse { + /// One result per requested column and operation. + /// In request column order, then query order within each column. + pub results: Vec, +} + +/// Optional engine capability for reading persisted sketches. Each call takes its own snapshot. +#[async_trait] +pub trait SketchReader: Send + Sync { + /// Inspects coverage without reading algorithm payloads. Missing sketches remain explicit gaps. + async fn stat( + &self, + region_id: RegionId, + request: SketchRequest, + ) -> Result; + + /// Merges complete buckets and returns estimates with their coverage. Corrupt payloads are errors. + async fn query( + &self, + region_id: RegionId, + request: SketchRequest, + ) -> Result; +} + +#[cfg(test)] +mod tests { + use common_error::ext::ErrorExt; + + use super::*; + + fn request() -> SketchRequest { + SketchRequest { + time_range: SketchTimeRange { + start: Timestamp::new_microsecond(1001), + end: Timestamp::new_microsecond(1002), + }, + columns: vec!["value".to_string()], + queries: vec![SketchQuery::DistinctCount], + } + } + + #[test] + fn test_validate_request() { + let valid = request(); + assert!(valid.validate().is_ok()); + let mut empty_columns = valid.clone(); + empty_columns.columns.clear(); + let mut empty_queries = valid.clone(); + empty_queries.queries.clear(); + let mut empty_range = valid.clone(); + empty_range.time_range.end = empty_range.time_range.start; + let mut reversed_range = valid.clone(); + reversed_range.time_range.end = Timestamp::new_nanosecond(1_000_999); + for invalid in [empty_columns, empty_queries, empty_range, reversed_range] { + assert_eq!( + invalid.validate().unwrap_err().status_code(), + StatusCode::InvalidArguments + ); + } + for fraction in [0.0, 0.5, 1.0] { + let mut request = valid.clone(); + request.queries = vec![SketchQuery::Quantile { fraction }]; + assert!(request.validate().is_ok()); + } + for fraction in [f64::NAN, f64::NEG_INFINITY, f64::INFINITY, -0.1, 1.1] { + let mut request = valid.clone(); + request.queries = vec![SketchQuery::Quantile { fraction }]; + assert_eq!( + request.validate().unwrap_err().status_code(), + StatusCode::InvalidArguments + ); + } + let mut mixed_units = valid; + mixed_units.time_range = SketchTimeRange { + start: Timestamp::new_second(1), + end: Timestamp::new_nanosecond(1_000_000_001), + }; + assert!(mixed_units.validate().is_ok()); + } +}