Repository navigation
[Fix][Transform-V2] Optionally emit a DELETE when a SQL WHERE rejects an UPDATE_AFTER - #13393
SEPURI-SAI-KRISHNA wants to merge 6 commits into
Conversation
…AFTER The WHERE clause of the Sql and Calcite transforms judged each row on its own and kept its row kind. When an update moved a row out of the condition, its UPDATE_BEFORE (old values, matching) was kept and its UPDATE_AFTER (new values, not matching) was dropped. Sinks that write UPDATE_AFTER as an upsert and skip UPDATE_BEFORE (Jdbc with primary_keys, Elasticsearch, ClickHouse, Kudu, MongoDB) kept the old row, and the job finished without an error. A rejected UPDATE_AFTER is now projected and emitted as a DELETE, so the sink removes the row. Rejected INSERT, UPDATE_BEFORE and DELETE rows are still dropped, and a query without a WHERE clause does not change. - Zeta engine: the rejected row goes through the normal projection and lateral views with the DELETE row kind. - Calcite engine: a second plan of the query without its WHERE clause builds the image, for a single SELECT without GROUP BY or HAVING, with or without ORDER BY. - If that projection fails (the WHERE clause may guard it), the row is dropped as before and a warning is logged once. Documented in sql.md, calcite.md and incompatible-changes.md (EN, ZH). Closes apache#13384
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for contributing to Apache SeaTunnel! I reviewed the complete current diff and followed its entry points and failure paths. The items below need attention before merging; I hope the concrete paths make the next step straightforward.
What problem does this PR solve?
User pain point: after a CDC row stops matching WHERE, an upsert sink that ignores UPDATE_BEFORE can retain the old row because the new UPDATE_AFTER is filtered away.
Fix approach: project a rejected UPDATE_AFTER and send it as DELETE; Calcite compiles a second supported SELECT with WHERE removed.
One sentence: the ordinary stable-key update-out-of-filter case can remove its old target row.
Example: key 1 changes status active to inactive; SELECT id,status WHERE status=active now sends DELETE(id=1) instead of leaving the old active row in JDBC.
1. Code changes
1.1 Core logic
Complete runtime path:
CDC/FakeSource ordered changelog -> SQLTransform.transformRow -> ZetaSQLEngine.transformBySQL
-> filter true: project with original RowKind
-> false + UPDATE_AFTER: projectRow(..., DELETE) -> lateral view -> sink
-> false + other kind: drop; failed delete projection: warn once/debug later and drop
CalciteTransform.transformRow:85-88 -> CalciteSQLEngine.execute:212
-> original compiled plan -> if empty UPDATE_AFTER and fallback available
-> second single-SELECT plan without WHERE -> output DELETE, preserving tableId/options
-> fallback RuntimeException: warn/drop; close clears both plan references
JDBC generated keyed output -> BufferReducedBatchStatementExecutor.addToBatch:67-78
-> skips UPDATE_BEFORE -> buffers DELETE key -> deleteExecutor.executeBatch
JdbcSinkCDCChangelogIT:140-190 runs both transforms and queries exact final PostgreSQL rows.
Key findings and correctness:
All thirteen changed files, both engine entry points, the generated keyed JDBC executor and both new fixture bodies were read. The original stale-row condition is real: JDBC explicitly returns for UPDATE_BEFORE at BufferReducedBatchStatementExecutor:68-70. Normal matching rows preserve kinds/metadata; rejected non-update rows retain prior dropping behavior. Zeta applies lateral views after projecting the DELETE. Calcite removes WHERE only for a single SELECT without GROUP/HAVING and preserves ORDER BY; unsupported query shapes have no fallback. This is a stateless best-effort correction, not full materialized-view maintenance: it has no old projected image, so its guarantee depends on a stable projected target key. A failing guarded projection intentionally retains the old drop behavior and can still leave stale target data; the bilingual docs disclose that limitation. New deletes can also reach sinks for outside-to-outside updates, with Kudu not-found handling called out explicitly. No checkpoint state is added.
Before:
if (!retain) {
return null;
}After:
if (retain) {
return projectRow(inputFields, inputRow, inputRow.getRowKind(), outRowType);
}
if (inputRow.getRowKind() != RowKind.UPDATE_AFTER) {
return null;
}
return projectRow(inputFields, inputRow, RowKind.DELETE, outRowType);1.2 Compatibility
Partially incompatible observable changelog behavior, documented in both incompatible-changes pages. SQL signatures, option names/defaults, row schema and checkpoint bytes stay unchanged, but rejected UPDATE_AFTER now produces DELETE and may need target delete permission. Existing loaded stale rows require reload; Kudu may need ignore_not_found=true. Append-only targets are not upgraded into keyed deletion semantics. Project a stable target key; transformed/changing keys require a separate old-image contract.
1.3 Performance and side effects
Zeta projects rejected UPDATE_AFTER rows that previously skipped projection. Calcite adds a second compilation for supported WHERE queries, and a second per-row plan execution for empty rejected UPDATE_AFTER results. This adds CPU/GC and output/delete network operations; it adds no state buffer, coordinator lock, timer or checkpoint owner. The plan-local first-warning flag limits repeated stack traces at WARN; later failures remain DEBUG. Fallback failures are deliberately swallowed only in the new best-effort delete-image path, with a warning that keyed data may remain. Original-plan failures still propagate through the expression error path.
1.4 Errors, logging, and findings
Issue 1: Document the extracted plan-compilation contract
- Location:
seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/calcite/engine/CalciteSQLEngine.java:155. - Description and risk: toBindable is a newly extracted core planning method used for both original and WHERE-free plans. It has no method contract describing the enumerable conversion, input ownership and returned reusable plan. The mandatory core-method documentation requirement is not satisfied by the adjacent comment on compileWithoutWhere.
- Best improvement: Add a short Javadoc describing the logical-plan conversion and the reusable Bindable contract; keep it local to this helper. No planner redesign or new dependency is needed.
- Responsibility and trade-off: A precise stateless correction belongs in the transform engines that own filtering and projection. Retaining and pairing old images could support changing projected keys and failed new projections, but introduces recovery/state ownership and is a separate, larger design. Do not claim that stronger guarantee for this minimal patch.
- Severity: Medium; blocking: true.
- Previously raised by another reviewer: No, unless explicitly attributed above.
Issue 2: Close test engines even when assertions fail
- Location:
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/calcite/CalciteSQLEngineTest.java:4344. - Description and risk: The added Calcite tests call engine.close only after assertions. An assertion or execution failure skips cleanup of registered UDF lifecycle resources. This is a test failure-isolation risk rather than a demonstrated flaky assertion.
- Best improvement: Wrap each initialized engine in try/finally or try-with-resources, following the nearby existing lifecycle tests. Likewise close the SQLTransform fixtures where their lifecycle opens resources.
- Responsibility and trade-off: A precise stateless correction belongs in the transform engines that own filtering and projection. Retaining and pairing old images could support changing projected keys and failed new projections, but introduces recovery/state ownership and is a separate, larger design. Do not claim that stronger guarantee for this minimal patch.
- Severity: Medium; blocking: false.
- Previously raised by another reviewer: No, unless explicitly attributed above.
Community reconciliation: the collected review, inline and discussion histories contained no non-bot source finding or independent maintainer merge recommendation at this head. These are Daniel's initial complete-source conclusions.
2. Code quality
2.1 Conventions
Reviewed all changed files for license, imports, naming, core-method and state-field comments. See the numbered findings for the required changes.
2.2 Test coverage and stability
Stability rating: At risk. At risk for assertion-failure cleanup in Issue 2, non-blocking. Otherwise the tests use fixed row values, cover every RowKind, metadata, no-WHERE, ORDER BY, lateral expansion and guarded-projection failure, with no new sleeps/random/time assertions. The PostgreSQL IT truncates before/after, closes connections/statements/results, executes completed batch jobs and compares sorted exact stored rows rather than only exit codes. Its single reader setting and existing FakeSource split default avoid new scheduling-dependent expected values; Spark is explicitly disabled because it loses RowKind. Missing coverage worth adding includes outside-to-outside updates and unsupported Calcite query shapes. The shared stable-key assumption should be explicit in user guidance. No local build/tests/runtime was run.
2.3 Documentation
All six English/Chinese SQL, Calcite and incompatible-change additions agree on kinds, best-effort projection failure, Kudu delete behavior, target key selection and reload. Clarify that the projected key must remain stable across the update, since projecting only the new image cannot reconstruct an old transformed key. The guides correctly limit Calcite fallback query shape.
3. Architecture
3.1 Change location
A precise stateless correction belongs in the transform engines that own filtering and projection. Retaining and pairing old images could support changing projected keys and failed new projections, but introduces recovery/state ownership and is a separate, larger design. Do not claim that stronger guarantee for this minimal patch.
3.2 Maintainability
Keep the behavior, lifecycle ownership, and failure contract together. A precise stateless correction belongs in the transform engines that own filtering and projection. Retaining and pairing old images could support changing projected keys and failed new projections, but introduces recovery/state ownership and is a separate, larger design. Do not claim that stronger guarantee for this minimal patch.
3.3 Extensibility
Prefer the existing component boundary and tests over unrelated shared abstractions.
3.4 Upgrade impact
Partially incompatible observable changelog behavior, documented in both incompatible-changes pages. SQL signatures, option names/defaults, row schema and checkpoint bytes stay unchanged, but rejected UPDATE_AFTER now produces DELETE and may need target delete permission. Existing loaded stale rows require reload; Kudu may need ignore_not_found=true. Append-only targets are not upgraded into keyed deletion semantics. Project a stable target key; transformed/changing keys require a separate old-image contract.
4. Findings summary
Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.
| # | Finding | Location | Severity |
|---|---|---|---|
| 1 | Document the extracted plan-compilation contract | seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/calcite/engine/CalciteSQLEngine.java:155 |
Medium |
| 2 | Close test engines even when assertions fail | seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/calcite/CalciteSQLEngineTest.java:4344 |
Medium |
5. Merge recommendation
Merge after fixes
Blocking items: Issues 1. Current-head CI and write-capable maintainer review remain independent requirements.
Non-blocking suggestions: Issue 2: Close test engines even when assertions fail
Overall: the approach addresses a real path, but the listed blockers must be closed. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.
CI and repository state: Signal pull request update: SUCCESS; Build: SUCCESS; Build: success. GitHub reports BLOCKED / REVIEW_REQUIRED.
Verification: Reviewed all changed files and the referenced call sites at bf5223b0babf429e693a9c74ccd70e1a21152262 against merge base 7029c0969a9f6ea9add7a11f9262f42fe2ce9da9. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.
Review time: 2026-11-23T07:14:55.586718-05:00
Local evidence: git fetch obtained head bf5223b0babf429e693a9c74ccd70e1a21152262; git merge-base returned 7029c0969a9f6ea9add7a11f9262f42fe2ce9da9; git diff --stat reports 13 files changed, 655 insertions(+), 30 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.
Add where_rejected_update_as_delete (boolean, default false) to the Sql and Calcite transforms. With the default, the WHERE clause drops every row that does not match, as before. When enabled, a rejected UPDATE_AFTER is emitted as a DELETE of its projected row, in both the Zeta and the Calcite engine. The Calcite engine compiles the query without its WHERE clause only when the option is enabled. Tests assert the row kinds for both settings in both engines, the option rule, and that a table_transform entry reads the option. The Jdbc E2E checks exact final rows for Sql and Calcite with a schema primary key, a key set only on the sink, and a keyless append-only sink with the default. Docs (EN/ZH) describe the option, the stable-key requirement and the projection limits. The incompatible-changes entries are removed, since the default behavior no longer changes. Also add the Javadoc of CalciteSQLEngine.toBindable and close the test engines and transforms in finally blocks.
…lete # Conflicts: # seatunnel-transforms-v2/src/main/java/org/apache/seatunnel/transform/sql/SQLTransform.java
|
Thank you @DanielLeens for the review. Following the discussion on #13384, this update makes the behavior opt-in and covers both points:
Locally on JDK 17: the whole transforms module 2059 tests with 0 failures, and |
…lete # Conflicts: # docs/en/transforms/sql.md # docs/zh/transforms/sql.md
…lete # Conflicts: # seatunnel-e2e/seatunnel-connector-v2-e2e/connector-jdbc-e2e/connector-jdbc-e2e-part-3/src/test/java/org/apache/seatunnel/connectors/seatunnel/jdbc/JdbcSinkCDCChangelogIT.java
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the update and contribution to Apache SeaTunnel. I re-reviewed the complete latest diff, including the default-false policy, schema-change engine replacement and added database cases. Previous blocking Issue 1 is closed; I do not see a remaining production source blocker in this bounded opt-in design.
What problem does this PR solve?
User pain: A CDC update moving a row out of WHERE can leave the old keyed target row because Jdbc ignores UPDATE_BEFORE and the new image is filtered out.
Fix: Add default-false where_rejected_update_as_delete to Sql and Calcite; opt-in rejected UPDATE_AFTER emits its projected new image as DELETE.
One sentence: Provide a bounded, explicitly selected correction for stable-key filtered CDC updates.
Example: With the option enabled and unchanged id=1, active-to-inactive produces DELETE(1); with the default it retains the historical filter-only behavior.
1. Code changes
1.1 Core logic
Complete runtime path:
Transform factory option rule -> per-table or top-level config -> Sql/Calcite transform
-> SQLTransform.newSqlEngine -> setWhereRejectedUpdateAsDelete -> init
-> schema candidate evaluate uses same newSqlEngine -> commit swaps live engine, closes retired
-> CalciteTransform.open uses final configured flag; schema change closes engine and lazy reopen retains it
Sql ZETA/INTERNAL -> SQLEngineFactory:27-29 -> ZetaSQLEngine.transformBySQL
-> WHERE true: normal projection/original RowKind
-> WHERE false + opt-in UPDATE_AFTER: projectRow DELETE -> lateral views -> sink
-> other rejected rows drop; new-image projection failure warns once and drops
Calcite init -> original bindable + opt-in WHERE-free single SELECT plan, excluding GROUP/HAVING
-> original result empty + UPDATE_AFTER + fallback present -> execute fallback as DELETE
-> preserve table ID/options; guarded projection failure drops; close clears both plans
Keyed Jdbc BufferReducedBatchStatementExecutor:67-78 skips UPDATE_BEFORE, routes DELETE by key
-> real PostgreSQL E2E compares sorted stored rows for source-schema key / sink-only key
-> default-false keyless case asserts historical append results
Key findings and correctness:
- Read the full 25-file diff, all six E2E fixtures and new UT assertions. The stale-row path is real because keyed Jdbc skips UPDATE_BEFORE; the transform changes are normally reached for enabled rejected UPDATE_AFTER rows, not only recovery.
- Existing constructors/default settings retain false. No WHERE-free plan is compiled when disabled. Factories advertise the Option, with per-table entries passed as their own ReadonlyConfig by AbstractMultiCatalogTransform:66-69/97-108, matching the explicit no-inheritance documentation. Both ZETA and INTERNAL select ZetaSQLEngine.
- SQL schema changes build candidates using newSqlEngine:169, not raw createSqlEngine. evaluate:535 initializes the configured candidate; commit:576-594 adopts it and closes the retired engine. Calcite schema invalidation closes and lazily reopens using its final option. This addresses the author's new lifecycle point with source evidence.
- The previous Issue 1 toBindable Javadoc is present. Most engine fixtures now use try-with-resources/finally; the two newly added multi-catalog rule tests still omit close, so optional Issue 2 remains narrowly scoped below.
- This is stateless best-effort behavior, not full CDC materialized-view maintenance: only the new projected key is available, and failed projection can still leave stale data. Keys must remain stable, the sink must actually delete by them, and old stale targets may need reload. Outside-to-outside updates can issue harmless absent-key deletes only for sinks whose semantics allow them; Kudu requires its documented ignore-not-found choice.
- Calcite supports only a single SELECT without GROUP/HAVING for fallback, optionally wrapped in ORDER BY. Unsupported query shapes keep dropping rejected rows. Zeta applies lateral views to projected DELETE images; preserving a key through any such expansion remains the user's responsibility. No state buffer, checkpoint format or old-row pairing is introduced.
Before:
private final String sql;
private final String inputTableName;
private transient CalciteSQLEngine engine;
public CalciteTransform(@NonNull ReadonlyConfig config, @NonNull CatalogTable catalogTable) {
super(catalogTable, config.get(TransformCommonOptions.ROW_ERROR_HANDLE_WAY_OPTION));
this.sql = config.get(CalciteTransformConfig.SQL);
List<String> pluginInputIdentifiers = config.get(ConnectorCommonOptions.PLUGIN_INPUT);
if (pluginInputIdentifiers != null && !pluginInputIdentifiers.isEmpty()) {
this.inputTableName = pluginInputIdentifiers.get(0);
After:
private final String sql;
private final String inputTableName;
private final boolean whereRejectedUpdateAsDelete;
private transient CalciteSQLEngine engine;
public CalciteTransform(@NonNull ReadonlyConfig config, @NonNull CatalogTable catalogTable) {
super(catalogTable, config.get(TransformCommonOptions.ROW_ERROR_HANDLE_WAY_OPTION));
this.sql = config.get(CalciteTransformConfig.SQL);
this.whereRejectedUpdateAsDelete =
config.get(TransformCommonOptions.WHERE_REJECTED_UPDATE_AS_DELETE);
List<String> pluginInputIdentifiers = config.get(ConnectorCommonOptions.PLUGIN_INPUT);
if (pluginInputIdentifiers != null && !pluginInputIdentifiers.isEmpty()) {
this.inputTableName = pluginInputIdentifiers.get(0);
1.2 Compatibility
Fully compatible for existing configurations: the new boolean Option defaults to false, old engine constructors delegate with false, and existing filtered rows retain their previous disposition. Enabling the new option intentionally adds DELETE records and corresponding target permissions/CPU/network work. API addition is default-method/overload based; no existing option/default, schema, protocol or checkpoint serialization format is removed. No incompatible-changes entry is necessary for the unchanged default. Opt-in users need stable selected sink keys, a deleting target, and possible target reload.
1.3 Performance and side effects
Disabled behavior avoids fallback compilation/execution. Enabled Zeta adds projection/lateral work on rejected UPDATE_AFTER; Calcite adds a second compilation and potentially another per-row plan execution. Output DELETEs add sink/network cost. No unbounded row state, timer, coordinator lock or shared retry owner is introduced; per-engine warning flags limit repeated WARN stack traces. Existing UDF/projection side effects can run in the fallback and callers should not treat SQL projections as durable old-row storage. No measured throughput claim.
1.4 Errors, logging, and findings
Issue 2: Close the newly added multi-catalog fixtures as well
- Location:
seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/calcite/CalciteSQLEngineTest.java:4484. - Description and risk: The new table_transform option test creates a CalciteMultiCatalogTransform, lazily opens its engine through flatMap, and never closes it, on either success or assertion failure. SQLMultiCatalogFlatMapTransformTest:171-186 follows the same pattern. The direct engine and schema-change fixtures are now correctly scoped; this is the remaining part of earlier non-blocking Issue 2, not a new runtime blocker.
- Best improvement: Wrap each multi-catalog fixture in try/finally and call close; retain the exact row-kind assertions. This keeps lifecycle/UDF cleanup evidence consistent without changing production behavior.
- Responsibility and trade-off: The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
- Severity: Medium; blocking: false.
- Previously raised by another reviewer: No, unless explicitly attributed above.
The collected non-Daniel review/inline/discussion history contains no independent source finding or maintainer approval/change request to endorse or dispute. The author's direct reply is addressed here in the same full review: the planning Javadoc is fixed, direct fixtures are scoped, default compatibility is preserved, and newSqlEngine applies the flag to committed candidates. Current queued Build is a fresh gate on this head, not the old head's successful run. Daniel's technical blocker is cleared; a COMMENT cannot dismiss a historical requested-changes record or substitute for write-capable maintainer approval.
2. Code quality
2.1 Conventions
Reviewed all changed files for license, imports, naming, core-method and state-field comments. See the numbered findings for the required changes.
2.2 Test coverage and stability
Stability rating: At risk. At risk only for optional Issue 2 cleanup. New row-kind tests use fixed values, check disabled/enabled behavior, projection output, table ID/options, no-WHERE, ORDER BY, guarded-projection failure, GROUP BY exclusion, per-table config, lateral expansion and SQL schema-change replacement. E2E truncates before/after in finally, closes JDBC resources, uses a completed batch job and compares exact ordered database rows for schema keys, sink-only keys and the keyless default. Spark remains disabled with the existing explicit RowKind-loss reason. There are no new sleeps, random ports, timing-dependent expected rows or weakened result assertions. No local transform tests or E2E were executed; the author's reported 2059 tests and four Zeta cases remain their evidence.
2.3 Documentation
EN/ZH Sql and Calcite guides agree on false default, row-kind table, stable keys, sink-only/source-schema keys, per-table non-inheritance, keyless append limitations, Kudu behavior, guarded projection and target reload. The obsolete unconditional incompatible-change entries are absent from the final target-relative diff. This is more precise than the prior always-on proposal; no full old-image or exactly-once guarantee is implied.
3. Architecture
3.1 Change location
The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.2 Maintainability
Keep the behavior, lifecycle ownership, and failure contract together. The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.3 Extensibility
Prefer the existing component boundary and tests over unrelated shared abstractions.
3.4 Upgrade impact
Fully compatible for existing configurations: the new boolean Option defaults to false, old engine constructors delegate with false, and existing filtered rows retain their previous disposition. Enabling the new option intentionally adds DELETE records and corresponding target permissions/CPU/network work. API addition is default-method/overload based; no existing option/default, schema, protocol or checkpoint serialization format is removed. No incompatible-changes entry is necessary for the unchanged default. Opt-in users need stable selected sink keys, a deleting target, and possible target reload.
4. Findings summary
Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.
| # | Finding | Location | Severity |
|---|---|---|---|
| 2 | Close the newly added multi-catalog fixtures as well | seatunnel-transforms-v2/src/test/java/org/apache/seatunnel/transform/calcite/CalciteSQLEngineTest.java:4484 |
Medium |
5. Merge recommendation
Can merge once the recorded CI and repository gates are satisfied
Blocking items: No source blocker. Current-head CI and write-capable maintainer review remain independent requirements.
Non-blocking suggestions: Issue 2: Close the newly added multi-catalog fixtures as well
Overall: the reviewed source path is coherent; no runtime acceptance is claimed beyond the actual CI result. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.
CI and repository state: Signal pull request update: SUCCESS; Build: IN_PROGRESS; Build: queued. GitHub reports BLOCKED / REVIEW_REQUIRED.
Verification: Reviewed all changed files and the referenced call sites at b2408e367e507c2f35c3a0c6ecf7738f3709ef13 against merge base 60e039a810844323172d4048f721bc88146e9a83. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.
Review time: 2026-11-26T08:40:49.651180-05:00
Local evidence: git fetch obtained head b2408e367e507c2f35c3a0c6ecf7738f3709ef13; git merge-base returned 60e039a810844323172d4048f721bc88146e9a83; git diff --stat reports 25 files changed, 1513 insertions(+), 35 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.
|
Thanks @DanielLeens. One note: on dev, |
DanielLeens
left a comment
There was a problem hiding this comment.
Thanks for the careful follow-up! I re-reviewed the complete latest head. Both new wrapper fixtures now call close in finally, so my remaining optional Issue 2 is closed. Your distinction between calling the public wrapper lifecycle and the separate child-close propagation issue is correct.
What problem does this PR solve?
User pain: A CDC update moving a row outside WHERE can leave its old target row because keyed Jdbc ignores UPDATE_BEFORE and the new image is filtered away.
Change: Add default-false where_rejected_update_as_delete to Sql/Calcite; when enabled, project a rejected UPDATE_AFTER as DELETE.
In one sentence: Allow explicitly opted-in stable-key CDC filters to remove a row that stops matching. Example: id=1 active -> inactive deletes target id=1 instead of leaving its old active image.
1. Code changes
1.1 Core logic
Complete runtime path:
Factory option rule -> top-level or complete per-table configuration -> Sql/Calcite transform
SQLTransform.open/newSqlEngine -> apply flag before init; schema evaluate builds same configured candidate -> commit adopts candidate and closes retired engine
ZETA and INTERNAL -> ZetaSQLEngine WHERE -> accepted normal projection / rejected opt-in UPDATE_AFTER -> project DELETE -> lateral expansion
Calcite init -> original plan plus supported WHERE-free SELECT plan -> empty original result and UPDATE_AFTER -> fallback DELETE
-> row table ID/options preserved; fallback projection exception warns once then drops
Keyed Jdbc BufferReducedBatchStatementExecutor skips UPDATE_BEFORE, executes DELETE by sink key
TransformFlowLifeCycle.close -> wrapper public close; current AbstractMultiCatalogTransform has no child-close propagation
Key findings and correctness:
- Re-read all 25 changed files, six real database fixtures and the schema-change paths. The stale-target problem is real on the normal keyed CDC path.
- The default remains false and old constructors preserve it. Disabled Calcite avoids compiling a second plan; per-table entries read their own configuration rather than silently inheriting a top-level flag.
- SQL schema candidates use newSqlEngine at lines 167-170 and 534-542, so a successful schema change retains the option. Both ZETA and INTERNAL select ZetaSQLEngine. Calcite invalidation lazily reopens using its configured final flag.
- This is deliberately bounded, stateless best-effort behavior: only the new projected key is available. Stable keys and a sink that actually deletes are required; projection failure can still leave stale data, and previously stale rows may need reload. Calcite fallback excludes GROUP/HAVING and unsupported query shapes.
- Both multi-catalog tests now call public close in finally, closing my optional Issue 2 as requested. The author is correct that AbstractMultiCatalogTransform itself currently lacks child-close propagation. That existing lifecycle issue belongs to #13131/#13180; these tests now follow the same public close contract as TransformFlowLifeCycle, and I do not require an unrelated lifecycle redesign here.
Before: a rejected UPDATE_AFTER returned no row.
After:
if (!whereRejectedUpdateAsDelete || inputRow.getRowKind() != RowKind.UPDATE_AFTER) {
return null;
}
return projectRow(inputFields, inputRow, RowKind.DELETE, outRowType);The default-false guard preserves old behavior; the configured engine factory also applies it to schema-change candidates.
1.2 Compatibility
Fully compatible by default: the new Option defaults false, old constructors delegate with false, and existing rejected rows are dropped as before. Enabling it intentionally adds DELETEs and sink permissions/cost. No wire/checkpoint format or existing option/default is changed. Opt-in users need stable selected keys and may need target reload; bilingual guides explain these limits.
1.3 Performance and side effects
Disabled behavior avoids fallback planning. Enabled Zeta adds projection/lateral work; Calcite compiles a second plan and can evaluate a row twice. Extra DELETEs incur target/network work. There is no old-image buffer, checkpoint state, coordinator lock or per-row global retry owner. UDF side effects can occur in the fallback; this is not exactly-once materialized-view maintenance.
1.4 Errors, logging, and findings
No new source-level blocker found. Exceptions must still reach the existing job failure path; this review does not substitute for current-head CI.
Community input: no independent technical finding or maintainer approval/change request was present in the collected discussion.
2. Code quality
2.1 Conventions
Reviewed all changed files for license, imports, naming, core-method and state-field comments. No additional convention blocker found.
2.2 Test coverage and stability
Stability rating: Stable. Stable fixed row-kind and projected-value assertions cover enabled/disabled modes, NULL/empty rejection, options/table IDs, ORDER BY, unsupported GROUP shape, guarded projection, lateral expansion, per-table configuration and schema candidate replacement. The PostgreSQL IT waits for completed batch jobs and compares sorted exact target rows for source-schema keys, sink-only keys and default keyless append behavior; cleanup truncates in finally and closes JDBC resources. Both wrapper fixtures now close in finally at CalciteSQLEngineTest and SQLMultiCatalogFlatMapTransformTest. Their actual child cleanup remains limited by the separately identified wrapper issue; no runtime closure beyond that public API is claimed. Current exact-head Build is queued, not successful acceptance for this new head. No local tests ran.
2.3 Documentation
EN/ZH Sql and Calcite guides agree on the default, row-kind table, stable/sink-only keys, keyless append behavior, per-table non-inheritance, Kudu ignore-not-found, guarded projection and reload. No unconditional incompatible-change entry is needed for unchanged default behavior.
3. Architecture
3.1 Change location
The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.2 Maintainability
Keep the behavior, lifecycle ownership, and failure contract together. The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
3.3 Extensibility
Prefer the existing component boundary and tests over unrelated shared abstractions.
3.4 Upgrade impact
Fully compatible by default: the new Option defaults false, old constructors delegate with false, and existing rejected rows are dropped as before. Enabling it intentionally adds DELETEs and sink permissions/cost. No wire/checkpoint format or existing option/default is changed. Opt-in users need stable selected keys and may need target reload; bilingual guides explain these limits.
4. Findings summary
Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.
| # | Finding | Location | Severity |
|---|---|---|---|
| - | No new source blocker found | - | - |
5. Merge recommendation
Can merge once the recorded CI and repository gates are satisfied
Blocking items: No source blocker. Current-head CI and write-capable maintainer review remain independent requirements.
Non-blocking suggestions: None beyond the validation limits above.
Overall: the reviewed source path is coherent; no runtime acceptance is claimed beyond the actual CI result. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.
CI and repository state: Signal pull request update: SUCCESS; Build: QUEUED; Build: queued; Build: queued. GitHub reports BLOCKED / REVIEW_REQUIRED.
Verification: Reviewed all changed files and the referenced call sites at 2484f6b27cc54055f91d1e0323add215f450ac4a against merge base 60e039a810844323172d4048f721bc88146e9a83. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.
Review time: 2026-11-27T04:47:39.025169-05:00
Local evidence: git fetch obtained head 2484f6b27cc54055f91d1e0323add215f450ac4a; git merge-base returned 60e039a810844323172d4048f721bc88146e9a83; git diff --stat reports 25 files changed, 1521 insertions(+), 35 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.
Yes, glad to contribute to Apache SeaTunnel.
Purpose of this pull request
Closes #13384. Following the review there (@zhangshenghang, @SEZ9), the fix is opt-in: the existing
WHEREbehavior stays the default, and a job enables the new behavior withwhere_rejected_update_as_delete = true.The
WHEREclause of theSqlandCalcitetransforms judges each row on its own and keeps its row kind. When an update moves a row out of the condition, itsUPDATE_BEFORE(old values, matching) passes and itsUPDATE_AFTER(new values, not matching) is dropped. Sinks that writeUPDATE_AFTERas an upsert and skipUPDATE_BEFORE(for example Jdbc with a key) keep the old row, and the job finishes without an error.New option, the same in
SqlandCalcite:where_rejected_update_as_delete, boolean, defaultfalse.WHEREfalse(default)trueUPDATE_AFTERDELETEINSERT,UPDATE_BEFORE,DELETEZetaSQLEngine.transformBySQL: with the option, the rejected row goes through the normalprojectand lateral views, withDELETE.CalciteSQLEngine: theWHEREclause is compiled into the plan, so with the optioninit()also compiles the query without itsWHEREclause, for a singleSELECT(optionally underORDER BY) withoutGROUP BYorHAVING. Other query shapes drop the row as withfalse. Without the option nothing extra is compiled.TransformCommonOptionsand declared by both factories. Atable_transformentry reads it from the entry.WHEREclause can guard the projection (select 10 / x ... where x <> 0). If the projection of a rejectedUPDATE_AFTERfails, the row is dropped and a WARN is logged once per transform (then DEBUG).When to enable it
Documented in
sql.mdandcalcite.md(EN, ZH):DELETEis built from the new values only. If the query does not select the key, the output schema has no primary key and the sink cannot find the row.primary_keysand without a schema primary key would write theDELETEas a new row. This is why the option is off by default.DELETEis also sent when the old values did not match either: the sink needs theDELETEprivilege, and the Kudu sink needsignore_not_found = true.Does this PR introduce any user-facing change?
Yes, a new option
where_rejected_update_as_delete(defaultfalse) on theSqlandCalcitetransforms. With the default, behavior is unchanged, so there is noincompatible-changes.mdentry. Described indocs/en|zh/transforms/sql.md(section "WHERE on a CDC stream") anddocs/en|zh/transforms/calcite.md.How was this patch tested?
SQLTransformTest(Zeta) andCalciteSQLEngineTest: every row kind through a matching and a non-matchingWHERE, with the option absent,falseandtrue, asserting row kinds, values, table id and options; a query withoutWHEREkeeps every row kind for both settings;LATERAL VIEW(Zeta);ORDER BY, andGROUP BYdropping the row (Calcite); a failing projection drops the row; the transforms read the option from their config.SQLMultiCatalogFlatMapTransformTestandCalciteSQLEngineTest: atable_transformentry reads the option.SQLTransformFactoryTest,CalciteTransformFactoryTest: the option is optional, defaults tofalse, and does not make the transform-level rule partial.table_transformreads).SQLTransformSchemaChangeTest: after a schema change (dev's schema evolution swaps in the engine it evaluated), a rejectedUPDATE_AFTERis still aDELETEwith the option and still dropped without it. Both the live engine and every candidate are created throughnewSqlEngine(), which applies the option; with the candidate created without it, this test fails.seatunnel-transforms-v2module on JDK 17, after merging devf08c722acb: 2059 tests, 0 failures, 0 errors.JdbcSinkCDCChangelogIT(existing class, PostgreSQL), FakeSource ->SqlorCalcitewithWHERE status = 'active'-> Jdbc. Row 1 goesactive -> inactive, row 3inactive -> active, row 2 staysactive. Exact final rows, for both transforms:true, key from the schema primary key:[(2, active), (3, active)];true, no schema key,primary_keyson the sink:[(2, active), (3, active)];[(1, active), (1, active), (2, active), (3, active)], the same rows as before this PR (the rejectedUPDATE_AFTERis not appended).JdbcSinkCDCChangelogITpasses (4 tests, 6 new jobs).spotless:apply,git diff --check.Check list
New License Guide (no new jar)
incompatible-changes.mdto describe the incompatibility caused by this PR. (not needed: the default keeps the old behavior)