Skip to content

[Feature Request]: Native schema evolution for restricted Instant ADD COLUMN #33035

Open

Description

@VioletQwQ-0

Is there an existing issue for the same feature request?

  • I have checked the existing issues.

Is your feature request related to a problem?

COPY ALTER rewrites historical rows even when the new column has the same known value, NULL, for every existing row. This issue tracks the native schema evolution design for the ADD COLUMN portion of #12555.

Describe the feature you'd like

Support one trailing nullable column with an omitted default or DEFAULT NULL. Start with ordinary persistent user tables under pessimistic read-committed autocommit. Exclude explicit transactions, column positioning, compound ALTER, partitioned tables and tables with secondary indexes, referential constraints, CHECK constraints or CDC/publication coverage. An explicit unsupported ALGORITHM=INSTANT request must explain the rejection. An eligible implicit request that loses Instant admission must complete through the existing COPY path where supported.

Describe implementation you've considered

  1. Unify interpretation of missing columns across scans, pruning, aggregates, statistics and replay. Persist the original default and stable physical column sequence. A nonempty old object can synthesize values only when its schema history justifies them. PR foundation: feat: unify column reads for schema evolution (PR 1) #32989.
  2. Gate Instant writes by protocol version and an account-level switch, disabled by default. Recheck the committed account setting at final admission. Keep CN and TN schema versions and column sequences consistent across concurrent writes, object sealing and commit. Protect both directions of CDC/publication admission, including publication scope changes.
  3. Preserve the source snapshot's schema metadata and next column sequence through CLONE, RESTORE and restart, including holes left by previously allocated columns.

Documentation, Adoption, Use Case, Migration Strategy

Document enable_instant_add_column, the supported SQL and table shapes, fallback behavior and downgrade restrictions after the first Instant ADD. Turning the switch off must preserve reads, recovery and compaction for existing evolved tables.

Additional information

Acceptance criteria:

  • Verify historical NULLs and new writes through actual SQL and verify object identity across Instant ADD.
  • Exercise concurrent appends and commit ordering, malformed layouts, and historical object import through CLONE/RESTORE.
  • Verify snapshot column-sequence high-water marks, independent parent/child evolution, restart and compaction.
  • Use two existing CN connections to verify explicit rejection and implicit COPY after disable. Exercise a concurrent publication scope change and assert the final catalog state.

Track the read foundation and the subsequent SQL/write implementation together. Keep this issue open through end-to-end acceptance.

Activity

  1. self-assigned this
    on Nov 21, 2026
  2. VioletQwQ-0 commented on Nov 25, 2026

    @VioletQwQ-0
    CollaboratorAuthor

    Native schema evolution design (NULL-default initial scope) · revision 1

    Tracking #33035. Implementation series #32989 provides the shared read semantics, PR 2 enables restricted Instant ADD, and PR 3 qualifies distributed correctness, recovery, and performance. Design decision Option A: NULL-default initial scope using existing metadata with zero proto/ changes. This revision updates the issue's original default-storage and protocol-gate proposals and is open for design review. Record reviewer approval of this revision here and link the decision from the implementation PRs before implementation approval.

    Scope and design-review trigger

    This is a feature spanning catalog publication, object I/O, CN execution, TN replay/compaction, and DDL admission. It changes the interpretation of persisted layouts and the write/recovery contract, so the full series requires design review under feature-design-review.md §§1–2. Today COPY rewrites historical rows to add a column. The initial scope enables metadata-only, single tail ADD of a nullable column with an implicit or explicit SQL NULL default on eligible tables, in standalone pessimistic RC. Unsupported shapes follow COPY unless INSTANT is explicitly requested, in which case they fail. PR 1 keeps SQL ADD/DROP on COPY. Non-NULL historical values, positional ADD, and Instant DROP are follow-up work.

    Read contract, ownership, and resource bounds

    CN binds ColumnReadSpec to the statement's catalog snapshot; ordinary tables (!features.IsSchemaEvolved) return nil with zero per-statement spec allocation. TN builds and caches one *ColumnReadSpec lazily per immutable finalized catalog Schema via sync.Once (reset on Finalize, rebuilt on Clone, reclaimed with the schema version). Both activate exclusively through features.IsSchemaEvolved on the persisted table feature bit. PR 2 may set that bit only with a committed eligible ADD. Ordinary tables keep the legacy path.

    An object or logtail batch visible to the same table lineage supplies physical layout evidence. For a requested sequence present in that layout, return its stored value. A sequence above the layout's maximum can be synthesized only for a known column of the bound evolved schema, as typed NULL with zero NDV and a NULL count equal to the row count. An absent sequence at or below the maximum is a layout error. Empty objects yield typed empty statistics. Disk reads, pruning, aggregates, ordering, statistics, logtail reads, WAL, and compaction share this interpretation. Later SET DEFAULT / DROP DEFAULT affects subsequent inserts; the reader never derives historical values from the current write default.

    Decision log (rejected alternatives)

    • No plan.Default / proto/ changes in the initial scope: The schema snapshot, existing feature bit, stable sequence numbers, and physical MaxSeqnum are sufficient for NULL-default historical reads. Extending mutable plan.Default couples immutable storage history to SQL default projections (which drop unrecognized fields); non-NULL historical defaults are deferred to a separate design with a dedicated immutable representation.
    • No per-feature MORPCVersion gate: Per repository upgrade-compatibility.md, MatrixOne uses shutdown-only upgrades with same-binary clusters, so per-feature RPC version gates are omitted.

    Write, recovery, and release boundaries

    PR 2 uses existing ADD/guarded replace requests and the table's sequence high-water mark. The account-wide switch (enable_instant_add_column) defaults off; the executor rechecks it under the table lock against authoritative catalog state. TN validates append batches and every uploaded object block, rechecks the schema at commit, fences old appendable objects at schema publication, and returns retryable schema-change errors for stale writers. CLONE and RESTORE preserve the same snapshot's feature bit, sequences, and high-water mark. Compaction writes the synthesized NULLs into the current layout. Positional WAL replay stages all fallible missing-column work under the append lock before deleting old PK entries or overwriting rows.

    Use the repository's shutdown-upgrade policy. Verify the applicable published source release and its artifacts against the target, including old catalog defaults, old objects, WAL and checkpoints, reads and new writes after restart. Qualify repeated ADD followed by SET/DROP DEFAULT, exact returned rows and aggregates, retained object IDs, stale-writer interleavings, snapshot/clone/restore, cross-CN switch-off, concurrent publication scope changes, and compaction. Measure ordinary-table read overhead and evolving-table DDL cost as object count grows. Package-level regression evidence, release-artifact upgrade, and multi-CN/performance qualification are separate acceptance steps.

  3. VioletQwQ-0 commented on Nov 25, 2026

    @VioletQwQ-0
    CollaboratorAuthor

    Native schema evolution v1 design · revision 2

    Tracking #33035. Implementation series #32989 establishes the read and WAL replay contracts. PR 2 enables restricted Instant ADD. PR 3 qualifies distributed correctness, shutdown upgrade, recovery, and performance. This revision records Option A (NULL-only v1 using existing metadata) and the WAL recovery decision. It is pending reviewer approval. Record approval of revision 2 on the issue and link the approved revision from the implementation PRs.

    Problem, scope, and design-review trigger

    COPY rewrites existing data to add a column. A metadata-only ADD leaves old objects and in-memory batches visible to the new schema, so scans, filters, aggregates, and recovery must agree on the value of a physically absent column. The full feature crosses CN, TN, catalog, object storage, and recovery, and changes the interpretation of persisted data. The series therefore requires design review under the repository's feature-design-review contract.

    v1 accepts a single tail ADD of a nullable column with an implicit or explicit SQL NULL default on an eligible table, in a standalone pessimistic RC transaction. Unsupported shapes fall back to COPY, and explicitly requested INSTANT returns an error. PR 1 keeps SQL ADD and DROP on COPY. Non-NULL historical defaults, positional ADD, Instant DROP, and mixed DDL/DML in an explicit transaction are later work.

    Four independent responsibilities

    Responsibility Owner and invariant
    Stable column identity The catalog assigns a table-lineage SeqNum and maintains a monotonic NextColSeqnum. A rename preserves the sequence. DROP retires it, including when a later ADD reuses the name. Idx is the column's position in one schema.
    Evidence of the written layout An object/block supplies physical slot presence and MaxSeqnum. In-memory and logtail reads use the write schema or batch layout. Named WAL uses a source schema resolved from the replay transaction and catalog MVCC. Compatible renames use the complete ordered PrepareTS layout. The chosen schema supplies the complete source column set and allocation high-water mark.
    Historical value for a proven absent column v1 supplies typed SQL NULL. Subsequent SET/DROP DEFAULT only affects future inserts through the existing write default.
    Unified read result ColumnReadSpec serves scans, pruning, aggregates, ordering, statistics and compaction. A present physical column returns its value. For an evolved table, a known sequence above the layout maximum yields typed NULL, zero NDV, and NULL count equal to row count. A missing physical slot at or below the maximum or an unknown requested column is a layout error. Empty objects yield typed empty statistics. WAL uses the spec to fill columns after resolving source identity.

    Stable field IDs and separation of initial and write defaults follow the Apache Iceberg design precedent. v1 fixes the initial value to NULL and uses MatrixOne's existing block metadata and catalog MVCC. No new interoperability requirements arise from this internal read contract.

    Workspace and committed logtail reads

    • Workspace INSERTs keep logical columns after the generated row ID. A dense TableDef needs no mapping allocation and computes the position directly. Sparse TableDefs map each physical sequence to its logical position for projections, including resumed batches, PK envelopes and probes, and independent membership filters. An unknown sequence, a position beyond the batch or a nil vector returns an error.
    • Committed logtail uses physical slots after the row ID and commit timestamp. It gets dropped-slot markers from ReplayBatch.Attrs, with nil vectors also treated as absent. Both ordinary and materialized Data Branch snapshot reads reject an interior hole for evolved tables. Legacy reads materialize NULL or short-circuit their membership filter for absent values.

    WAL recovery, write admission, and failure containment

    • WAL recovery restores the checkpoint catalog and object list before consuming subsequent WAL. A memory node keeps the schema published when it is constructed, including a carrier recreated from an append record. The append command's Ts is the writer's prepare timestamp and an object creation hint. The writer can bind its layout before a rename and prepare after it.
    • On a successful in-transaction column rename, TN updates the buffered batch's names and name index. Freeze applies reserved rows with the local schema before the pre-WAL worker assigns PrepareTS. During PrepareCommit, the worker selects the latest eligible table MVCC schema at PrepareTS, including its own DDL. It releases the table read lock before waiting for any earlier prepare to commit or roll back in the WAL and apply workers.
    • If the local and prepare schemas have the same allocation watermark, ordered sequences and types, TN rebuilds the append batch's names and name index as a unit by SeqNum. A two-column name swap preserves vector positions, previous row reservations and PK entries. Any subsequent positional apply uses the same bound schema as the WAL payload. The existing AppendCmd encoding carries the resulting names.
    • Checkpoint recovery can collapse the table's schema history to a single node. Replay accepts the PrepareTS schema for a complete ordered batch compatible with the writer's visible layout. Replay otherwise retains StartTS visibility and the existing complete-layout fallback for older same-transaction rename records. A checkpoint that discarded a legacy writer's original names cannot supply the missing historical identity. The installer validates every vector against the chosen source. For independently committed session temporary tables, replay binds the exact live table generation committed by PrepareTS. Ordinary transaction lookup retains the owner check.
    • The installer validates the source columns before changing data or the PK index. It resolves each name in the source schema and uses the resulting SeqNum to find the destination vector through writeSchema.SeqnumMap. Only a source-proven column absent from the destination within its allocated sequence range can be discarded as dropped. An unknown name, omitted required source column, incompatible type or vector shape, or incompatible sequence fails closed. A destination-only column can be synthesized on an evolved table only if its sequence had yet to be allocated in the source. A legacy mo_tables record may derive an omitted rel_logical_id from rel_id; an explicit NULL is preserved.
    • Positional installation stages allocations under the append lock before replacing rows or PK entries. An in-range missing column reserves its NULL bitmap with nulls.TryExpand before marking the overwritten range. A failed allocation releases the staged vectors and preserves the rows, PK index and pool usage. A renamed PK uses the same source sequence mapping for its index update. Invalid WAL still reaches the recovery error path with the command and destination context.
    • Snapshot scans bind the table snapshot’s ColumnReadSpec for persisted data reads and committed logtail rows. A missing tail uses the spec to fill typed NULL. An empty in-layout slot is a layout error on an evolved table. Tombstone reads use their own layout. Persisted PK probes use the physical PK sequence for object and block ZoneMaps.
    • PR 2 uses existing guarded ADD requests. The account switch defaults off and the executor rechecks it against the authoritative catalog under the table lock. TN proves admissible ADD shape before setting the feature bit, checks append batches and every uploaded object block, and fences old appendable objects at schema publication. At commit a proven stale writer gets a retryable schema-change error; a malformed payload is rejected. Historical CLONE imports require membership in the source snapshot's visible object set. CLONE and RESTORE carry the same snapshot's feature bit, sequence IDs and high-water mark. Existing tenant/transaction visibility and DDL authorization still govern access. Compaction materializes the typed NULLs in the current layout.

    Decision log

    Decision Rationale
    Accept Option A The existing feature bit, SeqNum, and write-layout evidence suffice for NULL-only v1. WAL encoding, object format, system table schema, proto/ and generated plan messages keep their existing format.
    Reject extending plan.Default with HasOriginDefault and a historical literal v1 has one historical value. New fields would add persistent catalog encoding and projection obligations. Current write defaults retain their existing owner. A future non-NULL historical value requires a separately reviewed immutable representation.
    Reject a per-feature MORPCVersion gate The repository supports shutdown upgrade only. All peers run the target binary after restart. The account switch controls new Instant ADD admission and the persisted table bit controls reading existing data.
    Reject name-only WAL matching and a payload-derived layout maximum A rename preserves identity, and dropping then re-adding a name creates a new identity. Guessing from a subset of names can silently convert data or a corrupt record to NULL.

    Cache & resource bounds

    CN binds the spec to the statement's table snapshot and shares it with that read's consumers. Ordinary tables get a nil spec with zero spec allocations on CN and TN. TN uses sync.Once to cache one spec per immutable finalized Schema. A new finalized schema has its own cache. Both sides activate via features.IsSchemaEvolved; cache entries scale with referenced schemas and the number of their columns. There is no per-object spec or background worker. WAL resolves the catalog MVCC version and validates the batch and destination layout once per installation. Temporary positional storage is bounded by the columns that need allocation and one memory object’s row layout. A patch whose data, NULL bitmap and varlena area already have capacity writes in place after allocations succeed. DDL sealing work grows with the candidate appendable objects. Import validation grows with objects, blocks per object, and checked columns.

    Verification, release, and review decision

    The PR 1 local regressions assert exact read/statistics results, reject unknown or missing WAL columns, preserve values across a trailing rename and rename with DROP/ADD, and check row, PK index, and memory-pool state after a fill failure. TN restart regressions cover both a writer whose prepare follows another transaction's RENAME and a single transaction that inserts and renames. Global-checkpoint regressions persist the renamed catalog before the old writer prepares, then restart and check both a simple rename and a same-type name swap through exact values and a PK point lookup. CN regressions cover sparse PK pruning and compare historical tail columns with in-layout holes in persisted and committed logtail snapshot reads.

    PR 1 stopped TAE upgrade, review 6057510195. The source was published MatrixOne v4.2.9, commit 6c05e42f9f660a207077b050b8ec285ccf3f8103 (published 2026-11-23 07:32:06 UTC). A test-only probe ran against that checkout with its own native libraries. It committed an ordinary append, a pre-rename append, old_value → new_value through the released TAE alter API, and a post-rename append. It verified the user objects were appendable and unpersisted, then closed the engine normally. WAL watermark was 5 and the checkpointed LSN was 0. The closed directory contained wal-1.rot (13,404 bytes, SHA-256 5cf8df60adc0affe71fdd3c7fe92127d336f71d5f4a7309529ed471bc251ce9e) and its lock file.

    The target rebased on c90a2c4e5797457a78d82cdcd8cba756b563de93 originally rejected mo_database.datname because release WAL uses charset 0 and main declares charset 3. Replay now normalizes this metadata for built-in catalog text only when the remaining type matches. The compatibility test rejects a different width and leaves the user-table mismatch strict. The final local commit 45e8276758837b8c94be429f2de95069b351a67f reopened a fresh copy of the same closed directory successfully. Exact scans and PK lookups saw ordinary={(1,101)} and renamed(new_value)={(11,201),(12,202)}. Target commits added (2,102) and (13,203), and both tables read back their complete old and new rows.

    With the same temporary upgrade_probe_test.go in each checkout, the release command was MO_UPGRADE_PHASE=produce MO_UPGRADE_DATA=<fixture> go test -p 2 -mod=readonly -count=1 -v -timeout=120s -run '^TestStoppedUpgradeReleaseAppendWAL$' ./pkg/vm/engine/tae/db/test after make cgo -j4 and setting the release CGo include, library and runtime paths. The target command was MO_UPGRADE_PHASE=consume MO_UPGRADE_DATA=<copy-of-closed-fixture> .agents/skills/mo-dev/scripts/mo-cgo-test -mod=readonly -p 1 -count=1 -v -timeout=120s -run '^TestStoppedUpgradeReleaseAppendWAL$' ./pkg/vm/engine/tae/db/test. The exact-commit repeat supplied the same probe through a Go overlay without changing the checkout. This run covers the TAE storage/WAL boundary. Distributed service upgrade and checkpoint migration remain PR 3 qualification.

    PR 2 must demonstrate stale writes versus same-generation malformed inputs, source-snapshot object admission, committed rows and aggregates after repeated ADD and SET/DROP DEFAULT, retained object IDs, concurrent publication/stop-write boundaries, CLONE/RESTORE and compaction. PR 3 uses a supported published source release and identified artifacts to test shutdown upgrade with old catalog defaults, objects, checkpoints, WAL and post-restart writes. Mixed-version operation and downgrade are outside the release contract. PR 3 also measures ordinary-table read cost and varies active appendable objects, blocks per object and table width independently; compare latency, throughput, allocations and I/O under equal workload and configuration.

    Review disposition Revision 2 is open for design review. PR 2 owns the proof of stale write and source-snapshot provenance before admission. PR 3 owns release-artifact, multi-CN and performance evidence before rollout. Local PR 1 regression evidence, reviewer approval and those release gates have separate completion criteria.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions