Skip to content

[Fix][Connector-V2] Remove fixed sleep in AssertSinkWriter close and assert own table only - #11995

Merged
davidzollo merged 2 commits into
apache:devfrom
corgy-w:corgy/fix-assert-no-sleep
Sep 1, 2026
Merged

davidzollo merged 2 commits into
apache:devfrom
corgy-w:corgy/fix-assert-no-sleep

Conversation

@corgy-w

@corgy-w corgy-w commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Purpose of this pull request

AssertSinkWriter.close() sleeps 1000ms to wait for other sink writers to finish, assuming a multi-writer job. This heuristic both slows down every job completion (even single-table jobs pay 1s) and is unreliable under load.

The writer already routes each row to the shared LONG_ACCUMULATOR keyed by table name in write() (its own table when assertRowRules contains multiple tables, the unique key otherwise). close() should validate only the rules of the table this writer is responsible for — using the same table-selection decision as write() — instead of waiting for unrelated writers.

Changes:

  • remove WAIT_SINK_WRITER_COMPLETE_TIME and the Thread.sleep
  • filter assertRowRules in close() by the writer's own catalogTableName when multiple tables are configured
  • add AssertSinkWriterCloseTest covering the multi-table close behavior and the MIN_ROW validation on the writer's own table

Does this PR introduce any user-facing change?

No; assertion semantics are unchanged for single-table jobs, and multi-table jobs now fail fast with accurate per-table counts instead of relying on a fixed delay.

Known limitation

For a single table with parallelism > 1, each parallel subtask owns its own AssertSinkWriter and close() is invoked per subtask without a barrier across siblings. In that case assertRowRules.size() == 1 bypasses the per-table filter (same as before), and the shared LONG_ACCUMULATOR for the table can still be written concurrently by sibling instances when one closes — the removed sleep had provided only a weak, unreliable buffer for this window. This PR does not regress that path relative to the previous behavior (the sleep never bounded sibling completion time), and all existing Assert E2E configs use parallelism = 1, so it is out of scope here; a barrier-based fix would be a separate follow-up.

How was this patch tested?

  • ./mvnw spotless:apply -pl seatunnel-connectors-v2/connector-assert
  • AssertSinkWriterCloseTest (2 tests) passes with the fix, and the regression test fails against the previous implementation (table B's unfulfilled MIN_ROW rule is no longer asserted by table A's writer).

…assert own table only

AssertSinkWriter.close() slept 1000ms to wait for other sink writers to
finish, assuming a multi-writer job. That heuristic both slows down every
job completion and is unreliable. The writer already routes rows per table
into the shared LONG_ACCUMULATOR on write(), so close() should validate
only the rules of the table this writer is responsible for (matching the
same tableName decision used in write()).

- remove WAIT_SINK_WRITER_COMPLETE_TIME / Thread.sleep
- filter assertRowRules in close() by own catalogTableName when multiple
- add AssertSinkWriterCloseTest covering the multi-table case

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

AssertSinkWriter.close() used to Thread.sleep(1000) on every close, then validate the row-count rules of every configured table (not just the table this writer instance owns), hoping that a flat 1-second delay was enough for sibling per-table writers (in a multi-table Assert sink job) to finish accumulating their counts first. This PR removes the sleep and narrows close() to validate only the rules of the table the current writer instance is actually responsible for (catalogTableName), matching the same table-selection logic write() already uses. Net effect: single-table jobs no longer pay an unconditional 1s tax on completion, and multi-table jobs get a deterministic, race-free validation instead of a timing gamble.

1. Code Change Review

1.1 Core Logic Analysis

Before (AssertSinkWriter.java):

private final long WAIT_SINK_WRITER_COMPLETE_TIME = 1000L;
...
public void close() {
    try {
        Thread.sleep(WAIT_SINK_WRITER_COMPLETE_TIME);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    if (!assertRowRules.isEmpty()) {
        assertRowRules.entrySet().stream()
                .filter(entry -> !entry.getValue().isEmpty())
                .forEach(...validate against LONG_ACCUMULATOR.get(entry.getKey())...);
    }
    ...
}

After:

public void close() {
    if (!assertRowRules.isEmpty()) {
        assertRowRules.entrySet().stream()
                .filter(entry -> !entry.getValue().isEmpty()
                        && (assertRowRules.size() == 1
                                || entry.getKey().equals(this.catalogTableName)))
                .forEach(...);
    }
    ...
}

Why this is correct, not just "sleep removed": I traced how multiple AssertSinkWriter instances actually get created and closed for a multi-table job (AssertSink.java:60-99, AssertSink.createWriter, MultiTableSinkWriter.java):

  • AssertSink is instantiated once per CatalogTable, but its constructor parses the full rules.tables_configs block, so assertRowRules on every per-table AssertSink/AssertSinkWriter instance contains entries for all configured tables, not just its own (AssertSink.java:69-80, initTableRule). Only catalogTableName (AssertSink.java:68) differs per instance.
  • In write() (unchanged by this PR), when assertRowRules.size() > 1, the accumulation key is element.getTableId(), which for a per-table writer instance is always its own table (MultiTableSinkWriter routes rows to the sub-writer registered for that SinkIdentifier/table, see MultiTableSinkWriter.java:653-663 offerRowElement / table-keyed tableIdWriterMap). So LONG_ACCUMULATOR[tableX] is, in practice, only ever written by tableX's own writer instance.
  • MultiTableSinkWriter.close() (MultiTableSinkWriter.java:864-892) calls checkQueueRemain() (which busy-waits until every sub-writer's queue is fully drained, across all tables) before invoking sinkWriter.close() on any sub-writer. So by the time any table's AssertSinkWriter.close() runs, every table's rows are already flushed into the shared accumulator.

Combining these two facts: scoping the validation to entry.getKey().equals(this.catalogTableName) makes each writer's row-count check depend only on counts it wrote itself, which is a genuinely deterministic condition, not a race mitigated by luck. This is a materially better fix than the 1s sleep it replaces — the sleep never had a correctness guarantee (git history shows this same Thread.sleep was added/removed across several past commits in this file, suggesting past naive-removal attempts likely reintroduced the very race this PR now closes at the root instead of papering over).

Does this silently skip assertions for other tables (the reviewer's core concern)? No, for the standard multi-table-sink path: AssertSink is instantiated once per table, so there are exactly as many AssertSinkWriter instances as tables, each with a distinct catalogTableName. Table B's rule is still validated — just by table B's own writer, not redundantly by every other table's writer as well. Under MultiTableSinkWriter.close()'s "first-exception-wins" policy (MultiTableSinkWriter.java:882-889), a violation on table B surfaces the job failure exactly the same way whether 1 writer or N writers detect it. I verified this against fakesource_to_multi_table_assert.conf (2 tables, each with its own MIN_ROW/MAX_ROW), which is exercised by FakeSourceToAssertIT for non-Flink engines — this is precisely the scenario the new AssertSinkWriterCloseTest regression-tests at the unit level.

Residual (pre-existing, not introduced by this PR) risk — parallelism > 1 on a single table. When a single table's Assert sink runs with parallelism > 1 (not routed through MultiTableSinkWriter, since there is only one table), each parallel subtask gets its own independent AssertSinkWriter and calls close() via SinkFlowLifeCycle.close() (seatunnel-engine-server/.../SinkFlowLifeCycle.java:271-273) with no barrier across sibling parallel subtasks. In that case assertRowRules.size() == 1, so the new filter is bypassed entirely (same as before) and LONG_ACCUMULATOR for the shared table is still being concurrently written by sibling instances when any one instance closes. The removed sleep offered a (weak, unreliable) buffer for this specific case; now there is none. I don't consider this a regression this PR should be blocked on: every existing Assert e2e config uses parallelism = 1 (checked all 4 .conf files under connector-assert-e2e), the docs' examples also use parallelism = 1, and the sleep never reliably fixed this window anyway (1 real second is not a bound on sibling completion time under load). But it is a real, currently-undocumented limitation that this PR's description doesn't call out. See Issue 2 below.

1.2 Compatibility Impact

Fully compatible. No config Option renamed/removed/defaulted differently, no public API/SPI signature change (the removed field was private), no checkpoint/savepoint state involved (AssertSinkWriter uses Void state and does not override snapshotState), and the author's own claim ("assertion semantics are unchanged for single-table jobs") checks out from the code: for assertRowRules.size() == 1 the filter condition short-circuits to true, exactly reproducing pre-PR behavior for the single-table case.

1.3 Performance / Side-Effect Analysis

This is a real, measurable improvement, not just cosmetic:

  • Every job using the Assert sink previously paid an unconditional 1s Thread.sleep per writer-close, even for the common single-table case where the sleep bought nothing. That tax is now gone.
  • In the multi-table case, MultiTableSinkWriter.close() (MultiTableSinkWriter.java:876-892) closes sub-writers sequentially within each queue's lock; if N assert-sink table-writers happened to land in the same queue (hash-bucketed), the old code paid N * 1s of sequential sleep on job completion. That's now eliminated too.
  • The old code also did O(tables²) redundant work in the worst case (every writer validating every table's rules on every close). The new code is O(tables) — each table validated exactly once, by its own writer. No coverage loss (see 1.1), just removal of N-fold redundant checking.
  • No new allocations, no new locks, no change to GC/memory profile.

1.4 Error Handling and Logging

No behavioral changes to exception types (AssertConnectorException is still thrown the same way on rule violation), and no new exception paths were introduced by removing the try { Thread.sleep } catch (InterruptedException) block — that block only ever wrapped a spurious interrupt into a RuntimeException, which is no longer reachable code (there's nothing left to interrupt). This is a legitimate simplification, not silently swallowed error handling.

Issue 1

  • Location: seatunnel-connectors-v2/connector-assert/src/main/java/org/apache/seatunnel/connectors/seatunnel/assertion/sink/AssertSinkWriter.java:104-112
  • Problem description: close() now relies on a non-obvious cross-class invariant (that MultiTableSinkWriter drains all sub-writers' queues before calling any sub-writer's close(), and that each table's LONG_ACCUMULATOR entry is only ever written by its own table's writer instance) with zero comment explaining it. The removed sleep at least had a one-line comment describing the (wrong) intent; the replacement has none.
  • Potential risk: a future maintainer, seeing close() immediately validate counts with no wait, could "fix" what looks like a re-introduced race by adding back a sleep or a different ad-hoc wait, undoing this fix. This file's own git history shows this exact sleep being added and removed multiple times already.
  • Best improvement: add a short comment on close() (or just above the filter) stating that validation is scoped to the writer's own table because each table's counter is only ever incremented by that table's own writer, and that MultiTableSinkWriter guarantees all rows are flushed before any sub-writer's close() runs — so no additional synchronization is required here.
  • Severity: Medium
  • Raised by another reviewer: No

Issue 2

  • Location: seatunnel-connectors-v2/connector-assert/src/main/java/org/apache/seatunnel/connectors/seatunnel/assertion/sink/AssertSinkWriter.java:104 (interacts with write() at lines 74-82, unchanged)
  • Problem description: for a single table run with parallelism > 1, assertRowRules.size() == 1 bypasses the new per-table filter (same as pre-PR behavior) and multiple sibling AssertSinkWriter instances share LONG_ACCUMULATOR/TABLE_NAMES with no barrier between them (SinkFlowLifeCycle.close() calls writer.close() per-subtask with no cross-subtask synchronization). The removed sleep was the only (weak) mitigation for this window; it is now gone with nothing in its place.
  • Potential risk: row-count/table-name assertions on a parallelism>1 single-table job can flake (false pass or false fail) depending on which parallel subtask happens to finish and call close() first — a pre-existing issue, but now with strictly less timing buffer than before.
  • Best improvement: not necessarily a code fix in this PR (no current test or documented use case relies on parallelism > 1 for row-count assertions — all shipped .conf examples and e2e configs use parallelism = 1), but the PR/description should call this limitation out explicitly, and ideally docs/en/connectors/sink/Assert.md / docs/zh/... should note that row-count (MIN_ROW/MAX_ROW) and table-name assertions require parallelism = 1 to be reliable.
  • Severity: Medium
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

The production change itself is minimal and idiomatic. Two comment gaps, both non-trivial enough to note:

  • AssertSinkWriter.close() — see Issue 1 above (missing invariant-explaining comment on a concurrency-adjacent method).
  • AssertSinkWriterCloseTest has no class-level Javadoc (project convention expects one, especially for a regression test whose entire purpose is documenting a fixed race). That said, the per-test inline comments are unusually good — each test explains exactly what the old implementation did wrong and what the new one guarantees, which substantially covers the intent a class Javadoc would otherwise carry. I'd still ask for a short class Javadoc pointing at this being the regression coverage for the sleep removal.

2.2 Test Coverage and Test Stability

Stability rating: Stable. No hard sleeps, no Thread.sleep/timing dependency, no shared mutable state leaking across the two test methods despite LONG_ACCUMULATOR/TABLE_NAMES being static fields on the production class — the two tests were deliberately given disjoint table-name keys (tableA_mult/tableB_other vs. tableA_fail/tableB_other reusing tableB_other only as an unincremented key), so there is no cross-test interference even though state is static and JUnit does not reset it between methods. Assertions are exact (assertDoesNotThrow / assertThrows(AssertConnectorException.class, ...)), not weak existence checks.

Coverage is on-point for the stated fix:

  • testCloseOnlyAssertsOwnTableWhenMultipleTables: reproduces exactly the bug being fixed — table B never receives a row and has MIN_ROW=1; under the old implementation this would have failed table A's writer; under the new implementation table A's writer only checks its own rule and passes. This is a genuine regression test (the PR description confirms it fails against the pre-fix implementation).
  • testCloseThrowsWhenOwnTableRuleNotMet: confirms the fix didn't overcorrect into skipping the writer's own table validation — MIN_ROW=2 with only 1 row written still throws.

This satisfies the mandatory flaky-test-risk review for PRs touching test infrastructure: the fix replaces a hard-sleep synchronization anti-pattern with a design that removes the actual race (see 1.1) rather than papering over it with polling or a longer sleep, and the new test is itself deterministic. No weakening of any existing test — this is new coverage, and the existing multi-table e2e (fakesource_to_multi_table_assert.conf via FakeSourceToAssertIT) and all single-table e2e/unit coverage is untouched and continues to exercise the unchanged code paths.

One gap: no test exercises the parallelism > 1 single-table scenario referenced in Issue 2 (arguably out of scope for this PR, since no such test existed before either).

2.3 Documentation Updates

No user-facing config/behavior changed, so no docs/en/docs/zh update is strictly required for the core fix, and none was made — consistent with the PR's own "No user-facing change" statement. See Issue 2 for a suggested (non-blocking) doc addition about the parallelism limitation.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix, not a workaround. It replaces a timing-based hack with a scoping change that eliminates the actual cross-writer dependency the sleep was trying to paper over, using information (catalogTableName) the class already had and already used in write().

3.2 Maintainability

Net negative line count, no new abstractions, and the deleted code (a sleep + interrupted-exception wrapper that could never actually happen anymore) reduces surface area. Would be improved by the comment in Issue 1 given the invariant is genuinely non-obvious and this file has a history of the same sleep being re-added.

3.3 Extensibility

No impact — the change is local to one method's filter predicate.

3.4 Historical-Version Compatibility

No checkpoint/savepoint state, no serialized format, no config option touched. Old jobs, old JSON, and upgrade paths are unaffected.

4. Issue Summary

Number Issue Location Severity
1 close() lacks a comment explaining why no synchronization/wait is needed after removing the sleep AssertSinkWriter.java:104-112 Medium
2 parallelism > 1 single-table row-count/table-name assertions have no barrier between sibling writer instances (pre-existing, undocumented, now with less timing buffer than before) AssertSinkWriter.java:104, write() lines 74-82 Medium
3 New AssertSinkWriterCloseTest class has no class-level Javadoc AssertSinkWriterCloseTest.java:1 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed

    • None that are correctness-blocking. Issue 1 (add an explanatory comment to close()) is a low-cost ask I'd like addressed before merge given this exact sleep has been added/removed multiple times in this file's history — a one-line comment materially reduces the odds of a future regression.
  2. Recommended fixes — non-blocking

    • Issue 2: document the parallelism = 1 expectation for row-count/table-name assertions in the Assert sink docs (or file a separate follow-up issue to make it robust to parallelism > 1).
    • Issue 3: add a short class-level Javadoc to AssertSinkWriterCloseTest describing the regression it guards against.

Overall assessment: this is a well-reasoned, correctly-scoped fix — I verified independently (via AssertSink.java, MultiTableSinkWriter.java, and the multi-table e2e config) that the new per-table filter is not just "faster" but actually removes the underlying race the sleep existed for, and that no table's assertions are silently skipped in the standard multi-table path. The new unit test is deterministic and directly reproduces the bug being fixed. CI (Build) is still queued on the fork as of this review (PR opened minutes ago) — nothing to diagnose yet, and the branch is fully in sync with dev (0 behind). No upstream sync needed.

@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: AssertSinkWriter.close() used to Thread.sleep(1000) on every close, then validate row-count rules for every configured table (not just the table the writer instance owns) — a timing gamble that could either fail incorrectly (checking a sibling table's not-yet-populated count) or hide real bugs.
  • Fix approach: remove the sleep entirely and scope close() to validate only the rules of the table the writer instance actually owns (catalogTableName), the same table-selection logic write() already uses.
  • One-sentence summary: replaces a timing-based hack with a scoping fix that removes the actual cross-writer dependency at its root, instead of papering over it with a longer wait.

Re-review note: the only commit added since my previous review (f3c95536) is 67162eeb — chore: trigger CI, which is an empty commit with zero file changes (git show --stat 67162eeb shows no diff). So this is not a new round of code to re-analyze; it's the same diff with fresh CI data. I re-verified my prior findings independently against the current head rather than just restating them, and I'm folding a CI-status update into this same review per the no-duplicate-round rule rather than posting a separate "still queued" comment.

1. Code Change Review

1.1 Core Logic Analysis

Before (AssertSinkWriter.java, pre-PR):

private final long WAIT_SINK_WRITER_COMPLETE_TIME = 1000L;
...
public void close() {
    try {
        Thread.sleep(WAIT_SINK_WRITER_COMPLETE_TIME);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    if (!assertRowRules.isEmpty()) {
        assertRowRules.entrySet().stream()
                .filter(entry -> !entry.getValue().isEmpty())
                .forEach(...validate against LONG_ACCUMULATOR.get(entry.getKey())...);
    }
    ...
}

After (AssertSinkWriter.java:104-112):

public void close() {
    if (!assertRowRules.isEmpty()) {
        assertRowRules.entrySet().stream()
                .filter(entry -> !entry.getValue().isEmpty()
                        && (assertRowRules.size() == 1
                                || entry.getKey().equals(this.catalogTableName)))
                .forEach(...);
    }
    ...
}

Key Findings:

  • I independently traced AssertSink.java:59-95 (AssertSink(ReadonlyConfig, CatalogTable) / initTableRule): the sink is constructed once per CatalogTable (multi-table sinks get one AssertSink/AssertSinkWriter instance per table via SupportMultiTableSink), but the constructor loops over the entire tables_configs block and populates assertRowRules with entries for every configured table — only catalogTableName (line 68) is unique per instance. This confirms the bug being fixed is real: pre-PR, every table's writer redundantly (and racily) validated every other table's rule too.
  • write() (unchanged) already scopes accumulation correctly: for assertRowRules.size() > 1 it keys LONG_ACCUMULATOR by element.getTableId(), which for a given sub-writer is always its own table. So in practice LONG_ACCUMULATOR[tableX] is only ever incremented by tableX's own writer instance.
  • I independently traced MultiTableSinkWriter.close() (seatunnel-api/.../multitablesink/MultiTableSinkWriter.java:865-892): it calls checkQueueRemain() (a poll loop on hasPendingRuntimeWrites(), MultiTableSinkWriter.java:991-1001, not a fixed sleep) which busy-waits until every queue across all tables is fully drained, before looping through and calling close() on each per-table sub-writer sequentially, in the same calling thread. So for the standard multi-table-in-one-writer path, by the time any table's AssertSinkWriter.close() runs, all tables' rows are already flushed into the shared static accumulator — narrowing the check to this.catalogTableName is a deterministic, race-free condition, not a coincidence.
  • New unit test (AssertSinkWriterCloseTest) directly reproduces the fixed bug: table B has MIN_ROW=1 and never receives a row; table A's writer under the old code would evaluate B's rule too and fail; under the new code it only checks its own table and passes (testCloseOnlyAssertsOwnTableWhenMultipleTables). A second test (testCloseThrowsWhenOwnTableRuleNotMet) confirms the writer still correctly fails on its own table's unmet rule, so the fix isn't an overcorrection that silently skips validation.
  • Residual, pre-existing risk not fixed by this PR — see Issue 2 below (same finding I flagged in my prior review; I re-verified it still applies and is still unaddressed on the current head, no apology needed since this was already raised, just carried forward).

Runtime path relevant to the residual risk: for a single-table job with parallelism > 1, AssertSinkWriter is not wrapped by MultiTableSinkWriter (there's only one table). Each parallel subtask gets its own AssertSinkWriter instance, and SinkFlowLifeCycle.close() (seatunnel-engine-server/.../task/flow/SinkFlowLifeCycle.java:271-273) calls writer.close() independently per-subtask as soon as that subtask's own upstream data is exhausted — there is no barrier across sibling subtasks at this layer. Since assertRowRules.size() == 1 in this scenario, the new per-table filter is bypassed (assertRowRules.size() == 1 short-circuits true) — identical behavior to pre-PR, minus the sleep. LONG_ACCUMULATOR/TABLE_NAMES remain static and shared across sibling subtask instances with no synchronization.

I confirmed this is not a hypothetical: seatunnel-e2e/seatunnel-connector-v2-e2e/connector-iceberg-e2e/src/test/resources/iceberg/filter_iceberg_source.conf and filter_iceberg_source_tables.conf both set parallelism = 2 on a single/filtered table with both MAX_ROW and MIN_ROW rules (filter_iceberg_source.conf:22,50,54). If the one row matching f1 = 10 lands in the split owned by the other parallel subtask, the subtask that finishes first can call close() and see the static counter still at 0, throwing a false MIN_ROW failure — a real, structurally-exposed flakiness surface for exactly the anti-pattern this batch's review rules ask me to check for (deleting a sleep without replacing it with a deterministic wait, for a case the sleep was actually covering). This CI run's iceberg-connector-it job is still queued as of this review (see Section on CI below), so it hasn't empirically exercised this path yet either way.

1.2 Compatibility Impact

Fully compatible. No Option renamed/removed/re-defaulted, no public API/SPI signature change (removed field was private), no checkpoint/savepoint state involved (AssertSinkWriter returns Void state, doesn't override snapshotState). For the single-table case (assertRowRules.size() == 1), the filter's || short-circuits to true, exactly reproducing pre-PR semantics (functionally unchanged there, just minus the sleep).

1.3 Performance / Side-Effect Analysis

Net positive: every job using the Assert sink previously paid an unconditional 1s Thread.sleep per writer close regardless of table count; that tax is gone. In the multi-table case, MultiTableSinkWriter.close() closes sub-writers sequentially per queue lock — if N assert sub-writers landed in the same queue, the old code paid N * 1s sequentially on job completion; also gone. The old code additionally did O(tables²) redundant validation in the worst case; the new code is O(tables). No new allocations/locks, no GC/memory profile change.

1.4 Error Handling and Logging

No new exception paths. The deleted try { Thread.sleep } catch (InterruptedException) { throw new RuntimeException(e) } block only ever wrapped a spurious interrupt — with the sleep gone there's nothing left to interrupt, so this is a legitimate simplification, not silently swallowed error handling. AssertConnectorException is still thrown identically on rule violation.

Issue 1

  • Location: seatunnel-connectors-v2/connector-assert/src/main/java/org/apache/seatunnel/connectors/seatunnel/assertion/sink/AssertSinkWriter.java:104-112
  • Problem description: close() now relies on a non-obvious cross-class invariant (that MultiTableSinkWriter drains all sub-writers' queues before calling any sub-writer's close(), and that each table's LONG_ACCUMULATOR entry is only ever written by its own table's writer instance) with zero comment explaining it. The deleted sleep at least had a one-line (incorrect) comment describing intent; the replacement has none.
  • Potential risk: a future maintainer, seeing close() validate immediately with no wait, could "fix" what looks like a reintroduced race by adding a sleep back — undoing this fix. (This file's git history shows the same sleep pattern added/removed multiple times already.)
  • Best improvement: add a short comment above the filter explaining why no wait is needed — each table's counter is only incremented by that table's own writer, and MultiTableSinkWriter guarantees full drain before any sub-writer's close() runs.
  • Severity: Medium
  • Raised by another reviewer: No (carried forward from my own prior review, still unaddressed on the current head — the intervening commit is empty).

Issue 2

  • Location: seatunnel-connectors-v2/connector-assert/src/main/java/org/apache/seatunnel/connectors/seatunnel/assertion/sink/AssertSinkWriter.java:104 (interacts with unchanged write() at lines 74-82); concrete exposure at seatunnel-e2e/seatunnel-connector-v2-e2e/connector-iceberg-e2e/src/test/resources/iceberg/filter_iceberg_source.conf:22,50,54 and filter_iceberg_source_tables.conf:22 (both parallelism = 2 with MIN_ROW).
  • Problem description: for a single-table job with parallelism > 1, assertRowRules.size() == 1 bypasses the new per-table filter (identical to pre-PR) and sibling AssertSinkWriter instances share static LONG_ACCUMULATOR/TABLE_NAMES with no barrier (SinkFlowLifeCycle.close() calls writer.close() per-subtask independently, no cross-subtask sync).
  • Potential risk: row-count/table-name assertions on a parallelism > 1 single-table job can flake (false pass or false fail) depending on which parallel subtask finishes and calls close() first. This is pre-existing (the sleep never actually bounded sibling completion time either), but the sleep provided some buffer that is now fully gone — net effect is strictly less timing margin than before for this specific, real (not hypothetical) case.
  • Best improvement: not necessarily a code fix in this PR — no test currently exercises row-count assertions under parallelism > 1 intentionally. But the PR description and/or docs/en/connectors/sink/Assert.md / docs/zh/... should note that MIN_ROW/MAX_ROW/table-name assertions require parallelism = 1 (or single-writer-per-table) to be reliable, since two shipped e2e configs currently run exactly this unreliable combination.
  • Severity: Medium
  • Raised by another reviewer: No (carried forward from my own prior review; still unaddressed).

2. Code Quality Assessment

2.1 Coding Standards

Production change is minimal and idiomatic. Two comment gaps: Issue 1 above, and AssertSinkWriterCloseTest still has no class-level Javadoc (project convention expects one; the per-test inline comments are unusually thorough and largely cover the same ground, but a class Javadoc pointing at "this is the regression coverage for the sleep removal" is still the right home for that context per repo convention).

2.2 Test Coverage and Test Stability

Stability rating: Stable. I re-verified this against the live fork CI run for the current head (see below) rather than just re-reading the code: AssertSinkWriterCloseTest ran and passed — Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.128 s. No Thread.sleep/timing dependency in the test itself, exact assertions (assertDoesNotThrow / assertThrows(AssertConnectorException.class, ...)) rather than weak existence checks, and the two tests use disjoint table-name keys so the static LONG_ACCUMULATOR/TABLE_NAMES fields (not reset by JUnit between methods) don't cross-contaminate the two test cases.

Coverage is on-point for the stated fix and directly reproduces the bug being fixed (see 1.1). It does not cover the parallelism > 1 single-table scenario in Issue 2 — reasonable to treat as out of scope for this PR since no such test existed before either, but it means the CI run cannot vouch for that path either way.

Note on this specific re-review's CI run: iceberg-connector-it (the module containing the two parallelism = 2 + MIN_ROW configs called out in Issue 2) is still queued as of this review and has not executed yet in the current fork run, so I can't report an empirical pass/fail for that residual-risk path from this run — flagging it as still-open based on code-level analysis, not CI evidence either way.

2.3 Documentation Updates

No user-facing config/behavior changed for the fixed path, so no docs/en/docs/zh update is strictly required for the core fix. See Issue 2 for a non-blocking suggested doc note about the parallelism = 1 expectation.

3. Architectural Soundness

3.1 Elegance of the Solution

Precise fix, not a workaround — it removes the actual cross-writer dependency the sleep was trying to paper over, using information (catalogTableName) the class already had and already used in write(), rather than tuning the sleep duration or adding a different ad-hoc wait.

3.2 Maintainability

Net negative line count, no new abstractions; would benefit from the Issue 1 comment given this exact sleep pattern has a history of being re-added in this file.

3.3 Extensibility

No impact — change is local to one method's filter predicate.

3.4 Historical-Version Compatibility

No checkpoint/savepoint state, no serialized format, no config option touched. Old jobs, old JSON, and upgrade paths are unaffected.

CI Status (live re-check for this re-review)

Base comparison: branch is fully in sync with dev (0 commits behind at the merge-base used for this review), mergeable: MERGEABLE. No upstream-sync action needed.

Fork run for the current head (corgy-w/seatunnel, run 33144897524, triggered by the empty chore: trigger CI commit 67162eeb) is still in progress — most jobs (Code style, License header, Dead links, Sanity check, Helm chart, most unit-test/updated-modules-integration-test shards) have completed and passed. One job so far shows a failure: unit-test (11, ubuntu-latest) — but the single test failure in that shard is CoordinatorServiceTest.testClearCoordinatorServiceDropsPendingJobsUnderRejectStrategy:642 » ConditionTimeout, in seatunnel-engine-server, an Awaitility-condition-timeout test completely unrelated to connector-assert (this PR touches no engine-server code). AssertSinkWriterCloseTest itself passed cleanly in that same shard. Several iceberg-connector-it / updated-modules-integration-test-part-* jobs are still queued/in_progress and have not reported a result yet. I'm not treating the CoordinatorServiceTest failure as attributable to this PR, but the run has not fully concluded — the apache-side Build check correctly shows pending.

4. Issue Summary

Number Issue Location Severity
1 close() lacks a comment explaining why no synchronization/wait is needed after removing the sleep AssertSinkWriter.java:104-112 Medium
2 parallelism > 1 single-table row-count/table-name assertions have no barrier between sibling writer instances (pre-existing, undocumented, now with strictly less timing buffer than before); concretely exposed by 2 shipped e2e configs AssertSinkWriter.java:104, write() lines 74-82; filter_iceberg_source.conf, filter_iceberg_source_tables.conf Medium
3 AssertSinkWriterCloseTest has no class-level Javadoc AssertSinkWriterCloseTest.java:1 Low

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed

    • None that are correctness-blocking. Issue 1 (a one-line explanatory comment on close()) is a low-cost ask I'd still like addressed before merge, given this exact sleep has already been added and removed multiple times in this file's history — the comment materially reduces the odds of a future well-intentioned regression.
  2. Recommended fixes — non-blocking

    • Issue 2: document the parallelism = 1 expectation for row-count/table-name assertions (or file a follow-up to make it robust under parallelism > 1), since two shipped e2e configs currently rely on this unstated assumption.
    • Issue 3: add a short class-level Javadoc to AssertSinkWriterCloseTest.

Overall assessment: this remains a well-reasoned, correctly-scoped fix. I independently re-traced AssertSink.java, MultiTableSinkWriter.java, and SinkFlowLifeCycle.java for this re-review (not just re-reading my prior conclusions) and they confirm the same result: the per-table filter genuinely removes the race for the standard multi-table-in-one-writer path (backed by a deterministic, non-flaky new unit test that I confirmed passed in the live CI run), and no table's assertions are silently skipped in that path. No blockers found beyond the previously-raised, still-open Issue 1. CI has not fully concluded on this run yet (one unrelated flaky failure so far, several jobs including iceberg-connector-it still pending) — will need a final green (or a clean rerun of the unrelated CoordinatorServiceTest flake) before merge, but that's a CI-completion gate, not a code concern.

@corgy-w

corgy-w commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @DanielLeens for the deep trace confirming the fix is correct and materially better than the sleep.

Regarding Issue 2 (parallelism > 1 on a single table): I agree it's a real, pre-existing limitation and not something this PR should try to solve. I've documented it explicitly in the PR description under "Known limitation" (§ 1.4/1.2 follow-up) so reviewers and users are aware. A barrier-based close for parallel subtasks would be a separate, larger change.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for the quick follow-up on Issue 2, and for adding the "Known limitation" section to the PR description — that's the right home for it.

One factual correction on that section though, since it affects how safe the documented limitation actually is: the description currently says "all existing Assert E2E configs use parallelism = 1", but that's not accurate. The two configs I cited in Issue 2 are on dev right now, unmodified by this PR:

  • seatunnel-e2e/seatunnel-connector-v2-e2e/connector-iceberg-e2e/src/test/resources/iceberg/filter_iceberg_source.conf — line 22 sets parallelism = 2, and lines 48-54 configure Assert row_rules with MAX_ROW/MIN_ROW on that same source.
  • seatunnel-e2e/seatunnel-connector-v2-e2e/connector-iceberg-e2e/src/test/resources/iceberg/filter_iceberg_source_tables.conf — same pattern, parallelism = 2 at line 22, MAX_ROW/MIN_ROW rules at lines 52-58.

I re-checked both directly against apache/seatunnel:dev just now (this PR doesn't touch either file) to be sure I wasn't citing something stale. So the residual risk in Issue 2 isn't just a hypothetical single-table-parallelism scenario — it's the exact combination two shipped e2e configs currently run. Could you update the "Known limitation" wording to reflect that (e.g. "existing configs that combine parallelism > 1 with row-count assertions on a single table, such as filter_iceberg_source.conf, are exposed to this pre-existing race — not fixed by this PR, tracked as a follow-up")? I don't want a reviewer or user reading "all existing configs use parallelism = 1" and concluding this is purely theoretical when it isn't.

To be clear, I'm not asking you to fix Issue 2 in this PR — I agreed in my last review it's a reasonable follow-up, not a blocker here. This is just about the description being accurate about scope.

Separately, Issue 1 (the one-line comment on close() explaining why no wait/sync is needed post-sleep-removal) and Issue 3 (class Javadoc on AssertSinkWriterCloseTest) are still open — I don't see a new commit on the branch since my last review (head is still 67162eeb), so there's nothing new to re-verify on those yet. I'll do a full pass again once the fixes land.

@DanielLeens

Copy link
Copy Markdown
Contributor

CI has now fully concluded on the current head (67162eeb) — the Build check completed successfully, so the "pending / not fully concluded" state I noted in my last review is resolved.

That doesn't change the merge-readiness bottom line though: Issue 1 (a one-line comment on close() explaining why no synchronization/wait is needed after the sleep removal) and Issue 3 (class-level Javadoc on AssertSinkWriterCloseTest) are still open asks from my review, and there's no new commit on the branch since then. Once those land I'll do a final pass.

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

+1
LGTM

Thanks for your contribution! This is a solid addition to the project, and your attention to detail really shows. Contributors like you are what keep this community moving forward. Feel free to keep the PRs coming — we're always glad to have you here!

Please ignore the following message if you have joined in the Slack~

To facilitate focused communication among contributors, we’ve created a brand-new dedicated #contributors channel in official Slack workspace.
Slack workspace link: https://s.apache.org/seatunnel-slack

This channel is designed for technical discussions, feature design brainstorming, roadmap sync and direct communication with project core Contributors. Everyone who contributes code, docs, test cases or community ideas is warmly invited to join, share thoughts and collaborate together under The Apache Way. Welcome to join 😄

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.

3 participants