Skip to content

[Fix][API] Reject an ADD COLUMN whose AFTER column is missing from the schema - #13267

Merged
nzw921rx merged 1 commit into
apache:devfrom
corgy-w:fix/schema-add-column-after-anchor
Nov 17, 2026
Merged

nzw921rx merged 1 commit into
apache:devfrom
corgy-w:fix/schema-add-column-after-anchor

Conversation

@corgy-w

@corgy-w corgy-w commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

What

AlterTableSchemaEventHandler now rejects an ADD COLUMN ... AFTER <column> event whose anchor column is not in the schema, instead of silently inserting the new column at position 0.

Why

applyAddColumn looks the anchor up and adds right after it:

} else if (addColumnEvent.getAfterColumn() != null) {
    int index = originFields.indexOf(addColumnEvent.getAfterColumn());
    newColumns.add(index + 1, column);          // index == -1  ->  add(0, column)
}

When the schema has no column with that name, indexOf returns -1, -1 + 1 is 0, and LinkedList.add(0, column) prepends the column. Nothing throws and nothing is logged, so the schema change looks applied while the column order now disagrees with the event and with the physical table. Every positional row-to-schema mapping downstream (TableSchemaChangeEventDispatcher is used by the JDBC, Doris, Paimon, StarRocks, Databend and Elasticsearch sink writers) is then off by one for that table.

The anchor name comes from the source and is not validated: the MySQL CDC alter-table parser passes the raw AFTER identifier, and the SQL Server and Postgres resolvers do the same, so a renamed, projected-away or differently-cased anchor reaches this code. The sibling branch applyModifyColumn already treats an unknown AFTER column as a hard failure (Optional.get()), so the two paths contradicted each other.

Fix

Treat an unknown anchor as an invalid event for this schema and fail loudly:

int index = originFields.indexOf(addColumnEvent.getAfterColumn());
if (index < 0) {
    throw new SchemaEvolutionException(
            SchemaEvolutionErrorCode.SCHEMA_EVENT_PROCESSING_FAILED,
            String.format(
                    "Cannot add column '%s' after '%s': table %s has no such column,"
                            + " existing columns: %s",
                    column.getName(),
                    addColumnEvent.getAfterColumn(),
                    addColumnEvent.tableIdentifier(),
                    originFields));
}
newColumns.add(index + 1, column);

The message names the table, the anchor and the existing columns, so the mismatch is diagnosable from the job log.

How verified

New AlterTableSchemaEventHandlerTest (no external services):

  • addColumnAfterExistingColumnKeepsItsPosition — [a, b] + ADD c AFTER a → [a, c, b] (guards the normal path);
  • addColumnAfterUnknownColumnIsRejected — [a, b] + ADD c AFTER missing must throw SchemaEvolutionException.

Results:

  • before the fix: AssertionFailedError: Expected SchemaEvolutionException to be thrown, but nothing was thrown (the schema came back as [c, a, b]);
  • after the fix: Tests run: 5, Failures: 0, Errors: 0 (mvn -o -pl seatunnel-api test -Dtest='AlterTableSchemaEventHandlerTest,RestoreTableSchemaEventTest'), including the existing restore tests.

Compatibility

No public API or option change. The behaviour change is that an ADD COLUMN ... AFTER event naming an unknown column now fails the schema change instead of corrupting the row layout; ADD COLUMN (append), ADD COLUMN FIRST and ADD COLUMN AFTER <existing> are unchanged.

@github-actions github-actions Bot added the api label Nov 13, 2026

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for contributing to Apache SeaTunnel! I reviewed the complete two-file diff at 7c98c63d8049f88e18fa4461d4a4ed14404715bb, including schema-event dispatch, the CDC deserializer, and the existing modify-column fallback.

What Problem Does This PR Solve?

User pain point: An ADD COLUMN event naming an absent AFTER column silently inserts the new field first, although the event did not request that order.

Fix approach: Reject a missing anchor with a contextual schema-evolution exception before constructing the replacement schema.

One-sentence summary: Invalid column placement now fails clearly instead of silently rearranging the schema. For example, [a,b] + ADD c AFTER missing no longer becomes [c,a,b]; [a,b] + ADD c AFTER a still becomes [a,c,b].

1. Code Change Review

1.1 Core Logic Analysis

Core location: seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/handler/AlterTableSchemaEventHandler.java:121-137.

Before:

int index = originFields.indexOf(addColumnEvent.getAfterColumn());
newColumns.add(index + 1, column);

After:

int index = originFields.indexOf(addColumnEvent.getAfterColumn());
if (index < 0) {
    throw new SchemaEvolutionException(
        SchemaEvolutionErrorCode.SCHEMA_EVENT_PROCESSING_FAILED,
        /* table, new column, missing anchor and existing columns */);
}
newColumns.add(index + 1, column);

Key findings: The handler is registered for ADD and composite ALTER events. Valid ADD AFTER requests reach the same insertion path. The new failure is restricted to an absent anchor for a genuinely new column; duplicate ADD events still take the pre-existing modify-column path at lines 108-115. This is a precise validation fix, not repair of the upstream cause of a schema mismatch.

CDC source resolves a schema change
 -> SeaTunnelRowDebeziumDeserializeSchema processes the event
 -> TableSchemaChangeEventDispatcher.reset(currentSchema).apply(event)
    [TableSchemaChangeEventDispatcher.java:59-69]
 -> AlterTableSchemaEventHandler.apply()
    -> ADD dispatch [AlterTableSchemaEventHandler.java:81-82]
       or composite events applied in sequence [84-90]
    -> applyAddColumn() [104-146]
       -> FIRST: prepend
       -> AFTER: find anchor; reject absence before returning any new schema
       -> no position: append
 -> caller receives the replacement schema only on success
 -> CDC row converters and downstream schema-event handling use that schema

The normal valid event path remains reachable. The guard prevents a malformed or mismatched event from silently taking the FIRST position. It does not reconcile renamed/projected columns; producers of such events must still supply a schema-consistent event. Restore events retain their separate return path at lines 66-67. No schema serializer or checkpoint representation changes.

1.2 Compatibility Impact

Fully compatible for valid event contracts, APIs, options/defaults, protocols, and serialized schemas. Invalid missing-anchor events intentionally change from silent insertion to failure. Operators encountering this error must correct the event/schema mismatch rather than rely on the old incorrect placement. No valid historical configuration needs migration.

1.3 Performance / Side-Effect Analysis

The existing linear anchor lookup remains; the extra check is constant-time. Error-message allocation occurs only on the invalid path. The schema list is copied before modification, so throwing does not mutate the input schema. No new networking, shared state, locks, retries, threads, resources, or per-record GC pressure is introduced. Composite events stop at the first invalid member rather than returning a partially constructed schema.

1.4 Error Handling and Logging

The existing SCHEMA_EVENT_PROCESSING_FAILED code is reused. The message includes the table, new field, anchor, and current columns. The exception propagates instead of reporting a successful schema change; no credential logging is added.

Issue 1: Document the new regression-test class's responsibility

  • Location: seatunnel-api/src/test/java/org/apache/seatunnel/api/table/schema/handler/AlterTableSchemaEventHandlerTest.java:30.
  • Problem description: The new class has no class-level explanation of the positional-schema invariant it protects. Its tests exercise a production schema-evolution contract, not generic object construction.
  • Potential risk: Future maintenance can miss why both valid placement and rejection are required together.
  • Best improvement: Add a short class Javadoc explaining that the tests prevent absent AFTER anchors from becoming position zero while preserving valid column ordering. The test class itself is the appropriate location; no production abstraction is needed.
  • Severity: Medium; non-blocking.
  • Raised by another reviewer: No.

2. Code Quality Assessment

2.1 Coding Standards

The production comment explains the -1 + 1 defect, existing error types are reused, and the new file has an ASF header. Issue 1 addresses the missing class comment. Changed-file reconciliation and git diff --check passed.

2.2 Test Coverage and Test Stability

Stability rating: Stable. AlterTableSchemaEventHandlerTest.java:35-41 asserts exact valid column order; lines 50-62 assert rejection of a missing anchor and useful error context. Removing the new guard makes the negative test fail. Tests use real schemas and the public handler, with no timing, ports, external services, mutable global fixture, reflection, or mock-only assertions.

The focused unit tests cover the changed decision; they do not prove end-to-end CDC recovery or projected-schema event generation. Those unchanged paths must not be claimed as newly validated. The current-head Build was still running at the snapshot.

Local commands: exact-head fetch/worktree checkout, complete git diff, searches and reads of handler/dispatcher/deserializer callers, API changed-file reconciliation, and git diff --check. Local compilation, unit tests, integration tests, and E2E were not run, as requested.

2.3 Documentation Updates

No new user option or valid schema operation is introduced. No new configuration example is needed in either docs/en or docs/zh. The intentional invalid-event rejection should remain explicit in the PR/release explanation; it is not a promise to automatically repair mismatched schemas.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix. The shared schema handler owns positional application, so validating the anchor here protects every caller. Validating only one CDC parser would miss other producers; silently selecting another position would preserve corruption. The smallest safe fix and best responsibility boundary coincide. Automatic source/sink schema reconciliation would be a different, substantially larger feature.

3.2 Maintainability

The new guard states the invariant and gives actionable failure context. Existing FIRST, append, restore, and duplicate-column branches remain distinct.

3.3 Extensibility

All callers of the shared handler receive the validation without connector-specific conditions. No new extension contract is needed.

3.4 Historical-Version Compatibility

Valid historical events and serialized schemas are unchanged. An invalid event previously producing incorrect order now fails explicitly; do not treat that prior silent behavior as a valid ordering guarantee.

4. Issue Summary

Number Issue Location Severity
1 Explain the regression-test class's invariant AlterTableSchemaEventHandlerTest.java:30 Medium, non-blocking

No blocking source issues found. The complete diff, event dispatch, normal and invalid paths, compatibility, test failure capability, error propagation, and merge gates were inspected.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed: Complete and pass the current-head Build, then obtain the repository-required review. No source blocker was found in this patch.
  2. Recommended fixes — non-blocking: Issue 1: add the short test-class explanation.

Overall, rejecting an impossible position is safer than guessing one. No broader implementation is required. Being behind dev alone does not justify a sync request, and pending CI is not a diagnosed source failure. There was no existing non-author review to reconcile in the collected discussion.

@corgy-w
corgy-w force-pushed the fix/schema-add-column-after-anchor branch from 7c98c63 to 2693b1c Compare November 16, 2026 11:25
@corgy-w
corgy-w requested a review from nzw921rx November 17, 2026 07:05

@nzw921rx nzw921rx left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 LGTM
Accurate repair

@nzw921rx
nzw921rx added this pull request to the merge queue Nov 17, 2026
Merged via the queue into apache:dev with commit c812d79 Nov 17, 2026
3 checks passed

@SEZ9 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on this. I reviewed the latest head 2693b1ca234d.

What this PR fixes

  • User pain: An ADD COLUMN ... AFTER <col> event whose anchor is not in the current TableSchema was silently prepended (indexOf returns -1, so add(0, column)). The in-memory column order then no longer matched the event or the physical table, with no error or log.
  • Fix approach: AlterTableSchemaEventHandler.applyAddColumn now checks if (index < 0) (AlterTableSchemaEventHandler.java:123) and throws SchemaEvolutionException(SCHEMA_EVENT_PROCESSING_FAILED, ...) naming the new column, the anchor, the table and the existing columns. A new AlterTableSchemaEventHandlerTest covers one valid-anchor case and one missing-anchor case.
  • One-line summary: The guard is correct for a truly absent anchor, but it is an exact, case-sensitive indexOf match, and it fires first on the CDC source, outside the resolver try/catch in SeaTunnelRowDebeziumDeserializeSchema. As a result, an anchor that differs only by case (MySQL AFTER ID against a tracked column id; the MySQL listener only strips quotes from the name) or an anchor that diverged through schema-changes.include/exclude now fails the job instead of being misplaced. Separately, the add-as-modify and CHANGE COLUMN paths still fail with a bare NoSuchElementException, the deprecated AlterTableEventHandler.java:113 keeps the silent prepend, and incompatible-changes.md is not updated. I would hold the merge until the filter-divergence case and the compatibility note are addressed.

Runtime chain I rechecked

Source side (the new throw fires here first, before any sink sees the event)
SeaTunnelRowDebeziumDeserializeSchema.deserialize()  SeaTunnelRowDebeziumDeserializeSchema.java:109
  -> deserializeSchemaChangeRecord()  SeaTunnelRowDebeziumDeserializeSchema.java:123,135
     -> schemaChangeResolver.resolve(record, tables)  :140   (only this call is inside the try/catch at :138-150)
        -> CustomAlterTableParserListener: afterColumn = parser.parseName(ctx.uid(1)); AlterTableAddColumnEvent.addAfter(...)  CustomAlterTableParserListener.java:107-110
           -> MySqlAntlrDdlParser.parseName() -> withoutQuotes(uidContext)  MySqlAntlrDdlParser.java:355-356   (quotes stripped, no case folding)
     -> schemaChangeEventFilter.filter(schemaChangeEvent)  :159   (schema-changes.include/exclude; can drop earlier events the anchor depends on)
     -> tableSchemaChangeHandler.reset(changeBefore.getTableSchema()).apply(event)  :186-188 (per sub-event of AlterTableColumnsEvent, with changeBefore = changeAfter at :198) / :202-204 (single event)   (not inside any try/catch)
        -> TableSchemaChangeEventDispatcher.apply(): handlers.get(event.getClass()); handler.reset(schema).apply(event)  TableSchemaChangeEventDispatcher.java:64-69
           -> AlterTableSchemaEventHandler.apply(SchemaChangeEvent)  AlterTableSchemaEventHandler.java:60-63
              -> apply(schema, alterTableEvent): instanceof AlterTableAddColumnEvent -> applyAddColumn()  :81-82
                 -> originFields.contains(column.getName()) -> applyModifyColumn(...)  :108-116   (new guard skipped; unknown anchor ends in Optional.get() at :226)
                 -> int index = originFields.indexOf(addColumnEvent.getAfterColumn())  :122   (exact String.equals)
                 -> if (index < 0) throw new SchemaEvolutionException(SCHEMA_EVENT_PROCESSING_FAILED, ...)  :123-136   [CHANGED]
                    -> SchemaEvolutionException(errorCode, errorMessage): tableIdentifier = null, jobId = null  SchemaEvolutionException.java:33-37
                 -> newColumns.add(index + 1, column)  :137
     -> collector.collect(schemaChangeEvent)  :229   (never reached when the guard throws; the exception propagates out of deserialize())

Sink side (same handler, same guard)
AbstractJdbcSinkWriter.applySchemaChange(event)  AbstractJdbcSinkWriter.java:73
  -> tableSchemaChanger.reset(tableSchema).apply(event)  :79   (throws before reOpenOutputFormat()/dialect.applySchemaChange at :80,:99)
     -> TableSchemaChangeEventDispatcher.apply()  TableSchemaChangeEventDispatcher.java:60-69
        -> AlterTableSchemaEventHandler.apply(): AlterTableColumnsEvent loops newSchema = apply(newSchema, columnEvent)  AlterTableSchemaEventHandler.java:84-90
           -> applyAddColumn() -> guard at :123-136   [CHANGED]
  Same dispatcher is constructed in DorisSinkWriter.java:87, DatabendSinkWriter.java:77, StarRocksSinkWriter.java:59, PaimonSinkWriter.java:113, ElasticsearchSinkWriter.java:125, RedisSinkWriter.java:105
  ElasticsearchSinkWriter.applySchemaChange(): applySingleSchemaChangeEvent() -> esRestClient.addField(...)  ElasticsearchSinkWriter.java:192-197,219   runs before tableSchemaChangeEventHandler.reset(tableSchema).apply(event)  :202
  Direct handler callers: AbstractWriteStrategy.java:277, AbstractBigQuerySinkWriter.java:287, AbstractCatalogSupportMapTransform.java:67, SQLTransform.java:242, CalciteTransform.java:169, TextChunkTransform.java:87

Not touched by this PR (same defect remains)
DataTypeChangeEventDispatcher.createHandlers(): new AlterTableEventHandler()  DataTypeChangeEventDispatcher.java:77
  -> AlterTableEventHandler.applyAddColumn(): index = originFields.indexOf(getAfterColumn()); originFields.add(index + 1, ...)  AlterTableEventHandler.java:113-115   (still prepends on -1)
  Instantiated by SeaTunnelSourceCollector.java:78, IcebergSinkWriter.java:76, ConsoleSinkWriter.java:65

Test entry points
AlterTableSchemaEventHandlerTest.addColumnAfterExistingColumnKeepsItsPosition()  AlterTableSchemaEventHandlerTest.java:35-42 -> handler.reset(schema("a","b")).apply(addAfter(TABLE, column("c"), "a"))
AlterTableSchemaEventHandlerTest.addColumnAfterUnknownColumnIsRejected()  AlterTableSchemaEventHandlerTest.java:50-63 -> assertThrows(SchemaEvolutionException) on addAfter(TABLE, column("c"), "missing")

Findings

Issue 1: The fail-fast has no recovery path, and it also fires where the tracked schema diverges from the source table by design (schema-changes.exclude)

  • Location: seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/handler/AlterTableSchemaEventHandler.java:127
  • Why it matters: Root cause: the comment and message assume a missing anchor means "the event does not describe this table". The handler is applied to SeaTunnel's tracked schema, though, and that schema can legitimately differ from the physical source table.
  • SchemaChangeEventFilter documents that a filtered-out event is "neither forwarded to downstream coordination nor applied to the produced schema". With schema-changes.exclude = ["change.column"], a rename a -> a2 is dropped in SeaTunnelRowDebeziumDeserializeSchema before the schema is updated. A later, fully valid ADD COLUMN c AFTER a2 is an eligible add.column event applied to a schema that still has a. It used to be prepended; now it throws.
  • The throw is deterministic: it depends only on the tracked schema and the event. If the job restarts from a checkpoint taken before the DDL record, the record is read again and fails the same way. This PR adds no skip option and no documented recovery procedure.
  • Some callers reach the throw after external side effects. ElasticsearchSinkWriter.applySchemaChange runs esRestClient.addField(...) for every sub-event before it calls tableSchemaChangeEventHandler.reset(tableSchema).apply(event). The index mapping is therefore already changed when the runtime schema update is rejected. JDBC, Doris, StarRocks and Databend apply the handler before their physical DDL and are not affected this way.
  • Fix: keep the strict check in the handler, but make the source lenient where divergence is intentional. When schemaChangeEventFilter is not a no-op (isNoOp()) and the anchor is absent from the produced schema, rewrite the event in SeaTunnelRowDebeziumDeserializeSchema to AlterTableAddColumnEvent.add(...) (append) with a WARN before applying and forwarding it. Source and sinks then stay in step.
  • Since a running job can now fail where it previously continued, please also record the behaviour change and the recovery steps in docs/en/introduction/concepts/incompatible-changes.md (and the zh counterpart).
  • Evidence: seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/handler/AlterTableSchemaEventHandler.java:127 throw new SchemaEvolutionException(; seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/handler/AlterTableSchemaEventHandler.java:128 SchemaEvolutionErrorCode.SCHEMA_EVENT_PROCESSING_FAILED,; seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/handler/AlterTableSchemaEventHandler.java:123 if (index < 0) {
  • Suggested fix: "It does not describe this table" does not always hold. With schema-changes.exclude = ["change.column"] the CDC source deliberately does not apply a rename a -> a2 to the produced schema (see the SchemaChangeEventFilter Javadoc), so a later valid ADD COLUMN c AFTER a2 arrives here with an anchor the tracked schema cannot have. The throw is deterministic, so a restart from a checkpoint taken before the DDL record reads it again and fails the same way. Could the source rewrite such an event to a plain append (with a WARN) when the filter is active, and could we note the new failure mode and how to recover in incompatible-changes.md? Also note that ElasticsearchSinkWriter.applySchemaChange calls addField before invoking this handler, so there the rejection arrives after the mapping was already changed.
  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: MySQL-CDC source with schema-changes.exclude = ["change.column"] on table t(a, b). Run ALTER TABLE t CHANGE a a2 INT (filtered, tracked schema stays [a, b]). Then run ALTER TABLE t ADD COLUMN c INT AFTER a2. The deserializer throws SchemaEvolutionException: Cannot add column 'c' after 'a2': table ... has no such column, existing columns: [a, b] instead of emitting the add-column event.

Issue 2: Tests cover only a standalone event on a bare handler; the composite path the CDC source actually emits and the already-existing-column path are not pinned

  • Location: seatunnel-api/src/test/java/org/apache/seatunnel/api/table/schema/handler/AlterTableSchemaEventHandlerTest.java:62
  • Why it matters: Root cause: both tests call new AlterTableSchemaEventHandler().reset(schema("a", "b")).apply(...) with a single AlterTableAddColumnEvent.
  • CDC sources wrap column changes in an AlterTableColumnsEvent. The guard is only correct there because the private apply loop (AlterTableSchemaEventHandler.java:84-90) threads the intermediate schema through each sub-event. A statement like ADD x, ADD y AFTER x must keep working, since x does not exist in the original schema. Nothing asserts that today, so a later refactor that validates anchors against the original schema would reject valid multi-clause DDL unnoticed.
  • The rejection test's only assertion is that the message contains missing.
  • The branch where the added column already exists and the anchor is unknown has no test. It currently behaves differently: it is routed to applyModifyColumn and ends in a NoSuchElementException from Optional.get().
  • Fix: add cases to this class for
  • (1) a composite AlterTableColumnsEvent with [ADD x, ADD y AFTER x] expecting [a, b, x, y],
  • (2) a composite whose second sub-event has an unknown anchor, expecting the SchemaEvolutionException, and
  • (3) the existing-column case once it is routed through the same check.
  • Evidence: seatunnel-api/src/test/java/org/apache/seatunnel/api/table/schema/handler/AlterTableSchemaEventHandlerTest.java:62 Assertions.assertTrue(failure.getMessage().contains("missing"), failure.getMessage());
  • Suggested fix: Could we also pin the composite path here? CDC sources emit AlterTableColumnsEvent, and the guard is only safe because the handler threads the intermediate schema through the sub-events, so [ADD x, ADD y AFTER x] must still yield [a, b, x, y]. A second case with an unknown anchor in the second sub-event, asserting the SchemaEvolutionException, would cover the failure path of the loop. Right now the only assertion on the rejection is the message text.
  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: Schema [a, b], handler.apply(AlterTableAddColumnEvent.addAfter(TABLE, column("b"), "missing")) throws java.util.NoSuchElementException from applyModifyColumn, and no test pins it. Likewise no test applies AlterTableColumnsEvent[ADD x, ADD y AFTER x] to [a, b] to pin [a, b, x, y].

Issue 3: The new tests cover a single standalone event; the composite and replay paths where the guard can misfire are not exercised

  • Location: seatunnel-api/src/test/java/org/apache/seatunnel/api/table/schema/handler/AlterTableSchemaEventHandlerTest.java:50
  • Why it matters: The two tests call AlterTableSchemaEventHandler directly with one AlterTableAddColumnEvent. The shapes that production resolvers emit are not covered.
  • Chained adds in one AlterTableColumnsEvent: the SQL Server and Postgres resolvers anchor each added column on the preceding column of the new table layout (SqlServerSchemaChangeResolver.buildAddEvent, PostgresRelationSchemaChangeResolver.resolveAddedColumns). Two columns added together therefore arrive as ADD c AFTER b, ADD d AFTER c, where the second anchor only exists after the first sub-event is applied. The handler and the CDC deserializer do apply sub-events sequentially, but nothing pins that. A later refactor that validates anchors against the original schema would now fail jobs instead of misordering a column.
  • An anchor that differs only by case, e.g. MySQL AFTER ID against a tracked column id. The lookup is an exact indexOf, so this is rejected today; a test should pin whichever behaviour is intended.
  • An ADD whose column already exists with an unknown anchor (the modify fallback, which still throws NoSuchElementException).
  • The TableSchemaChangeEventDispatcher entry point, which is what the CDC deserializer and most sink writers (JDBC, Doris, StarRocks, Databend, Paimon, Elasticsearch, Redis) call.
    Please add these cases to this test class; they are cheap and need no external services.
  • Evidence: seatunnel-api/src/test/java/org/apache/seatunnel/api/table/schema/handler/AlterTableSchemaEventHandlerTest.java:60 TABLE, column("c"), "missing")));
  • Suggested fix: Could we extend this class with the shapes the resolvers produce? (1) An AlterTableColumnsEvent with ADD c AFTER b then ADD d AFTER c, asserting [a, b, c, d], since the second anchor only exists after the first sub-event. (2) An anchor differing only by case, to pin the intended behaviour. (3) An ADD of an already-existing column with an unknown anchor (the modify fallback). (4) The same assertions through TableSchemaChangeEventDispatcher, which is what the CDC deserializer and most sink writers call.
  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: No test applies AlterTableColumnsEvent[ADD c AFTER b, ADD d AFTER c] to schema [a, b] and asserts [a, b, c, d]. A refactor that validates anchors against the original schema would make the new guard reject this valid event with every current test still passing.

Issue 4: The exception uses the two-argument constructor, so getTableIdentifier() and getJobId() are always null even though the event exposes both

  • Location: seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/handler/AlterTableSchemaEventHandler.java:134
  • Why it matters: Root cause: new SchemaEvolutionException(errorCode, message) sets tableIdentifier = null and jobId = null (SchemaEvolutionException.java:33-37). The table is only interpolated into the message string through %s.
  • SchemaEvolutionException already has a (errorCode, errorMessage, tableIdentifier, jobId) constructor that fills the getters and appends [Table: ...] [Job: ...] via enrichErrorMessage. TableEvent exposes getJobId().
  • Impact: anything that inspects the structured fields gets nulls, and the job id can never appear in the message.
  • The job id may still be unset when the handler runs inside the CDC deserializer, because the resolvers do not set it. enrichErrorMessage skips null values, so passing it through is safe and picks up the job id wherever it has been set.
  • Fix: pass addColumnEvent.tableIdentifier() and addColumnEvent.getJobId() to the four-argument constructor, and drop the table %s placeholder from the format string so the table is not printed twice.
  • Evidence: seatunnel-api/src/main/java/org/apache/seatunnel/api/table/schema/handler/AlterTableSchemaEventHandler.java:134 addColumnEvent.tableIdentifier(),
  • Suggested fix: Small one: the two-argument constructor leaves getTableIdentifier() and getJobId() null. SchemaEvolutionException has a (code, message, tableIdentifier, jobId) overload that fills both and appends [Table: ..] [Job: ..] to the message (null values are skipped). Passing addColumnEvent.tableIdentifier() and addColumnEvent.getJobId() there would keep the structured context; the table %s placeholder can then be dropped so the table is not printed twice.
  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: Schema [a, b], apply(AlterTableAddColumnEvent.addAfter(TableIdentifier.of("catalog","db","t"), column("c"), "missing")). The caught exception has getTableIdentifier() == null and getJobId() == null, although the event's tableIdentifier() is catalog.db.t.

On points raised earlier in this thread

  • +1 — I checked this independently: The review describes the change rather than a defect, and the description still holds at head 2693b1c even though it was written against 7c98c63. An ADD COLUMN whose AFTER anchor is absent now throws a SchemaEvolutionException before the replacement schema is built, and an existing anchor still inserts directly after it. This agreement covers only the visible part of the claim; the body is truncated, and it does not address the divergent-schema case confirmed in F2.

Review conclusion

Conclusion: final approval remains pending on the previous comments

2. Remaining follow-ups

  • Issue 1: The fail-fast has no recovery path, and it also fires where the tracked schema diverges from the source table by design (schema-changes.exclude)
  • Issue 2: Tests cover only a standalone event on a bare handler; the composite path the CDC source actually emits and the already-existing-column path are not pinned
  • Issue 3: The new tests cover a single standalone event; the composite and replay paths where the guard can misfire are not exercised
  • Issue 4: The exception uses the two-argument constructor, so getTableIdentifier() and getJobId() are always null even though the event exposes both

Thanks for the updates so far. Happy to discuss the remaining points.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants