Skip to content

feat: schema evolution for StarRocks and Snowflake sinks - #94

Merged
dariomazzitelli-sys merged 9 commits into
mainfrom
feat/schema-evolution-sr-sf
Apr 29, 2026
Merged

dariomazzitelli-sys merged 9 commits into
mainfrom
feat/schema-evolution-sr-sf

Conversation

@dariomazzitellireplik-coder

@dariomazzitellireplik-coder dariomazzitellireplik-coder commented Apr 29, 2026 •

Copy link
Copy Markdown
Collaborator

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 COLUMN events were dropped at the sink's match arm and never propagated — Stream Load filtered the new column via max_filter_ratio (StarRocks); Snowflake's MERGE never projected _DATA:"col"::TYPE for 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)

Source DDL Action
ADD COLUMN Auto-applied via ALTER TABLE ADD COLUMN
DROP COLUMN Logged WARN, target keeps the dead column
MODIFY COLUMN type Logged ERROR, target keeps the old cast
RENAME COLUMN Seen as drop+add (pgoutput limitation), behaves as both above

Recovery from DROP/RENAME drift is operator-driven: manual ALTER on target + POST /api/v1/cdc/snapshot/start to refresh values.

What changed

New shared module src/connectors/sinks/schema_evolution.rs — sink-agnostic compute_schema_evolution_plan, SchemaDiff, AddedColumn, TypeChange, diff_against_cache extracted 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 via INFORMATION_SCHEMA.TABLES_CONFIG. Tables without the property enter degraded mode (loud WARN at setup + per-event WARN + schema_evolution_skipped_total counter increment); tables with the property apply ALTERs synchronously.
  • apply_diff — ALTER TABLE ADD COLUMN (no IF NOT EXISTS because StarRocks rejects it; idempotency via INFORMATION_SCHEMA pre-check) followed by post-ALTER verification.
  • reconcile_target_schema at startup catches drift accumulated while the daemon was down.
  • Accepts both INFORMATION_SCHEMA.TABLES_CONFIG JSON form ("fast_schema_evolution":"true") and the SHOW CREATE TABLE form ("fast_schema_evolution" = "true").

Snowflake (src/connectors/sinks/snowflake/schema_evolution.rs):

  • apply_diff — BEGIN; ALTER ...; COMMIT; per batch with ROLLBACK on partial failure. No DEFAULT (Snowflake rejects expressions in ALTER ADD, precedent in commit 88dad04).
  • ALTER privilege validated implicitly via the existing audit-column ALTER in setup::run_setup.
  • source_schemas refactored from Vec<...> (frozen at setup) to Arc<RwLock<Vec<...>>> (shared with normalizer) so post-ALTER MERGEs see the new columns.
  • reconcile_target_schema symmetric to StarRocks.

Observability: new schema_evolution_skipped_total counter exposed at GET /api/v1/cdc/metrics. Aggregated by the pipeline from per-batch SinkResult.schema_evolution_skipped.

Documentation: README, docs/configuration.md (sink-specific requirements + observability), expanded internal-docs/sinks/{starrocks,snowflake}.md, new internal-docs/sr-sf-schema-evolution.md, CHANGELOG [Unreleased] entry. Cargo bumped 2.1.0 → 2.2.0.

Validation

  • 148/148 unit tests pass, clippy + fmt clean.
  • End-to-end verify suite (ez-cdc verify --sink demo-starrocks against 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.
  • Demo arranca zero-touch via the sister PR (Feature/schema evolution #7 in ez-cdc-cli, already merged) which fixed the demo bootstrap to publish port 8040 and create the target DB+tables with fast_schema_evolution=true.

Companion changes

Out of scope (deferred to future PRs)

  • Aggressive auto-replication of DROP/MODIFY/RENAME (Flink CDC / AWS DMS model).
  • StarRocks server versions older than 3.2.
  • StarRocks Primary Key tables that need to add KEY columns (engine limitation, documented).
  • Postgres sink table-creation policy (debate orthogonal to this PR).

Test plan

  • cargo test — 148/148 pass
  • cargo clippy --all-targets -- -D warnings — clean
  • cargo fmt -- --check — clean
  • ez-cdc verify --source demo-pg --sink demo-starrocks --dbmazz-image ghcr.io/ez-cdc/dbmazz:2.2.0-dev -y — passes
  • Verify against Snowflake (skipped here — no live SF account in this repro environment; the code path mirrors StarRocks setup-side and is covered by unit tests)
  • Smoke test: ez-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

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.
@dariomazzitelli-sys
dariomazzitelli-sys merged commit 7a1bcab into main Apr 29, 2026
2 checks passed
@dariomazzitelli-sys
dariomazzitelli-sys deleted the feat/schema-evolution-sr-sf branch April 29, 2026 04:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants