Repository navigation
feat: schema evolution for StarRocks and Snowflake sinks - #94
Merged
Merged
Conversation
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<u32>` 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.
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<RwLock<HashMap<...>>>` 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.
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<RwLock<HashMap<...>>>`
+ `table_schemas: Arc<RwLock<Vec<...>>>` (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<RwLock<Vec<...>>>`
- `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.
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.
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.
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.
`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.
…EXISTS 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.
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.
dariomazzitellireplik-coder
requested review from
dariomazzitelli-sys and
tanokl
as code owners
April 29, 2026 04:44
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Brings StarRocks and Snowflake sinks to functional parity with the Postgres sink for schema evolution. Closes the silent-data-loss path where source
ALTER TABLE ADD COLUMNevents were dropped at the sink'smatcharm and never propagated — Stream Load filtered the new column viamax_filter_ratio(StarRocks); Snowflake's MERGE never projected_DATA:"col"::TYPEfor it. This was scope-out of the v1.7.0 PR that fixed the same bug for Postgres (internal-docs/pg-sink-schema-evolution-solution.md§3 — "Snowflake / StarRocks evolution audit. Out of scope for this branch.").Conservative policy (uniform across all three sinks)
ADD COLUMNALTER TABLE ADD COLUMNDROP COLUMNWARN, target keeps the dead columnMODIFY COLUMN typeERROR, target keeps the old castRENAME COLUMNRecovery from
DROP/RENAMEdrift is operator-driven: manualALTERon target +POST /api/v1/cdc/snapshot/startto refresh values.What changed
New shared module
src/connectors/sinks/schema_evolution.rs— sink-agnosticcompute_schema_evolution_plan,SchemaDiff,AddedColumn,TypeChange,diff_against_cacheextracted from the PG sink. Three sinks consume the same diff logic.StarRocks (
src/connectors/sinks/starrocks/schema_evolution.rs):validate_server_version— server ≥ 3.2.0 hard requirement (fail loud).detect_fast_schema_evolution_per_table— per-table flag detection viaINFORMATION_SCHEMA.TABLES_CONFIG. Tables without the property enter degraded mode (loud WARN at setup + per-event WARN +schema_evolution_skipped_totalcounter increment); tables with the property apply ALTERs synchronously.apply_diff—ALTER TABLE ADD COLUMN(noIF NOT EXISTSbecause StarRocks rejects it; idempotency viaINFORMATION_SCHEMApre-check) followed by post-ALTER verification.reconcile_target_schemaat startup catches drift accumulated while the daemon was down.INFORMATION_SCHEMA.TABLES_CONFIGJSON form ("fast_schema_evolution":"true") and theSHOW CREATE TABLEform ("fast_schema_evolution" = "true").Snowflake (
src/connectors/sinks/snowflake/schema_evolution.rs):apply_diff—BEGIN; ALTER ...; COMMIT;per batch with ROLLBACK on partial failure. NoDEFAULT(Snowflake rejects expressions inALTER ADD, precedent in commit88dad04).setup::run_setup.source_schemasrefactored fromVec<...>(frozen at setup) toArc<RwLock<Vec<...>>>(shared with normalizer) so post-ALTER MERGEs see the new columns.reconcile_target_schemasymmetric to StarRocks.Observability: new
schema_evolution_skipped_totalcounter exposed atGET /api/v1/cdc/metrics. Aggregated by the pipeline from per-batchSinkResult.schema_evolution_skipped.Documentation: README,
docs/configuration.md(sink-specific requirements + observability), expandedinternal-docs/sinks/{starrocks,snowflake}.md, newinternal-docs/sr-sf-schema-evolution.md, CHANGELOG[Unreleased]entry. Cargo bumped 2.1.0 → 2.2.0.Validation
ez-cdc verify --sink demo-starrocksagainst StarRocks 3.3.22 allin1) — passes including D4 (TOAST column survives unrelated UPDATE) and C10 (NULL roundtrip), the two checks that exposed the original bug for the PG sink.ez-cdc-cli, already merged) which fixed the demo bootstrap to publish port 8040 and create the target DB+tables withfast_schema_evolution=true.Companion changes
ez-cdc-cli(merged): https://github.com/ez-cdc/ez-cdc-cli/pull/7 — fixes demo bootstrap for StarRocks + adds interactive--demo-sinkprompt when omitted.Out of scope (deferred to future PRs)
DROP/MODIFY/RENAME(Flink CDC / AWS DMS model).Test plan
cargo test— 148/148 passcargo clippy --all-targets -- -D warnings— cleancargo fmt -- --check— cleanez-cdc verify --source demo-pg --sink demo-starrocks --dbmazz-image ghcr.io/ez-cdc/dbmazz:2.2.0-dev -y— passesez-cdc demo up --sink starrocks+ez-cdc run --demo --demo-sink starrocks --dbmazz-image ghcr.io/ez-cdc/dbmazz:2.2.0-dev— daemon arranca, snapshot completa 8000 rows in <1s