Skip to main content

sql_splitter/profile/
mod.rs

1//! Bounded profiling: turn a SQL dump's column values into fixed-size,
2//! generator-neutral *evidence*.
3//!
4//! The profiler scans data and accumulates bounded sketches
5//! ([`ColumnSketches`]) whose memory does not grow with input size — a column
6//! spanning a billion rows costs the same as one spanning a thousand. The
7//! result is a tree of neutral [`evidence`] structs: observations and
8//! confidence only, with no opinion about how to regenerate the data. Later
9//! stages (schema inference, generation heuristics) consume that evidence
10//! without depending on how it was collected.
11//!
12//! The three properties this module guarantees, enforced by
13//! `tests/generate_profile_test.rs`:
14//!
15//! * **Bounded** — retained items and bytes stay within the [`ProfileBudget`].
16//! * **Mergeable** — sketches over disjoint partitions merge into the same
17//!   bounded evidence as a single pass (exactly, for the non-sampled parts).
18//! * **Seeded** — the same seed yields the same reservoir sample.
19
20pub mod evidence;
21pub mod heuristics;
22mod profiler;
23mod sketches;
24
25pub use evidence::{
26    BooleanEvidence, CharClasses, ColumnEvidence, DumpProfile, NumericEvidence,
27    RelationshipEvidence, StringShapeEvidence, TableEvidence, TimestampRangeEvidence, TopKEntry,
28};
29pub use heuristics::{
30    Confidence, Decision, InferenceError, InferenceOptions, InferenceResult, ModelInference,
31    Precedence, RejectedCandidate,
32};
33pub use profiler::{DumpProfiler, DumpProfilerBuilder};
34pub use sketches::ColumnSketches;
35
36use serde::{Deserialize, Serialize};
37use std::fmt;
38
39// --- Bounding constants -----------------------------------------------------
40//
41// These fix the per-column memory ceiling independently of the (unbounded)
42// input. `ProfileBudget::retained_bytes_ceiling` sums them so callers can
43// assert the profiler never exceeds its footprint.
44
45/// HyperLogLog precision `p`; register count is `2^p`. `p = 12` gives 4096
46/// registers (~1.6% standard error), comfortably inside the 10% tolerance the
47/// distinct-count tests require, for 4 KiB of fixed overhead per column.
48pub(crate) const HLL_PRECISION: u32 = 12;
49/// Number of HyperLogLog registers (`2^HLL_PRECISION`).
50pub(crate) const HLL_REGISTERS: usize = 1 << HLL_PRECISION;
51/// Byte ceiling for a single retained reservoir sample value.
52pub(crate) const MAX_SAMPLE_VALUE_BYTES: usize = 256;
53/// Byte ceiling for a single retained top-k key.
54pub(crate) const MAX_TOPK_KEY_BYTES: usize = 256;
55/// Byte ceiling for the retained common prefix / suffix of a string column.
56pub(crate) const MAX_AFFIX_BYTES: usize = 64;
57/// Byte ceiling for a retained min/max timestamp string.
58pub(crate) const MAX_TIMESTAMP_BYTES: usize = 64;
59/// Bookkeeping bytes charged per top-k counter, on top of its key.
60pub(crate) const TOPK_COUNTER_OVERHEAD: usize = 16;
61/// Bytes charged per numeric-histogram bin (`f64` centroid + `u64` count).
62pub(crate) const HISTOGRAM_BIN_BYTES: usize = 16;
63
64/// Errors from building or combining profile evidence.
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub enum ProfileError {
67    /// Two accumulators built with incompatible configuration were merged
68    /// (e.g. different reservoir capacities or histogram bin counts).
69    IncompatibleMerge {
70        /// Which configuration mismatched.
71        detail: &'static str,
72    },
73}
74
75impl ProfileError {
76    pub(crate) fn incompatible_merge(detail: &'static str) -> Self {
77        ProfileError::IncompatibleMerge { detail }
78    }
79}
80
81impl fmt::Display for ProfileError {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            ProfileError::IncompatibleMerge { detail } => {
85                write!(f, "cannot merge profile accumulators: {detail} mismatch")
86            }
87        }
88    }
89}
90
91impl std::error::Error for ProfileError {}
92
93/// How deeply to profile a dump.
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(rename_all = "snake_case")]
96pub enum ProfileDepth {
97    /// Structure only: names, types, nullability. No data scan.
98    Schema,
99    /// Cheap per-column stats: counts, null rate, distinct estimate, ranges.
100    Basic,
101    /// Everything: quantiles, heavy hitters, string shape, samples.
102    Full,
103}
104
105/// Per-column bounds on how much the profiler may retain. Every accumulator is
106/// sized from these three knobs; the derived methods report the resulting
107/// item and byte ceilings.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
109pub struct ProfileBudget {
110    /// Reservoir sample capacity (retained example values per column).
111    pub sample_rows: usize,
112    /// Number of heavy-hitter slots (Space-Saving counters).
113    pub top_k: usize,
114    /// Number of numeric-histogram bins.
115    pub histogram_bins: usize,
116}
117
118impl Default for ProfileBudget {
119    fn default() -> Self {
120        Self {
121            sample_rows: 1_000,
122            top_k: 32,
123            histogram_bins: 32,
124        }
125    }
126}
127
128impl ProfileBudget {
129    /// Upper bound on [`ColumnSketches::retained_items`]: the reservoir, top-k,
130    /// and histogram each cap at their configured size.
131    pub fn retained_items_per_column(&self) -> usize {
132        self.sample_rows + self.top_k + self.histogram_bins
133    }
134
135    /// Upper bound on [`ColumnSketches::retained_bytes`]: the worst-case heap
136    /// footprint of every accumulator, summed. Input size never pushes actual
137    /// retention past this.
138    pub fn retained_bytes_ceiling(&self) -> usize {
139        self.sample_rows * MAX_SAMPLE_VALUE_BYTES
140            + self.top_k * (MAX_TOPK_KEY_BYTES + TOPK_COUNTER_OVERHEAD)
141            + HLL_REGISTERS
142            + self.histogram_bins * HISTOGRAM_BIN_BYTES
143            + 2 * MAX_AFFIX_BYTES
144            + 2 * MAX_TIMESTAMP_BYTES
145    }
146}
147
148/// A single observed column value, borrowed for the duration of the call.
149///
150/// This is the profiler's neutral input alphabet: the value families the
151/// sketches know how to summarize. Text/JSON/timestamp variants borrow so a
152/// scan never has to allocate to observe.
153#[derive(Debug, Clone, PartialEq)]
154pub enum ProfileValue<'a> {
155    /// SQL `NULL`.
156    Null,
157    /// A boolean.
158    Boolean(bool),
159    /// A signed integer.
160    Integer(i64),
161    /// A fixed-point decimal: `minor * 10^-scale`.
162    Decimal { minor: i128, scale: u8 },
163    /// Free text.
164    Text(&'a str),
165    /// A timestamp rendering (ISO-8601 recommended; compared lexically).
166    DateTime(&'a str),
167    /// A JSON document rendering.
168    Json(&'a str),
169}