Skip to main content

sql_splitter/profile/
profiler.rs

1//! Stream a SQL dump into a neutral [`DumpProfile`] in a single pass.
2//!
3//! [`DumpProfiler`] drives the production parser's [`Parser::visit_events`]
4//! visitor: DDL statements build schema evidence as they arrive, and each
5//! decoded data row is routed — value by value, by column identity — into the
6//! per-column bounded sketches from [`crate::profile::sketches`]. Nothing here
7//! buffers a whole INSERT/COPY block: the visitor delivers one tuple / one COPY
8//! line at a time, so resident memory is bounded by the [`ProfileBudget`], never
9//! by the row count.
10//!
11//! # Depths
12//! * [`ProfileDepth::Schema`] reads no values — it counts rows and, per column,
13//!   total/null tallies only (exact), producing the portable schema with no
14//!   value-derived evidence.
15//! * [`ProfileDepth::Basic`] adds the cheap per-column metrics: distinct
16//!   estimate, min/max, quantiles, string shape, length, top-k, and a bounded
17//!   sample.
18//! * [`ProfileDepth::Full`] additionally computes pairwise evidence for the
19//!   *bounded* candidate set: declared foreign-key pairs (child→parent coverage)
20//!   and same-table temporal orderings. Planner-nominated pairs plug in through
21//!   the same [`RelationshipEvidence`] surface.
22//!
23//! Every depth returns the *same* portable schema and the *same* exact row and
24//! null counts; the depths differ only in how much value-derived evidence they
25//! attach.
26
27use std::collections::HashSet;
28use std::io::Read;
29use std::path::Path;
30
31use ahash::AHashMap;
32
33use crate::diagnostic::{codes, Diagnostic};
34use crate::parser::mysql_insert::{
35    hash_pk_tuple, parse_insert_tuple, InsertRowContext, ParsedRow, PkTuple, PkValue, RowExtraction,
36};
37use crate::parser::postgres_copy::{parse_copy_columns, CopyParser, ParsedCopyRow};
38use crate::parser::{
39    detect_dialect_from_file, determine_buffer_size, Parser, ParserEvent, RowFlow, SqlDialect,
40    StatementType, SMALL_BUFFER_SIZE,
41};
42use crate::schema::{Column, ColumnType, Schema, SchemaBuilder, TableId, TableSchema};
43use crate::synthetic::schema::PortableSchema;
44
45use super::evidence::{ColumnEvidence, DumpProfile, RelationshipEvidence, TableEvidence};
46use super::{ColumnSketches, ProfileBudget, ProfileDepth, ProfileValue};
47
48/// Streams a SQL dump into a [`DumpProfile`]. Build one with
49/// [`DumpProfiler::builder`].
50#[derive(Debug, Clone)]
51pub struct DumpProfiler {
52    depth: ProfileDepth,
53    budget: ProfileBudget,
54    seed: u64,
55    dialect: Option<SqlDialect>,
56}
57
58impl Default for DumpProfiler {
59    fn default() -> Self {
60        Self {
61            depth: ProfileDepth::Full,
62            budget: ProfileBudget::default(),
63            seed: 0,
64            dialect: None,
65        }
66    }
67}
68
69impl DumpProfiler {
70    /// Start configuring a profiler.
71    pub fn builder() -> DumpProfilerBuilder {
72        DumpProfilerBuilder::default()
73    }
74
75    /// Profile a dump on disk. Opens the file through the shared input layer
76    /// (transparent decompression / zip), and auto-detects the dialect from the
77    /// header unless one was configured on the builder.
78    pub fn profile_path(&self, path: &Path) -> anyhow::Result<DumpProfile> {
79        let dialect = match self.dialect {
80            Some(d) => d,
81            None => detect_dialect_from_file(path)?.dialect,
82        };
83        let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
84        let buffer_size = determine_buffer_size(file_size);
85        let reader = crate::splitter::open_input(path)?;
86        self.run(reader, dialect, buffer_size)
87    }
88
89    /// Profile a dump from an arbitrary reader. The dialect must be given
90    /// explicitly (there is no file header to sniff a compressed input from).
91    pub fn profile_reader<R: Read>(
92        &self,
93        reader: R,
94        dialect: SqlDialect,
95    ) -> anyhow::Result<DumpProfile> {
96        self.run(reader, dialect, SMALL_BUFFER_SIZE)
97    }
98
99    fn run<R: Read>(
100        &self,
101        reader: R,
102        dialect: SqlDialect,
103        buffer_size: usize,
104    ) -> anyhow::Result<DumpProfile> {
105        let mut parser = Parser::with_dialect(reader, buffer_size, dialect);
106        let mut run = ProfileRun::new(self.depth, self.budget, self.seed, dialect);
107        parser.visit_events(|event| run.on_event(event))?;
108        Ok(run.finish())
109    }
110}
111
112/// Builder for [`DumpProfiler`].
113#[derive(Debug, Clone, Default)]
114pub struct DumpProfilerBuilder {
115    inner: DumpProfilerConfig,
116}
117
118// A small config carrier so the builder can start from `Default` without
119// exposing the profiler's private fields.
120#[derive(Debug, Clone)]
121struct DumpProfilerConfig {
122    depth: ProfileDepth,
123    budget: ProfileBudget,
124    seed: u64,
125    dialect: Option<SqlDialect>,
126}
127
128impl Default for DumpProfilerConfig {
129    fn default() -> Self {
130        let d = DumpProfiler::default();
131        Self {
132            depth: d.depth,
133            budget: d.budget,
134            seed: d.seed,
135            dialect: d.dialect,
136        }
137    }
138}
139
140impl DumpProfilerBuilder {
141    /// How deep to profile (default [`ProfileDepth::Full`]).
142    pub fn depth(mut self, depth: ProfileDepth) -> Self {
143        self.inner.depth = depth;
144        self
145    }
146
147    /// Per-column retention budget (default [`ProfileBudget::default`]).
148    pub fn budget(mut self, budget: ProfileBudget) -> Self {
149        self.inner.budget = budget;
150        self
151    }
152
153    /// Seed for the reservoir sampler, making retained samples reproducible.
154    pub fn seed(mut self, seed: u64) -> Self {
155        self.inner.seed = seed;
156        self
157    }
158
159    /// Force a SQL dialect instead of auto-detecting from the file header.
160    pub fn dialect(mut self, dialect: SqlDialect) -> Self {
161        self.inner.dialect = Some(dialect);
162        self
163    }
164
165    /// Finalize the profiler.
166    pub fn build(self) -> DumpProfiler {
167        DumpProfiler {
168            depth: self.inner.depth,
169            budget: self.inner.budget,
170            seed: self.inner.seed,
171            dialect: self.inner.dialect,
172        }
173    }
174}
175
176// ---------------------------------------------------------------------------
177// Streaming run state
178// ---------------------------------------------------------------------------
179
180/// Coarse column family, derived once from the schema so row observation never
181/// has to re-borrow the schema to decide how to interpret a value.
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183enum ColumnKind {
184    Bool,
185    Int,
186    BigInt,
187    Decimal,
188    DateTime,
189    Json,
190    Text,
191}
192
193impl ColumnKind {
194    fn from_column(col: &Column) -> Self {
195        if col.source_type.to_ascii_lowercase().contains("json") {
196            return ColumnKind::Json;
197        }
198        match col.col_type {
199            ColumnType::Bool => ColumnKind::Bool,
200            ColumnType::Int => ColumnKind::Int,
201            ColumnType::BigInt => ColumnKind::BigInt,
202            ColumnType::Decimal => ColumnKind::Decimal,
203            ColumnType::DateTime => ColumnKind::DateTime,
204            ColumnType::Text | ColumnType::Uuid | ColumnType::Other(_) => ColumnKind::Text,
205        }
206    }
207}
208
209/// Per-column accumulator: exact total/null tallies at every depth, plus the
210/// value sketches at [`ProfileDepth::Basic`] and above.
211struct ColumnAccum {
212    name: String,
213    kind: ColumnKind,
214    total: u64,
215    nulls: u64,
216    sketches: Option<ColumnSketches>,
217}
218
219/// A same-table pair of timestamp columns, tracked for temporal ordering
220/// (`from <= to`) at [`ProfileDepth::Full`].
221struct TemporalPair {
222    from: usize,
223    to: usize,
224    both_present: u64,
225    ordered: u64,
226}
227
228/// A budget-capped set of 64-bit value hashes. Once full it stops inserting and
229/// records that it overflowed, so retention never scales with the row count.
230struct BoundedHashSet {
231    set: HashSet<u64>,
232    cap: usize,
233    overflowed: bool,
234}
235
236impl BoundedHashSet {
237    fn new(cap: usize) -> Self {
238        Self {
239            set: HashSet::new(),
240            cap: cap.max(1),
241            overflowed: false,
242        }
243    }
244
245    fn insert(&mut self, hash: u64) {
246        if self.set.len() < self.cap {
247            self.set.insert(hash);
248        } else if !self.set.contains(&hash) {
249            self.overflowed = true;
250        }
251    }
252
253    fn contains(&self, hash: u64) -> bool {
254        self.set.contains(&hash)
255    }
256
257    fn is_empty(&self) -> bool {
258        self.set.is_empty()
259    }
260}
261
262/// A declared foreign key reduced to the local column ordinals that carry its
263/// child values, so coverage can be tracked without re-borrowing the schema per
264/// row. `referenced_table_id` is resolved only at `build()`, so we key by
265/// `fk_index` and resolve the parent at finish.
266struct FkCandidate {
267    fk_index: u16,
268    ordinals: Vec<usize>,
269}
270
271/// Per-table profiling state.
272struct TableProfile {
273    name: String,
274    table_id: TableId,
275    row_count: u64,
276    columns: Vec<ColumnAccum>,
277    // Full-depth relationship tracking (empty otherwise).
278    pk_hashes: BoundedHashSet,
279    fk_candidates: Vec<FkCandidate>,
280    fk_child: AHashMap<u16, BoundedHashSet>,
281    temporal: Vec<TemporalPair>,
282    /// Whether a `GEN-PROFILE-DECODE-SKIPPED` warning has already been raised for
283    /// this table, so a run of undecodable rows warns once, not per row.
284    decode_warned: bool,
285}
286
287/// Buffered rows for a table whose data arrived before its DDL, retained up to
288/// the sample budget for a bounded replay once the schema appears.
289struct PendingTable {
290    row_count: u64,
291    retained: Vec<PendingRow>,
292    overflowed: bool,
293    header: Option<Vec<u8>>,
294    copy_columns: Option<Vec<String>>,
295}
296
297enum PendingRow {
298    Insert(Vec<u8>),
299    Copy(Vec<u8>),
300}
301
302/// Column context for the INSERT statement currently being streamed.
303struct InsertCtx {
304    table_idx: usize,
305    context: InsertRowContext,
306}
307
308/// Column context for the COPY block currently being streamed.
309struct CopyCtx {
310    table_idx: usize,
311    columns: Vec<String>,
312}
313
314struct ProfileRun {
315    depth: ProfileDepth,
316    budget: ProfileBudget,
317    seed: u64,
318    dialect: SqlDialect,
319    builder: SchemaBuilder,
320    tables: Vec<TableProfile>,
321    table_index: AHashMap<String, usize>,
322    insert_ctx: Option<InsertCtx>,
323    copy_ctx: Option<CopyCtx>,
324    /// The schema-late COPY table whose block is currently open. `CopyRow`
325    /// events carry no table name, so this is the *only* reliable way to route
326    /// pending COPY rows — a predicate scan over `pending` would misroute when
327    /// two tables both have COPY data before either's DDL.
328    pending_copy_key: Option<String>,
329    pending: AHashMap<String, PendingTable>,
330    warnings: Vec<Diagnostic>,
331    next_seed: u64,
332}
333
334impl ProfileRun {
335    fn new(depth: ProfileDepth, budget: ProfileBudget, seed: u64, dialect: SqlDialect) -> Self {
336        Self {
337            depth,
338            budget,
339            seed,
340            dialect,
341            builder: SchemaBuilder::new(),
342            tables: Vec::new(),
343            table_index: AHashMap::new(),
344            insert_ctx: None,
345            copy_ctx: None,
346            pending_copy_key: None,
347            pending: AHashMap::new(),
348            warnings: Vec::new(),
349            next_seed: 0,
350        }
351    }
352
353    fn key(name: &str) -> String {
354        name.to_ascii_lowercase()
355    }
356
357    fn on_event(&mut self, event: ParserEvent<'_>) -> anyhow::Result<RowFlow> {
358        match event {
359            ParserEvent::Statement(bytes) => self.on_statement(bytes),
360            ParserEvent::InsertRow {
361                header,
362                row,
363                first_in_statement,
364            } => self.on_insert_row(header, row, first_in_statement),
365            ParserEvent::CopyStart(header) => self.on_copy_start(header),
366            ParserEvent::CopyRow(line) => self.on_copy_row(line),
367            ParserEvent::CopyEnd => {
368                self.copy_ctx = None;
369                self.pending_copy_key = None;
370                Ok(RowFlow::Continue)
371            }
372        }
373    }
374
375    fn on_statement(&mut self, bytes: &[u8]) -> anyhow::Result<RowFlow> {
376        let (stmt_type, name) = Parser::<&[u8]>::parse_statement_with_dialect(bytes, self.dialect);
377        self.builder.ingest_statement(bytes, self.dialect);
378        if stmt_type == StatementType::CreateTable && !name.is_empty() {
379            self.register_table(&name);
380        }
381        Ok(RowFlow::Continue)
382    }
383
384    /// Ensure a [`TableProfile`] exists for a freshly created table, then replay
385    /// any rows that were buffered before the DDL arrived.
386    fn register_table(&mut self, name: &str) {
387        let key = Self::key(name);
388        if self.table_index.contains_key(&key) {
389            return;
390        }
391        let Some(table_id) = self.builder.schema().get_table_id(name) else {
392            return;
393        };
394        let profile = self.build_table_profile(name, table_id);
395        let idx = self.tables.len();
396        self.tables.push(profile);
397        self.table_index.insert(key.clone(), idx);
398
399        if let Some(pending) = self.pending.remove(&key) {
400            self.replay_pending(idx, pending);
401        }
402    }
403
404    fn build_table_profile(&mut self, name: &str, table_id: TableId) -> TableProfile {
405        let schema = self.builder.schema();
406        let table = schema
407            .table(table_id)
408            .expect("table id just resolved from builder");
409        let full = self.depth == ProfileDepth::Full;
410
411        let columns: Vec<ColumnAccum> = table
412            .columns
413            .iter()
414            .map(|col| {
415                let kind = ColumnKind::from_column(col);
416                // A credential-named, string-shaped column never enters the
417                // sketches: its raw values (hashes, tokens, keys) must not be
418                // retained in evidence. The exact total/null counts tracked
419                // separately below are still kept, so null-rate survives.
420                let credential = matches!(kind, ColumnKind::Text | ColumnKind::Json)
421                    && crate::profile::heuristics::is_credential_name(&col.name);
422                let sketches = if self.depth == ProfileDepth::Schema || credential {
423                    None
424                } else {
425                    let s = ColumnSketches::new(&self.budget, self.seed ^ self.next_seed);
426                    self.next_seed = self.next_seed.wrapping_add(1);
427                    Some(s)
428                };
429                ColumnAccum {
430                    name: col.name.clone(),
431                    kind,
432                    total: 0,
433                    nulls: 0,
434                    sketches,
435                }
436            })
437            .collect();
438
439        // Same-table temporal candidate pairs (Full only): ordered pairs of
440        // timestamp columns, bounded by the schema's column count.
441        let temporal = if full {
442            let ts_cols: Vec<usize> = table
443                .columns
444                .iter()
445                .enumerate()
446                .filter(|(_, c)| ColumnKind::from_column(c) == ColumnKind::DateTime)
447                .map(|(i, _)| i)
448                .collect();
449            let mut pairs = Vec::new();
450            for (a_pos, &a) in ts_cols.iter().enumerate() {
451                for &b in &ts_cols[a_pos + 1..] {
452                    pairs.push(TemporalPair {
453                        from: a,
454                        to: b,
455                        both_present: 0,
456                        ordered: 0,
457                    });
458                }
459            }
460            pairs
461        } else {
462            Vec::new()
463        };
464
465        // Declared FKs reduced to local column ordinals (resolved at CREATE
466        // TABLE time; only the *referenced* table id is deferred to `build()`).
467        let fk_candidates: Vec<FkCandidate> = if full {
468            table
469                .foreign_keys
470                .iter()
471                .enumerate()
472                .filter(|(_, fk)| !fk.columns.is_empty())
473                .map(|(fk_index, fk)| FkCandidate {
474                    fk_index: fk_index as u16,
475                    ordinals: fk.columns.iter().map(|c| c.0 as usize).collect(),
476                })
477                .collect()
478        } else {
479            Vec::new()
480        };
481
482        TableProfile {
483            name: name.to_string(),
484            table_id,
485            row_count: 0,
486            columns,
487            pk_hashes: BoundedHashSet::new(self.budget.sample_rows),
488            fk_candidates,
489            fk_child: AHashMap::new(),
490            temporal,
491            decode_warned: false,
492        }
493    }
494
495    // --- INSERT path -------------------------------------------------------
496
497    fn on_insert_row(
498        &mut self,
499        header: &[u8],
500        row: &[u8],
501        first_in_statement: bool,
502    ) -> anyhow::Result<RowFlow> {
503        if first_in_statement {
504            self.prepare_insert(header);
505        }
506
507        // Every delivered `InsertRow` is a real `(...)` tuple, so it counts
508        // toward the exact row total for a known table regardless of whether the
509        // secondary value decode succeeds. Decode success only governs per-column
510        // value/null evidence.
511        if let Some(table_idx) = self.insert_ctx.as_ref().map(|c| c.table_idx) {
512            match self.decode_insert_row(row) {
513                Some((idx, parsed)) => self.observe_insert(idx, &parsed),
514                None => {
515                    self.tables[table_idx].row_count += 1;
516                    self.warn_decode_skipped(table_idx);
517                }
518            }
519        } else {
520            // Schema-late: buffer the raw tuple for replay once the DDL arrives.
521            let cap = self.budget.sample_rows;
522            if let Some(table) = self.pending_insert_target(header) {
523                table.push_insert(row, cap);
524            }
525        }
526
527        Ok(RowFlow::Continue)
528    }
529
530    fn decode_insert_row(&self, row: &[u8]) -> Option<(usize, ParsedRow)> {
531        let ctx = self.insert_ctx.as_ref()?;
532        let table_idx = ctx.table_idx;
533        let table_id = self.tables[table_idx].table_id;
534        let table = self.builder.schema().table(table_id)?;
535        let parsed =
536            parse_insert_tuple(row, table, &ctx.context, self.dialect, RowExtraction::Full)?;
537        Some((table_idx, parsed))
538    }
539
540    fn prepare_insert(&mut self, header: &[u8]) {
541        self.insert_ctx = None;
542        let (_, name) = Parser::<&[u8]>::parse_statement_with_dialect(header, self.dialect);
543        if name.is_empty() {
544            return;
545        }
546        let key = Self::key(&name);
547        if let Some(&table_idx) = self.table_index.get(&key) {
548            let table_id = self.tables[table_idx].table_id;
549            let schema = self.builder.schema();
550            if let Some(table) = schema.table(table_id) {
551                let context = InsertRowContext::from_header(header, table);
552                self.insert_ctx = Some(InsertCtx { table_idx, context });
553            }
554        } else {
555            // Schema-late: remember the first header so the replay can rebuild
556            // context (single-layout-per-pending-table assumption — a later
557            // INSERT into the same table with a different column list would
558            // replay under this one).
559            self.pending
560                .entry(key)
561                .or_insert_with(PendingTable::new)
562                .header
563                .get_or_insert_with(|| header.to_vec());
564        }
565    }
566
567    /// Look up (creating if needed) the pending buffer for the INSERT whose
568    /// header names an as-yet-unknown table.
569    fn pending_insert_target(&mut self, header: &[u8]) -> Option<&mut PendingTable> {
570        let (_, name) = Parser::<&[u8]>::parse_statement_with_dialect(header, self.dialect);
571        if name.is_empty() {
572            return None;
573        }
574        let key = Self::key(&name);
575        let entry = self.pending.entry(key).or_insert_with(PendingTable::new);
576        // Single-layout-per-pending-table: the first header wins for replay.
577        entry.header.get_or_insert_with(|| header.to_vec());
578        Some(entry)
579    }
580
581    // --- COPY path ---------------------------------------------------------
582
583    fn on_copy_start(&mut self, header: &[u8]) -> anyhow::Result<RowFlow> {
584        self.copy_ctx = None;
585        self.pending_copy_key = None;
586        let header_str = String::from_utf8_lossy(header);
587        let (_, name) = Parser::<&[u8]>::parse_statement_with_dialect(header, self.dialect);
588        if name.is_empty() {
589            return Ok(RowFlow::Continue);
590        }
591        let columns = parse_copy_columns(&header_str);
592        let key = Self::key(&name);
593        if let Some(&table_idx) = self.table_index.get(&key) {
594            self.copy_ctx = Some(CopyCtx { table_idx, columns });
595        } else {
596            // Schema-late COPY: record which table this open block belongs to so
597            // its rows route unambiguously, and stash the column layout for
598            // replay (single-layout-per-pending-table assumption).
599            //
600            // TODO(deferred, L21): if a `CREATE TABLE` for this key arrives while
601            // this block is still open, `register_table` removes the pending
602            // entry, leaving `pending_copy_key` dangling so the block's remaining
603            // rows are silently dropped. Adopting the open block into the newly
604            // registered table would fix it. Deferred: pg_dump never interleaves
605            // a table definition inside its own open COPY block (malformed input
606            // only).
607            let entry = self
608                .pending
609                .entry(key.clone())
610                .or_insert_with(PendingTable::new);
611            entry.copy_columns.get_or_insert(columns);
612            self.pending_copy_key = Some(key);
613        }
614        Ok(RowFlow::Continue)
615    }
616
617    fn on_copy_row(&mut self, line: &[u8]) -> anyhow::Result<RowFlow> {
618        if let Some(table_idx) = self.copy_ctx.as_ref().map(|c| c.table_idx) {
619            // Known table. A blank line inside a COPY block is padding, not a
620            // row, so it must not count; every genuine data line counts toward
621            // the exact total whether or not its values decode.
622            let single_col = self.tables[table_idx].columns.len() == 1;
623            if !copy_line_is_data(line, single_col) {
624                return Ok(RowFlow::Continue);
625            }
626            match self.decode_copy_row(line) {
627                Some((idx, parsed)) => self.observe_copy(idx, &parsed),
628                None => {
629                    self.tables[table_idx].row_count += 1;
630                    self.warn_decode_skipped(table_idx);
631                }
632            }
633        } else if let Some(key) = self.pending_copy_key.clone() {
634            // Schema-late COPY: route by the explicitly tracked open-block key,
635            // never a predicate scan (which would misroute with two pending
636            // COPY tables). Buffer genuine data lines only. The COPY header's
637            // column list gives the arity even before the CREATE TABLE, so a
638            // single-column block correctly treats a blank line as an
639            // empty-string row rather than padding.
640            let cap = self.budget.sample_rows;
641            if let Some(table) = self.pending.get_mut(&key) {
642                let single_col = table
643                    .copy_columns
644                    .as_ref()
645                    .is_some_and(|columns| columns.len() == 1);
646                if copy_line_is_data(line, single_col) {
647                    table.push_copy(line, cap);
648                }
649            }
650        }
651        Ok(RowFlow::Continue)
652    }
653
654    /// Raise `GEN-PROFILE-DECODE-SKIPPED` once per table when a delivered row
655    /// failed value decoding: it is still counted in the exact row total, but
656    /// contributes no per-column evidence.
657    fn warn_decode_skipped(&mut self, table_idx: usize) {
658        let table = &mut self.tables[table_idx];
659        if table.decode_warned {
660            return;
661        }
662        table.decode_warned = true;
663        self.warnings.push(Diagnostic::warning(
664            &codes::PROFILE_DECODE_SKIPPED,
665            format!("tables.{}", table.name),
666            "rows failed value decoding; they are counted in the exact row total but \
667             contributed no per-column evidence",
668        ));
669    }
670
671    fn decode_copy_row(&self, line: &[u8]) -> Option<(usize, ParsedCopyRow)> {
672        let ctx = self.copy_ctx.as_ref()?;
673        let table_idx = ctx.table_idx;
674        let table_id = self.tables[table_idx].table_id;
675        let table = self.builder.schema().table(table_id)?;
676        let parsed = decode_copy_line(line, table, ctx.columns.clone())?;
677        Some((table_idx, parsed))
678    }
679
680    // --- Row observation ---------------------------------------------------
681
682    fn observe_insert(&mut self, table_idx: usize, row: &ParsedRow) {
683        let ncols = self.tables[table_idx].columns.len();
684        self.observe_row(
685            table_idx,
686            ncols,
687            |ord| row.get_column_value(ord),
688            row.pk.as_ref(),
689        );
690    }
691
692    fn observe_copy(&mut self, table_idx: usize, row: &ParsedCopyRow) {
693        let ncols = self.tables[table_idx].columns.len();
694        self.observe_row(
695            table_idx,
696            ncols,
697            |ord| row.get_column_value(ord),
698            row.pk.as_ref(),
699        );
700    }
701
702    /// The single per-row hot path shared by INSERT and COPY: tally total/null,
703    /// feed the value sketches, and (at Full depth) update FK/PK/temporal
704    /// evidence.
705    fn observe_row<'r>(
706        &mut self,
707        table_idx: usize,
708        ncols: usize,
709        value: impl Fn(usize) -> Option<&'r PkValue>,
710        pk: Option<&PkTuple>,
711    ) {
712        let full = self.depth == ProfileDepth::Full;
713        let cap = self.budget.sample_rows;
714        let table = &mut self.tables[table_idx];
715        table.row_count += 1;
716
717        for (ord, acc) in table.columns.iter_mut().enumerate().take(ncols) {
718            let Some(v) = value(ord) else { continue };
719            acc.total += 1;
720            if v.is_null() {
721                acc.nulls += 1;
722            }
723            if let Some(sketches) = &mut acc.sketches {
724                observe_pk_value(sketches, acc.kind, v);
725            }
726        }
727
728        if !full {
729            return;
730        }
731
732        if let Some(pk) = pk {
733            table.pk_hashes.insert(hash_pk_tuple(pk));
734        }
735        // Child FK values, hashed the same way parent PKs are, so coverage is a
736        // plain set-membership test at finish.
737        for candidate in &table.fk_candidates {
738            let mut tuple = PkTuple::new();
739            let mut complete = true;
740            for &ord in &candidate.ordinals {
741                match value(ord) {
742                    Some(v) if !v.is_null() => tuple.push(v.clone()),
743                    _ => {
744                        complete = false;
745                        break;
746                    }
747                }
748            }
749            if complete && !tuple.is_empty() {
750                table
751                    .fk_child
752                    .entry(candidate.fk_index)
753                    .or_insert_with(|| BoundedHashSet::new(cap))
754                    .insert(hash_pk_tuple(&tuple));
755            }
756        }
757        for pair in &mut table.temporal {
758            if let (Some(PkValue::Text(a)), Some(PkValue::Text(b))) =
759                (value(pair.from), value(pair.to))
760            {
761                pair.both_present += 1;
762                if a <= b {
763                    pair.ordered += 1;
764                }
765            }
766        }
767    }
768
769    // --- Schema-late replay ------------------------------------------------
770
771    fn replay_pending(&mut self, table_idx: usize, pending: PendingTable) {
772        let table_id = self.tables[table_idx].table_id;
773
774        // Replay every retained row through the normal decode/observe path.
775        for row in &pending.retained {
776            match row {
777                PendingRow::Insert(bytes) => {
778                    let parsed = pending.header.as_ref().and_then(|header| {
779                        let schema = self.builder.schema();
780                        let table = schema.table(table_id)?;
781                        let ctx = InsertRowContext::from_header(header, table);
782                        parse_insert_tuple(bytes, table, &ctx, self.dialect, RowExtraction::Full)
783                    });
784                    if let Some(parsed) = parsed {
785                        self.observe_insert(table_idx, &parsed);
786                    }
787                }
788                PendingRow::Copy(bytes) => {
789                    let cols = pending.copy_columns.clone().unwrap_or_default();
790                    let parsed = {
791                        let schema = self.builder.schema();
792                        schema
793                            .table(table_id)
794                            .and_then(|table| decode_copy_line(bytes, table, cols))
795                    };
796                    if let Some(parsed) = parsed {
797                        self.observe_copy(table_idx, &parsed);
798                    }
799                }
800            }
801        }
802
803        // The retained sample may be smaller than what actually streamed by:
804        // fix the row count to the true total and flag the coverage gap.
805        let observed = self.tables[table_idx].row_count;
806        if pending.row_count > observed {
807            self.tables[table_idx].row_count = pending.row_count;
808        }
809        if pending.overflowed {
810            self.warnings.push(Diagnostic::warning(
811                &codes::PROFILE_SCHEMA_LATE,
812                format!("tables.{}", self.tables[table_idx].name),
813                format!(
814                    "had {} data rows before its DDL; only {} were retained for value profiling \
815                     (counts remain exact)",
816                    pending.row_count,
817                    pending.retained.len()
818                ),
819            ));
820        }
821    }
822
823    // --- Finalize ----------------------------------------------------------
824
825    fn finish(mut self) -> DumpProfile {
826        // Resolve FK references now that all DDL has been seen.
827        let schema = std::mem::take(&mut self.builder).build();
828
829        // Map table id -> profile index, so FK coverage can reach the parent's
830        // retained PK set.
831        let mut id_to_idx: AHashMap<u32, usize> = AHashMap::new();
832        for (idx, t) in self.tables.iter().enumerate() {
833            id_to_idx.insert(t.table_id.0, idx);
834        }
835
836        // Any pending table that never got its DDL: surface its exact row count
837        // and warn that its columns could not be profiled.
838        // Sort by table key so the warnings are deterministic; the pending map
839        // is a randomized-seed hashmap whose drain order varies run to run.
840        let mut leftovers: Vec<(String, PendingTable)> = self.pending.drain().collect();
841        leftovers.sort_by(|a, b| a.0.cmp(&b.0));
842        for (key, pending) in leftovers {
843            self.warnings.push(Diagnostic::warning(
844                &codes::PROFILE_SCHEMA_LATE,
845                format!("tables.{key}"),
846                format!(
847                    "had {} data rows but no CREATE TABLE was seen; it could not be profiled",
848                    pending.row_count
849                ),
850            ));
851        }
852
853        let depth = self.depth;
854        let relationships = self.compute_relationships(&schema, &id_to_idx);
855
856        let tables = self
857            .tables
858            .into_iter()
859            .enumerate()
860            .map(|(idx, table)| {
861                finish_table(table, relationships.get(&idx).cloned().unwrap_or_default())
862            })
863            .collect();
864
865        // The profiler already built the full DDL schema in this same pass;
866        // capture it as a portable snapshot so downstream inference never has
867        // to re-read the dump to recover it.
868        let portable = PortableSchema::from_runtime(&schema, self.dialect);
869
870        DumpProfile {
871            depth,
872            schema: portable,
873            tables,
874            warnings: self.warnings,
875        }
876    }
877
878    /// Build the Full-depth relationship evidence per table index.
879    fn compute_relationships(
880        &self,
881        schema: &Schema,
882        id_to_idx: &AHashMap<u32, usize>,
883    ) -> AHashMap<usize, Vec<RelationshipEvidence>> {
884        let mut out: AHashMap<usize, Vec<RelationshipEvidence>> = AHashMap::new();
885        if self.depth != ProfileDepth::Full {
886            return out;
887        }
888
889        for (idx, table) in self.tables.iter().enumerate() {
890            let Some(table_schema) = schema.table(table.table_id) else {
891                continue;
892            };
893            let mut rels = Vec::new();
894
895            // Declared foreign keys: child -> parent coverage over bounded sets.
896            for (fk_index, fk) in table_schema.foreign_keys.iter().enumerate() {
897                let Some(child) = table.fk_child.get(&(fk_index as u16)) else {
898                    continue;
899                };
900                if child.is_empty() {
901                    continue;
902                }
903                let Some(parent_id) = fk.referenced_table_id else {
904                    continue;
905                };
906                let Some(&parent_idx) = id_to_idx.get(&parent_id.0) else {
907                    continue;
908                };
909                let parent = &self.tables[parent_idx].pk_hashes;
910                let matched = child.set.iter().filter(|h| parent.contains(**h)).count();
911                let coverage = matched as f64 / child.set.len() as f64;
912                let bounded = child.overflowed || parent.overflowed;
913                rels.push(RelationshipEvidence {
914                    from_column: fk.column_names.join(","),
915                    to_table: fk.referenced_table.clone(),
916                    to_column: fk.referenced_columns.join(","),
917                    coverage,
918                    confidence: if bounded { 0.5 } else { 1.0 },
919                });
920            }
921
922            // Same-table temporal orderings.
923            for pair in &table.temporal {
924                if pair.both_present == 0 {
925                    continue;
926                }
927                let coverage = pair.ordered as f64 / pair.both_present as f64;
928                rels.push(RelationshipEvidence {
929                    from_column: table.columns[pair.from].name.clone(),
930                    to_table: table.name.clone(),
931                    to_column: table.columns[pair.to].name.clone(),
932                    coverage,
933                    confidence: coverage,
934                });
935            }
936
937            if !rels.is_empty() {
938                out.insert(idx, rels);
939            }
940        }
941        out
942    }
943}
944
945/// True when a raw COPY line is a genuine data row, matching
946/// [`CopyParser::parse_line`]'s own skip rules: the `\.` terminator and (for
947/// multi-column tables) a blank padding line are *not* rows. Lets the exact row
948/// count be decided independently of whether the value decode succeeds.
949fn copy_line_is_data(line: &[u8], empty_is_row: bool) -> bool {
950    let line = if line.last() == Some(&b'\r') {
951        &line[..line.len() - 1]
952    } else {
953        line
954    };
955    !(line == b"\\." || (line.is_empty() && !empty_is_row))
956}
957
958/// Decode one COPY data line into a [`ParsedCopyRow`] with full column identity,
959/// building a fresh (bounded, per-line) parser context bound to the schema.
960fn decode_copy_line(
961    line: &[u8],
962    table: &TableSchema,
963    columns: Vec<String>,
964) -> Option<ParsedCopyRow> {
965    let (parser, empty_is_row) = CopyParser::new(b"")
966        .with_schema(table)
967        .with_column_order(columns)
968        .with_extraction(RowExtraction::Full)
969        .prepared();
970    parser.parse_line(line, empty_is_row)
971}
972
973/// Fold one already-decoded column value into its sketches, interpreting it
974/// through the schema-derived [`ColumnKind`].
975fn observe_pk_value(sketches: &mut ColumnSketches, kind: ColumnKind, value: &PkValue) {
976    match value {
977        PkValue::Null => sketches.observe(ProfileValue::Null),
978        PkValue::Int(n) => observe_integer(sketches, kind, *n as i128),
979        PkValue::BigInt(n) => observe_integer(sketches, kind, *n),
980        PkValue::Text(s) => observe_text(sketches, kind, s),
981    }
982}
983
984fn observe_integer(sketches: &mut ColumnSketches, kind: ColumnKind, n: i128) {
985    match kind {
986        ColumnKind::Bool if n == 0 || n == 1 => {
987            sketches.observe(ProfileValue::Boolean(n == 1));
988        }
989        ColumnKind::Decimal => sketches.observe(ProfileValue::Decimal { minor: n, scale: 0 }),
990        _ => match i64::try_from(n) {
991            Ok(v) => sketches.observe(ProfileValue::Integer(v)),
992            Err(_) => sketches.observe(ProfileValue::Decimal { minor: n, scale: 0 }),
993        },
994    }
995}
996
997fn observe_text(sketches: &mut ColumnSketches, kind: ColumnKind, s: &str) {
998    match kind {
999        ColumnKind::DateTime => sketches.observe(ProfileValue::DateTime(s)),
1000        ColumnKind::Json => sketches.observe(ProfileValue::Json(s)),
1001        ColumnKind::Bool => match parse_bool(s) {
1002            Some(b) => sketches.observe(ProfileValue::Boolean(b)),
1003            None => sketches.observe(ProfileValue::Text(s)),
1004        },
1005        ColumnKind::Decimal => match parse_decimal(s) {
1006            Some((minor, scale)) => sketches.observe(ProfileValue::Decimal { minor, scale }),
1007            None => sketches.observe(ProfileValue::Text(s)),
1008        },
1009        ColumnKind::Int | ColumnKind::BigInt => match s.parse::<i128>() {
1010            Ok(n) => observe_integer(sketches, kind, n),
1011            Err(_) => sketches.observe(ProfileValue::Text(s)),
1012        },
1013        ColumnKind::Text => sketches.observe(ProfileValue::Text(s)),
1014    }
1015}
1016
1017/// Parse a boolean rendered as text (`t`/`true`/`1`/`yes` and their negatives).
1018fn parse_bool(s: &str) -> Option<bool> {
1019    match s.trim().to_ascii_lowercase().as_str() {
1020        "t" | "true" | "yes" | "y" => Some(true),
1021        "f" | "false" | "no" | "n" => Some(false),
1022        _ => None,
1023    }
1024}
1025
1026/// Parse a plain fixed-point decimal string into `(minor, scale)` such that the
1027/// value equals `minor * 10^-scale`. Rejects anything that is not sign + digits
1028/// with at most one decimal point (scientific notation, currency, etc.).
1029fn parse_decimal(s: &str) -> Option<(i128, u8)> {
1030    let s = s.trim();
1031    let (neg, body) = match s.strip_prefix('-') {
1032        Some(rest) => (true, rest),
1033        None => (false, s.strip_prefix('+').unwrap_or(s)),
1034    };
1035    let (int_part, frac_part) = match body.split_once('.') {
1036        Some((a, b)) => (a, b),
1037        None => (body, ""),
1038    };
1039    if int_part.is_empty() && frac_part.is_empty() {
1040        return None;
1041    }
1042    if !int_part.bytes().all(|b| b.is_ascii_digit()) {
1043        return None;
1044    }
1045    if !frac_part.bytes().all(|b| b.is_ascii_digit()) {
1046        return None;
1047    }
1048    let mut digits = String::with_capacity(int_part.len() + frac_part.len());
1049    digits.push_str(int_part);
1050    digits.push_str(frac_part);
1051    let mut minor: i128 = digits.parse().ok()?;
1052    if neg {
1053        minor = -minor;
1054    }
1055    let scale = u8::try_from(frac_part.len()).ok()?;
1056    Some((minor, scale))
1057}
1058
1059/// Finalize one table's accumulated state into neutral evidence.
1060fn finish_table(table: TableProfile, relationships: Vec<RelationshipEvidence>) -> TableEvidence {
1061    let columns = table
1062        .columns
1063        .into_iter()
1064        .map(finish_column)
1065        .collect::<Vec<_>>();
1066    let confidence = if table.row_count > 0 { 1.0 } else { 0.0 };
1067    TableEvidence {
1068        table: table.name,
1069        row_count: Some(table.row_count),
1070        columns,
1071        relationships,
1072        confidence,
1073    }
1074}
1075
1076fn finish_column(acc: ColumnAccum) -> ColumnEvidence {
1077    match acc.sketches {
1078        Some(sketches) => {
1079            let mut ev = sketches.finish();
1080            ev.name = acc.name;
1081            ev
1082        }
1083        None => {
1084            // Schema depth: exact counts, no value-derived evidence.
1085            let null_rate = if acc.total == 0 {
1086                0.0
1087            } else {
1088                acc.nulls as f64 / acc.total as f64
1089            };
1090            // Ad-hoc confidence: rises toward 1.0 with the non-null observation
1091            // count (mirrors `ColumnSketches::confidence`). Both paths share
1092            // this intentionally heuristic scale.
1093            let non_null = acc.total.saturating_sub(acc.nulls);
1094            ColumnEvidence {
1095                name: acc.name,
1096                total_count: acc.total,
1097                null_count: acc.nulls,
1098                null_rate,
1099                distinct_estimate: 0.0,
1100                sample_values: Vec::new(),
1101                truncated_sample_count: 0,
1102                boolean: None,
1103                numeric: None,
1104                decimal_scale: None,
1105                string_shape: None,
1106                top_k: Vec::new(),
1107                timestamp_range: None,
1108                json_valid_rate: None,
1109                confidence: 1.0 - 1.0 / (1.0 + non_null as f64),
1110            }
1111        }
1112    }
1113}
1114
1115impl PendingTable {
1116    fn new() -> Self {
1117        Self {
1118            row_count: 0,
1119            retained: Vec::new(),
1120            overflowed: false,
1121            header: None,
1122            copy_columns: None,
1123        }
1124    }
1125
1126    fn push_insert(&mut self, row: &[u8], cap: usize) {
1127        self.row_count += 1;
1128        if self.retained.len() < cap {
1129            self.retained.push(PendingRow::Insert(row.to_vec()));
1130        } else {
1131            self.overflowed = true;
1132        }
1133    }
1134
1135    fn push_copy(&mut self, line: &[u8], cap: usize) {
1136        self.row_count += 1;
1137        if self.retained.len() < cap {
1138            self.retained.push(PendingRow::Copy(line.to_vec()));
1139        } else {
1140            self.overflowed = true;
1141        }
1142    }
1143}