From 4b05c5a764555b32eac0d8e37684057228a1978e Mon Sep 17 00:00:00 2001 From: Dario Mazzitelli Date: Tue, 28 Apr 2026 17:48:10 -0300 Subject: [PATCH 1/9] refactor: extract shared schema_evolution module from PG sink Move `SchemaDiff`, `AddedColumn`, `TypeChange`, `diff_against_cache` and `compute_schema_evolution_plan` from `postgres/schema_tracking.rs` and `postgres/raw_table.rs` into a sink-agnostic `src/connectors/sinks/schema_evolution.rs`. The PG sink now consumes the shared module; OID-specific concerns (`_dbmazz._schema_tracking`, `alter_add_column_sql`) stay PG-specific. This refactor unblocks StarRocks and Snowflake sinks consuming the same diff logic in upcoming changes. PG sink behavior is preserved bit-for-bit; all 18 unit tests pass. `AddedColumn::pg_type_id` is now `Option` to accommodate non-PG sources that may emit `CdcRecord::SchemaChange` in the future. PG sink call sites use `.expect()` to assert the PG-source contract. --- src/connectors/sinks/mod.rs | 4 +- src/connectors/sinks/postgres/raw_table.rs | 243 +------- .../sinks/postgres/schema_tracking.rs | 427 ++------------ src/connectors/sinks/schema_evolution.rs | 529 ++++++++++++++++++ 4 files changed, 591 insertions(+), 612 deletions(-) create mode 100644 src/connectors/sinks/schema_evolution.rs diff --git a/src/connectors/sinks/mod.rs b/src/connectors/sinks/mod.rs index 72acf0b..c40814c 100644 --- a/src/connectors/sinks/mod.rs +++ b/src/connectors/sinks/mod.rs @@ -24,6 +24,8 @@ //! sink.write_batch(records).await?; //! ``` +pub(crate) mod schema_evolution; + #[cfg(feature = "sink-postgres")] pub mod postgres; #[cfg(feature = "sink-snowflake")] @@ -124,8 +126,6 @@ mod tests { #[cfg(feature = "sink-snowflake")] #[test] fn test_create_snowflake_sink() { - use serial_test::serial; - std::env::set_var("SINK_SNOWFLAKE_ACCOUNT", "test_account"); std::env::set_var("SINK_SNOWFLAKE_WAREHOUSE", "COMPUTE_WH"); diff --git a/src/connectors/sinks/postgres/raw_table.rs b/src/connectors/sinks/postgres/raw_table.rs index 1b49a88..28a5340 100644 --- a/src/connectors/sinks/postgres/raw_table.rs +++ b/src/connectors/sinks/postgres/raw_table.rs @@ -12,13 +12,13 @@ use bytes::{BufMut, BytesMut}; use futures_util::SinkExt; use tokio::sync::watch; use tokio_postgres::Client; -use tracing::{error, info, warn}; +use tracing::info; use super::schema_tracking::{self, SchemaState}; use super::types::pg_oid_to_target_type; -use crate::core::record::{CdcRecord, ColumnValue, TableRef, Value}; -use crate::core::traits::{SourceColumn, SourceTableSchema}; -use crate::source::converter::pg_type_to_data_type; +use crate::connectors::sinks::schema_evolution::compute_schema_evolution_plan; +use crate::core::record::{CdcRecord, ColumnValue, Value}; +use crate::core::traits::SourceTableSchema; /// Metadata schema name const METADATA_SCHEMA: &str = "_dbmazz"; @@ -62,12 +62,15 @@ pub async fn write_batch_to_raw( // is complete (Risk #6). A COPY failure rolls back the DDL too. for (table, diff) in &pending_diffs { for added in &diff.added { + let pg_type_id = added + .pg_type_id + .expect("PG sink: AddedColumn must carry pg_type_id (PG source contract)"); let sql = format!( r#"ALTER TABLE "{}"."{}" ADD COLUMN IF NOT EXISTS "{}" {}"#, target_schema, table.name, added.name, - pg_oid_to_target_type(added.pg_type_id) + pg_oid_to_target_type(pg_type_id) ); tx.batch_execute(&sql).await.with_context(|| { format!( @@ -228,95 +231,9 @@ pub async fn write_batch_to_raw( Ok((rows_written, bytes_written)) } -/// Pure pre-pass: clone the current schema snapshot and walk the batch's -/// `SchemaChange` records to compute the per-table schema diffs that need -/// DDL applied during the transaction. -/// -/// Returns `(working, pending_diffs)` where: -/// - `working` is the post-batch schema state — the snapshot with every -/// added column folded in. This is the value that Phase 3 broadcasts on -/// the watch channel after a successful commit. -/// - `pending_diffs` is the list of `(TableRef, SchemaDiff)` pairs that -/// actually have new columns and require ALTER TABLE during Phase 2a. -/// Type-change-only and drop-only diffs are logged here and excluded -/// from this list (they need no DDL). -/// -/// Pure function — no DB, no I/O, no locking. Safe to unit-test. -fn compute_schema_evolution_plan( - snapshot: &HashMap, - records: &[CdcRecord], -) -> ( - HashMap, - Vec<(TableRef, schema_tracking::SchemaDiff)>, -) { - // Clone the snapshot into a mutable working map. - // Each SchemaChange in the batch is diffed against `working` (not the - // original snapshot), and `working` is mutated in-place after each diff so - // that a second SchemaChange for the same table in the same batch sees the - // already-added columns and does not re-emit them. - // - // After this loop, `working` reflects the schema state that will exist AFTER - // the entire batch is committed. It is broadcast in Phase 3. - let mut working: HashMap = snapshot.clone(); - - // Only diffs with non-empty `added` need DDL work. Type-change-only and - // drop-only diffs are logged here and are no-ops for the transaction. - let mut pending_diffs: Vec<(TableRef, schema_tracking::SchemaDiff)> = Vec::new(); - - for record in records { - if let CdcRecord::SchemaChange { table, columns, .. } = record { - let diff = schema_tracking::diff_against_cache(&working, table, columns); - - // Log type changes (no DDL — operator intervention required). - for tc in &diff.type_changed { - error!( - table = %table.qualified_name(), - column = %tc.name, - old_oid = tc.old_pg_type_id, - new_oid = tc.new_pg_type_id, - "pg_sink: type change not supported, MERGE keeps old cast" - ); - } - - // Log drops (no DDL — target keeps dead column). - for dropped in &diff.dropped { - warn!( - table = %table.qualified_name(), - column = %dropped, - "pg_sink: column drop ignored, target keeps dead column" - ); - } - - if !diff.added.is_empty() { - let src_schema = table.schema.clone().unwrap_or_else(|| "public".to_string()); - let qn = table.qualified_name(); - - // Ensure the table exists in `working` before pushing columns. - let entry = working.entry(qn).or_insert_with(|| SourceTableSchema { - schema: src_schema, - name: table.name.clone(), - columns: Vec::new(), - primary_keys: Vec::new(), - }); - - // Advance working map so subsequent SchemaChange events for the - // same table see these columns and don't re-emit them (Risk #7). - for added in &diff.added { - entry.columns.push(SourceColumn { - name: added.name.clone(), - data_type: pg_type_to_data_type(added.pg_type_id), - nullable: added.nullable, - pg_type_id: added.pg_type_id, - }); - } - - pending_diffs.push((table.clone(), diff)); - } - } - } - - (working, pending_diffs) -} +// `compute_schema_evolution_plan` lives in +// `crate::connectors::sinks::schema_evolution` and is imported at the top +// of this file. The PG sink consumes the shared, sink-agnostic version. /// Fields for a single raw table row. struct RawRow<'a> { @@ -437,8 +354,7 @@ fn value_to_json(value: &Value) -> serde_json::Value { #[cfg(test)] mod tests { use super::*; - use crate::core::position::SourcePosition; - use crate::core::record::{ColumnDef, ColumnValue, DataType}; + use crate::core::record::ColumnValue; #[test] fn test_columns_to_json() { @@ -545,135 +461,8 @@ mod tests { assert!(result["nested"].is_array()); } - // ------------------------------------------------------------------ - // compute_schema_evolution_plan tests - // ------------------------------------------------------------------ - - #[test] - fn test_compute_schema_evolution_plan_no_schema_change() { - // Snapshot contains one table. - let mut snapshot: HashMap = HashMap::new(); - snapshot.insert( - "public.orders".to_string(), - SourceTableSchema { - schema: "public".to_string(), - name: "orders".to_string(), - columns: vec![SourceColumn { - name: "id".to_string(), - data_type: DataType::Int32, - nullable: false, - pg_type_id: 23, - }], - primary_keys: vec!["id".to_string()], - }, - ); - - // Batch contains only an Insert — no SchemaChange. - let records = vec![CdcRecord::Insert { - table: TableRef::new(Some("public".into()), "orders".into()), - columns: vec![], - position: SourcePosition::Lsn(0), - }]; - - let (working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); - - assert!( - pending_diffs.is_empty(), - "Insert-only batch must produce no pending diffs" - ); - // working must be identical to the input snapshot. - assert_eq!( - working - .get("public.orders") - .expect("table must exist in working") - .columns - .len(), - 1, - "working schema must equal the input snapshot when no SchemaChange is present" - ); - } - - #[test] - fn test_compute_schema_evolution_plan_cold_start_added_column() { - // Cold start: empty snapshot — table has never been seen. - let snapshot: HashMap = HashMap::new(); - - let records = vec![CdcRecord::SchemaChange { - table: TableRef::new(Some("public".into()), "orders".into()), - columns: vec![ - ColumnDef::with_pg_oid("id".into(), DataType::Int32, false, 23), - ColumnDef::with_pg_oid("description".into(), DataType::String, true, 25), - ], - position: SourcePosition::Lsn(100), - }]; - - let (working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); - - assert_eq!( - pending_diffs.len(), - 1, - "one SchemaChange for a new table must produce exactly one pending diff" - ); - assert_eq!( - pending_diffs[0].1.added.len(), - 2, - "both columns are new (cold-start) — both must appear in added" - ); - assert_eq!( - working - .get("public.orders") - .expect("public.orders must be in working after cold-start SchemaChange") - .columns - .len(), - 2, - "working must contain both columns after cold-start SchemaChange" - ); - } - - #[test] - fn test_compute_schema_evolution_plan_intra_batch_dedup() { - // Snapshot has public.orders with one column — id. - let mut snapshot: HashMap = HashMap::new(); - snapshot.insert( - "public.orders".to_string(), - SourceTableSchema { - schema: "public".to_string(), - name: "orders".to_string(), - columns: vec![SourceColumn { - name: "id".to_string(), - data_type: DataType::Int32, - nullable: false, - pg_type_id: 23, - }], - primary_keys: vec!["id".to_string()], - }, - ); - - // Two SchemaChange records for the same table in the same batch, - // both declaring the same `description` column. - // The second SchemaChange must see `description` already in the - // working map and produce an empty diff (Risk #7 invariant). - let schema_change = CdcRecord::SchemaChange { - table: TableRef::new(Some("public".into()), "orders".into()), - columns: vec![ - ColumnDef::with_pg_oid("id".into(), DataType::Int32, false, 23), - ColumnDef::with_pg_oid("description".into(), DataType::String, true, 25), - ], - position: SourcePosition::Lsn(200), - }; - let records = vec![schema_change.clone(), schema_change]; - - let (_working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); - - assert_eq!( - pending_diffs.len(), - 1, - "two identical SchemaChange events in the same batch must produce only one pending diff (Risk #7)" - ); - assert_eq!( - pending_diffs[0].1.added.len(), - 1, - "only `description` should be in the added set — `id` was already in the snapshot" - ); - } + // compute_schema_evolution_plan tests live in + // `crate::connectors::sinks::schema_evolution` (the shared module), + // since the function is sink-agnostic. The PG sink tests here cover + // only PG-sink-specific helpers. } diff --git a/src/connectors/sinks/postgres/schema_tracking.rs b/src/connectors/sinks/postgres/schema_tracking.rs index bc75854..0fb9fd5 100644 --- a/src/connectors/sinks/postgres/schema_tracking.rs +++ b/src/connectors/sinks/postgres/schema_tracking.rs @@ -25,10 +25,18 @@ use tokio_postgres::{Client, Transaction}; use tracing::{error, info, warn}; use crate::connectors::sinks::postgres::types::pg_oid_to_target_type; -use crate::core::record::{ColumnDef, TableRef}; +use crate::connectors::sinks::schema_evolution::AddedColumn; +use crate::core::record::TableRef; use crate::core::traits::{SourceColumn, SourceTableSchema}; use crate::source::converter::pg_type_to_data_type; +// Re-export the shared diff function so any future external caller of +// `schema_tracking::diff_against_cache` keeps compiling. Internal PG-sink +// callers (raw_table.rs) consume the function directly from the shared +// module via `crate::connectors::sinks::schema_evolution`. +#[allow(unused_imports)] +pub use crate::connectors::sinks::schema_evolution::diff_against_cache; + /// In-memory schema cache: qualified table name → `SourceTableSchema`. /// /// Key format: `"."` — matches the normalizer's @@ -39,51 +47,11 @@ pub type SchemaState = Arc>; pub const TRACKING_TABLE: &str = "_dbmazz._schema_tracking"; // --------------------------------------------------------------------------- -// Public types +// Public types — moved to `crate::connectors::sinks::schema_evolution`. +// `SchemaDiff`, `AddedColumn`, `TypeChange`, and `diff_against_cache` are +// imported above and re-exported for backward-compatible call sites. // --------------------------------------------------------------------------- -/// Result of diffing a `SchemaChange` event against the current target cache. -/// Computed per table, per batch. Empty diffs are no-ops. -#[derive(Debug, Default)] -pub struct SchemaDiff { - /// Columns present in the new schema that are missing from the cache. - /// Only entries with `pg_type_id.is_some()` are included. - pub added: Vec, - /// Columns whose `pg_type_id` in the cache disagrees with the new schema. - /// Handled by `error!` log; no DDL. - pub type_changed: Vec, - /// Columns present in the cache but absent from the new schema (source - /// dropped the column while the daemon was running). - /// Handled by `warn!` log; no DDL. Target keeps the column as dead data. - pub dropped: Vec, -} - -/// A new column that needs to be materialized on the target. -#[derive(Debug, Clone)] -pub struct AddedColumn { - pub name: String, - pub pg_type_id: u32, - pub nullable: bool, - /// Zero-based ordinal relative to the current tracking state. - pub ordinal: i32, -} - -/// A column whose type OID changed between cache and the incoming schema. -#[derive(Debug, Clone)] -pub struct TypeChange { - pub name: String, - pub old_pg_type_id: u32, - pub new_pg_type_id: u32, -} - -impl SchemaDiff { - /// Returns `true` when there is nothing to do (no DDL, no logs). - #[allow(dead_code)] - pub fn is_noop(&self) -> bool { - self.added.is_empty() && self.type_changed.is_empty() && self.dropped.is_empty() - } -} - // --------------------------------------------------------------------------- // DDL helpers // --------------------------------------------------------------------------- @@ -303,6 +271,13 @@ pub async fn insert_tracked_columns( let lsn_i64 = lsn as i64; for col in added { + // pg_type_id is `Option` on the shared `AddedColumn` (sink-agnostic). + // The PG source always populates it; `.expect()` makes the contract loud + // for any future non-PG source that wires SchemaChange events into + // this PG sink path (which would be a misconfiguration). + let pg_type_id = col + .pg_type_id + .expect("PG sink: AddedColumn must carry pg_type_id (PG source contract)"); tx.execute( &format!( "INSERT INTO {} (job_name, src_schema, src_table, column_name, pg_type_id, ordinal, nullable, added_at_lsn) @@ -316,7 +291,7 @@ pub async fn insert_tracked_columns( &src_schema, &table.name, &col.name, - &col.pg_type_id, + &pg_type_id, &col.ordinal, &col.nullable, &lsn_i64, @@ -335,142 +310,11 @@ pub async fn insert_tracked_columns( } // --------------------------------------------------------------------------- -// Diff logic (pure) +// Diff logic — moved to `crate::connectors::sinks::schema_evolution`. +// `diff_against_cache` is re-exported at the top of this module for +// backward compatibility with existing call sites. // --------------------------------------------------------------------------- -/// Compute a `SchemaDiff` between the cached `SourceTableSchema` for `table` -/// and the `new_cols` coming from a `CdcRecord::SchemaChange`. Pure -/// function — no DB, no locking. Safe to call without a tx. -/// -/// If the table is not in the cache at all, every `new_col` that has -/// `pg_type_id.is_some()` becomes an `Added` entry (cold-start case — -/// should normally not occur after setup). -/// -/// Columns with `pg_type_id == None` are silently skipped from `added` -/// (an `error!` is emitted; the branch is unreachable for the PG source -/// in practice, but must not panic). -/// -/// MUST diff by column NAME, not position (Risk #5 — pgoutput Relation -/// messages carry all columns, and source column order can change -/// independently of the column set). -/// -/// **Ordinal contract**: `added[i].ordinal` is computed as -/// `cached_schema.columns.len() + (i-th additive column)` — i.e. it is -/// **absolute against the cache passed in**, not absolute against the -/// tracking table. Callers that diff multiple `SchemaChange` events for -/// the same table within a single batch (Section 4 of the implementation -/// plan) MUST fold each diff back into the working cache BEFORE calling -/// `diff_against_cache` for the next event, so successive ordinals stay -/// monotonic. The Phase 1 pre-pass in `raw_table::write_batch_to_raw` -/// does exactly this via the `working: HashMap` -/// local map. -pub fn diff_against_cache( - cache: &HashMap, - table: &TableRef, - new_cols: &[ColumnDef], -) -> SchemaDiff { - let src_schema = table.schema.as_deref().unwrap_or("public"); - let qn = format!("{}.{}", src_schema, table.name); - - let mut diff = SchemaDiff::default(); - - // Build a name→pg_type_id map for the incoming columns so we can - // cross-reference against the cache in O(n) rather than O(n²). - let mut new_by_name: HashMap<&str, &ColumnDef> = HashMap::with_capacity(new_cols.len()); - for col in new_cols { - new_by_name.insert(col.name.as_str(), col); - } - - match cache.get(&qn) { - None => { - // Cold-start: table not in cache at all — every new col is Added. - let mut ordinal: i32 = 0; - for col in new_cols { - match col.pg_type_id { - Some(pg_type_id) => { - diff.added.push(AddedColumn { - name: col.name.clone(), - pg_type_id, - nullable: col.nullable, - ordinal, - }); - ordinal += 1; - } - None => { - error!( - table = %qn, - column = %col.name, - "pg_sink: SchemaChange column has no pg_type_id, skipping (non-PG source?)" - ); - } - } - } - } - Some(cached_schema) => { - // Build name→pg_type_id for the cached columns. - let cached_by_name: HashMap<&str, &SourceColumn> = cached_schema - .columns - .iter() - .map(|c| (c.name.as_str(), c)) - .collect(); - - // Check each incoming column against the cache. - // Ordinal for Added entries starts after the last cached ordinal. - let mut next_ordinal: i32 = cached_schema.columns.len() as i32; - - for col in new_cols { - match cached_by_name.get(col.name.as_str()) { - None => { - // Column is new. - match col.pg_type_id { - Some(pg_type_id) => { - diff.added.push(AddedColumn { - name: col.name.clone(), - pg_type_id, - nullable: col.nullable, - ordinal: next_ordinal, - }); - next_ordinal += 1; - } - None => { - error!( - table = %qn, - column = %col.name, - "pg_sink: SchemaChange column has no pg_type_id, skipping (non-PG source?)" - ); - } - } - } - Some(cached_col) => { - // Column exists — check for type change. - if let Some(new_oid) = col.pg_type_id { - if cached_col.pg_type_id != new_oid { - diff.type_changed.push(TypeChange { - name: col.name.clone(), - old_pg_type_id: cached_col.pg_type_id, - new_pg_type_id: new_oid, - }); - } - } - // If pg_type_id is None on the incoming side we cannot - // determine the new OID, so we skip the type-change - // check silently (non-PG source path, unreachable here). - } - } - } - - // Check for dropped columns (present in cache, absent from new). - for cached_col in &cached_schema.columns { - if !new_by_name.contains_key(cached_col.name.as_str()) { - diff.dropped.push(cached_col.name.clone()); - } - } - } - } - - diff -} - // --------------------------------------------------------------------------- // Startup reconciliation // --------------------------------------------------------------------------- @@ -526,9 +370,10 @@ pub async fn reconcile_on_startup( // Column in source but not in tracking → ADD COLUMN. let added = AddedColumn { name: source_col.name.clone(), - pg_type_id: source_col.pg_type_id, + data_type: source_col.data_type.clone(), nullable: true, // always nullable on reconcile (Risk §5.7) ordinal: next_ordinal, + pg_type_id: Some(source_col.pg_type_id), }; let sql = alter_add_column_sql(target_schema, &source.name, &added); @@ -616,11 +461,14 @@ pub async fn reconcile_on_startup( primary_keys: source.primary_keys.clone(), }); for added in newly_added { + let pg_type_id = added + .pg_type_id + .expect("PG sink: AddedColumn must carry pg_type_id (PG source contract)"); entry.columns.push(SourceColumn { name: added.name, - data_type: pg_type_to_data_type(added.pg_type_id), + data_type: pg_type_to_data_type(pg_type_id), nullable: added.nullable, - pg_type_id: added.pg_type_id, + pg_type_id, }); } } @@ -642,7 +490,10 @@ pub async fn reconcile_on_startup( /// "" `. Always nullable with no default — matches backfill /// semantics (NULL for pre-existing rows). All identifiers are double-quoted. fn alter_add_column_sql(target_schema: &str, table_name: &str, column: &AddedColumn) -> String { - let col_type = pg_oid_to_target_type(column.pg_type_id); + let pg_type_id = column + .pg_type_id + .expect("PG sink: AddedColumn must carry pg_type_id (PG source contract)"); + let col_type = pg_oid_to_target_type(pg_type_id); format!( r#"ALTER TABLE "{}"."{}" ADD COLUMN IF NOT EXISTS "{}" {}"#, target_schema, table_name, column.name, col_type @@ -658,204 +509,9 @@ mod tests { use super::*; use crate::core::record::DataType; - // ------------------------------------------------------------------ - // Helpers — build fixtures inline per test - // ------------------------------------------------------------------ - - fn make_source_col(name: &str, pg_type_id: u32) -> SourceColumn { - SourceColumn { - name: name.to_owned(), - data_type: pg_type_to_data_type(pg_type_id), - nullable: true, - pg_type_id, - } - } - - fn make_col_def(name: &str, pg_type_id: Option) -> ColumnDef { - ColumnDef { - name: name.to_owned(), - data_type: DataType::String, - nullable: true, - pg_type_id, - } - } - - fn make_schema(schema: &str, name: &str, cols: Vec) -> SourceTableSchema { - SourceTableSchema { - schema: schema.to_owned(), - name: name.to_owned(), - columns: cols, - primary_keys: vec!["id".to_owned()], - } - } - - fn table_ref(schema: &str, name: &str) -> TableRef { - TableRef { - schema: Some(schema.to_owned()), - name: name.to_owned(), - } - } - - fn cache_with( - schema: &str, - name: &str, - cols: Vec, - ) -> HashMap { - let mut m = HashMap::new(); - m.insert( - format!("{}.{}", schema, name), - make_schema(schema, name, cols), - ); - m - } - - // ------------------------------------------------------------------ - // diff_against_cache tests - // ------------------------------------------------------------------ - - #[test] - fn test_diff_against_cache_no_change() { - let cache = cache_with( - "public", - "orders", - vec![make_source_col("id", 23), make_source_col("amount", 1700)], - ); - let new_cols = vec![ - make_col_def("id", Some(23)), - make_col_def("amount", Some(1700)), - ]; - let diff = diff_against_cache(&cache, &table_ref("public", "orders"), &new_cols); - assert!(diff.is_noop(), "expected no-op diff for identical schemas"); - } - - #[test] - fn test_diff_against_cache_only_added() { - let cache = cache_with("public", "orders", vec![make_source_col("id", 23)]); - let new_cols = vec![ - make_col_def("id", Some(23)), - make_col_def("description", Some(25)), // new text column - ]; - let diff = diff_against_cache(&cache, &table_ref("public", "orders"), &new_cols); - assert_eq!(diff.added.len(), 1); - assert_eq!(diff.added[0].name, "description"); - assert_eq!(diff.added[0].pg_type_id, 25); - assert!(diff.type_changed.is_empty()); - assert!(diff.dropped.is_empty()); - } - - #[test] - fn test_diff_against_cache_only_type_changed() { - let cache = cache_with( - "public", - "orders", - vec![make_source_col("amount", 23)], // int4 - ); - let new_cols = vec![make_col_def("amount", Some(20))]; // int8 - let diff = diff_against_cache(&cache, &table_ref("public", "orders"), &new_cols); - assert!(diff.added.is_empty()); - assert_eq!(diff.type_changed.len(), 1); - assert_eq!(diff.type_changed[0].name, "amount"); - assert_eq!(diff.type_changed[0].old_pg_type_id, 23); - assert_eq!(diff.type_changed[0].new_pg_type_id, 20); - assert!(diff.dropped.is_empty()); - } - - #[test] - fn test_diff_against_cache_only_dropped() { - let cache = cache_with( - "public", - "orders", - vec![make_source_col("id", 23), make_source_col("legacy", 25)], - ); - let new_cols = vec![make_col_def("id", Some(23))]; // "legacy" missing - let diff = diff_against_cache(&cache, &table_ref("public", "orders"), &new_cols); - assert!(diff.added.is_empty()); - assert!(diff.type_changed.is_empty()); - assert_eq!(diff.dropped.len(), 1); - assert_eq!(diff.dropped[0], "legacy"); - } - - #[test] - fn test_diff_against_cache_mixed() { - // id: unchanged, status: type change int4→int8, description: new, legacy: dropped - let cache = cache_with( - "public", - "orders", - vec![ - make_source_col("id", 23), - make_source_col("status", 23), - make_source_col("legacy", 25), - ], - ); - let new_cols = vec![ - make_col_def("id", Some(23)), - make_col_def("status", Some(20)), // type change - make_col_def("description", Some(25)), // new - // "legacy" absent → dropped - ]; - let diff = diff_against_cache(&cache, &table_ref("public", "orders"), &new_cols); - assert_eq!(diff.added.len(), 1, "should have one added column"); - assert_eq!(diff.added[0].name, "description"); - assert_eq!(diff.type_changed.len(), 1, "should have one type change"); - assert_eq!(diff.type_changed[0].name, "status"); - assert_eq!(diff.dropped.len(), 1, "should have one dropped column"); - assert_eq!(diff.dropped[0], "legacy"); - } - - #[test] - fn test_diff_against_cache_cold_start() { - // Table not in cache at all — every incoming column with Some(pg_type_id) → Added. - let cache: HashMap = HashMap::new(); - let new_cols = vec![make_col_def("id", Some(23)), make_col_def("name", Some(25))]; - let diff = diff_against_cache(&cache, &table_ref("public", "customers"), &new_cols); - assert_eq!(diff.added.len(), 2); - assert!(diff.type_changed.is_empty()); - assert!(diff.dropped.is_empty()); - } - - #[test] - fn test_diff_against_cache_skips_missing_pg_oid() { - let cache = cache_with("public", "orders", vec![make_source_col("id", 23)]); - let new_cols = vec![ - make_col_def("id", Some(23)), - make_col_def("mystery", None), // no pg_type_id — must be skipped - ]; - let diff = diff_against_cache(&cache, &table_ref("public", "orders"), &new_cols); - // "mystery" must not appear in added (pg_type_id is None). - assert!( - diff.added.is_empty(), - "column with None pg_type_id must not be added" - ); - assert!( - diff.is_noop(), - "only a no-pg-oid column change — must be noop for DDL purposes" - ); - } - - #[test] - fn test_diff_against_cache_ignores_column_order() { - // Same columns, different order in the incoming SchemaChange — must be no-op. - let cache = cache_with( - "public", - "orders", - vec![ - make_source_col("id", 23), - make_source_col("amount", 1700), - make_source_col("name", 25), - ], - ); - // Incoming order reversed - let new_cols = vec![ - make_col_def("name", Some(25)), - make_col_def("amount", Some(1700)), - make_col_def("id", Some(23)), - ]; - let diff = diff_against_cache(&cache, &table_ref("public", "orders"), &new_cols); - assert!( - diff.is_noop(), - "reordered columns must produce a noop diff (Risk #5)" - ); - } + // Diff-logic tests live in `crate::connectors::sinks::schema_evolution` + // (the shared module). Tests here cover the PG-sink-specific helpers + // (`alter_add_column_sql`). // ------------------------------------------------------------------ // alter_add_column_sql tests @@ -865,9 +521,10 @@ mod tests { fn test_alter_add_column_sql_basic() { let col = AddedColumn { name: "description".to_owned(), - pg_type_id: 25, // text + data_type: DataType::String, nullable: true, ordinal: 3, + pg_type_id: Some(25), // text }; let sql = alter_add_column_sql("public", "orders", &col); assert_eq!( @@ -881,9 +538,13 @@ mod tests { // Table name that is a reserved word must be quoted correctly. let col = AddedColumn { name: "amount".to_owned(), - pg_type_id: 1700, // numeric + data_type: DataType::Decimal { + precision: 38, + scale: 9, + }, nullable: true, ordinal: 1, + pg_type_id: Some(1700), // numeric }; let sql = alter_add_column_sql("public", "order", &col); assert!( diff --git a/src/connectors/sinks/schema_evolution.rs b/src/connectors/sinks/schema_evolution.rs new file mode 100644 index 0000000..6de8190 --- /dev/null +++ b/src/connectors/sinks/schema_evolution.rs @@ -0,0 +1,529 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Shared schema-evolution diff logic across sinks. +//! +//! Hosts the pure (no DB, no I/O, no locking) computation that turns a +//! batch of `CdcRecord` events into a list of `(TableRef, SchemaDiff)` +//! pairs. Each sink consumes the result and applies dialect-specific DDL +//! to its target via its own per-sink module. +//! +//! This file is sink-agnostic. PG-specific concerns (OID preservation, +//! `_dbmazz._schema_tracking` table) live in `postgres::schema_tracking`. +//! +//! # Conservative policy +//! +//! All sinks share the same policy (codified in the spec at +//! `openspec/changes/schema-evolution-starrocks-snowflake/specs/`): +//! +//! - **ADD COLUMN** → auto-applied via `ALTER TABLE ADD COLUMN IF NOT EXISTS` +//! - **DROP COLUMN** → logged as `warn!`, target keeps the dead column +//! - **MODIFY COLUMN type** → logged as `error!`, target keeps the old cast +//! - **RENAME COLUMN** → seen as drop+add, both above apply + +use std::collections::HashMap; + +use tracing::{error, warn}; + +use crate::core::record::{CdcRecord, ColumnDef, DataType, TableRef}; +use crate::core::traits::{SourceColumn, SourceTableSchema}; + +// --------------------------------------------------------------------------- +// Public types +// --------------------------------------------------------------------------- + +/// A new column that needs to be materialized on the target. +/// +/// `pg_type_id` is `Some(_)` when the source is Postgres (the only source +/// today). Sinks that don't need OID-level fidelity can ignore it and use +/// `data_type` instead. +#[derive(Debug, Clone)] +pub struct AddedColumn { + pub name: String, + pub data_type: DataType, + pub nullable: bool, + /// Zero-based ordinal relative to the in-memory snapshot passed to + /// `compute_schema_evolution_plan`. Useful for sinks that maintain a + /// per-job tracking table (Postgres). Other sinks can ignore. + pub ordinal: i32, + /// Source PG OID. Only populated when source is Postgres. + pub pg_type_id: Option, +} + +/// A column whose type changed between cache and the incoming schema. +#[derive(Debug, Clone)] +#[allow(dead_code)] +pub struct TypeChange { + pub name: String, + pub old_data_type: DataType, + pub new_data_type: DataType, + /// Source-side OID before the change. Only populated when source is Postgres. + pub old_pg_type_id: Option, + /// Source-side OID after the change. Only populated when source is Postgres. + pub new_pg_type_id: Option, +} + +/// Result of diffing a `SchemaChange` event against the current target cache. +/// Empty diffs are no-ops. +#[derive(Debug, Default)] +pub struct SchemaDiff { + /// Columns present in the new schema that are missing from the cache. + pub added: Vec, + /// Columns whose type disagrees between cache and the new schema. + /// Handled by `error!` log; no DDL. + pub type_changed: Vec, + /// Columns present in the cache but absent from the new schema (source + /// dropped the column while the daemon was running). + /// Handled by `warn!` log; no DDL. Target keeps the column as dead data. + pub dropped: Vec, +} + +impl SchemaDiff { + /// Returns `true` when there is nothing to do (no DDL, no logs). + #[allow(dead_code)] + pub fn is_noop(&self) -> bool { + self.added.is_empty() && self.type_changed.is_empty() && self.dropped.is_empty() + } +} + +// --------------------------------------------------------------------------- +// Pure diff functions +// --------------------------------------------------------------------------- + +/// Compute a `SchemaDiff` between the cached `SourceTableSchema` for `table` +/// and the `new_cols` coming from a `CdcRecord::SchemaChange`. Pure +/// function — no DB, no locking. Safe to call without a tx. +/// +/// If the table is not in the cache at all, every `new_col` becomes an +/// `Added` entry (cold-start case — should normally not occur after setup). +/// +/// MUST diff by column NAME, not position — pgoutput Relation messages +/// carry all columns in source order, which can change independently of +/// the column set. +/// +/// # Type-change detection +/// +/// Compares both the generic `DataType` (always populated) AND the source +/// PG OID (when both sides have one and the cached side is non-zero). The +/// OID check catches NUMERIC precision/scale changes that map to the same +/// coarse `DataType::Decimal` bucket. +/// +/// # Ordinal contract +/// +/// `added[i].ordinal` is `cached_schema.columns.len() + (i-th additive column)` +/// — absolute against the cache passed in, not against any persistent +/// tracking table. Callers that diff multiple `SchemaChange` events for +/// the same table within a single batch MUST fold each diff back into the +/// working cache BEFORE calling this for the next event, so ordinals stay +/// monotonic. `compute_schema_evolution_plan` does this automatically. +pub fn diff_against_cache( + cache: &HashMap, + table: &TableRef, + new_cols: &[ColumnDef], +) -> SchemaDiff { + let src_schema = table.schema.as_deref().unwrap_or("public"); + let qn = format!("{}.{}", src_schema, table.name); + + let mut diff = SchemaDiff::default(); + + let mut new_by_name: HashMap<&str, &ColumnDef> = HashMap::with_capacity(new_cols.len()); + for col in new_cols { + new_by_name.insert(col.name.as_str(), col); + } + + match cache.get(&qn) { + None => { + // Cold-start: table not in cache at all — every new col is Added. + for (i, col) in new_cols.iter().enumerate() { + diff.added.push(AddedColumn { + name: col.name.clone(), + data_type: col.data_type.clone(), + nullable: col.nullable, + #[allow(clippy::cast_possible_wrap)] + ordinal: i as i32, + pg_type_id: col.pg_type_id, + }); + } + } + Some(cached_schema) => { + let cached_by_name: HashMap<&str, &SourceColumn> = cached_schema + .columns + .iter() + .map(|c| (c.name.as_str(), c)) + .collect(); + + #[allow(clippy::cast_possible_wrap)] + let mut next_ordinal: i32 = cached_schema.columns.len() as i32; + + for col in new_cols { + match cached_by_name.get(col.name.as_str()) { + None => { + // Column is new. + diff.added.push(AddedColumn { + name: col.name.clone(), + data_type: col.data_type.clone(), + nullable: col.nullable, + ordinal: next_ordinal, + pg_type_id: col.pg_type_id, + }); + next_ordinal += 1; + } + Some(cached_col) => { + // Column exists — check for type change. + // DataType comparison covers the generic case. + // OID comparison catches PG-specific precision changes + // when both sides have a real (non-zero) OID. + let dt_changed = cached_col.data_type != col.data_type; + let oid_changed = match (cached_col.pg_type_id, col.pg_type_id) { + (cached, Some(new)) if cached != 0 => cached != new, + _ => false, + }; + if dt_changed || oid_changed { + diff.type_changed.push(TypeChange { + name: col.name.clone(), + old_data_type: cached_col.data_type.clone(), + new_data_type: col.data_type.clone(), + old_pg_type_id: if cached_col.pg_type_id == 0 { + None + } else { + Some(cached_col.pg_type_id) + }, + new_pg_type_id: col.pg_type_id, + }); + } + } + } + } + + // Check for dropped columns (present in cache, absent from new). + for cached_col in &cached_schema.columns { + if !new_by_name.contains_key(cached_col.name.as_str()) { + diff.dropped.push(cached_col.name.clone()); + } + } + } + } + + diff +} + +/// Pure pre-pass: clone the current schema snapshot and walk the batch's +/// `SchemaChange` records to compute the per-table schema diffs that need +/// DDL applied during the batch. +/// +/// Returns `(working, pending_diffs)` where: +/// - `working` is the post-batch schema state — the snapshot with every +/// added column folded in. Sinks broadcast or persist this after a +/// successful commit (PG via `watch::send_replace`, others via in-memory +/// write-lock on `Arc>`). +/// - `pending_diffs` is the list of `(TableRef, SchemaDiff)` pairs that +/// actually have new columns and require ALTER TABLE during the batch. +/// Type-change-only and drop-only diffs are logged here and excluded +/// from this list (they need no DDL). +/// +/// Pure function — no DB, no I/O, no locking. Safe to unit-test. +pub fn compute_schema_evolution_plan( + snapshot: &HashMap, + records: &[CdcRecord], +) -> ( + HashMap, + Vec<(TableRef, SchemaDiff)>, +) { + let mut working: HashMap = snapshot.clone(); + let mut pending_diffs: Vec<(TableRef, SchemaDiff)> = Vec::new(); + + for record in records { + if let CdcRecord::SchemaChange { table, columns, .. } = record { + let diff = diff_against_cache(&working, table, columns); + + // Log type changes (no DDL — operator intervention required). + for tc in &diff.type_changed { + error!( + table = %table.qualified_name(), + column = %tc.name, + old_type = ?tc.old_data_type, + new_type = ?tc.new_data_type, + "schema evolution: type change not supported, MERGE keeps old cast" + ); + } + + // Log drops (no DDL — target keeps dead column). + for dropped in &diff.dropped { + warn!( + table = %table.qualified_name(), + column = %dropped, + "schema evolution: column drop ignored, target keeps dead column" + ); + } + + if !diff.added.is_empty() { + let src_schema = table + .schema + .clone() + .unwrap_or_else(|| "public".to_string()); + let qn = table.qualified_name(); + + // Ensure the table exists in `working` before pushing columns. + let entry = working.entry(qn).or_insert_with(|| SourceTableSchema { + schema: src_schema, + name: table.name.clone(), + columns: Vec::new(), + primary_keys: Vec::new(), + }); + + // Advance working map so subsequent SchemaChange events for + // the same table see these columns and don't re-emit them. + for added in &diff.added { + entry.columns.push(SourceColumn { + name: added.name.clone(), + data_type: added.data_type.clone(), + nullable: added.nullable, + // Carry the OID through if the source provided one. + // Sinks that don't need OIDs ignore this field. + pg_type_id: added.pg_type_id.unwrap_or(0), + }); + } + + pending_diffs.push((table.clone(), diff)); + } + } + } + + (working, pending_diffs) +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::position::SourcePosition; + use crate::core::record::{ColumnDef, TableRef}; + + fn cache_with_orders_id() -> HashMap { + let mut snapshot: HashMap = HashMap::new(); + snapshot.insert( + "public.orders".to_string(), + SourceTableSchema { + schema: "public".to_string(), + name: "orders".to_string(), + columns: vec![SourceColumn { + name: "id".to_string(), + data_type: DataType::Int32, + nullable: false, + pg_type_id: 23, + }], + primary_keys: vec!["id".to_string()], + }, + ); + snapshot + } + + #[test] + fn no_schema_change_returns_empty_diffs() { + let snapshot = cache_with_orders_id(); + + let records = vec![CdcRecord::Insert { + table: TableRef::new(Some("public".into()), "orders".into()), + columns: vec![], + position: SourcePosition::Lsn(0), + }]; + + let (working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); + + assert!( + pending_diffs.is_empty(), + "Insert-only batch must produce no pending diffs" + ); + assert_eq!( + working + .get("public.orders") + .expect("table must exist in working") + .columns + .len(), + 1, + "working must equal input snapshot when no SchemaChange present" + ); + } + + #[test] + fn cold_start_added_column() { + let snapshot: HashMap = HashMap::new(); + + let records = vec![CdcRecord::SchemaChange { + table: TableRef::new(Some("public".into()), "orders".into()), + columns: vec![ + ColumnDef::with_pg_oid("id".into(), DataType::Int32, false, 23), + ColumnDef::with_pg_oid("description".into(), DataType::String, true, 25), + ], + position: SourcePosition::Lsn(100), + }]; + + let (working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); + + assert_eq!( + pending_diffs.len(), + 1, + "one SchemaChange for a new table must produce exactly one pending diff" + ); + assert_eq!( + pending_diffs[0].1.added.len(), + 2, + "both columns are new (cold-start) — both must appear in added" + ); + assert_eq!( + working + .get("public.orders") + .expect("public.orders must be in working after cold-start SchemaChange") + .columns + .len(), + 2, + "working must contain both columns after cold-start SchemaChange" + ); + } + + #[test] + fn intra_batch_dedup() { + // Snapshot has public.orders with one column — id. + let snapshot = cache_with_orders_id(); + + // Two SchemaChange records for the same table in the same batch, + // both declaring the same `description` column. The second must see + // `description` already in the working map and not re-emit. + let schema_change = CdcRecord::SchemaChange { + table: TableRef::new(Some("public".into()), "orders".into()), + columns: vec![ + ColumnDef::with_pg_oid("id".into(), DataType::Int32, false, 23), + ColumnDef::with_pg_oid("description".into(), DataType::String, true, 25), + ], + position: SourcePosition::Lsn(200), + }; + let records = vec![schema_change.clone(), schema_change]; + + let (_working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); + + assert_eq!( + pending_diffs.len(), + 1, + "two identical SchemaChange events in one batch must produce only one pending diff" + ); + assert_eq!( + pending_diffs[0].1.added.len(), + 1, + "only `description` should be added — `id` was already in the snapshot" + ); + } + + #[test] + fn type_change_logged_no_ddl() { + // Snapshot has id as Int32. Incoming claims id is Int64 — type changed. + let snapshot = cache_with_orders_id(); + + let records = vec![CdcRecord::SchemaChange { + table: TableRef::new(Some("public".into()), "orders".into()), + columns: vec![ColumnDef::with_pg_oid( + "id".into(), + DataType::Int64, + false, + 20, + )], + position: SourcePosition::Lsn(300), + }]; + + let (_working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); + + assert!( + pending_diffs.is_empty(), + "type-change-only diff must NOT produce a pending diff (no DDL)" + ); + } + + #[test] + fn dropped_column_logged_no_ddl() { + // Snapshot has orders(id, name). Incoming has only orders(id). + // → name was dropped. + let mut snapshot: HashMap = HashMap::new(); + snapshot.insert( + "public.orders".to_string(), + SourceTableSchema { + schema: "public".to_string(), + name: "orders".to_string(), + columns: vec![ + SourceColumn { + name: "id".into(), + data_type: DataType::Int32, + nullable: false, + pg_type_id: 23, + }, + SourceColumn { + name: "name".into(), + data_type: DataType::String, + nullable: true, + pg_type_id: 25, + }, + ], + primary_keys: vec!["id".into()], + }, + ); + + let records = vec![CdcRecord::SchemaChange { + table: TableRef::new(Some("public".into()), "orders".into()), + columns: vec![ColumnDef::with_pg_oid( + "id".into(), + DataType::Int32, + false, + 23, + )], + position: SourcePosition::Lsn(400), + }]; + + let (_working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); + + assert!( + pending_diffs.is_empty(), + "drop-only diff must NOT produce a pending diff (no DDL)" + ); + } + + #[test] + fn diff_against_cache_cold_start() { + let cache: HashMap = HashMap::new(); + let table = TableRef::new(Some("public".into()), "orders".into()); + let cols = vec![ + ColumnDef::with_pg_oid("id".into(), DataType::Int32, false, 23), + ColumnDef::with_pg_oid("name".into(), DataType::String, true, 25), + ]; + + let diff = diff_against_cache(&cache, &table, &cols); + + assert_eq!(diff.added.len(), 2); + assert!(diff.type_changed.is_empty()); + assert!(diff.dropped.is_empty()); + assert_eq!(diff.added[0].ordinal, 0); + assert_eq!(diff.added[1].ordinal, 1); + } + + #[test] + fn diff_against_cache_no_pg_type_id_still_produces_added() { + // Non-PG source: ColumnDef has pg_type_id = None. + let cache: HashMap = HashMap::new(); + let table = TableRef::new(Some("public".into()), "orders".into()); + let cols = vec![ColumnDef { + name: "id".into(), + data_type: DataType::Int32, + nullable: false, + pg_type_id: None, + }]; + + let diff = diff_against_cache(&cache, &table, &cols); + + assert_eq!( + diff.added.len(), + 1, + "added entries are produced even without pg_type_id" + ); + assert!(diff.added[0].pg_type_id.is_none()); + } +} From cbbb74710f9c83cc1dfe1d23ed7d1d9fd1cf447d Mon Sep 17 00:00:00 2001 From: Dario Mazzitelli Date: Tue, 28 Apr 2026 17:56:32 -0300 Subject: [PATCH 2/9] feat: schema evolution for StarRocks sink MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implement ADD COLUMN auto-application for the StarRocks sink under the conservative policy already used by the PG sink (DROP/MODIFY/RENAME remain warn-only). New `starrocks/schema_evolution.rs` module owns: - `validate_server_version`: hard-requires StarRocks ≥ 3.2.0 (fail loud) - `detect_fast_schema_evolution_per_table`: per-table flag detection against INFORMATION_SCHEMA.TABLES_CONFIG; degraded mode (loud WARN + per-event WARN at runtime) when the property is missing - `reconcile_target_schema`: startup catch-up via diff between source schema and target INFORMATION_SCHEMA.COLUMNS - `apply_diff`: ALTER TABLE ADD COLUMN with backtick-quoted identifiers, post-ALTER verification via INFORMATION_SCHEMA, and refresh of the in-memory target column cache Wired into `StarRocksSink`: - new `schema_evolution: StarRocksSchemaEvolution` field - new `schema_cache: Arc>>` seeded from source schemas at setup, mutated after each successful runtime evolution - `setup()` runs version + per-table-flag + reconcile validations - `write_batch()` Phase 1 walks SchemaChange events via the shared `compute_schema_evolution_plan`, dispatches per-table to `apply_diff` or to the warn-only degraded path; Phase 2 runs the existing Stream Load flow Halt-loud on ALTER failure: errors bubble through Phase 1 and trigger `CdcState::Stopped` via the existing pipeline error path. 10 unit tests added (version parsing, properties detection); all 93 sink tests pass; clippy clean. --- src/connectors/sinks/starrocks/mod.rs | 102 +++- .../sinks/starrocks/schema_evolution.rs | 576 ++++++++++++++++++ 2 files changed, 675 insertions(+), 3 deletions(-) create mode 100644 src/connectors/sinks/starrocks/schema_evolution.rs diff --git a/src/connectors/sinks/starrocks/mod.rs b/src/connectors/sinks/starrocks/mod.rs index 8d5516a..4b0ad78 100644 --- a/src/connectors/sinks/starrocks/mod.rs +++ b/src/connectors/sinks/starrocks/mod.rs @@ -38,19 +38,22 @@ //! - `dbmazz_cdc_version`: Source LSN/position for ordering mod config; +pub(crate) mod schema_evolution; mod setup; pub mod stream_load; pub(crate) mod types; -use anyhow::{anyhow, Result}; +use anyhow::{anyhow, Context, Result}; use async_trait::async_trait; use chrono::Utc; use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; -use tracing::info; +use tokio::sync::RwLock; +use tracing::{info, warn}; use crate::config::SinkConfig; +use crate::connectors::sinks::schema_evolution::compute_schema_evolution_plan; use crate::core::traits::SourceTableSchema; use crate::core::{ CdcRecord, ColumnValue, LoadingModel, Sink, SinkCapabilities, SinkMode, SinkResult, @@ -58,6 +61,7 @@ use crate::core::{ }; pub use self::config::StarRocksSinkConfig; +use self::schema_evolution::StarRocksSchemaEvolution; use self::stream_load::{StreamLoadClient, StreamLoadOptions}; use self::types::TypeMapper; @@ -86,12 +90,20 @@ fn is_internal_table(table_name: &str) -> bool { /// table model. pub struct StarRocksSink { /// Configuration for the StarRocks connection - #[allow(dead_code)] config: StarRocksSinkConfig, /// HTTP Stream Load client stream_load: StreamLoadClient, /// Type mapper for converting CDC types to StarRocks types type_mapper: TypeMapper, + /// Schema-evolution machinery: per-table flag detection, target column + /// cache, runtime ALTER application. Shared between `setup()` and + /// `write_batch()`. + schema_evolution: StarRocksSchemaEvolution, + /// In-memory snapshot of the schema dbmazz currently believes is in + /// effect on the target. Keyed by `.`. + /// Populated in `setup()` from the introspected source schemas, mutated + /// in `write_batch()` after each successful schema-evolution batch. + schema_cache: Arc>>, } impl StarRocksSink { @@ -116,6 +128,7 @@ impl StarRocksSink { sr_config.user.clone(), sr_config.password.clone(), ); + let schema_evolution = StarRocksSchemaEvolution::new(&sr_config)?; info!("StarRocksSink initialized:"); info!(" HTTP URL: {}", sr_config.http_url); @@ -126,6 +139,8 @@ impl StarRocksSink { config: sr_config, stream_load, type_mapper: TypeMapper::new(), + schema_evolution, + schema_cache: Arc::new(RwLock::new(HashMap::new())), }) } @@ -343,6 +358,31 @@ impl Sink for StarRocksSink { let sr_setup = setup::StarRocksSetup::new(self.config.clone())?; let tables: Vec = source_schemas.iter().map(|s| s.name.clone()).collect(); sr_setup.run(&tables).await?; + + // Schema evolution validation: + // 1. Server version must be ≥ 3.2.0 (hard requirement, fail loud). + // 2. Detect `fast_schema_evolution=true` per table — tables without + // it operate in degraded mode (loud WARN at runtime, ALTERs skipped). + // 3. Reconcile target schema against source for tables with the flag. + self.schema_evolution.validate_server_version().await?; + self.schema_evolution + .detect_fast_schema_evolution_per_table(&tables) + .await?; + self.schema_evolution + .reconcile_target_schema(source_schemas) + .await?; + + // Seed the schema cache with the introspected source state so the + // diff in write_batch() has a real baseline (avoiding cold-start + // re-emission of every column on the first SchemaChange). + { + let mut cache = self.schema_cache.write().await; + for src in source_schemas { + cache.insert(format!("{}.{}", src.schema, src.name), src.clone()); + } + } + + info!("[OK] StarRocksSink schema evolution setup complete"); Ok(()) } @@ -355,6 +395,62 @@ impl Sink for StarRocksSink { }); } + // ─── Phase 1: schema evolution pre-pass ────────────────────────── + // Walk the batch's `SchemaChange` events, compute per-table diffs, + // apply ALTERs on tables with `fast_schema_evolution=true`, and + // emit loud WARN logs for tables without the flag (degraded mode). + // + // Halt-loud on ALTER failure: bubbling the error up causes the + // pipeline to set CdcState::Stopped (existing behaviour in + // `pipeline::flush_batch`). + let snapshot = self.schema_cache.read().await.clone(); + let (working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); + + for (table, diff) in &pending_diffs { + let table_name = table.name.as_str(); + if self + .schema_evolution + .is_schema_evolution_enabled(table_name) + .await + { + self.schema_evolution + .apply_diff(table_name, diff) + .await + .with_context(|| { + format!( + "starrocks_sink: schema evolution failed for table {}", + table_name + ) + })?; + } else { + // Degraded mode: table doesn't have fast_schema_evolution=true. + // Emit a per-event WARN per added column. The metric counter + // (`schema_evolution_skipped_total`) is wired in section 4 + // of the change spec; until then the WARN log is the + // observability surface. + for added in &diff.added { + warn!( + table = %table_name, + column = %added.name, + "starrocks_sink: schema change skipped — \ + fast_schema_evolution=true not set on target table. \ + New column will NOT be propagated; data writes \ + continue without it." + ); + } + } + } + + // Update the cache so the next batch sees the post-evolution state + // even for tables in degraded mode (avoids re-emitting the same + // WARN on every batch for the same column). + { + let mut cache = self.schema_cache.write().await; + *cache = working; + } + + // ─── Phase 2: data writes ──────────────────────────────────────── + // Cache timestamp for entire batch let synced_at = Utc::now().format("%Y-%m-%d %H:%M:%S").to_string(); diff --git a/src/connectors/sinks/starrocks/schema_evolution.rs b/src/connectors/sinks/starrocks/schema_evolution.rs new file mode 100644 index 0000000..1515838 --- /dev/null +++ b/src/connectors/sinks/starrocks/schema_evolution.rs @@ -0,0 +1,576 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! StarRocks-specific schema evolution: ALTER TABLE ADD COLUMN application, +//! `fast_schema_evolution` per-table detection, server version validation, +//! and target-side schema cache. +//! +//! Consumes the sink-agnostic `SchemaDiff` produced by +//! `crate::connectors::sinks::schema_evolution::compute_schema_evolution_plan` +//! and emits StarRocks-dialect DDL via the MySQL protocol pool. +//! +//! # Hard requirements (validated at setup, fail loud if missing) +//! +//! - **Server version ≥ 3.2.0**. Older versions don't support +//! `fast_schema_evolution` and would require a poll loop on +//! `SHOW ALTER TABLE` that adds complexity for no demonstrated demand. +//! +//! # Per-table degraded mode +//! +//! - **Table has `fast_schema_evolution=true`** → ADD COLUMN applies in +//! metadata-only milliseconds. Stream Load following the ALTER sees the +//! new column immediately. +//! - **Table missing the property** → schema evolution is **disabled** for +//! that table. The daemon arranca anyway with a loud `WARN` at setup +//! plus per-event `WARN` and a `schema_evolution_skipped_total` counter +//! when SchemaChange events arrive. The table behaves as it did before +//! this change (data loads succeed, but column additions are silently +//! filtered by Stream Load via `max_filter_ratio`). + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use anyhow::{anyhow, Context, Result}; +use mysql_async::{prelude::Queryable, Conn, OptsBuilder, Pool}; +use tokio::sync::RwLock; +use tracing::{info, warn}; + +use crate::connectors::sinks::schema_evolution::SchemaDiff; +use crate::connectors::sinks::starrocks::config::StarRocksSinkConfig; +use crate::connectors::sinks::starrocks::types::TypeMapper; +use crate::utils::validate_sql_identifier; + +/// Minimum supported StarRocks server version. +/// +/// Older versions don't support `fast_schema_evolution` table property — +/// `ALTER TABLE` is asynchronous and slow on big tables, which would force +/// a poll loop that we explicitly chose not to implement. +const MIN_SERVER_VERSION_MAJOR: u32 = 3; +const MIN_SERVER_VERSION_MINOR: u32 = 2; + +/// Cached metadata about a column in a target StarRocks table. Built from +/// `INFORMATION_SCHEMA.COLUMNS` on demand. +#[derive(Debug, Clone)] +#[allow(dead_code)] +pub struct TargetColumn { + pub name: String, + /// Raw `COLUMN_TYPE` value from `INFORMATION_SCHEMA.COLUMNS`. Useful + /// for diagnostic logging; not used for type-equality checks (the diff + /// logic compares by NAME only). + pub data_type_str: String, + pub nullable: bool, +} + +/// StarRocks-specific schema evolution machinery. Owned by `StarRocksSink`, +/// shared between `setup()` and `write_batch()`. +pub struct StarRocksSchemaEvolution { + pool: Pool, + database: String, + type_mapper: TypeMapper, + /// Tables (by short name, no `db.` prefix) that have + /// `fast_schema_evolution=true` → schema evolution is **enabled**. + /// Populated once at setup; not mutated at runtime. + schema_evolution_enabled: Arc>>, + /// Cache: target table name → its current column list. Refreshed after + /// each successful ALTER and on every `refresh_target_schema_cache` call. + target_columns: Arc>>>, +} + +impl StarRocksSchemaEvolution { + /// Creates a new instance with its own MySQL pool. Independent from + /// `StarRocksSetup`'s pool — both can coexist; `mysql_async::Pool` is + /// `Clone` and internally Arc-counted, but we keep the construction + /// site here for self-containment. + pub fn new(config: &StarRocksSinkConfig) -> Result { + let opts = OptsBuilder::default() + .ip_or_hostname(config.hostname()) + .tcp_port(config.mysql_port) + .user(Some(config.user.clone())) + .pass(Some(config.password.clone())) + .db_name(Some(config.database.clone())) + .prefer_socket(false); // StarRocks doesn't support Unix socket + Ok(Self { + pool: Pool::new(opts), + database: config.database.clone(), + type_mapper: TypeMapper::new(), + schema_evolution_enabled: Arc::new(RwLock::new(HashSet::new())), + target_columns: Arc::new(RwLock::new(HashMap::new())), + }) + } + + // --------------------------------------------------------------------- + // Setup-time validation + // --------------------------------------------------------------------- + + /// Validate that the connected StarRocks server is at least version 3.2.0. + /// Fails loud if older — does not arrancar in degraded mode for old + /// versions because `fast_schema_evolution` does not exist there at all. + /// + /// Parses the result of `SELECT current_version()` (StarRocks) which + /// returns a string like `"3.2.4"`, `"3.3.0-rc01"`, or `"3.4.1 8b4e8f9"`. + pub async fn validate_server_version(&self) -> Result<()> { + let mut conn = self.get_conn().await?; + + // StarRocks exposes its version via `current_version()`; MySQL-protocol + // layer also accepts `SELECT @@version` but that returns a synthetic + // value that includes a MySQL compat prefix on some builds. Prefer + // `current_version()` for accuracy. + let raw_version: Option = conn + .query_first("SELECT current_version()") + .await + .map_err(|e| anyhow!("Failed to query StarRocks server version: {}", e))?; + + let version_str = raw_version.ok_or_else(|| { + anyhow!("StarRocks `SELECT current_version()` returned no row") + })?; + + let (major, minor) = parse_server_version(&version_str).ok_or_else(|| { + anyhow!( + "Could not parse StarRocks version string: {:?}", + version_str + ) + })?; + + if major < MIN_SERVER_VERSION_MAJOR + || (major == MIN_SERVER_VERSION_MAJOR && minor < MIN_SERVER_VERSION_MINOR) + { + return Err(anyhow!( + "StarRocks server version {}.{} is too old (got {:?}). \ + Minimum required: {}.{}.0. \ + Older versions do not support fast_schema_evolution and would \ + require synchronous polling on `SHOW ALTER TABLE`. \ + Upgrade your StarRocks cluster to 3.2 or later.", + major, + minor, + version_str, + MIN_SERVER_VERSION_MAJOR, + MIN_SERVER_VERSION_MINOR + )); + } + + info!( + " [OK] StarRocks server version {}.{}+ detected (raw: {})", + major, minor, version_str + ); + Ok(()) + } + + /// For each configured table, detect whether `fast_schema_evolution` is + /// enabled. Tables with the property are added to the + /// `schema_evolution_enabled` set; tables without are logged once with + /// an actionable WARN. + /// + /// This is opportunistic — failure to query `INFORMATION_SCHEMA.TABLES_CONFIG` + /// for a single table degrades that table to disabled and continues + /// (rather than failing setup entirely). The catalog query itself + /// failing for a known reason (permissions, missing table) bubbles up. + pub async fn detect_fast_schema_evolution_per_table( + &self, + tables: &[String], + ) -> Result<()> { + let mut conn = self.get_conn().await?; + let mut enabled = self.schema_evolution_enabled.write().await; + + for table_qualified in tables { + // Strip any schema prefix; StarRocks uses unqualified table names. + let table_name = table_qualified + .split('.') + .next_back() + .unwrap_or(table_qualified) + .to_string(); + + let has_flag = self + .table_has_fast_schema_evolution(&mut conn, &table_name) + .await + .unwrap_or_else(|e| { + warn!( + table = %table_name, + error = %e, + "starrocks_sink: failed to detect fast_schema_evolution; treating as disabled" + ); + false + }); + + if has_flag { + info!( + " [OK] Table {} has fast_schema_evolution=true (schema evolution enabled)", + table_name + ); + enabled.insert(table_name); + } else { + warn!( + table = %table_name, + "starrocks_sink: schema evolution DISABLED for table — \ + fast_schema_evolution=true not set on target. \ + Schema additions in source will NOT be propagated to this table. \ + To enable, recreate the table with \ + PROPERTIES('fast_schema_evolution'='true') (StarRocks 3.2+; \ + this property is creation-only and cannot be added via ALTER)." + ); + // Not inserted into `enabled` — skip path activates at runtime. + } + } + + Ok(()) + } + + /// Lightweight reconciliation pass on startup. For tables whose source + /// schema has columns missing from the target schema, emit `ALTER TABLE + /// ADD COLUMN` to bring the target up to date. + /// + /// Skipped for tables without `fast_schema_evolution=true` — for those + /// the daemon emits a WARN at setup time (see + /// `detect_fast_schema_evolution_per_table`) and proceeds. + /// + /// Fails loud on any individual ALTER failure: setup error surfaces in + /// `/healthz` and the daemon does not begin CDC. + pub async fn reconcile_target_schema( + &self, + source_schemas: &[crate::core::traits::SourceTableSchema], + ) -> Result<()> { + let enabled = self.schema_evolution_enabled.read().await.clone(); + + for source in source_schemas { + if !enabled.contains(&source.name) { + // Skip tables without the flag — degraded mode covers them. + continue; + } + + // Refresh the target column cache for this table. + self.refresh_target_schema_cache(&source.name).await?; + + // Build a name set of the current target columns. + let target_names: HashSet = self + .target_columns + .read() + .await + .get(&source.name) + .map(|cols| cols.iter().map(|c| c.name.to_lowercase()).collect()) + .unwrap_or_default(); + + // Build a synthetic SchemaDiff with the missing source columns. + let mut diff = SchemaDiff::default(); + for (i, src_col) in source.columns.iter().enumerate() { + if !target_names.contains(&src_col.name.to_lowercase()) { + diff.added.push(crate::connectors::sinks::schema_evolution::AddedColumn { + name: src_col.name.clone(), + data_type: src_col.data_type.clone(), + nullable: true, // always nullable on reconcile + #[allow(clippy::cast_possible_wrap)] + ordinal: i as i32, + pg_type_id: Some(src_col.pg_type_id), + }); + } + } + + if diff.added.is_empty() { + continue; + } + + info!( + table = %source.name, + added_count = diff.added.len(), + "starrocks_sink: reconcile_on_startup applying ALTERs" + ); + self.apply_diff(&source.name, &diff).await.with_context(|| { + format!( + "starrocks_sink: reconcile_on_startup failed for table {}", + source.name + ) + })?; + } + + Ok(()) + } + + // --------------------------------------------------------------------- + // Runtime DDL + // --------------------------------------------------------------------- + + /// Apply a `SchemaDiff` to the target table: emit `ALTER TABLE ADD COLUMN` + /// for each added column, verify each via `INFORMATION_SCHEMA`, and + /// refresh the target_columns cache once at the end. + /// + /// Caller MUST check `is_schema_evolution_enabled(table)` first; this + /// function unconditionally applies the diff. Tables without the flag + /// should be filtered out at the call site. + pub async fn apply_diff(&self, table_name: &str, diff: &SchemaDiff) -> Result<()> { + validate_sql_identifier(table_name) + .map_err(|e| anyhow!("Invalid table name '{}': {}", table_name, e))?; + validate_sql_identifier(&self.database) + .map_err(|e| anyhow!("Invalid database name '{}': {}", self.database, e))?; + + if diff.added.is_empty() { + return Ok(()); + } + + let mut conn = self.get_conn().await?; + + for added in &diff.added { + validate_sql_identifier(&added.name) + .map_err(|e| anyhow!("Invalid column name '{}': {}", added.name, e))?; + + let starrocks_type = self.type_mapper.to_starrocks_type(&added.data_type); + // Backtick-quoted column name to handle reserved words; database + // and table identifiers are validated above so direct interpolation + // is safe (no user-controlled SQL injection vector). + let sql = format!( + "ALTER TABLE `{}`.`{}` ADD COLUMN IF NOT EXISTS `{}` {}", + self.database, table_name, added.name, starrocks_type + ); + conn.query_drop(&sql).await.with_context(|| { + format!( + "starrocks_sink: ALTER TABLE failed for {}.{} column {}", + self.database, table_name, added.name + ) + })?; + + // Verify the column actually appeared in INFORMATION_SCHEMA. + // With fast_schema_evolution=true this is metadata-only and + // returns within milliseconds; the verify is a defensive sanity + // check rather than a real poll. + self.verify_alter_completed(&mut conn, table_name, &added.name) + .await?; + + info!( + table = %table_name, + column = %added.name, + starrocks_type = %starrocks_type, + "starrocks_sink: ADD COLUMN applied" + ); + } + + // Drop the connection so refresh_target_schema_cache can take its own. + drop(conn); + self.refresh_target_schema_cache(table_name).await?; + Ok(()) + } + + /// Returns `true` if the table is in the schema-evolution-enabled set. + pub async fn is_schema_evolution_enabled(&self, table_name: &str) -> bool { + self.schema_evolution_enabled + .read() + .await + .contains(table_name) + } + + /// Reload the column list for `table_name` from `INFORMATION_SCHEMA.COLUMNS`. + /// Stores the result in the in-memory cache. Used both at setup and after + /// runtime ALTERs. + pub async fn refresh_target_schema_cache(&self, table_name: &str) -> Result<()> { + let mut conn = self.get_conn().await?; + + let rows: Vec<(String, String, String)> = conn + .exec( + "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? + ORDER BY ORDINAL_POSITION", + (&self.database, table_name), + ) + .await + .with_context(|| { + format!( + "starrocks_sink: failed to refresh target schema for {}.{}", + self.database, table_name + ) + })?; + + let columns: Vec = rows + .into_iter() + .map(|(name, data_type_str, is_nullable)| TargetColumn { + name, + data_type_str, + nullable: is_nullable.eq_ignore_ascii_case("YES"), + }) + .collect(); + + let mut cache = self.target_columns.write().await; + cache.insert(table_name.to_string(), columns); + Ok(()) + } + + // --------------------------------------------------------------------- + // Private helpers + // --------------------------------------------------------------------- + + async fn get_conn(&self) -> Result { + self.pool + .get_conn() + .await + .map_err(|e| anyhow!("starrocks_sink: failed to get MySQL connection: {}", e)) + } + + /// Confirm a column appears in `INFORMATION_SCHEMA.COLUMNS` after an ALTER. + /// With fast_schema_evolution this is metadata-only and instant; the + /// check is a defensive sanity validation rather than a real poll. + async fn verify_alter_completed( + &self, + conn: &mut Conn, + table_name: &str, + column_name: &str, + ) -> Result<()> { + let exists: Option = conn + .exec_first( + "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?", + (&self.database, table_name, column_name), + ) + .await + .map_err(|e| anyhow!("Failed to verify ALTER for {}.{}: {}", table_name, column_name, e))?; + + if exists.is_none() { + return Err(anyhow!( + "starrocks_sink: ALTER TABLE {}.{} ADD COLUMN {} reported success \ + but the column did not appear in INFORMATION_SCHEMA. \ + Check fast_schema_evolution=true is set on the table.", + self.database, table_name, column_name + )); + } + Ok(()) + } + + /// Query `INFORMATION_SCHEMA.TABLES_CONFIG` for the table's + /// `PROPERTIES` string and check whether `"fast_schema_evolution" = "true"` + /// appears in it. + async fn table_has_fast_schema_evolution( + &self, + conn: &mut Conn, + table_name: &str, + ) -> Result { + // `INFORMATION_SCHEMA.TABLES_CONFIG` is StarRocks-specific (3.2+). + // PROPERTIES is a string column; format includes `"key" = "value"` pairs. + let row: Option<(String,)> = conn + .exec_first( + "SELECT PROPERTIES FROM INFORMATION_SCHEMA.TABLES_CONFIG + WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?", + (&self.database, table_name), + ) + .await + .with_context(|| { + format!( + "starrocks_sink: failed to query TABLES_CONFIG for {}.{}", + self.database, table_name + ) + })?; + + let Some((properties,)) = row else { + // Table not in TABLES_CONFIG — should not happen if setup + // verified existence already, but be defensive. + warn!( + table = %table_name, + "starrocks_sink: table not present in INFORMATION_SCHEMA.TABLES_CONFIG" + ); + return Ok(false); + }; + + Ok(properties_contain_fast_schema_evolution(&properties)) + } +} + +// --------------------------------------------------------------------------- +// Free functions (unit-testable) +// --------------------------------------------------------------------------- + +/// Parse a StarRocks version string like `"3.2.4"`, `"3.3.0-rc01"`, or +/// `"3.4.1 8b4e8f9"` into `(major, minor)`. Returns `None` if the format +/// is not recognised. +fn parse_server_version(s: &str) -> Option<(u32, u32)> { + // Take everything before the first whitespace (build-hash suffix) and + // the first dash (rc/alpha suffix). + let head = s + .split(|c: char| c.is_whitespace() || c == '-') + .next()? + .trim(); + let mut parts = head.split('.'); + let major: u32 = parts.next()?.parse().ok()?; + let minor: u32 = parts.next()?.parse().ok()?; + Some((major, minor)) +} + +/// Check whether a `PROPERTIES` string from `INFORMATION_SCHEMA.TABLES_CONFIG` +/// contains `"fast_schema_evolution" = "true"`. Tolerates whitespace and +/// case variations. +fn properties_contain_fast_schema_evolution(properties: &str) -> bool { + // Lowercase the whole string and look for the canonical key=true pattern. + // Tolerates `"fast_schema_evolution"="true"` (no spaces) and the + // canonical SHOW CREATE TABLE rendering with spaces. + let lower = properties.to_ascii_lowercase(); + // Strip whitespace so `"fast_schema_evolution" = "true"` and + // `"fast_schema_evolution"="true"` match the same needle. + let stripped: String = lower.chars().filter(|c| !c.is_whitespace()).collect(); + stripped.contains("\"fast_schema_evolution\"=\"true\"") +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_version_simple() { + assert_eq!(parse_server_version("3.2.4"), Some((3, 2))); + assert_eq!(parse_server_version("3.3.0"), Some((3, 3))); + assert_eq!(parse_server_version("4.0.0"), Some((4, 0))); + } + + #[test] + fn parse_version_with_rc_suffix() { + assert_eq!(parse_server_version("3.3.0-rc01"), Some((3, 3))); + assert_eq!(parse_server_version("3.2.0-alpha"), Some((3, 2))); + } + + #[test] + fn parse_version_with_build_hash() { + assert_eq!(parse_server_version("3.4.1 8b4e8f9"), Some((3, 4))); + assert_eq!(parse_server_version("3.2.0 abc123"), Some((3, 2))); + } + + #[test] + fn parse_version_invalid() { + assert_eq!(parse_server_version(""), None); + assert_eq!(parse_server_version("not-a-version"), None); + assert_eq!(parse_server_version("3"), None); + assert_eq!(parse_server_version("3."), None); + assert_eq!(parse_server_version("3.x"), None); + } + + #[test] + fn fast_schema_evolution_property_detection() { + // Canonical SHOW CREATE TABLE rendering with spaces. + assert!(properties_contain_fast_schema_evolution( + r#""replication_num" = "3", "fast_schema_evolution" = "true""# + )); + // No-space variant. + assert!(properties_contain_fast_schema_evolution( + r#""fast_schema_evolution"="true""# + )); + // Case variations. + assert!(properties_contain_fast_schema_evolution( + r#""Fast_Schema_Evolution" = "TRUE""# + )); + // Embedded among other properties. + assert!(properties_contain_fast_schema_evolution( + r#""bucket_size" = "10", "fast_schema_evolution" = "true", "replication_num" = "3""# + )); + } + + #[test] + fn fast_schema_evolution_property_absent() { + assert!(!properties_contain_fast_schema_evolution("")); + assert!(!properties_contain_fast_schema_evolution( + r#""replication_num" = "3""# + )); + // Property is set to false. + assert!(!properties_contain_fast_schema_evolution( + r#""fast_schema_evolution" = "false""# + )); + // Different key that contains the substring (not actually our key). + assert!(!properties_contain_fast_schema_evolution( + r#""fast_schema_evolution_disabled" = "true""# + )); + } +} From 9ae533e6ac5262f49d0d485191d0c49cf0e5ecd5 Mon Sep 17 00:00:00 2001 From: Dario Mazzitelli Date: Tue, 28 Apr 2026 18:03:06 -0300 Subject: [PATCH 3/9] feat: schema evolution for Snowflake sink MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implement ADD COLUMN auto-application for the Snowflake sink under the conservative policy (DROP/MODIFY/RENAME warn-only). New `snowflake/schema_evolution.rs` module owns: - `apply_diff`: BEGIN/ALTER/COMMIT transaction with quoted, uppercased identifiers; ROLLBACK on partial failure; no DEFAULT clause (Snowflake rejects expressions, precedent in 88dad04) - `reconcile_target_schema`: startup catch-up via diff between source schema and target INFORMATION_SCHEMA.COLUMNS - `refresh_target_schema_cache`: in-memory column cache backed by INFORMATION_SCHEMA query result parsing - `validate_alter_privilege`: info-only NOOP; the existing audit-column ALTER in `setup::run_setup` already validates the privilege implicitly, runtime failures halt loud Refactor in `SnowflakeSink`: - `source_schemas: Vec<...>` → `schema_state: Arc>>` + `table_schemas: Arc>>` (mirror for normalizer) - `setup()` builds the schema_evolution helper, runs reconcile, seeds both shared maps - `write_batch()` Phase 1 walks SchemaChange via the shared `compute_schema_evolution_plan`, applies ALTERs per table, updates the shared schema state; Phase 2 runs the existing Parquet/COPY flow Refactor in `normalizer.rs`: - `NormalizerConfig.table_schemas` is now `Arc>>` - `normalize_batch_inner` takes a read snapshot at the start of each drain so the MERGE generator sees post-evolution columns 4 unit tests added for INFORMATION_SCHEMA row parsing; all 34 Snowflake sink tests pass (87 total in the sink suite); clippy clean. --- src/connectors/sinks/snowflake/mod.rs | 116 +++++- src/connectors/sinks/snowflake/normalizer.rs | 14 +- .../sinks/snowflake/schema_evolution.rs | 384 ++++++++++++++++++ 3 files changed, 503 insertions(+), 11 deletions(-) create mode 100644 src/connectors/sinks/snowflake/schema_evolution.rs diff --git a/src/connectors/sinks/snowflake/mod.rs b/src/connectors/sinks/snowflake/mod.rs index 5b3797f..7ae4f9b 100644 --- a/src/connectors/sinks/snowflake/mod.rs +++ b/src/connectors/sinks/snowflake/mod.rs @@ -19,25 +19,33 @@ pub mod config; pub mod merge_generator; pub mod normalizer; pub mod parquet_writer; +pub(crate) mod schema_evolution; pub mod setup; pub mod stage; pub(crate) mod types; use anyhow::{Context, Result}; use async_trait::async_trait; +use std::collections::HashMap; use std::sync::atomic::{AtomicI64, Ordering}; use std::sync::Arc; -use tokio::sync::mpsc; +use tokio::sync::{mpsc, RwLock}; use tracing::info; use crate::config::SinkConfig; +use crate::connectors::sinks::schema_evolution::compute_schema_evolution_plan; use crate::core::traits::{SourceTableSchema, StageFormat}; use crate::core::{CdcRecord, LoadingModel, Sink, SinkCapabilities, SinkMode, SinkResult}; use self::client::SnowflakeClient; pub use self::config::SnowflakeSinkConfig; +use self::schema_evolution::SnowflakeSchemaEvolution; use self::stage::StageManager; +/// Shared cache type — same shape as PG sink's `SchemaState`. +/// Keyed by `.`. +pub(crate) type SchemaState = Arc>>; + /// Default file accumulation threshold before triggering COPY INTO. const DEFAULT_FLUSH_THRESHOLD_FILES: usize = 20; @@ -92,8 +100,18 @@ pub struct SnowflakeSink { staged_records: u64, flush_threshold_files: usize, flush_threshold_bytes: u64, - // Schema cache for normalizer - source_schemas: Vec, + /// Shared source schema state — `Arc>` so the writer can + /// update it after a successful schema-evolution batch and the + /// normalizer reads the post-evolution columns at the start of each + /// drain. Keyed by `.`. + schema_state: SchemaState, + /// Shared `Vec` consumed by the normalizer's MERGE + /// generator. Mirrors the same data as `schema_state` but pre-shaped + /// for the normalizer's existing iteration. Updated transactionally + /// alongside `schema_state` after each ALTER. + table_schemas: Arc>>, + /// Schema-evolution machinery. Lazily built once `client` is connected. + schema_evolution: Option>, } impl SnowflakeSink { @@ -132,7 +150,9 @@ impl SnowflakeSink { .ok() .and_then(|v| v.parse().ok()) .unwrap_or(DEFAULT_FLUSH_THRESHOLD_BYTES), - source_schemas: Vec::new(), + schema_state: Arc::new(RwLock::new(HashMap::new())), + table_schemas: Arc::new(RwLock::new(Vec::new())), + schema_evolution: None, }) } @@ -292,7 +312,9 @@ impl Sink for SnowflakeSink { async fn setup(&mut self, source_schemas: &[SourceTableSchema]) -> Result<()> { let client = self.ensure_client().await?; - // Run DDL setup + // Run DDL setup (target table creation + audit columns). + // The audit-column ALTER inside `run_setup` implicitly validates + // the role's ALTER TABLE privilege — failures bubble up loud. setup::run_setup( &client, &self.config.database, @@ -304,16 +326,41 @@ impl Sink for SnowflakeSink { .await .context("Snowflake setup failed")?; - self.source_schemas = source_schemas.to_vec(); + // Build the schema_evolution helper (now that client is connected). + let schema_evolution = Arc::new(SnowflakeSchemaEvolution::new( + client.clone(), + self.config.database.clone(), + self.config.schema.clone(), + )); + schema_evolution.validate_alter_privilege(); + schema_evolution + .reconcile_target_schema(source_schemas) + .await + .context("Snowflake reconcile_target_schema failed")?; + self.schema_evolution = Some(schema_evolution); + + // Seed the shared schema state so the diff in write_batch() has a + // real baseline (avoiding cold-start re-emission of every column). + { + let mut state = self.schema_state.write().await; + for src in source_schemas { + state.insert(format!("{}.{}", src.schema, src.name), src.clone()); + } + } + { + let mut tables = self.table_schemas.write().await; + *tables = source_schemas.to_vec(); + } - // Spawn normalizer (Primary mode only) + // Spawn normalizer (Primary mode only). Pass the shared + // `table_schemas` so it sees post-evolution schema on every drain. if self.mode == SinkMode::Primary { let normalizer_config = normalizer::NormalizerConfig { client_config: self.config.clone(), database: self.config.database.clone(), target_schema: self.config.schema.clone(), job_name: self.config.safe_job_name(), - table_schemas: source_schemas.to_vec(), + table_schemas: self.table_schemas.clone(), merge_interval_ms: self.config.merge_interval_ms, soft_delete: self.config.soft_delete, }; @@ -339,6 +386,59 @@ impl Sink for SnowflakeSink { let _client = self.ensure_client().await?; + // ─── Phase 1: schema evolution pre-pass ────────────────────────── + // Walk the batch's `SchemaChange` events, compute per-table diffs, + // apply ALTERs inside transactions. The shared + // `compute_schema_evolution_plan` already logs DROP/MODIFY/RENAME + // as warn-only; only ADD diffs reach `pending_diffs`. + // + // Halt-loud on ALTER failure: bubbling the error up causes the + // pipeline to set CdcState::Stopped via the existing pipeline + // error path. + let snapshot = self.schema_state.read().await.clone(); + let (working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); + + if !pending_diffs.is_empty() { + let schema_evolution = self.schema_evolution.as_ref().ok_or_else(|| { + anyhow::anyhow!( + "snowflake_sink: schema_evolution helper not initialized (setup() must run first)" + ) + })?; + + for (table, diff) in &pending_diffs { + schema_evolution + .apply_diff(&table.name, diff) + .await + .with_context(|| { + format!( + "snowflake_sink: schema evolution failed for table {}", + table.name + ) + })?; + } + + // Update the shared cache so the next normalizer drain sees + // the post-evolution columns when generating MERGE. + { + let mut state = self.schema_state.write().await; + *state = working; + } + // Mirror into the normalizer-shaped Vec. + { + let state_snapshot = self.schema_state.read().await.clone(); + let mut tables = self.table_schemas.write().await; + *tables = state_snapshot.into_values().collect(); + } + } else { + // Even with no pending diffs, the working map may have absorbed + // a no-op SchemaChange (e.g. column ordering reshuffle). Update + // anyway to keep state coherent. + let mut state = self.schema_state.write().await; + *state = working; + } + + // ─── Phase 2: data writes ──────────────────────────────────────── + // Track last position let last_position = records.iter().rev().find_map(|r| match r { CdcRecord::Insert { position, .. } diff --git a/src/connectors/sinks/snowflake/normalizer.rs b/src/connectors/sinks/snowflake/normalizer.rs index b357fa2..8846433 100644 --- a/src/connectors/sinks/snowflake/normalizer.rs +++ b/src/connectors/sinks/snowflake/normalizer.rs @@ -10,7 +10,7 @@ use anyhow::{Context, Result}; use std::sync::Arc; -use tokio::sync::mpsc; +use tokio::sync::{mpsc, RwLock}; use tracing::{debug, error, info, warn}; use super::client::SnowflakeClient; @@ -33,7 +33,10 @@ pub struct NormalizerConfig { pub database: String, pub target_schema: String, pub job_name: String, - pub table_schemas: Vec, + /// Shared with `SnowflakeSink`: the writer updates this `Arc>` + /// after each successful schema-evolution batch so the MERGE generator + /// here picks up the new columns in the next drain cycle. + pub table_schemas: Arc>>, #[allow(dead_code)] pub merge_interval_ms: u64, pub soft_delete: bool, @@ -218,11 +221,16 @@ async fn normalize_batch_inner( return Ok(()); } + // Snapshot the shared table_schemas at the start of this drain so the + // MERGE generator sees post-evolution columns. Read lock is held only + // for the clone; subsequent SQL execution holds no lock. + let table_schemas_snapshot = config.table_schemas.read().await.clone(); + // 2. For each table: get TOAST combinations, generate MERGE, execute for dst_table in &tables { // Find the source schema for this table let table_name = dst_table.split('.').next_back().unwrap_or(dst_table); - let source_schema = config.table_schemas.iter().find(|s| s.name == table_name); + let source_schema = table_schemas_snapshot.iter().find(|s| s.name == table_name); let source_schema = match source_schema { Some(s) => s, diff --git a/src/connectors/sinks/snowflake/schema_evolution.rs b/src/connectors/sinks/snowflake/schema_evolution.rs new file mode 100644 index 0000000..9b30a53 --- /dev/null +++ b/src/connectors/sinks/snowflake/schema_evolution.rs @@ -0,0 +1,384 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Snowflake-specific schema evolution: ALTER TABLE ADD COLUMN application +//! inside `BEGIN/COMMIT`, target-side schema cache, and reconcile-on-startup. +//! +//! Consumes the sink-agnostic `SchemaDiff` produced by +//! `crate::connectors::sinks::schema_evolution::compute_schema_evolution_plan` +//! and emits Snowflake-dialect DDL via the HTTP client. +//! +//! # Conservative policy +//! +//! - **ADD COLUMN** → auto-applied via `ALTER TABLE ADD COLUMN IF NOT EXISTS` +//! inside a transaction. +//! - **DROP / MODIFY / RENAME** → handled by the shared `compute_schema_evolution_plan` +//! which logs the events and excludes them from the pending diffs. Target +//! keeps the dead column / old type. +//! +//! # Privilege validation +//! +//! Snowflake's existing `setup::run_setup` already issues `ALTER TABLE ADD +//! COLUMN` for the four audit columns (`_DBMAZZ_OP_TYPE`, etc.) — so the +//! runtime privilege requirement is implicitly validated at setup-time. +//! `validate_alter_privilege` here logs that fact and returns `Ok` rather +//! than re-running an explicit probe, to avoid emitting catalog mutations +//! that would clutter audit logs in production accounts. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use anyhow::{anyhow, Context, Result}; +use tokio::sync::RwLock; +use tracing::{info, warn}; + +use super::client::SnowflakeClient; +use super::types::TypeMapper; +use crate::connectors::sinks::schema_evolution::SchemaDiff; +use crate::core::traits::SourceTableSchema; +use crate::utils::validate_sql_identifier; + +/// Cached metadata about a column in a target Snowflake table. Built from +/// `INFORMATION_SCHEMA.COLUMNS` on demand. Used purely for diff computation +/// and observability — not for type checks (those are coarse, name-based). +#[derive(Debug, Clone)] +#[allow(dead_code)] +pub struct TargetColumn { + pub name: String, + pub data_type_str: String, + pub nullable: bool, +} + +/// Snowflake schema evolution machinery. +/// +/// Owned by `SnowflakeSink`, shared between `setup()` and `write_batch()` +/// via reference — the underlying client is already an `Arc` so cloning is +/// cheap. +pub struct SnowflakeSchemaEvolution { + client: Arc, + database: String, + schema: String, + type_mapper: TypeMapper, + /// Cache: target table name (UPPERCASE Snowflake convention) → its + /// current column list. Refreshed after each successful ALTER and on + /// every `refresh_target_schema_cache` call. + target_columns: Arc>>>, +} + +impl SnowflakeSchemaEvolution { + pub fn new(client: Arc, database: String, schema: String) -> Self { + Self { + client, + database, + schema, + type_mapper: TypeMapper::new(), + target_columns: Arc::new(RwLock::new(HashMap::new())), + } + } + + // --------------------------------------------------------------------- + // Setup-time validation + // --------------------------------------------------------------------- + + /// Logs that ALTER TABLE privilege will be implicitly validated by the + /// existing audit-column setup path. Always returns `Ok` — actual + /// privilege failures surface loud at the next ALTER call site. + pub fn validate_alter_privilege(&self) { + info!( + " [OK] Snowflake ALTER TABLE privilege validates implicitly at setup \ + via existing audit-column ALTER. Runtime privilege failures halt the \ + pipeline loud (CdcState::Stopped) with the Snowflake error verbatim." + ); + } + + /// Reconcile target schema with source schema on startup. For each table, + /// compute the columns present in source but missing from target and + /// emit `ALTER TABLE ADD COLUMN` inside one transaction per table. Halts + /// loud on any DDL failure. + pub async fn reconcile_target_schema( + &self, + source_schemas: &[SourceTableSchema], + ) -> Result<()> { + for source in source_schemas { + // Snowflake convention: identifiers are usually uppercase. The + // setup path creates target tables matching the SOURCE name + // (which is typically lowercase from PG); INFORMATION_SCHEMA on + // Snowflake then reports the unquoted-name normalised UPPERCASE. + // Refresh and use uppercase for the cache key. + let target_name = source.name.to_uppercase(); + self.refresh_target_schema_cache(&target_name).await?; + + let target_names: HashSet = self + .target_columns + .read() + .await + .get(&target_name) + .map(|cols| cols.iter().map(|c| c.name.to_uppercase()).collect()) + .unwrap_or_default(); + + // Build a synthetic SchemaDiff with the missing source columns. + let mut diff = SchemaDiff::default(); + for (i, src_col) in source.columns.iter().enumerate() { + if !target_names.contains(&src_col.name.to_uppercase()) { + diff.added + .push(crate::connectors::sinks::schema_evolution::AddedColumn { + name: src_col.name.clone(), + data_type: src_col.data_type.clone(), + nullable: true, + #[allow(clippy::cast_possible_wrap)] + ordinal: i as i32, + pg_type_id: Some(src_col.pg_type_id), + }); + } + } + + if diff.added.is_empty() { + continue; + } + + info!( + table = %source.name, + added_count = diff.added.len(), + "snowflake_sink: reconcile_on_startup applying ALTERs" + ); + self.apply_diff(&source.name, &diff).await.with_context(|| { + format!( + "snowflake_sink: reconcile_on_startup failed for table {}", + source.name + ) + })?; + } + + Ok(()) + } + + // --------------------------------------------------------------------- + // Runtime DDL + // --------------------------------------------------------------------- + + /// Apply a `SchemaDiff` to the target table inside a single transaction: + /// `BEGIN; ALTER ...; ALTER ...; COMMIT`. On any DDL failure, ROLLBACK + /// is attempted and the error is bubbled up. + /// + /// Snowflake rejects DEFAULT expressions on `ALTER TABLE ADD COLUMN` — + /// added columns are nullable with no default. Backfill semantics: NULL + /// for pre-existing rows, populated for any post-DDL writes. + pub async fn apply_diff(&self, table_name: &str, diff: &SchemaDiff) -> Result<()> { + validate_sql_identifier(table_name) + .map_err(|e| anyhow!("Invalid table name '{}': {}", table_name, e))?; + validate_sql_identifier(&self.database) + .map_err(|e| anyhow!("Invalid database name '{}': {}", self.database, e))?; + validate_sql_identifier(&self.schema) + .map_err(|e| anyhow!("Invalid target schema name '{}': {}", self.schema, e))?; + + if diff.added.is_empty() { + return Ok(()); + } + + // Open transaction. If we fail mid-batch, ROLLBACK keeps the target + // in a known state (no partial column adds). + self.client + .execute("BEGIN TRANSACTION") + .await + .context("snowflake_sink: failed to BEGIN TRANSACTION for schema evolution")?; + + // Best-effort: collect the result of each ALTER inside this scope so + // we always issue a COMMIT or ROLLBACK before returning. + let result: Result<()> = async { + for added in &diff.added { + validate_sql_identifier(&added.name) + .map_err(|e| anyhow!("Invalid column name '{}': {}", added.name, e))?; + + let sf_type = self.type_mapper.to_snowflake_type(&added.data_type); + // Snowflake quoted identifiers preserve case. Database/schema + // are validated above; table+column are validated here. + let sql = format!( + r#"ALTER TABLE "{}"."{}"."{}" ADD COLUMN IF NOT EXISTS "{}" {}"#, + self.database.to_uppercase(), + self.schema.to_uppercase(), + table_name.to_uppercase(), + added.name.to_uppercase(), + sf_type + ); + self.client.execute(&sql).await.with_context(|| { + format!( + "snowflake_sink: ALTER TABLE failed for {}.{}.{} column {}", + self.database, self.schema, table_name, added.name + ) + })?; + info!( + table = %table_name, + column = %added.name, + snowflake_type = %sf_type, + "snowflake_sink: ADD COLUMN applied" + ); + } + Ok(()) + } + .await; + + match result { + Ok(()) => { + self.client + .execute("COMMIT") + .await + .context("snowflake_sink: COMMIT failed after schema evolution ALTERs")?; + // Refresh the in-memory target column cache for this table. + self.refresh_target_schema_cache(&table_name.to_uppercase()) + .await?; + Ok(()) + } + Err(err) => { + if let Err(rb_err) = self.client.execute("ROLLBACK").await { + warn!( + rollback_error = %rb_err, + "snowflake_sink: ROLLBACK failed after ALTER error; the transaction may be left open until the connection closes" + ); + } + Err(err) + } + } + } + + /// Reload the column list for `table_name` from `INFORMATION_SCHEMA.COLUMNS`. + pub async fn refresh_target_schema_cache(&self, table_name: &str) -> Result<()> { + // INFORMATION_SCHEMA names are uppercase by Snowflake convention. + let database_upper = self.database.to_uppercase(); + let schema_upper = self.schema.to_uppercase(); + let table_upper = table_name.to_uppercase(); + let sql = format!( + r#"SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE + FROM "{}"."INFORMATION_SCHEMA"."COLUMNS" + WHERE TABLE_SCHEMA = '{}' + AND TABLE_NAME = '{}' + ORDER BY ORDINAL_POSITION"#, + database_upper, schema_upper, table_upper + ); + + let result = self.client.execute(&sql).await.with_context(|| { + format!( + "snowflake_sink: failed to refresh target schema for {}.{}.{}", + database_upper, schema_upper, table_upper + ) + })?; + + let columns = parse_information_schema_rows(&result); + + let mut cache = self.target_columns.write().await; + cache.insert(table_upper, columns); + Ok(()) + } +} + +// --------------------------------------------------------------------------- +// Free functions (unit-testable) +// --------------------------------------------------------------------------- + +/// Parse a Snowflake `INFORMATION_SCHEMA.COLUMNS` query result into a list +/// of `TargetColumn`s. The `data` field of `QueryResult` is JSON; rows are +/// arrays of stringified values. +fn parse_information_schema_rows(result: &super::client::QueryResult) -> Vec { + let mut cols = Vec::new(); + let Some(ref data) = result.data else { + return cols; + }; + let Some(rows) = data.as_array() else { + return cols; + }; + for row in rows { + let Some(arr) = row.as_array() else { + continue; + }; + let name = arr + .first() + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let data_type_str = arr + .get(1) + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let nullable = arr + .get(2) + .and_then(|v| v.as_str()) + .map(|s| s.eq_ignore_ascii_case("YES")) + .unwrap_or(false); + if !name.is_empty() { + cols.push(TargetColumn { + name, + data_type_str, + nullable, + }); + } + } + cols +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::connectors::sinks::snowflake::client::QueryResult; + + fn make_result(rows: serde_json::Value) -> QueryResult { + QueryResult { + success: true, + data: Some(rows), + query_id: "test".to_string(), + message: String::new(), + } + } + + #[test] + fn parse_rows_empty_data() { + let r = QueryResult { + success: true, + data: None, + query_id: "test".to_string(), + message: String::new(), + }; + assert!(parse_information_schema_rows(&r).is_empty()); + } + + #[test] + fn parse_rows_typical() { + let r = make_result(serde_json::json!([ + ["ID", "NUMBER", "NO"], + ["NAME", "VARCHAR", "YES"], + ["CREATED_AT", "TIMESTAMP_TZ", "NO"] + ])); + let cols = parse_information_schema_rows(&r); + assert_eq!(cols.len(), 3); + assert_eq!(cols[0].name, "ID"); + assert_eq!(cols[0].data_type_str, "NUMBER"); + assert!(!cols[0].nullable); + assert_eq!(cols[1].name, "NAME"); + assert!(cols[1].nullable); + assert_eq!(cols[2].name, "CREATED_AT"); + assert!(!cols[2].nullable); + } + + #[test] + fn parse_rows_skips_empty_names() { + let r = make_result(serde_json::json!([ + ["", "NUMBER", "NO"], + ["VALID", "VARCHAR", "YES"] + ])); + let cols = parse_information_schema_rows(&r); + assert_eq!(cols.len(), 1); + assert_eq!(cols[0].name, "VALID"); + } + + #[test] + fn parse_rows_handles_partial_rows() { + // Row missing nullable column → defaults to NOT NULL. + let r = make_result(serde_json::json!([["ID", "NUMBER"]])); + let cols = parse_information_schema_rows(&r); + assert_eq!(cols.len(), 1); + assert!(!cols[0].nullable); + } +} From 4721b40044c0fc3017b78a21cdd1abd965d424e4 Mon Sep 17 00:00:00 2001 From: Dario Mazzitelli Date: Tue, 28 Apr 2026 18:07:57 -0300 Subject: [PATCH 4/9] feat: schema_evolution_skipped_total metric MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New counter exposed via GET /api/v1/cdc/metrics to surface the count of SchemaChange events that the sink skipped because the target table didn't satisfy the sink's schema-evolution prerequisite (StarRocks degraded mode when fast_schema_evolution=true is missing). - `SharedState::schema_evolution_skipped: AtomicU64` + accessor - `SinkResult.schema_evolution_skipped: u64` (sink → pipeline) - Pipeline aggregates per-batch counts into the global counter - `MetricsSample.schema_evolution_skipped_total` populated by the background sampler each second - StarRocks sink emits the count from the degraded-mode WARN path - Documented in docs/configuration.md 143/143 tests passing; clippy clean. --- docs/configuration.md | 15 +++++++++++++++ src/connectors/sinks/postgres/mod.rs | 7 ++----- src/connectors/sinks/snowflake/mod.rs | 8 +++----- src/connectors/sinks/starrocks/mod.rs | 15 ++++++--------- src/control/metrics_sampler.rs | 1 + src/control/state.rs | 22 ++++++++++++++++++++++ src/core/traits.rs | 8 +++++++- src/pipeline/mod.rs | 7 ++++++- 8 files changed, 62 insertions(+), 21 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 3f2f177..78076ca 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -66,6 +66,21 @@ every option documented inline. The default location is |---|---|---| | `DBMAZZ_CONTROL_PORT` | `50051` | Port the internal HTTP control plane binds to (health, status, metrics, control). Formerly `GRPC_PORT`; the legacy name is still read for rolling compatibility. | +## Observability + +The HTTP control plane exposes runtime metrics at `GET /api/v1/cdc/metrics`. Notable counters: + +| Field | Description | +|---|---| +| `events_per_second` | Throughput of CDC events processed in the last second. | +| `lag_bytes` | Difference between `current_lsn` and `confirmed_lsn` (PostgreSQL source). | +| `lag_events` | Pending events queued in the in-memory pipeline channel. | +| `replication_lag_ms` | End-to-end lag from source commit timestamp to sink ack. | +| `schema_evolution_skipped_total` | Cumulative count of `SchemaChange` events skipped because the target table doesn't satisfy the sink's schema-evolution prerequisite (e.g. StarRocks `fast_schema_evolution=true` not set). A non-zero value here means the daemon emitted a `WARN: schema change skipped` log somewhere — review the logs for the specific table/column. | +| `total_events_processed` | Cumulative event count since daemon start. | +| `total_batches_sent` | Cumulative batches flushed to sink. | +| `cpu_millicores` | Process CPU usage (1000 = 1 full core). | + ## Logging | Variable | Default | Description | diff --git a/src/connectors/sinks/postgres/mod.rs b/src/connectors/sinks/postgres/mod.rs index 0d582f8..d647004 100644 --- a/src/connectors/sinks/postgres/mod.rs +++ b/src/connectors/sinks/postgres/mod.rs @@ -267,11 +267,7 @@ impl Sink for PostgresSink { async fn write_batch(&mut self, records: Vec) -> Result { if records.is_empty() { - return Ok(SinkResult { - records_written: 0, - bytes_written: 0, - last_position: None, - }); + return Ok(SinkResult::default()); } // Track last position for checkpoint @@ -339,6 +335,7 @@ impl Sink for PostgresSink { records_written, bytes_written, last_position, + schema_evolution_skipped: 0, }) } diff --git a/src/connectors/sinks/snowflake/mod.rs b/src/connectors/sinks/snowflake/mod.rs index 7ae4f9b..041da17 100644 --- a/src/connectors/sinks/snowflake/mod.rs +++ b/src/connectors/sinks/snowflake/mod.rs @@ -377,11 +377,7 @@ impl Sink for SnowflakeSink { async fn write_batch(&mut self, records: Vec) -> Result { if records.is_empty() { - return Ok(SinkResult { - records_written: 0, - bytes_written: 0, - last_position: None, - }); + return Ok(SinkResult::default()); } let _client = self.ensure_client().await?; @@ -461,6 +457,7 @@ impl Sink for SnowflakeSink { records_written: 0, bytes_written: 0, last_position, + schema_evolution_skipped: 0, }); } @@ -496,6 +493,7 @@ impl Sink for SnowflakeSink { records_written: data_count, bytes_written: file_size, last_position, + schema_evolution_skipped: 0, }) } diff --git a/src/connectors/sinks/starrocks/mod.rs b/src/connectors/sinks/starrocks/mod.rs index 4b0ad78..4ddeaff 100644 --- a/src/connectors/sinks/starrocks/mod.rs +++ b/src/connectors/sinks/starrocks/mod.rs @@ -388,11 +388,7 @@ impl Sink for StarRocksSink { async fn write_batch(&mut self, records: Vec) -> Result { if records.is_empty() { - return Ok(SinkResult { - records_written: 0, - bytes_written: 0, - last_position: None, - }); + return Ok(SinkResult::default()); } // ─── Phase 1: schema evolution pre-pass ────────────────────────── @@ -405,6 +401,7 @@ impl Sink for StarRocksSink { // `pipeline::flush_batch`). let snapshot = self.schema_cache.read().await.clone(); let (working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); + let mut schema_evolution_skipped: u64 = 0; for (table, diff) in &pending_diffs { let table_name = table.name.as_str(); @@ -424,10 +421,8 @@ impl Sink for StarRocksSink { })?; } else { // Degraded mode: table doesn't have fast_schema_evolution=true. - // Emit a per-event WARN per added column. The metric counter - // (`schema_evolution_skipped_total`) is wired in section 4 - // of the change spec; until then the WARN log is the - // observability surface. + // Emit a per-column WARN; the pipeline adds the count to + // `schema_evolution_skipped_total` exposed via /metrics. for added in &diff.added { warn!( table = %table_name, @@ -437,6 +432,7 @@ impl Sink for StarRocksSink { New column will NOT be propagated; data writes \ continue without it." ); + schema_evolution_skipped += 1; } } } @@ -496,6 +492,7 @@ impl Sink for StarRocksSink { records_written: total_written as usize, bytes_written: total_bytes, last_position, + schema_evolution_skipped, }) } diff --git a/src/control/metrics_sampler.rs b/src/control/metrics_sampler.rs index 4b38be6..fcd49aa 100644 --- a/src/control/metrics_sampler.rs +++ b/src/control/metrics_sampler.rs @@ -54,6 +54,7 @@ pub async fn run_metrics_sampler(shared: Arc) { total_batches_sent: shared.batches_sent(), cpu_millicores: cpu.cpu_millicores(), replication_lag_ms: shared.replication_lag_ms(), + schema_evolution_skipped_total: shared.schema_evolution_skipped(), }; *shared.latest_metrics.write().await = sample; diff --git a/src/control/state.rs b/src/control/state.rs index 8fb3f57..e81428f 100644 --- a/src/control/state.rs +++ b/src/control/state.rs @@ -54,6 +54,12 @@ pub struct MetricsSample { pub total_batches_sent: u64, pub cpu_millicores: u64, pub replication_lag_ms: u64, + /// Cumulative count of `CdcRecord::SchemaChange` events that the sink + /// could not auto-apply because the target table does not have the + /// per-sink prerequisite (e.g. StarRocks `fast_schema_evolution=true`). + /// A non-zero value here means the operator should review the daemon + /// logs for `WARN: schema change skipped` entries. + pub schema_evolution_skipped_total: u64, } /// Per-table snapshot progress counters. @@ -74,6 +80,8 @@ pub struct SharedState { pub pending_events: AtomicU64, pub events_processed: AtomicU64, pub batches_sent: AtomicU64, + /// Counter for SchemaChange events that the sink couldn't auto-apply. + pub schema_evolution_skipped: AtomicU64, pub shutdown_tx: watch::Sender, pub config: RwLock, // Timestamp of last processed event (to calculate events/sec) @@ -122,6 +130,7 @@ impl SharedState { pending_events: AtomicU64::new(0), events_processed: AtomicU64::new(0), batches_sent: AtomicU64::new(0), + schema_evolution_skipped: AtomicU64::new(0), shutdown_tx, config: RwLock::new(config), last_event_time: RwLock::new(std::time::Instant::now()), @@ -191,6 +200,19 @@ impl SharedState { self.batches_sent.load(Ordering::Relaxed) } + /// Increment the schema-evolution skip counter. Called by sinks when a + /// `SchemaChange` event arrives for a table that doesn't satisfy the + /// sink's schema-evolution prerequisite (StarRocks: missing the + /// `fast_schema_evolution=true` table property). + pub fn increment_schema_evolution_skipped(&self) { + self.schema_evolution_skipped + .fetch_add(1, Ordering::Relaxed); + } + + pub fn schema_evolution_skipped(&self) -> u64 { + self.schema_evolution_skipped.load(Ordering::Relaxed) + } + #[allow(dead_code)] pub fn events_last_second(&self) -> u64 { self.events_last_second.swap(0, Ordering::Relaxed) diff --git a/src/core/traits.rs b/src/core/traits.rs index bed9d24..e0bbf9d 100644 --- a/src/core/traits.rs +++ b/src/core/traits.rs @@ -42,12 +42,18 @@ pub enum StageFormat { } /// Result returned from sink write operations -#[derive(Debug, Clone)] +#[derive(Debug, Clone, Default)] #[allow(dead_code)] pub struct SinkResult { pub records_written: usize, pub bytes_written: u64, pub last_position: Option, + /// Number of `CdcRecord::SchemaChange` events that the sink could not + /// auto-apply during this batch (e.g. StarRocks degraded mode where + /// the target table lacks `fast_schema_evolution=true`). The pipeline + /// adds this to the global `schema_evolution_skipped_total` counter + /// surfaced in `/api/v1/cdc/metrics`. + pub schema_evolution_skipped: u64, } /// Schema of a source table — provided to sinks during setup so they can diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs index dcee601..873f073 100644 --- a/src/pipeline/mod.rs +++ b/src/pipeline/mod.rs @@ -133,10 +133,15 @@ impl Pipeline { let record_count = records.len(); match self.sink.write_batch(records).await { - Ok(_result) => { + Ok(result) => { // Update metric for batches sent if let Some(state) = &self.shared_state { state.increment_batches(); + // Aggregate any schema-evolution skips from this batch + // into the global counter exposed via /api/v1/cdc/metrics. + for _ in 0..result.schema_evolution_skipped { + state.increment_schema_evolution_skipped(); + } // Calculate end-to-end replication lag if self.last_commit_timestamp_us > 0 { From 452a86b1f1fd46d932459bbca421eeb12a688625 Mon Sep 17 00:00:00 2001 From: Dario Mazzitelli Date: Tue, 28 Apr 2026 18:14:56 -0300 Subject: [PATCH 5/9] docs: schema evolution for StarRocks + Snowflake MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit User-facing: - README.md: StarRocks entry now reflects "3.2+" + fast_schema_evolution - docs/configuration.md: new "Sink-specific requirements" section documenting per-sink prerequisites; observability section explains the new schema_evolution_skipped_total counter Internal: - internal-docs/sinks/starrocks.md: full schema evolution section covering hard requirements, ADD/DROP/MODIFY behavior, degraded mode, and PK-table limitation - internal-docs/sinks/snowflake.md: full schema evolution section with BEGIN/COMMIT semantics, source_schemas refresh, recovery flow - internal-docs/sr-sf-schema-evolution.md (new): cross-sink design notes mirroring pg-sink-schema-evolution.md — policy rationale, architecture, why no _schema_tracking for SR/SF, atomicity per sink, operator recovery flow, observability, out-of-scope items CHANGELOG.md: comprehensive [Unreleased] entry under Added/Changed/Fixed. Cargo.toml: 2.1.0 → 2.2.0 (MINOR — backward-compatible user-visible feature). Cargo.lock regenerated. --- CHANGELOG.md | 57 +++++++++++++++++++++++++++++++++++++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- README.md | 4 +-- docs/configuration.md | 32 ++++++++++++++++++++++++ 5 files changed, 93 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef45fe5..89a5f41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,63 @@ All notable changes to dbmazz will be documented here. ## [Unreleased] +### Added + +- **Schema evolution for the StarRocks and Snowflake sinks.** Source-side + `ALTER TABLE ADD COLUMN` is now propagated automatically to the target table + in both sinks, bringing them to parity with the Postgres sink (which gained + this in v1.7.0). The conservative policy is shared across all three sinks: + ADD applies, DROP/MODIFY/RENAME log a warning and require operator + intervention via the snapshot trigger. Closes the silent data-loss window + where new source columns were dropped by Stream Load (StarRocks) or skipped + by the MERGE projection (Snowflake). +- **Shared `compute_schema_evolution_plan` module** at + `src/connectors/sinks/schema_evolution.rs` consumed by all three sinks. The + per-sink dialect-specific DDL lives in + `/schema_evolution.rs` modules. +- **`schema_evolution_skipped_total` metric** exposed at + `GET /api/v1/cdc/metrics`. Cumulative count of `SchemaChange` events the + sink could not auto-apply because the target table doesn't satisfy the + sink's prerequisite (StarRocks degraded mode). Non-zero values indicate + the daemon emitted `WARN: schema change skipped` log entries that the + operator should review. + +### Changed + +- **StarRocks sink: server version 3.2.0 is now a hard requirement.** The + daemon validates `current_version()` at setup and refuses to start against + older clusters. Older versions don't support `fast_schema_evolution`, which + is necessary for non-blocking ALTER application on the runtime path. +- **StarRocks sink: per-table `fast_schema_evolution=true` is recommended.** + Tables without the property continue to operate (degraded mode) but skip + schema evolution with a loud `WARN` per affected table at setup and per + skipped event at runtime. To enable schema evolution on an existing table, + recreate it via CTAS — the property is creation-only in StarRocks. +- **Snowflake sink: `ALTER TABLE` privilege on the target schema is now + required.** Implicitly validated at setup via the existing audit-column + ALTER. Runtime ALTER failures halt the pipeline with the Snowflake error + surfaced verbatim in `/api/v1/health` `error_detail`. +- **Snowflake sink: `source_schemas` is now shared between the writer and the + normalizer** via `Arc>>`. After a successful + schema-evolution batch, the writer takes a write lock and updates the + schema; the normalizer takes a read lock at the start of each drain cycle + so the MERGE generator projects post-evolution columns. Replaces the + previous frozen snapshot captured at setup time. +- **`SinkResult` struct gained a `schema_evolution_skipped: u64` field.** The + pipeline aggregates per-batch skip counts into the global metric. + +### Fixed + +- **Silent data loss when a source table gained a new column mid-stream + (StarRocks and Snowflake sinks).** Previously, `CdcRecord::SchemaChange` + events fell into a no-op `match` arm in both sinks (commits `c131f0d7` for + StarRocks, `685edfa9` for Snowflake). New columns flowed through to the + data-write phase but were filtered silently by Stream Load + (`max_filter_ratio`) or skipped by the MERGE projection + (`_DATA:"col"::TYPE`). This was scoped out of the v1.7.0 PR + (`internal-docs/pg-sink-schema-evolution-solution.md` §3 Non-goals); + this change closes that deuda. + ## [2.1.0] - 2026-04-23 ### Changed diff --git a/Cargo.lock b/Cargo.lock index 63edc84..1993a56 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -913,7 +913,7 @@ dependencies = [ [[package]] name = "dbmazz" -version = "2.1.0" +version = "2.2.0" dependencies = [ "anyhow", "arrow", diff --git a/Cargo.toml b/Cargo.toml index 2baf43b..34f47c2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dbmazz" -version = "2.1.0" +version = "2.2.0" edition = "2021" license = "Elastic-2.0" # Minimum Supported Rust Version. diff --git a/README.md b/README.md index 2648d03..c7e18d0 100644 --- a/README.md +++ b/README.md @@ -106,9 +106,9 @@ The CLI runs on Linux and macOS (`amd64` and `arm64`). | Source | Sink | Status | Notes | |---|---|:---:|---| -| PostgreSQL 12+ | **StarRocks** | ✅ Stable | JSON Stream Load, partial-update for TOAST columns, audit columns auto-managed | +| PostgreSQL 12+ | **StarRocks 3.2+** | ✅ Stable | JSON Stream Load, partial-update for TOAST columns, audit columns auto-managed, schema evolution requires per-table `fast_schema_evolution=true` | | PostgreSQL 12+ | **PostgreSQL 15+** | ✅ Stable | Binary `COPY` → raw table → `MERGE` normalizer; supports hard delete | -| PostgreSQL 12+ | **Snowflake** | ✅ Stable | Parquet → PUT (stage) → `COPY INTO` → background `MERGE`; JWT key-pair auth supported | +| PostgreSQL 12+ | **Snowflake** | ✅ Stable | Parquet → PUT (stage) → `COPY INTO` → background `MERGE`; JWT key-pair auth supported; requires `ALTER TABLE` privilege on target schema | | PostgreSQL 12+ | S3 / Iceberg | 🚧 Roadmap | Tracked in [issues](https://github.com/ez-cdc/dbmazz/issues) | | MySQL | * | 🚧 Roadmap | The source layer is generic; PostgreSQL is the only implementation today | diff --git a/docs/configuration.md b/docs/configuration.md index 78076ca..c6d26a3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -66,6 +66,38 @@ every option documented inline. The default location is |---|---|---| | `DBMAZZ_CONTROL_PORT` | `50051` | Port the internal HTTP control plane binds to (health, status, metrics, control). Formerly `GRPC_PORT`; the legacy name is still read for rolling compatibility. | +## Sink-specific requirements + +Each sink has its own server-side prerequisites that the operator must satisfy +**before** starting dbmazz. The daemon validates these at setup time and fails +loud with an actionable error message if they are missing. + +### StarRocks + +| Requirement | Why | How to satisfy | +|---|---|---| +| Server version ≥ 3.2.0 | Older versions do not support `fast_schema_evolution`; runtime ALTER would be asynchronous and slow | Upgrade your StarRocks cluster | +| Target tables created by the operator | dbmazz does not create tables (different table types, distribution keys, partitions are operator decisions) | `CREATE TABLE ... PROPERTIES('fast_schema_evolution' = 'true')` ahead of time | +| Per-table `fast_schema_evolution=true` (recommended) | Without it, schema evolution operates in **degraded mode**: dbmazz arranca, logs a loud `WARN` per affected table, and skips ALTER for that table on every `SchemaChange` event. The daemon does not fail, but new columns added in source are NOT propagated. | At table creation: include `PROPERTIES('fast_schema_evolution' = 'true')`. The property is creation-only — to add it to an existing table, recreate via CTAS. | +| MySQL protocol port (default 9030) | DDL operations (audit columns, schema evolution) flow through the MySQL protocol | Open the port in your network | + +### Snowflake + +| Requirement | Why | How to satisfy | +|---|---|---| +| `ALTER TABLE` privilege on target schema | dbmazz applies `ALTER TABLE ADD COLUMN` for audit columns at setup and for new source columns at runtime | `GRANT ALTER ON ALL TABLES IN SCHEMA . TO ROLE ` (or use a role with OWNERSHIP) | +| Warehouse + role + database configured via env vars | dbmazz uses these for COPY INTO / MERGE | See `SINK_SNOWFLAKE_*` env vars above | +| Target tables created by the operator | dbmazz does not create tables; CLUSTER BY, transient/permanent, and other Snowflake-specific decisions are operator-owned | `CREATE TABLE ...` ahead of time | +| Key-pair JWT auth (recommended over password) | Lower auth-related rotation overhead; `SINK_SNOWFLAKE_PRIVATE_KEY_PATH` env var | See [Snowflake key-pair auth docs](https://docs.snowflake.com/en/user-guide/key-pair-auth) | + +### PostgreSQL (sink) + +| Requirement | Why | How to satisfy | +|---|---|---| +| PostgreSQL 15+ | dbmazz uses `MERGE` (added in PG 15) | Upgrade | +| `CREATE` privilege on target database | dbmazz creates `_dbmazz` schema, raw table, metadata, schema-tracking, and target tables | `GRANT CREATE ON DATABASE TO ` | +| (Existing PG sink behavior) target tables created by dbmazz | The PG sink **does** create target tables if they don't exist (legacy behavior; not symmetric with SR/SF) | No action needed | + ## Observability The HTTP control plane exposes runtime metrics at `GET /api/v1/cdc/metrics`. Notable counters: From a201674e819ae054a6aa4fada2e8fe9237cd100c Mon Sep 17 00:00:00 2001 From: Dario Mazzitelli Date: Tue, 28 Apr 2026 18:18:54 -0300 Subject: [PATCH 6/9] test: add hermetic unit tests for StarRocks schema evolution MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tests that don't require a live MySQL pool — exercise the pre-network paths (validation, fast-path early returns, internal cache state): - apply_diff with empty SchemaDiff returns Ok without contacting the server (Pool::new is lazy) - is_schema_evolution_enabled defaults to false (degraded mode) and correctly reflects manual HashSet insertion - apply_diff rejects SQL-injection-shaped table names at validation time, before any DB call Snowflake hermetic coverage stays at the pure-function level (parse_information_schema_rows); full apply_diff round-trips require a live SnowflakeClient and are covered by the ez-cdc-cli verify suite. 147/147 tests passing; clippy + fmt clean. --- src/connectors/sinks/schema_evolution.rs | 5 +- .../sinks/snowflake/schema_evolution.rs | 20 ++- .../sinks/starrocks/schema_evolution.rs | 129 ++++++++++++++---- 3 files changed, 121 insertions(+), 33 deletions(-) diff --git a/src/connectors/sinks/schema_evolution.rs b/src/connectors/sinks/schema_evolution.rs index 6de8190..94b89af 100644 --- a/src/connectors/sinks/schema_evolution.rs +++ b/src/connectors/sinks/schema_evolution.rs @@ -257,10 +257,7 @@ pub fn compute_schema_evolution_plan( } if !diff.added.is_empty() { - let src_schema = table - .schema - .clone() - .unwrap_or_else(|| "public".to_string()); + let src_schema = table.schema.clone().unwrap_or_else(|| "public".to_string()); let qn = table.qualified_name(); // Ensure the table exists in `working` before pushing columns. diff --git a/src/connectors/sinks/snowflake/schema_evolution.rs b/src/connectors/sinks/snowflake/schema_evolution.rs index 9b30a53..5fe4140 100644 --- a/src/connectors/sinks/snowflake/schema_evolution.rs +++ b/src/connectors/sinks/snowflake/schema_evolution.rs @@ -141,12 +141,14 @@ impl SnowflakeSchemaEvolution { added_count = diff.added.len(), "snowflake_sink: reconcile_on_startup applying ALTERs" ); - self.apply_diff(&source.name, &diff).await.with_context(|| { - format!( - "snowflake_sink: reconcile_on_startup failed for table {}", - source.name - ) - })?; + self.apply_diff(&source.name, &diff) + .await + .with_context(|| { + format!( + "snowflake_sink: reconcile_on_startup failed for table {}", + source.name + ) + })?; } Ok(()) @@ -333,6 +335,12 @@ mod tests { } } + // Note: full `SnowflakeSchemaEvolution::apply_diff` tests require a + // live `SnowflakeClient` (which only constructs via a real `connect` + // call). The verify suite in ez-cdc-cli covers those integration tests + // end-to-end. Here we cover only the pure helpers that don't require + // a client. + #[test] fn parse_rows_empty_data() { let r = QueryResult { diff --git a/src/connectors/sinks/starrocks/schema_evolution.rs b/src/connectors/sinks/starrocks/schema_evolution.rs index 1515838..97e9912 100644 --- a/src/connectors/sinks/starrocks/schema_evolution.rs +++ b/src/connectors/sinks/starrocks/schema_evolution.rs @@ -120,9 +120,8 @@ impl StarRocksSchemaEvolution { .await .map_err(|e| anyhow!("Failed to query StarRocks server version: {}", e))?; - let version_str = raw_version.ok_or_else(|| { - anyhow!("StarRocks `SELECT current_version()` returned no row") - })?; + let version_str = raw_version + .ok_or_else(|| anyhow!("StarRocks `SELECT current_version()` returned no row"))?; let (major, minor) = parse_server_version(&version_str).ok_or_else(|| { anyhow!( @@ -164,10 +163,7 @@ impl StarRocksSchemaEvolution { /// for a single table degrades that table to disabled and continues /// (rather than failing setup entirely). The catalog query itself /// failing for a known reason (permissions, missing table) bubbles up. - pub async fn detect_fast_schema_evolution_per_table( - &self, - tables: &[String], - ) -> Result<()> { + pub async fn detect_fast_schema_evolution_per_table(&self, tables: &[String]) -> Result<()> { let mut conn = self.get_conn().await?; let mut enabled = self.schema_evolution_enabled.write().await; @@ -252,14 +248,15 @@ impl StarRocksSchemaEvolution { let mut diff = SchemaDiff::default(); for (i, src_col) in source.columns.iter().enumerate() { if !target_names.contains(&src_col.name.to_lowercase()) { - diff.added.push(crate::connectors::sinks::schema_evolution::AddedColumn { - name: src_col.name.clone(), - data_type: src_col.data_type.clone(), - nullable: true, // always nullable on reconcile - #[allow(clippy::cast_possible_wrap)] - ordinal: i as i32, - pg_type_id: Some(src_col.pg_type_id), - }); + diff.added + .push(crate::connectors::sinks::schema_evolution::AddedColumn { + name: src_col.name.clone(), + data_type: src_col.data_type.clone(), + nullable: true, // always nullable on reconcile + #[allow(clippy::cast_possible_wrap)] + ordinal: i as i32, + pg_type_id: Some(src_col.pg_type_id), + }); } } @@ -272,12 +269,14 @@ impl StarRocksSchemaEvolution { added_count = diff.added.len(), "starrocks_sink: reconcile_on_startup applying ALTERs" ); - self.apply_diff(&source.name, &diff).await.with_context(|| { - format!( - "starrocks_sink: reconcile_on_startup failed for table {}", - source.name - ) - })?; + self.apply_diff(&source.name, &diff) + .await + .with_context(|| { + format!( + "starrocks_sink: reconcile_on_startup failed for table {}", + source.name + ) + })?; } Ok(()) @@ -417,14 +416,23 @@ impl StarRocksSchemaEvolution { (&self.database, table_name, column_name), ) .await - .map_err(|e| anyhow!("Failed to verify ALTER for {}.{}: {}", table_name, column_name, e))?; + .map_err(|e| { + anyhow!( + "Failed to verify ALTER for {}.{}: {}", + table_name, + column_name, + e + ) + })?; if exists.is_none() { return Err(anyhow!( "starrocks_sink: ALTER TABLE {}.{} ADD COLUMN {} reported success \ but the column did not appear in INFORMATION_SCHEMA. \ Check fast_schema_evolution=true is set on the table.", - self.database, table_name, column_name + self.database, + table_name, + column_name )); } Ok(()) @@ -509,6 +517,81 @@ fn properties_contain_fast_schema_evolution(properties: &str) -> bool { #[cfg(test)] mod tests { use super::*; + use crate::connectors::sinks::schema_evolution::AddedColumn; + use crate::core::record::DataType; + + fn test_config() -> StarRocksSinkConfig { + StarRocksSinkConfig { + http_url: "http://localhost:9999".to_string(), + mysql_port: 9999, + database: "testdb".to_string(), + user: "root".to_string(), + password: String::new(), + timeout_secs: 30, + max_filter_ratio: 0.2, + } + } + + #[tokio::test] + async fn apply_diff_empty_returns_ok_without_connecting() { + // Pool::new doesn't establish a connection; only the first + // get_conn() does. apply_diff with an empty diff short-circuits + // before that, so this test verifies the fast path is genuinely + // pure (no network). + let se = StarRocksSchemaEvolution::new(&test_config()).unwrap(); + let diff = SchemaDiff::default(); + let result = se.apply_diff("orders", &diff).await; + assert!( + result.is_ok(), + "empty diff must return Ok without contacting the server" + ); + } + + #[tokio::test] + async fn is_schema_evolution_enabled_defaults_to_false() { + let se = StarRocksSchemaEvolution::new(&test_config()).unwrap(); + assert!( + !se.is_schema_evolution_enabled("orders").await, + "tables not added to the enabled set must default to false (degraded mode)" + ); + } + + #[tokio::test] + async fn is_schema_evolution_enabled_true_after_manual_insert() { + // Manually populate the set to verify the read-side logic without + // running the catalog query. + let se = StarRocksSchemaEvolution::new(&test_config()).unwrap(); + se.schema_evolution_enabled + .write() + .await + .insert("orders".to_string()); + assert!(se.is_schema_evolution_enabled("orders").await); + assert!(!se.is_schema_evolution_enabled("other").await); + } + + #[tokio::test] + async fn apply_diff_validates_table_name() { + let se = StarRocksSchemaEvolution::new(&test_config()).unwrap(); + let mut diff = SchemaDiff::default(); + diff.added.push(AddedColumn { + name: "tax".to_string(), + data_type: DataType::Int32, + nullable: true, + ordinal: 1, + pg_type_id: Some(23), + }); + // Table name with semicolon — must be rejected before any DB call. + let result = se.apply_diff("orders; DROP TABLE", &diff).await; + assert!( + result.is_err(), + "invalid table name must be rejected at validation" + ); + let err = result.unwrap_err().to_string(); + assert!( + err.contains("Invalid table name") || err.contains("SQL injection"), + "error must reference table-name validation; got: {err}" + ); + } #[test] fn parse_version_simple() { From 4e9b20f9ea2f8c9bd6286ec64fc093a28ee106e5 Mon Sep 17 00:00:00 2001 From: Dario Mazzitelli Date: Wed, 29 Apr 2026 00:57:02 -0300 Subject: [PATCH 7/9] fix(starrocks): detect fast_schema_evolution in JSON-format properties MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `INFORMATION_SCHEMA.TABLES_CONFIG.PROPERTIES` returns table properties as a JSON object (e.g. `{"fast_schema_evolution":"true",...}`) — NOT in the SHOW CREATE TABLE form (`"fast_schema_evolution" = "true"`). The original matcher only accepted the SHOW CREATE form, which made the daemon detect every existing table as flag-disabled and enter degraded mode regardless. Discovered while validating end-to-end against the demo stack: target tables had the property set, SHOW CREATE TABLE confirmed it, but the runtime detection logged `WARN: schema evolution DISABLED` for every table. Root cause: TABLES_CONFIG output is JSON, with `:` separator and no spaces. Now matches both: - `"fast_schema_evolution" = "true"` (SHOW CREATE TABLE) - `"fast_schema_evolution":"true"` (INFORMATION_SCHEMA.TABLES_CONFIG) New regression test `fast_schema_evolution_property_detection_json_format` exercises the actual production format (and confirms `"...":"false"` is correctly rejected). 148/148 tests pass; clippy clean. --- .../sinks/starrocks/schema_evolution.rs | 44 +++++++++++++++---- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/src/connectors/sinks/starrocks/schema_evolution.rs b/src/connectors/sinks/starrocks/schema_evolution.rs index 97e9912..69baa11 100644 --- a/src/connectors/sinks/starrocks/schema_evolution.rs +++ b/src/connectors/sinks/starrocks/schema_evolution.rs @@ -496,18 +496,25 @@ fn parse_server_version(s: &str) -> Option<(u32, u32)> { Some((major, minor)) } -/// Check whether a `PROPERTIES` string from `INFORMATION_SCHEMA.TABLES_CONFIG` -/// contains `"fast_schema_evolution" = "true"`. Tolerates whitespace and -/// case variations. +/// Check whether a `PROPERTIES` string contains +/// `"fast_schema_evolution" = "true"` (or the JSON equivalent). +/// +/// StarRocks renders `PROPERTIES` in two different formats depending on the +/// source: +/// +/// - `SHOW CREATE TABLE` returns the canonical key-value form: +/// `"fast_schema_evolution" = "true"` (with spaces and `=`). +/// - `INFORMATION_SCHEMA.TABLES_CONFIG.PROPERTIES` returns a JSON object: +/// `"fast_schema_evolution":"true"` (no spaces, `:` separator). +/// +/// We accept both. Whitespace and case are normalised before matching. fn properties_contain_fast_schema_evolution(properties: &str) -> bool { - // Lowercase the whole string and look for the canonical key=true pattern. - // Tolerates `"fast_schema_evolution"="true"` (no spaces) and the - // canonical SHOW CREATE TABLE rendering with spaces. let lower = properties.to_ascii_lowercase(); - // Strip whitespace so `"fast_schema_evolution" = "true"` and - // `"fast_schema_evolution"="true"` match the same needle. let stripped: String = lower.chars().filter(|c| !c.is_whitespace()).collect(); + // SHOW CREATE TABLE form: "fast_schema_evolution" = "true" + // INFORMATION_SCHEMA.TABLES_CONFIG (JSON) form: "fast_schema_evolution":"true" stripped.contains("\"fast_schema_evolution\"=\"true\"") + || stripped.contains("\"fast_schema_evolution\":\"true\"") } // --------------------------------------------------------------------------- @@ -641,6 +648,27 @@ mod tests { )); } + #[test] + fn fast_schema_evolution_property_detection_json_format() { + // INFORMATION_SCHEMA.TABLES_CONFIG.PROPERTIES returns JSON, not the + // SHOW CREATE TABLE rendering — this is the format actually used in + // production. Regression test for a real bug found running against + // StarRocks 3.3.22 where `INFORMATION_SCHEMA.TABLES_CONFIG` returned + // `"fast_schema_evolution":"true"` (JSON, colon) but the matcher + // only accepted the `=` form. + assert!(properties_contain_fast_schema_evolution( + r#"{"compression":"LZ4","fast_schema_evolution":"true","replication_num":"1"}"# + )); + // Bare key-value JSON without surrounding object. + assert!(properties_contain_fast_schema_evolution( + r#""fast_schema_evolution":"true""# + )); + // JSON form set to false → must NOT detect. + assert!(!properties_contain_fast_schema_evolution( + r#"{"compression":"LZ4","fast_schema_evolution":"false"}"# + )); + } + #[test] fn fast_schema_evolution_property_absent() { assert!(!properties_contain_fast_schema_evolution("")); From 4c75b9c3c8b06fa6c2e109f2c09bcdb1af2e88c5 Mon Sep 17 00:00:00 2001 From: Dario Mazzitelli Date: Wed, 29 Apr 2026 01:22:36 -0300 Subject: [PATCH 8/9] fix(starrocks): pre-check column existence; StarRocks rejects IF NOT EXISTS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit StarRocks parser rejects `ALTER TABLE ADD COLUMN IF NOT EXISTS`: ERROR 1064 (HY000): No viable statement for input 'ADD COLUMN IF'. The original `apply_diff` emitted IF NOT EXISTS as a defensive idempotency guard, but the DDL was never accepted. Discovered when the ez-cdc verify suite hit the reconcile path on a daemon restart against a target whose schema had drifted ahead (D4 had ALTERed `description` into the source). Fix: pre-check `INFORMATION_SCHEMA.COLUMNS` for each candidate column and skip the ALTER if the column already exists. Only then emit the ALTER without IF NOT EXISTS. Same effective semantics, compatible with the StarRocks parser, and idempotent across retries / cold starts where the in-memory cache might be stale. Behaviour unchanged for the happy path (column doesn't exist → ALTER applied → verify_alter_completed confirms). 38/38 StarRocks unit tests still pass. --- .../sinks/starrocks/schema_evolution.rs | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/src/connectors/sinks/starrocks/schema_evolution.rs b/src/connectors/sinks/starrocks/schema_evolution.rs index 69baa11..ac91369 100644 --- a/src/connectors/sinks/starrocks/schema_evolution.rs +++ b/src/connectors/sinks/starrocks/schema_evolution.rs @@ -290,6 +290,16 @@ impl StarRocksSchemaEvolution { /// for each added column, verify each via `INFORMATION_SCHEMA`, and /// refresh the target_columns cache once at the end. /// + /// # Idempotency + /// + /// StarRocks does **not** support `IF NOT EXISTS` in `ALTER TABLE ADD COLUMN` + /// (parser rejects it: `No viable statement for input 'ADD COLUMN IF'.`). + /// Idempotency is therefore implemented as a pre-check against + /// `INFORMATION_SCHEMA.COLUMNS`: if the column already exists on the + /// target, the ALTER is skipped with an info log. This makes + /// `apply_diff` safe to retry after a partial failure or to re-run + /// across daemon restarts when the in-memory cache is stale. + /// /// Caller MUST check `is_schema_evolution_enabled(table)` first; this /// function unconditionally applies the diff. Tables without the flag /// should be filtered out at the call site. @@ -309,12 +319,38 @@ impl StarRocksSchemaEvolution { validate_sql_identifier(&added.name) .map_err(|e| anyhow!("Invalid column name '{}': {}", added.name, e))?; + // Pre-check idempotency — StarRocks doesn't accept IF NOT EXISTS + // on ADD COLUMN, so we ask INFORMATION_SCHEMA whether the column + // is already there before issuing the DDL. + let column_exists: Option = conn + .exec_first( + "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?", + (&self.database, table_name, &added.name), + ) + .await + .with_context(|| { + format!( + "starrocks_sink: failed to pre-check column existence for {}.{}.{}", + self.database, table_name, added.name + ) + })?; + + if column_exists.is_some() { + info!( + table = %table_name, + column = %added.name, + "starrocks_sink: ADD COLUMN skipped — column already exists in target" + ); + continue; + } + let starrocks_type = self.type_mapper.to_starrocks_type(&added.data_type); // Backtick-quoted column name to handle reserved words; database // and table identifiers are validated above so direct interpolation // is safe (no user-controlled SQL injection vector). let sql = format!( - "ALTER TABLE `{}`.`{}` ADD COLUMN IF NOT EXISTS `{}` {}", + "ALTER TABLE `{}`.`{}` ADD COLUMN `{}` {}", self.database, table_name, added.name, starrocks_type ); conn.query_drop(&sql).await.with_context(|| { From 08dbfe8351e7d4c9085be921be661548410545b6 Mon Sep 17 00:00:00 2001 From: Dario Mazzitelli Date: Wed, 29 Apr 2026 01:30:31 -0300 Subject: [PATCH 9/9] chore: drop excessive comments across schema-evolution modules Lean on identifier names and shape; keep only WHY-comments where the reader can't otherwise tell (e.g. the StarRocks IF NOT EXISTS quirk, the Snowflake INFORMATION_SCHEMA uppercase normalisation, the OID-vs- DataType type-change check). Doc comments on public APIs preserved. Net: -103 lines, behaviour unchanged, 148/148 tests pass. --- src/connectors/sinks/schema_evolution.rs | 18 +--- src/connectors/sinks/snowflake/mod.rs | 27 ++---- .../sinks/snowflake/schema_evolution.rs | 18 +--- src/connectors/sinks/starrocks/mod.rs | 32 ++----- .../sinks/starrocks/schema_evolution.rs | 86 ++++--------------- 5 files changed, 39 insertions(+), 142 deletions(-) diff --git a/src/connectors/sinks/schema_evolution.rs b/src/connectors/sinks/schema_evolution.rs index 94b89af..678178c 100644 --- a/src/connectors/sinks/schema_evolution.rs +++ b/src/connectors/sinks/schema_evolution.rs @@ -133,7 +133,6 @@ pub fn diff_against_cache( match cache.get(&qn) { None => { - // Cold-start: table not in cache at all — every new col is Added. for (i, col) in new_cols.iter().enumerate() { diff.added.push(AddedColumn { name: col.name.clone(), @@ -158,7 +157,6 @@ pub fn diff_against_cache( for col in new_cols { match cached_by_name.get(col.name.as_str()) { None => { - // Column is new. diff.added.push(AddedColumn { name: col.name.clone(), data_type: col.data_type.clone(), @@ -169,10 +167,8 @@ pub fn diff_against_cache( next_ordinal += 1; } Some(cached_col) => { - // Column exists — check for type change. - // DataType comparison covers the generic case. - // OID comparison catches PG-specific precision changes - // when both sides have a real (non-zero) OID. + // OID check catches PG NUMERIC precision changes that + // map to the same coarse DataType::Decimal bucket. let dt_changed = cached_col.data_type != col.data_type; let oid_changed = match (cached_col.pg_type_id, col.pg_type_id) { (cached, Some(new)) if cached != 0 => cached != new, @@ -195,7 +191,6 @@ pub fn diff_against_cache( } } - // Check for dropped columns (present in cache, absent from new). for cached_col in &cached_schema.columns { if !new_by_name.contains_key(cached_col.name.as_str()) { diff.dropped.push(cached_col.name.clone()); @@ -236,7 +231,6 @@ pub fn compute_schema_evolution_plan( if let CdcRecord::SchemaChange { table, columns, .. } = record { let diff = diff_against_cache(&working, table, columns); - // Log type changes (no DDL — operator intervention required). for tc in &diff.type_changed { error!( table = %table.qualified_name(), @@ -247,7 +241,6 @@ pub fn compute_schema_evolution_plan( ); } - // Log drops (no DDL — target keeps dead column). for dropped in &diff.dropped { warn!( table = %table.qualified_name(), @@ -260,7 +253,6 @@ pub fn compute_schema_evolution_plan( let src_schema = table.schema.clone().unwrap_or_else(|| "public".to_string()); let qn = table.qualified_name(); - // Ensure the table exists in `working` before pushing columns. let entry = working.entry(qn).or_insert_with(|| SourceTableSchema { schema: src_schema, name: table.name.clone(), @@ -268,15 +260,13 @@ pub fn compute_schema_evolution_plan( primary_keys: Vec::new(), }); - // Advance working map so subsequent SchemaChange events for - // the same table see these columns and don't re-emit them. + // Fold added columns into `working` so a second SchemaChange + // for the same table in this batch doesn't re-emit them. for added in &diff.added { entry.columns.push(SourceColumn { name: added.name.clone(), data_type: added.data_type.clone(), nullable: added.nullable, - // Carry the OID through if the source provided one. - // Sinks that don't need OIDs ignore this field. pg_type_id: added.pg_type_id.unwrap_or(0), }); } diff --git a/src/connectors/sinks/snowflake/mod.rs b/src/connectors/sinks/snowflake/mod.rs index 041da17..3ace5b4 100644 --- a/src/connectors/sinks/snowflake/mod.rs +++ b/src/connectors/sinks/snowflake/mod.rs @@ -326,7 +326,6 @@ impl Sink for SnowflakeSink { .await .context("Snowflake setup failed")?; - // Build the schema_evolution helper (now that client is connected). let schema_evolution = Arc::new(SnowflakeSchemaEvolution::new( client.clone(), self.config.database.clone(), @@ -339,8 +338,8 @@ impl Sink for SnowflakeSink { .context("Snowflake reconcile_target_schema failed")?; self.schema_evolution = Some(schema_evolution); - // Seed the shared schema state so the diff in write_batch() has a - // real baseline (avoiding cold-start re-emission of every column). + // Seed both shared maps so write_batch() and the normalizer have + // a baseline; avoids cold-start re-emit on the first SchemaChange. { let mut state = self.schema_state.write().await; for src in source_schemas { @@ -352,8 +351,6 @@ impl Sink for SnowflakeSink { *tables = source_schemas.to_vec(); } - // Spawn normalizer (Primary mode only). Pass the shared - // `table_schemas` so it sees post-evolution schema on every drain. if self.mode == SinkMode::Primary { let normalizer_config = normalizer::NormalizerConfig { client_config: self.config.clone(), @@ -382,15 +379,8 @@ impl Sink for SnowflakeSink { let _client = self.ensure_client().await?; - // ─── Phase 1: schema evolution pre-pass ────────────────────────── - // Walk the batch's `SchemaChange` events, compute per-table diffs, - // apply ALTERs inside transactions. The shared - // `compute_schema_evolution_plan` already logs DROP/MODIFY/RENAME - // as warn-only; only ADD diffs reach `pending_diffs`. - // - // Halt-loud on ALTER failure: bubbling the error up causes the - // pipeline to set CdcState::Stopped via the existing pipeline - // error path. + // Phase 1 — schema evolution pre-pass. Bubbling an error here + // halts the pipeline loud (CdcState::Stopped via flush_batch). let snapshot = self.schema_state.read().await.clone(); let (working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); @@ -413,8 +403,6 @@ impl Sink for SnowflakeSink { })?; } - // Update the shared cache so the next normalizer drain sees - // the post-evolution columns when generating MERGE. { let mut state = self.schema_state.write().await; *state = working; @@ -426,14 +414,13 @@ impl Sink for SnowflakeSink { *tables = state_snapshot.into_values().collect(); } } else { - // Even with no pending diffs, the working map may have absorbed - // a no-op SchemaChange (e.g. column ordering reshuffle). Update - // anyway to keep state coherent. + // Update even on no-op SchemaChange (e.g. column reorder) to + // keep `working` and the cache coherent. let mut state = self.schema_state.write().await; *state = working; } - // ─── Phase 2: data writes ──────────────────────────────────────── + // Phase 2 — data writes. // Track last position let last_position = records.iter().rev().find_map(|r| match r { diff --git a/src/connectors/sinks/snowflake/schema_evolution.rs b/src/connectors/sinks/snowflake/schema_evolution.rs index 5fe4140..193419e 100644 --- a/src/connectors/sinks/snowflake/schema_evolution.rs +++ b/src/connectors/sinks/snowflake/schema_evolution.rs @@ -100,11 +100,8 @@ impl SnowflakeSchemaEvolution { source_schemas: &[SourceTableSchema], ) -> Result<()> { for source in source_schemas { - // Snowflake convention: identifiers are usually uppercase. The - // setup path creates target tables matching the SOURCE name - // (which is typically lowercase from PG); INFORMATION_SCHEMA on - // Snowflake then reports the unquoted-name normalised UPPERCASE. - // Refresh and use uppercase for the cache key. + // Snowflake unquoted identifiers normalise to UPPERCASE in + // INFORMATION_SCHEMA, so the cache key is uppercase here. let target_name = source.name.to_uppercase(); self.refresh_target_schema_cache(&target_name).await?; @@ -116,7 +113,6 @@ impl SnowflakeSchemaEvolution { .map(|cols| cols.iter().map(|c| c.name.to_uppercase()).collect()) .unwrap_or_default(); - // Build a synthetic SchemaDiff with the missing source columns. let mut diff = SchemaDiff::default(); for (i, src_col) in source.columns.iter().enumerate() { if !target_names.contains(&src_col.name.to_uppercase()) { @@ -177,23 +173,18 @@ impl SnowflakeSchemaEvolution { return Ok(()); } - // Open transaction. If we fail mid-batch, ROLLBACK keeps the target - // in a known state (no partial column adds). self.client .execute("BEGIN TRANSACTION") .await .context("snowflake_sink: failed to BEGIN TRANSACTION for schema evolution")?; - // Best-effort: collect the result of each ALTER inside this scope so - // we always issue a COMMIT or ROLLBACK before returning. + // Inner async block so we always issue COMMIT or ROLLBACK before returning. let result: Result<()> = async { for added in &diff.added { validate_sql_identifier(&added.name) .map_err(|e| anyhow!("Invalid column name '{}': {}", added.name, e))?; let sf_type = self.type_mapper.to_snowflake_type(&added.data_type); - // Snowflake quoted identifiers preserve case. Database/schema - // are validated above; table+column are validated here. let sql = format!( r#"ALTER TABLE "{}"."{}"."{}" ADD COLUMN IF NOT EXISTS "{}" {}"#, self.database.to_uppercase(), @@ -225,7 +216,6 @@ impl SnowflakeSchemaEvolution { .execute("COMMIT") .await .context("snowflake_sink: COMMIT failed after schema evolution ALTERs")?; - // Refresh the in-memory target column cache for this table. self.refresh_target_schema_cache(&table_name.to_uppercase()) .await?; Ok(()) @@ -242,9 +232,7 @@ impl SnowflakeSchemaEvolution { } } - /// Reload the column list for `table_name` from `INFORMATION_SCHEMA.COLUMNS`. pub async fn refresh_target_schema_cache(&self, table_name: &str) -> Result<()> { - // INFORMATION_SCHEMA names are uppercase by Snowflake convention. let database_upper = self.database.to_uppercase(); let schema_upper = self.schema.to_uppercase(); let table_upper = table_name.to_uppercase(); diff --git a/src/connectors/sinks/starrocks/mod.rs b/src/connectors/sinks/starrocks/mod.rs index 4ddeaff..1d6d787 100644 --- a/src/connectors/sinks/starrocks/mod.rs +++ b/src/connectors/sinks/starrocks/mod.rs @@ -359,11 +359,6 @@ impl Sink for StarRocksSink { let tables: Vec = source_schemas.iter().map(|s| s.name.clone()).collect(); sr_setup.run(&tables).await?; - // Schema evolution validation: - // 1. Server version must be ≥ 3.2.0 (hard requirement, fail loud). - // 2. Detect `fast_schema_evolution=true` per table — tables without - // it operate in degraded mode (loud WARN at runtime, ALTERs skipped). - // 3. Reconcile target schema against source for tables with the flag. self.schema_evolution.validate_server_version().await?; self.schema_evolution .detect_fast_schema_evolution_per_table(&tables) @@ -372,9 +367,9 @@ impl Sink for StarRocksSink { .reconcile_target_schema(source_schemas) .await?; - // Seed the schema cache with the introspected source state so the - // diff in write_batch() has a real baseline (avoiding cold-start - // re-emission of every column on the first SchemaChange). + // Seed the cache with the introspected source state so the diff + // in write_batch() has a baseline and doesn't cold-start re-emit + // every column on the first SchemaChange. { let mut cache = self.schema_cache.write().await; for src in source_schemas { @@ -391,14 +386,9 @@ impl Sink for StarRocksSink { return Ok(SinkResult::default()); } - // ─── Phase 1: schema evolution pre-pass ────────────────────────── - // Walk the batch's `SchemaChange` events, compute per-table diffs, - // apply ALTERs on tables with `fast_schema_evolution=true`, and - // emit loud WARN logs for tables without the flag (degraded mode). - // - // Halt-loud on ALTER failure: bubbling the error up causes the - // pipeline to set CdcState::Stopped (existing behaviour in - // `pipeline::flush_batch`). + // Phase 1 — schema evolution pre-pass. Bubbling an error here + // halts the pipeline loud via the existing `pipeline::flush_batch` + // path (CdcState::Stopped). let snapshot = self.schema_cache.read().await.clone(); let (working, pending_diffs) = compute_schema_evolution_plan(&snapshot, &records); let mut schema_evolution_skipped: u64 = 0; @@ -420,9 +410,6 @@ impl Sink for StarRocksSink { ) })?; } else { - // Degraded mode: table doesn't have fast_schema_evolution=true. - // Emit a per-column WARN; the pipeline adds the count to - // `schema_evolution_skipped_total` exposed via /metrics. for added in &diff.added { warn!( table = %table_name, @@ -437,15 +424,14 @@ impl Sink for StarRocksSink { } } - // Update the cache so the next batch sees the post-evolution state - // even for tables in degraded mode (avoids re-emitting the same - // WARN on every batch for the same column). + // Update cache even for degraded-mode tables so the same column + // doesn't trigger the WARN on every subsequent batch. { let mut cache = self.schema_cache.write().await; *cache = working; } - // ─── Phase 2: data writes ──────────────────────────────────────── + // Phase 2 — data writes. // Cache timestamp for entire batch let synced_at = Utc::now().format("%Y-%m-%d %H:%M:%S").to_string(); diff --git a/src/connectors/sinks/starrocks/schema_evolution.rs b/src/connectors/sinks/starrocks/schema_evolution.rs index ac91369..f7cf76d 100644 --- a/src/connectors/sinks/starrocks/schema_evolution.rs +++ b/src/connectors/sinks/starrocks/schema_evolution.rs @@ -77,10 +77,6 @@ pub struct StarRocksSchemaEvolution { } impl StarRocksSchemaEvolution { - /// Creates a new instance with its own MySQL pool. Independent from - /// `StarRocksSetup`'s pool — both can coexist; `mysql_async::Pool` is - /// `Clone` and internally Arc-counted, but we keep the construction - /// site here for self-containment. pub fn new(config: &StarRocksSinkConfig) -> Result { let opts = OptsBuilder::default() .ip_or_hostname(config.hostname()) @@ -103,18 +99,13 @@ impl StarRocksSchemaEvolution { // --------------------------------------------------------------------- /// Validate that the connected StarRocks server is at least version 3.2.0. - /// Fails loud if older — does not arrancar in degraded mode for old - /// versions because `fast_schema_evolution` does not exist there at all. - /// - /// Parses the result of `SELECT current_version()` (StarRocks) which - /// returns a string like `"3.2.4"`, `"3.3.0-rc01"`, or `"3.4.1 8b4e8f9"`. + /// Fails loud if older — `fast_schema_evolution` does not exist before 3.2. pub async fn validate_server_version(&self) -> Result<()> { let mut conn = self.get_conn().await?; - // StarRocks exposes its version via `current_version()`; MySQL-protocol - // layer also accepts `SELECT @@version` but that returns a synthetic - // value that includes a MySQL compat prefix on some builds. Prefer - // `current_version()` for accuracy. + // `@@version` on the MySQL-protocol layer returns a synthetic value + // with a MySQL compat prefix on some builds; `current_version()` + // returns the actual StarRocks version. let raw_version: Option = conn .query_first("SELECT current_version()") .await @@ -154,21 +145,14 @@ impl StarRocksSchemaEvolution { Ok(()) } - /// For each configured table, detect whether `fast_schema_evolution` is - /// enabled. Tables with the property are added to the - /// `schema_evolution_enabled` set; tables without are logged once with - /// an actionable WARN. - /// - /// This is opportunistic — failure to query `INFORMATION_SCHEMA.TABLES_CONFIG` - /// for a single table degrades that table to disabled and continues - /// (rather than failing setup entirely). The catalog query itself - /// failing for a known reason (permissions, missing table) bubbles up. + /// Populate `schema_evolution_enabled` from `INFORMATION_SCHEMA.TABLES_CONFIG`. + /// Per-table query failures degrade the table to disabled (loud WARN); + /// tables present without the property log a WARN with remediation. pub async fn detect_fast_schema_evolution_per_table(&self, tables: &[String]) -> Result<()> { let mut conn = self.get_conn().await?; let mut enabled = self.schema_evolution_enabled.write().await; for table_qualified in tables { - // Strip any schema prefix; StarRocks uses unqualified table names. let table_name = table_qualified .split('.') .next_back() @@ -203,7 +187,6 @@ impl StarRocksSchemaEvolution { PROPERTIES('fast_schema_evolution'='true') (StarRocks 3.2+; \ this property is creation-only and cannot be added via ALTER)." ); - // Not inserted into `enabled` — skip path activates at runtime. } } @@ -228,14 +211,11 @@ impl StarRocksSchemaEvolution { for source in source_schemas { if !enabled.contains(&source.name) { - // Skip tables without the flag — degraded mode covers them. continue; } - // Refresh the target column cache for this table. self.refresh_target_schema_cache(&source.name).await?; - // Build a name set of the current target columns. let target_names: HashSet = self .target_columns .read() @@ -244,7 +224,6 @@ impl StarRocksSchemaEvolution { .map(|cols| cols.iter().map(|c| c.name.to_lowercase()).collect()) .unwrap_or_default(); - // Build a synthetic SchemaDiff with the missing source columns. let mut diff = SchemaDiff::default(); for (i, src_col) in source.columns.iter().enumerate() { if !target_names.contains(&src_col.name.to_lowercase()) { @@ -252,7 +231,7 @@ impl StarRocksSchemaEvolution { .push(crate::connectors::sinks::schema_evolution::AddedColumn { name: src_col.name.clone(), data_type: src_col.data_type.clone(), - nullable: true, // always nullable on reconcile + nullable: true, #[allow(clippy::cast_possible_wrap)] ordinal: i as i32, pg_type_id: Some(src_col.pg_type_id), @@ -319,9 +298,8 @@ impl StarRocksSchemaEvolution { validate_sql_identifier(&added.name) .map_err(|e| anyhow!("Invalid column name '{}': {}", added.name, e))?; - // Pre-check idempotency — StarRocks doesn't accept IF NOT EXISTS - // on ADD COLUMN, so we ask INFORMATION_SCHEMA whether the column - // is already there before issuing the DDL. + // Idempotency pre-check: StarRocks rejects IF NOT EXISTS on + // ADD COLUMN, so we ask INFORMATION_SCHEMA before issuing DDL. let column_exists: Option = conn .exec_first( "SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS @@ -346,9 +324,6 @@ impl StarRocksSchemaEvolution { } let starrocks_type = self.type_mapper.to_starrocks_type(&added.data_type); - // Backtick-quoted column name to handle reserved words; database - // and table identifiers are validated above so direct interpolation - // is safe (no user-controlled SQL injection vector). let sql = format!( "ALTER TABLE `{}`.`{}` ADD COLUMN `{}` {}", self.database, table_name, added.name, starrocks_type @@ -360,10 +335,6 @@ impl StarRocksSchemaEvolution { ) })?; - // Verify the column actually appeared in INFORMATION_SCHEMA. - // With fast_schema_evolution=true this is metadata-only and - // returns within milliseconds; the verify is a defensive sanity - // check rather than a real poll. self.verify_alter_completed(&mut conn, table_name, &added.name) .await?; @@ -381,7 +352,6 @@ impl StarRocksSchemaEvolution { Ok(()) } - /// Returns `true` if the table is in the schema-evolution-enabled set. pub async fn is_schema_evolution_enabled(&self, table_name: &str) -> bool { self.schema_evolution_enabled .read() @@ -390,8 +360,6 @@ impl StarRocksSchemaEvolution { } /// Reload the column list for `table_name` from `INFORMATION_SCHEMA.COLUMNS`. - /// Stores the result in the in-memory cache. Used both at setup and after - /// runtime ALTERs. pub async fn refresh_target_schema_cache(&self, table_name: &str) -> Result<()> { let mut conn = self.get_conn().await?; @@ -436,9 +404,9 @@ impl StarRocksSchemaEvolution { .map_err(|e| anyhow!("starrocks_sink: failed to get MySQL connection: {}", e)) } - /// Confirm a column appears in `INFORMATION_SCHEMA.COLUMNS` after an ALTER. - /// With fast_schema_evolution this is metadata-only and instant; the - /// check is a defensive sanity validation rather than a real poll. + /// Defensive post-ALTER sanity check. With `fast_schema_evolution=true` + /// the column is visible immediately; without it this would never + /// succeed (and we wouldn't have reached this path anyway). async fn verify_alter_completed( &self, conn: &mut Conn, @@ -474,16 +442,11 @@ impl StarRocksSchemaEvolution { Ok(()) } - /// Query `INFORMATION_SCHEMA.TABLES_CONFIG` for the table's - /// `PROPERTIES` string and check whether `"fast_schema_evolution" = "true"` - /// appears in it. async fn table_has_fast_schema_evolution( &self, conn: &mut Conn, table_name: &str, ) -> Result { - // `INFORMATION_SCHEMA.TABLES_CONFIG` is StarRocks-specific (3.2+). - // PROPERTIES is a string column; format includes `"key" = "value"` pairs. let row: Option<(String,)> = conn .exec_first( "SELECT PROPERTIES FROM INFORMATION_SCHEMA.TABLES_CONFIG @@ -499,8 +462,6 @@ impl StarRocksSchemaEvolution { })?; let Some((properties,)) = row else { - // Table not in TABLES_CONFIG — should not happen if setup - // verified existence already, but be defensive. warn!( table = %table_name, "starrocks_sink: table not present in INFORMATION_SCHEMA.TABLES_CONFIG" @@ -517,11 +478,8 @@ impl StarRocksSchemaEvolution { // --------------------------------------------------------------------------- /// Parse a StarRocks version string like `"3.2.4"`, `"3.3.0-rc01"`, or -/// `"3.4.1 8b4e8f9"` into `(major, minor)`. Returns `None` if the format -/// is not recognised. +/// `"3.4.1 8b4e8f9"` into `(major, minor)`. Returns `None` if unparseable. fn parse_server_version(s: &str) -> Option<(u32, u32)> { - // Take everything before the first whitespace (build-hash suffix) and - // the first dash (rc/alpha suffix). let head = s .split(|c: char| c.is_whitespace() || c == '-') .next()? @@ -532,23 +490,11 @@ fn parse_server_version(s: &str) -> Option<(u32, u32)> { Some((major, minor)) } -/// Check whether a `PROPERTIES` string contains -/// `"fast_schema_evolution" = "true"` (or the JSON equivalent). -/// -/// StarRocks renders `PROPERTIES` in two different formats depending on the -/// source: -/// -/// - `SHOW CREATE TABLE` returns the canonical key-value form: -/// `"fast_schema_evolution" = "true"` (with spaces and `=`). -/// - `INFORMATION_SCHEMA.TABLES_CONFIG.PROPERTIES` returns a JSON object: -/// `"fast_schema_evolution":"true"` (no spaces, `:` separator). -/// -/// We accept both. Whitespace and case are normalised before matching. +/// Accept both the `SHOW CREATE TABLE` form (`"key" = "value"`) and the +/// `INFORMATION_SCHEMA.TABLES_CONFIG` JSON form (`"key":"value"`). fn properties_contain_fast_schema_evolution(properties: &str) -> bool { let lower = properties.to_ascii_lowercase(); let stripped: String = lower.chars().filter(|c| !c.is_whitespace()).collect(); - // SHOW CREATE TABLE form: "fast_schema_evolution" = "true" - // INFORMATION_SCHEMA.TABLES_CONFIG (JSON) form: "fast_schema_evolution":"true" stripped.contains("\"fast_schema_evolution\"=\"true\"") || stripped.contains("\"fast_schema_evolution\":\"true\"") }