Skip to content

[Test][API] Fix schema-change close race on Windows runners - #11642

Closed
davidzollo wants to merge 2 commits into
apache:devfrom
davidzollo:dev-fix-multitable-schemachange-close-race-20260803
Closed

davidzollo wants to merge 2 commits into
apache:devfrom
davidzollo:dev-fix-multitable-schemachange-close-race-20260803

Conversation

@davidzollo

Copy link
Copy Markdown
Contributor

Purpose

unit-test (11, windows-latest) currently fails on every PR that has merged recent dev:

[ERROR] MultiTableSinkWriterSchemaChangeBroadcastTest.schemaChangeKeepsIOExceptionContractWhenWorkerAlreadyFailed
java.lang.RuntimeException: java.io.IOException: boom-before-schema-entry

Observed on #11597, #11569, #11493, #11264 and #11203 — none of which touch multi-table sink code. The test arrived with #11015.

Root Cause

The test asserts the IOException contract of applySchemaChange, then calls coordinator.close() as unguarded teardown:

assertEquals("boom-before-schema-entry", schemaChangeFailure.getMessage());
coordinator.close();   // <- no assertion, but any throw fails the test

The worker failure it just asserted stays recorded. close() calls checkQueueRemain(), which only reaches subSinkErrorCheck() while hasPendingRuntimeWrites() is still true — so it rethrows the recorded failure exactly when the failing row has not been consumed yet.

That is pure scheduling luck. Linux runners normally find the queue already empty and close() returns cleanly; the slower Windows runners still hold the row, hit the rethrow, and fail the test.

Changes

Tolerate either teardown outcome, and assert that any close() failure has the same root cause. A genuinely unrelated shutdown failure still breaks the test, so this narrows rather than loosens what teardown accepts.

The contract assertions the test exists for are untouched.

Note

While tracing this, one inconsistency stood out but is deliberately left alone here: MultiTableSinkWriter#close() declares throws IOException, yet rethrows a recorded IOException as throw new RuntimeException(firstE[0]). Fixing that would change exception semantics on a path every multi-table sink job uses, which does not belong in a CI-stabilization change — flagging it for a maintainer's call.

Does this PR introduce any user-facing change?

No. Test-only.

How was this patch tested?

The Windows unit-test job on this PR exercises the previously failing case directly.

schemaChangeKeepsIOExceptionContractWhenWorkerAlreadyFailed asserts the
IOException contract of applySchemaChange, then calls coordinator.close()
as unguarded teardown.

The worker failure it just asserted stays recorded, so close() drains the
queue and rethrows it whenever the failing row has not been consumed yet.
That is scheduling dependent: Linux runners normally find the queue empty
and close() returns, Windows runners still hold the row and hit the
rethrow, failing unit-test (11, windows-latest) on every PR that merges dev.

Tolerate either outcome in teardown while pinning any close() failure to
the same root cause, so an unrelated shutdown failure still breaks the test.
The contract assertions are unchanged.
@github-actions github-actions Bot added the api label Aug 3, 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.

What Problem Does This PR Solve?

  • User pain point
    unit-test (11, windows-latest) has been failing on PRs that carry recent dev, with MultiTableSinkWriterSchemaChangeBroadcastTest.schemaChangeKeepsIOExceptionContractWhenWorkerAlreadyFailed throwing java.lang.RuntimeException: java.io.IOException: boom-before-schema-entry out of the unguarded coordinator.close() teardown call.
  • Fix approach
    This PR wraps that teardown call in a try/catch that tolerates a close() failure, but only when its root cause is the exact worker failure the test already asserted; any other shutdown failure still breaks the test.
  • One-sentence summary
    The goal is to make the schema-change contract test deterministic across runner speeds without loosening what its teardown accepts.

1. Code Change Review

1.1 Core Logic Analysis

Exact change description

The full diff is a single hunk in one test file:

  • seatunnel-api/src/test/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriterSchemaChangeBroadcastTest.java:413-425

Before / after snippets

Before:

assertEquals("boom-before-schema-entry", schemaChangeFailure.getMessage());
coordinator.close();

After:

assertEquals("boom-before-schema-entry", schemaChangeFailure.getMessage());
// ...explanatory comment...
try {
    coordinator.close();
} catch (IOException | RuntimeException closeFailure) {
    Throwable rootCause =
            closeFailure instanceof IOException ? closeFailure : closeFailure.getCause();
    assertEquals("boom-before-schema-entry", rootCause.getMessage());
}

Key findings

  • I traced the race in the current dev sources and I can confirm it is real; the one detail I would adjust is the wording of where the pending state lives (see Issue 2 below): by the time close() runs in this test, the failing row has already been polled off the queue — what is still pending is the worker's processingRow flag window.
  • The rethrow amplifier is checkQueueRemain() (MultiTableSinkWriter.java:940-950): once it observes hasPendingRuntimeWrites() true a single time, it sleeps 100 ms and then calls subSinkErrorCheck() unconditionally, which always throws because the worker failure stays recorded. A nanosecond-scale flag window therefore converts deterministically into a close() failure.
  • The catch is correctly narrowed. With the three-arg constructor used by this test (MultiTableSinkWriter.java:113-126, defaults FAIL_FAST + BATCH), the only throw close() can reach is throw new RuntimeException(firstE[0]) at MultiTableSinkWriter.java:892, where firstE[0] is the recorded IOException returned as-is by currentSubSinkFailure() (MultiTableSinkWriter.java:315-316), so getCause().getMessage() is exactly "boom-before-schema-entry".
  • The extra IOException catch arm is unreachable today under FAIL_FAST, but it is good future-proofing: if the throws IOException vs RuntimeException inconsistency the author flagged in the PR description is ever fixed in production code, this test keeps working unchanged.
  • No resource leak in either branch: close() captures the checkQueueRemain() failure first and still runs executorService.shutdownNow(), all sub-writer closes, and the resource-manager close before rethrowing (MultiTableSinkWriter.java:839-870), so swallowing the rethrow after asserting it is safe.

Deep logic analysis

The race, as it actually executes:

Test thread                                          Queue worker
-----------                                          ------------
coordinator.write(row)
  -> blockingQueues[0].offer(RowWriteRequest)
                                                     queue.poll() takes the row
                                                       [MultiTableWriterRunnable.java:98]
                                                     processingRow = true  [:102]
                                                     FailingRowSinkWriter.write throws
                                                       IOException("boom-before-schema-entry")
                                                     handleWriteFailure:
                                                       throwable = error  [:200]
spin loop sees getThrowable() != null                  |-- race window: processingRow
  [test:395-398]                                       |   is only cleared at [:133]
applySchemaChange                                      |   after failing pending
  -> subSinkErrorCheck() rethrows the recorded         |   schema requests [:119-131]
     IOException as-is
     [MultiTableSinkWriter.java:344-345, 297-330]
assertEquals(...)  [test:411]
coordinator.close()  [test:420]
  -> checkQueueRemain()  [MultiTableSinkWriter.java:842, 940-950]
     hasPendingRuntimeWrites()  [:952-964]
       queue: empty (row already polled)
       isProcessingRow(): true only if the worker is still inside the window
     true  -> sleep(100) -> subSinkErrorCheck() throws
              -> firstE[0] set -> full cleanup [:846-870]
              -> throw new RuntimeException(firstE[0])  [:892]
     false -> close() returns cleanly

On fast, lightly loaded runners the window between MultiTableWriterRunnable.java:200 and :133 is closed before the test thread reaches close(); on slow two-core Windows runners the worker can be preempted inside it, and one true reading is enough to guarantee the rethrow. Both outcomes are legitimate behavior of the current production code, and the test's actual subject — the IOException contract of applySchemaChange at test:404-411 — is untouched. Tolerating both outcomes while pinning the root cause is the right shape for this teardown.

I also verified the sibling test schemaChangeBarrierDetectsWorkerFailureAfterPreEnqueueCheck (test:475-478) is not exposed to the mirror-image flake: there the dead worker leaves the enqueued schema-change barrier element in the queue, so hasPendingRuntimeWrites() is deterministically true and assertThrows(RuntimeException.class, coordinator::close) stays sound. No change needed there.

1.2 Compatibility Impact

Fully compatible. The diff is confined to a unit-test class; no production code, no configuration, no serialized formats, and no user-visible behavior changes.

1.3 Performance / Side-Effect Analysis

  • No runtime impact on any engine or connector path.
  • Test execution time is unchanged: the try/catch adds no waits, and the pre-existing 100 ms sleep inside checkQueueRemain() was already paid whenever the race fired.
  • In both teardown branches the coordinator's executor and sub-writers are fully released before the test method returns, so no threads leak from this test into the rest of the unit-test JVM.

1.4 Error Handling and Logging

Issue 1

  • Location: seatunnel-api/src/test/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriterSchemaChangeBroadcastTest.java:421-424
  • Problem description: for a RuntimeException without a cause, closeFailure.getCause() returns null and rootCause.getMessage() throws a NullPointerException inside the catch block.
  • Potential risk: a genuinely new shutdown failure (for example a future NPE thrown directly by close()) still fails the test — so the guard works — but it surfaces as a confusing secondary NPE that hides the original closeFailure, making the next CI triage harder than it needs to be.
  • Best improvement: assert the root cause before dereferencing it and attach the original failure, e.g. assertNotNull(rootCause, () -> "unexpected close() failure: " + closeFailure); before the message assertion (or use assertInstanceOf(IOException.class, rootCause)).
  • Severity: Low
  • Raised by another reviewer: No

Issue 2

  • Location: seatunnel-api/src/test/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriterSchemaChangeBroadcastTest.java:414-417
  • Problem description: the new comment says Windows runners "still hold the row" at close time. In this test the spin loop at test:395-398 only exits after the worker recorded its failure, which means the row was already polled off the queue (MultiTableWriterRunnable.java:98); what hasPendingRuntimeWrites() (MultiTableSinkWriter.java:952-964) actually observes is the processingRow flag, which stays true from MultiTableWriterRunnable.java:102 until :133, after the failure bookkeeping at :200 and :119-131.
  • Potential risk: none functionally — the tolerance is correct either way — but a future reader chasing this race from the comment would inspect the queue instead of the flag window and could conclude the comment (and the tolerance) is stale.
  • Best improvement: reword to something like "the worker may still be flagged as processing the failed row (isProcessingRow()), so hasPendingRuntimeWrites() can still report pending work".
  • Severity: Low
  • Raised by another reviewer: No

Issue 3 (pre-existing, not introduced by this PR)

  • Location: seatunnel-api/src/test/java/org/apache/seatunnel/api/sink/multitablesink/MultiTableSinkWriterSchemaChangeBroadcastTest.java:82-91, 106-114, 131-140, 156-201, 216-224, 237-273, 286-322, 336-374
  • Problem description: the other eight tests in this class never call coordinator.close(), so each one leaks queueSize * 2 daemon executor threads that keep polling every 100 ms (MultiTableWriterRunnable.java:98) for the rest of the unit-test JVM.
  • Potential risk: accumulated polling threads add scheduling pressure on the two-core runners, which is precisely the kind of load that widens the preemption window this PR is working around; it can also mask future cross-test interference.
  • Best improvement: a follow-up (not this PR) that tracks created coordinators and closes them in an @AfterEach, guarding against the same benign rethrow this PR handles.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

The hunk follows the file's existing conventions (static JUnit 5 assertion imports, multi-catch, explanatory block comment above the non-obvious construct). Naming (closeFailure, rootCause) is clear. The new block carries a thorough comment explaining why the tolerance exists, which is exactly what a "tolerate either outcome" pattern needs to survive future refactors.

2.2 Test Coverage and Test Stability

This PR changes UT code, so a stability rating is mandatory from my side.

Test stability conclusion: Stable

  • The changed hunk introduces no sleeps, timeouts, ports, shared static state, or order dependence (test:419-425); it removes a scheduling-dependent failure instead of adding a wait to hide it.
  • Both teardown branches enforce the same invariant — any close() failure must carry the exact "boom-before-schema-entry" root cause (test:421-424) — so this narrows rather than loosens teardown, and a genuinely new shutdown regression still fails the test.
  • The residual nondeterminism is only in which branch executes on a given run; since both branches assert the same contract, that is an acceptable pattern for teardown of a test whose subject is applySchemaChange, not close().
  • The pre-existing patterns elsewhere in the file (fixed Thread.sleep(200) settle windows at test:189, test:261, test:308, test:361; the 50 ms bounded polling at test:395-398; unclosed coordinators per Issue 3) came in with #11015 and are unchanged here — they are follow-up material, not a reason to hold this fix.

I also verified the fix empirically on CI: all four unit-test lanes pass on this head, including unit-test (11, windows-latest), while I spot-checked the current heads of #11597 and #11569 and both show exactly that lane failing, matching the PR's description of the flake.

2.3 Documentation Updates

No docs/en or docs/zh update is needed: this is test-only with no user-visible behavior change.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix. It repairs the test at the exact point where the test — not the production code — made an over-strong assumption (that close() after an asserted worker failure never throws), and it does so without weakening the contract under test.

For completeness, the two shapes I weighed:

  • Option A (this PR): tolerate either teardown outcome, pinned to the same root cause. Simple, and stays correct even if close() timing changes again.
  • Option B: make teardown deterministic by spinning until queueRunnable.isProcessingRow() is false before close(), then asserting a clean close. Deterministic, but it couples the test to another internal flag and silently breaks if hasPendingRuntimeWrites() ever gains a new pending source.

From Daniel's side, Option A is the better trade for a teardown path, so I am fine with the shape as submitted.

3.2 Maintainability

The comment block plus the root-cause pin make the intent recoverable for future readers. Issues 1 and 2 are small polish items that would make the next CI triage on this test faster. The author's PR note explicitly flagging (and deliberately not fixing) the close() throws IOException-vs-RuntimeException inconsistency is the right scoping call — that behavior is even documented in the current Javadoc at MultiTableSinkWriter.java:831-834 — and I would support a separate issue to decide its fate on the production side.

3.3 Extensibility

The IOException | RuntimeException multi-catch means the test survives a future cleanup of close()'s exception contract without modification. Nothing else to extend in a teardown guard.

3.4 Historical-Version Compatibility

No impact on released behavior, state formats, or upgrade paths; this only changes what one unit test tolerates during teardown.

4. Issue Summary

No. Issue Location Severity
1 Null-cause RuntimeException in the catch would surface as a confusing NPE instead of a clear assertion failure MultiTableSinkWriterSchemaChangeBroadcastTest.java:421-424 Low
2 New comment says the queue "still holds the row"; the actual pending state at close time is the worker's processingRow flag window MultiTableSinkWriterSchemaChangeBroadcastTest.java:414-417 Low
3 (Pre-existing) sibling tests never close their coordinators, leaking daemon polling threads that add scheduling pressure in this JVM MultiTableSinkWriterSchemaChangeBroadcastTest.java:82-374 (eight tests) Low

5. Merge Recommendation

Conclusion: Ready to merge

  1. Blockers — must be fixed
  • None. I found no source-side blocker in this diff.
  1. Recommended fixes — non-blocking
  • Issue 1: guard the root cause with assertNotNull(...) (or assertInstanceOf) so an unrelated shutdown failure reports itself clearly.
  • Issue 2: reword the comment to point at the processingRow window rather than the queue contents.
  • Issue 3: follow-up PR to close coordinators in an @AfterEach across this test class.

Overall assessment:
The diagnosis in the PR description matches what the code actually does (with the one small wording nuance in Issue 2), the fix is minimal and narrowed to the exact recorded failure, and the previously failing lane passes on this head. This is a clean CI-stabilization change and I would like to see it in soon, since it unblocks the Windows lane for every other open PR.

On the current-head CI state: the aggregated Build check is red, but not because of this diff. The failures are Run / all-connectors-it-3 (11, ubuntu-latest) (step "run connector-v2 integration test (part-3)") and Run / kafka-connector-it (11, ubuntu-latest) (step "run kafka connector integration test"), both dying with "Run SeaTunnel on spark failed" / "SeaTunnel job executed failed" annotations; the JDK 8 siblings were then cancelled by matrix fail-fast. Those connector IT lanes only ran here because touching seatunnel-api triggers the broad matrix — this test-only diff is not on their classpath and cannot influence a packaged Spark e2e job. Meanwhile the lanes this diff can affect — all four unit-test lanes, including the previously failing unit-test (11, windows-latest) — are green. The branch is even with dev, so no sync is needed; a maintainer re-run of the two failed IT lanes should be enough to get the head green.

One caveat as usual: I only have read-level permission on this repo, so a write-capable maintainer will need to perform the final approval, the CI re-run, and the merge.

@davidzollo

davidzollo commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Investigated the Build failure on this head. Two jobs failed: all-connectors-it-3 (11, ubuntu-latest) and kafka-connector-it (11, ubuntu-latest). Both show the same Run SeaTunnel on spark failed / SeaTunnel job executed failed annotation pattern — unrelated to the single API test file this PR touches.

Same signature is showing up on other unrelated PRs right now (a Zeta metrics test PR, and a pure-Javadoc PR that's shown this exact failure since March) — pre-existing Spark e2e flake, not this PR's change. (Couldn't pull the full raw log to name the exact assertion — a proxy/TLS issue on my end reaching Azure blob storage, not a GitHub-side problem.)

Triggered a job-level rerun of the two failed jobs rather than the whole workflow.

@DanielLeens

Copy link
Copy Markdown
Contributor

Agreed, and this matches what I saw independently when I reviewed this head on 2026-08-04: the same two jobs — all-connectors-it-3 (11, ubuntu-latest) and kafka-connector-it (11, ubuntu-latest) — were the only failures, both with the identical Run SeaTunnel on spark failed / SeaTunnel job executed failed annotation, while all four unit-test lanes (including the previously-flaky unit-test (11, windows-latest) this PR actually targets) were green. Those connector IT lanes only run here because touching seatunnel-api pulls in the broad matrix — this diff is a single test-file change and isn't on their classpath, so it can't be causing a packaged Spark e2e job to fail.

Good catch cross-checking against other PRs — I can independently confirm that angle too: danielnadean just flagged the exact same Run SeaTunnel on spark failed signature a few seconds after your comment here, on #10583 (a pure-Javadoc PR, zero executable lines changed), also on kafka-connector-it plus two other ubuntu lanes. Two unrelated PRs, different authors, different files, different job-matrix JDKs (8 vs 11), hitting the identical annotation text at essentially the same moment is strong corroboration this is an infra-wide Spark e2e flake rather than anything in either diff — consistent with #10583's history of the same failure going back to March.

My conclusion stands: no source-side blocker in this PR, "Ready to merge" once the flaky lanes go green. Thanks for triggering the job-level rerun on the two failed jobs rather than the whole workflow — that's the right move here. I only have read-level access on this repo, so I can't kick off or watch the rerun myself, but a maintainer re-run of those two lanes (plus #10583's, if anyone with fork access there can trigger it) should be enough to clear this.

@DanielLeens

Copy link
Copy Markdown
Contributor

Good news on the CI front, and one heads-up.

I went back to check this head (5beec7c2) now that the reruns davidzollo triggered have had time to finish, and confirmed against the real fork run rather than just the apache-side pointer:

  • Run / all-connectors-it-3 (11, ubuntu-latest) — now success (completed 2026-08-10 16:06 UTC)
  • Run / kafka-connector-it (11, ubuntu-latest) — now success (completed 2026-08-10 17:13 UTC)
  • the JDK 8 siblings of both (all-connectors-it-3 (8, ...), kafka-connector-it (8, ...)) and kudu-connector-it (8, ...) also completed success on the same rerun
  • across the full check-run list on the fork build for this head, there is no longer a single non-success, non-skipped job

So the Spark e2e flake I flagged is cleared, and my technical conclusion from the 2026-08-04 review stands unchanged: no source-side blocker in this diff. The only outstanding items are still the two Low-severity, non-blocking polish suggestions from that review (guarding the null-cause path in the new catch block, and tightening the teardown comment's wording) — neither one gates a merge.

One separate thing I noticed while re-checking, unrelated to CI: GitHub is now reporting this PR as mergeable: false / mergeable_state: dirty against the current dev tip — this branch was opened against an older base back on 2026-08-03, and dev has moved on enough since then to produce a real conflict, not just a stale pointer. That's new since my last check (I confirmed "even with dev" at review time) and isn't something a job rerun can fix — it will need a rebase/merge of dev into this branch before it's actually mergeable.

So from Daniel's side: CI is clean, no code-side blocker — but the branch needs a sync with dev to resolve the merge conflict before it can go in. I only have read access here, so I can't push that rebase myself; whenever the branch gets updated, this should be ready to go. Thanks for chasing down the flaky lanes — the diagnosis held up.

@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.

Rechecked this unchanged head. Build, Notify test workflow, and labeler are now all SUCCESS — the aggregated Build red I mentioned last round was Run / all-connectors-it-3 and Run / kafka-connector-it, both unrelated to this diff, and both are green now. I still find no source-side blocker in the diff itself; this remains a clean, narrowly-scoped CI-stabilization fix that unblocks the Windows lane for other open PRs.

Blockers — must be fixed:

  • GitHub is currently reporting a real merge conflict against dev (mergeable: CONFLICTING, mergeStateStatus: DIRTY), not just a "needs rebase" advisory — this branch is 60 commits behind. Could you please sync with the latest dev and resolve the conflict? Once that's done and a fresh Build comes back green on the rebased head, I don't see anything else standing in the way from my side.

Recommended fixes — non-blocking (carried over from my last round):

  • Guard the root cause with assertNotNull(...) (or assertInstanceOf) so an unrelated shutdown failure reports itself clearly.
  • Reword the comment to point at the processingRow window rather than the queue contents.
  • Follow-up PR to close coordinators in an @AfterEach across this test class.

…260803

Resolves the conflict in schemaChangeKeepsIOExceptionContractWhenWorkerAlreadyFailed:
both this branch and dev independently added a close()-tolerance block to the same
test. Kept the union of both contracts -- this branch's broader catch
(IOException | RuntimeException, needed because Windows runners can surface the
raw IOException from close()) combined with dev's stricter assertSame identity
pin on the root cause, and merged both comments' explanations (the volatile
pending-flag window mechanism plus the Linux/Windows scheduling-luck outcome).
The resulting assertion is at least as strict as either parent.
@davidzollo

Copy link
Copy Markdown
Contributor Author

Closing as superseded: the same close()-race tolerance in MultiTableSinkWriterSchemaChangeBroadcastTest already landed on dev via #11726 (commit 22da84a), with a stricter check (assertSame on the wrapped root cause instead of message equality). After merging current dev into this branch the PR diff becomes empty, so there is nothing left for this PR to deliver.

@davidzollo davidzollo closed this Aug 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants