Skip to main content

spg_engine/
maintenance.rs

1//! Table-maintenance executors: `ANALYZE` (re-stat) and
2//! `COMPACT COLD SEGMENTS` (cold-segment merge). Split out of
3//! `lib.rs` (cut 19); verbatim move, the only edit beyond
4//! visibility is reuniting the `exec_compact_cold_segments` doc,
5//! whose first half had drifted above `set_session_param`.
6
7use alloc::string::{String, ToString};
8use alloc::vec::Vec;
9
10use spg_storage::{ColumnSchema, CompactReport, DataType, IndexKind, Row, StorageError, Value};
11
12use crate::{
13    COMPACTION_TARGET_DEFAULT_BYTES, Engine, EngineError, QueryResult, canonical_value_repr,
14    is_internal_table_name, sort_values_for_histogram, statistics,
15};
16
17impl Engine {
18    /// v6.2.0 — `ANALYZE [<table>]` runtime. Bare `ANALYZE` walks
19    /// every user table; `ANALYZE <name>` re-stats one. For each
20    /// target table, single-pass scan + per-column histogram +
21    /// `null_frac` + `n_distinct`. Replaces the table's prior
22    /// stats; resets the modified-row counter.
23    ///
24    /// v6.2.0 doesn't sample — it scans the full table. v6.2.x
25    /// can add reservoir sampling at the > 100 K-row mark; not a
26    /// scope blocker for the current commit since rows ≤ 100 K
27    /// analyse in milliseconds.
28    /// v7.39 (round 320, V53) — `DISCARD { ALL | PLANS | SEQUENCES | TEMP }`.
29    /// pgbouncer sends `DISCARD ALL` between pooled client sessions so the
30    /// next client sees a clean connection. It used to be swallowed as
31    /// "dump noise" on the theory that SPG had no per-connection state
32    /// worth discarding — untrue since round 279 gave every connection its
33    /// own session bag (GUC overrides, prepared statements, large-object
34    /// descriptors). A no-op meant one pooled client's state leaked to the
35    /// next one.
36    ///
37    /// PG 18.4 measured: `SET application_name='x'; PREPARE p …;
38    /// DISCARD ALL` leaves application_name back at its startup value and
39    /// `EXECUTE p` failing with "prepared statement \"p\" does not
40    /// exist"; inside a transaction block it is
41    /// `ERROR: DISCARD ALL cannot run inside a transaction block`.
42    ///
43    /// v7.39 (round 321, V54) — cursors are closed here too, as PG's
44    /// DISCARD ALL does. Round 320 had to leave them alone because the
45    /// cursor table was process-wide: closing "all" from one connection
46    /// would have closed another's. They live in the session bag now.
47    pub(crate) fn exec_discard(
48        &mut self,
49        target: spg_sql::ast::DiscardTarget,
50    ) -> Result<QueryResult, EngineError> {
51        use spg_sql::ast::DiscardTarget;
52        if matches!(target, DiscardTarget::All | DiscardTarget::Temp)
53            && self.current_tx.is_some_and(|tx| self.is_tx_open(tx))
54        {
55            return Err(EngineError::Unsupported(alloc::format!(
56                "DISCARD {target} cannot run inside a transaction block"
57            )));
58        }
59        match target {
60            DiscardTarget::All => {
61                self.reset_all_gucs();
62                self.prepared_statements.clear();
63                self.lo_descriptors.clear();
64                self.lo_next_fd = 0;
65                self.cursors.clear();
66                self.listen_channels.clear();
67                self.plan_cache.clear();
68                self.refresh_render_style();
69            }
70            DiscardTarget::Plans => self.plan_cache.clear(),
71            // SPG has neither temp tables nor per-session sequence state
72            // (`currval` reads the catalog), so there is nothing of either
73            // kind to throw away. Accepted so a client's sequence of
74            // DISCARDs runs, and tagged with the target it named.
75            DiscardTarget::Sequences | DiscardTarget::Temp => {}
76        }
77        Ok(QueryResult::CommandOk {
78            affected: 0,
79            modified_catalog: false,
80        })
81    }
82
83    pub(crate) fn exec_analyze(
84        &mut self,
85        target: Option<&str>,
86    ) -> Result<QueryResult, EngineError> {
87        // v7.38 元机制 D acceptor — `SPG_TEST_STATS_FROZEN=1` turns
88        // ANALYZE into a no-op so a test's statistic-version snapshot
89        // is stable across sessions. Pairs with the plan-cache
90        // version-aware invalidation: freezing stats also freezes
91        // plan reuse, which is what regression tests want when
92        // proving "same SQL, same plan".
93        if self.env_cfg().stats_frozen {
94            return Ok(QueryResult::CommandOk {
95                affected: 0,
96                modified_catalog: false,
97            });
98        }
99        let names: Vec<String> = if let Some(name) = target {
100            // Verify the table exists; surface a clear error if not.
101            if self.catalog.get(name).is_none() {
102                return Err(EngineError::Storage(StorageError::TableNotFound {
103                    name: name.to_string(),
104                }));
105            }
106            alloc::vec![name.to_string()]
107        } else {
108            self.catalog
109                .table_names()
110                .into_iter()
111                .filter(|n| !is_internal_table_name(n))
112                .collect()
113        };
114        let mut analysed = 0usize;
115        let now_us = self.clock.map(|f| f());
116        for table_name in &names {
117            self.analyze_one_table(table_name)?;
118            // v7.39 (pg_stat knife C) — stamp last_analyze.
119            if let Some(us) = now_us
120                && let Some(t) = self.catalog.get_mut(table_name)
121            {
122                t.stamp_analyze(us);
123            }
124            analysed += 1;
125        }
126        // v6.3.1 — plan cache invalidation. Bump stats version so
127        // future lookups see the new generation, and selectively
128        // evict every plan whose `source_tables` overlap with the
129        // ANALYZE target set. Bare ANALYZE (all tables) clears the
130        // whole cache.
131        if analysed > 0 {
132            self.statistics.bump_version();
133            if target.is_some() {
134                for t in &names {
135                    self.plan_cache.evict_referencing(t);
136                }
137            } else {
138                self.plan_cache.clear();
139            }
140        }
141        Ok(QueryResult::CommandOk {
142            affected: analysed,
143            modified_catalog: true,
144        })
145    }
146
147    /// Walk a single table's rows once and (re-)populate per-column
148    /// stats. Drops the existing stats for `table` first so columns
149    /// that have been DROP-ed between ANALYZEs don't leave stale
150    /// rows.
151    fn analyze_one_table(&mut self, table_name: &str) -> Result<(), EngineError> {
152        let table = self.catalog.get(table_name).ok_or_else(|| {
153            EngineError::Storage(StorageError::TableNotFound {
154                name: table_name.to_string(),
155            })
156        })?;
157        let schema = table.schema().clone();
158        let row_count = table.rows().len();
159        // For each column, collect (sorted) non-NULL textual values
160        // + count NULLs; then ask `statistics::build_histogram` to
161        // produce the 101 bounds and `estimate_n_distinct` the
162        // distinct count.
163        self.statistics.clear_table(table_name);
164        for (col_pos, col_schema) in schema.columns.iter().enumerate() {
165            // v6.2.0 skip: vector columns have their own stats
166            // shape (HNSW graph topology). v6.2 deliberation #1.
167            if matches!(col_schema.ty, DataType::Vector { .. }) {
168                continue;
169            }
170            let mut non_null_values: Vec<Value<'static>> = Vec::with_capacity(row_count);
171            let mut nulls: u64 = 0;
172            for row in table.rows() {
173                match row.values.get(col_pos) {
174                    Some(Value::Null) | None => nulls += 1,
175                    Some(v) => non_null_values.push(v.clone()),
176                }
177            }
178            // Sort by type-aware ordering (Int as int, Text as
179            // lex, etc.) so histogram bounds reflect the column's
180            // natural order — not lexicographic on the string
181            // representation, which would put "9" after "49".
182            non_null_values.sort_by(|a, b| sort_values_for_histogram(a, b));
183            let non_null: Vec<String> = non_null_values.iter().map(canonical_value_repr).collect();
184            let null_frac = if row_count == 0 {
185                0.0
186            } else {
187                #[allow(clippy::cast_precision_loss)]
188                let f = nulls as f32 / row_count as f32;
189                f
190            };
191            let n_distinct = statistics::estimate_n_distinct(&non_null);
192            let histogram_bounds = statistics::build_histogram(&non_null);
193            self.statistics.set(
194                table_name.to_string(),
195                col_schema.name.clone(),
196                statistics::ColumnStats {
197                    null_frac,
198                    n_distinct,
199                    histogram_bounds,
200                },
201            );
202        }
203        self.statistics.reset_modified(table_name);
204        // v6.7.0 — refresh the per-table cold_rows cache. Walk the
205        // BTree indices and count Cold locators (MAX across
206        // indices); store the result on the table. Surfaced via
207        // `spg_statistic.cold_row_count` (new column) and
208        // `spg_stat_segment.table_name` (new column).
209        let cold_count = {
210            let table = self
211                .active_catalog()
212                .get(table_name)
213                .expect("table still present");
214            table.count_cold_locators()
215        };
216        let table_mut = self
217            .active_catalog_mut()
218            .get_mut(table_name)
219            .expect("table still present");
220        table_mut.set_cold_row_count(cold_count);
221        Ok(())
222    }
223
224    /// v6.7.3 — `COMPACT COLD SEGMENTS` runtime path. Drives the
225    /// engine-layer compaction shim with the default
226    /// 4 MiB segment-size threshold. spg-server intercepts the
227    /// SQL before it reaches the engine on a server build —
228    /// it reads `SPG_COMPACTION_TARGET_SEGMENT_BYTES`, calls
229    /// `Engine::compact_cold_segments_with_target` directly with
230    /// the env value, and persists every merged segment to
231    /// `<db>.spg/segments/`. This arm only fires for engine-only
232    /// callers (spg-embedded, lib tests); in that mode merged
233    /// segments live in memory and are dropped at process exit.
234    /// v7.37.17 (17.6 sibling) — `TRUNCATE [TABLE] <t>[, ...]
235    /// [RESTART IDENTITY]`. Clears every row from each named
236    /// table by dispatching to `Table::truncate()` (already exists
237    /// for internal callers). RESTART IDENTITY additionally resets
238    /// the table's associated sequence back to its start value.
239    pub(crate) fn exec_truncate(
240        &mut self,
241        tables: &[String],
242        _restart_identity: bool,
243        only: bool,
244    ) -> Result<QueryResult, EngineError> {
245        // RESTART IDENTITY is parsed but not honored yet — the
246        // SequenceDef doesn't expose a restart primitive on the
247        // storage side today. Accepted-and-no-op for pg_dump compat;
248        // real sequence reset lands with the sequence-lifecycle epic.
249        //
250        // v7.39 (round 647) — `ONLY` and the descent it turns off.
251        // Measured on PG18: a plain TRUNCATE of a parent empties its
252        // children too; `TRUNCATE ONLY <inheritance parent>` empties the
253        // parent alone; and `TRUNCATE ONLY <partitioned parent>` is not
254        // a no-op but an error, because a partitioned parent holds
255        // nothing and the spelling can only mean a mistake.
256        //
257        // The whole expansion sits inside this branch rather than beside
258        // it — rounds 641/643/644/646 each measured what an extra test
259        // in a function's body costs when the row loop is downstream.
260        let mut targets: Vec<String> = tables.to_vec();
261        if !tables.is_empty() {
262            for name in tables {
263                if only {
264                    if crate::partition::is_partition_parent(self.active_catalog(), name) {
265                        return Err(EngineError::Unsupported(alloc::format!(
266                            "cannot truncate only a partitioned table"
267                        )));
268                    }
269                    continue;
270                }
271                let mut frontier = alloc::vec![name.clone()];
272                while let Some(cur) = frontier.pop() {
273                    for kid in crate::partition::children_of_parent(self.active_catalog(), &cur) {
274                        frontier.push(kid.clone());
275                        targets.push(kid);
276                    }
277                }
278            }
279        }
280        let mut affected: usize = 0;
281        for name in &targets {
282            let cat = self.active_catalog_mut();
283            let Some(t) = cat.get_mut(name) else {
284                // v7.39 (read01 round 50) — PG says "relation" for TRUNCATE
285                // (only DROP TABLE says "table"). 42P01 at the wire.
286                return Err(EngineError::Storage(StorageError::Corrupt(alloc::format!(
287                    "relation {name:?} does not exist"
288                ))));
289            };
290            affected = affected.saturating_add(t.row_count());
291            t.truncate();
292        }
293        Ok(QueryResult::CommandOk {
294            affected,
295            modified_catalog: false,
296        })
297    }
298
299    pub(crate) fn exec_compact_cold_segments(&mut self) -> Result<QueryResult, EngineError> {
300        let target = COMPACTION_TARGET_DEFAULT_BYTES;
301        let reports = self.compact_cold_segments_with_target(target)?;
302        let columns = alloc::vec![
303            ColumnSchema::new("table_name", DataType::Text, false),
304            ColumnSchema::new("index_name", DataType::Text, false),
305            ColumnSchema::new("sources_merged", DataType::BigInt, false),
306            ColumnSchema::new("merged_segment_id", DataType::BigInt, false),
307            ColumnSchema::new("merged_rows", DataType::BigInt, false),
308            ColumnSchema::new("deleted_rows_pruned", DataType::BigInt, false),
309            ColumnSchema::new("bytes_reclaimed_estimate", DataType::BigInt, false),
310        ];
311        let rows: Vec<Row<'static>> = reports
312            .into_iter()
313            .map(|(tname, iname, report)| {
314                Row::new(alloc::vec![
315                    Value::text(tname),
316                    Value::text(iname),
317                    Value::BigInt(i64::try_from(report.sources.len()).unwrap_or(i64::MAX)),
318                    Value::BigInt(i64::from(report.merged_segment_id.unwrap_or(0))),
319                    Value::BigInt(i64::try_from(report.merged_rows).unwrap_or(i64::MAX)),
320                    Value::BigInt(i64::try_from(report.deleted_rows_pruned).unwrap_or(i64::MAX),),
321                    Value::BigInt(
322                        i64::try_from(report.bytes_reclaimed_estimate).unwrap_or(i64::MAX),
323                    ),
324                ])
325            })
326            .collect();
327        Ok(QueryResult::Rows { columns, rows })
328    }
329
330    /// v6.7.3 — public shim around `Catalog::compact_cold_segments`
331    /// driving every BTree index on every user table. Returns one
332    /// `(table, index, report)` triple for each merge that
333    /// actually happened (no-op (table, index) pairs are filtered
334    /// out so callers can size persist-side work to the live
335    /// merges). Caller is responsible for persisting each
336    /// `report.merged_segment_bytes` and updating the on-disk
337    /// segment registry; engine layer is no_std and never
338    /// touches disk.
339    ///
340    /// Marks every touched table's cached `cold_row_count` stale
341    /// — compaction GC'd some shadowed rows, so the count must be
342    /// re-derived on the next ANALYZE.
343    pub fn compact_cold_segments_with_target(
344        &mut self,
345        target_segment_bytes: u64,
346    ) -> Result<Vec<(String, String, CompactReport)>, EngineError> {
347        let table_names = self.active_catalog().table_names();
348        let mut reports: Vec<(String, String, CompactReport)> = Vec::new();
349        for tname in table_names {
350            if is_internal_table_name(&tname) {
351                continue;
352            }
353            let idx_names: Vec<String> = {
354                let Some(t) = self.active_catalog().get(&tname) else {
355                    continue;
356                };
357                t.indices()
358                    .iter()
359                    .filter(|i| matches!(i.kind, IndexKind::BTree(_)))
360                    .map(|i| i.name.clone())
361                    .collect()
362            };
363            for iname in idx_names {
364                let report = self
365                    .active_catalog_mut()
366                    .compact_cold_segments(&tname, &iname, target_segment_bytes)
367                    .map_err(EngineError::Storage)?;
368                if report.merged_segment_id.is_some() {
369                    if let Some(t) = self.active_catalog_mut().get_mut(&tname) {
370                        t.mark_cold_row_count_stale();
371                    }
372                    reports.push((tname.clone(), iname, report));
373                }
374            }
375        }
376        Ok(reports)
377    }
378}