You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by "DanielLeens (via GitHub)" <gi...@apache.org> on 2026/09/15 05:50:33 UTC

[PR] [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them [seatunnel]

DanielLeens opened a new pull request, #12316:
URL: https://github.com/apache/seatunnel/pull/12316

   ## Summary
   
   Checkpoint and savepoint barriers can be starved by a busy source for an unbounded number of poll cycles, because the reader thread and the barrier injector share one unfair intrinsic monitor and the reader re-enters it immediately after every poll. This PR adds an explicit reader-to-injector handoff in `SourceFlowLifeCycle` so a barrier is injected within at most one `pollNext` call, for every source connector, without touching the public `Collector#getCheckpointLock()` contract.
   
   Observed on `dev`'s own `engine-v2-it` runs as `BackpressureSlowSinkIT#testCheckpointsKeepCompletingUnderSustainedBackpressure` failing at both `:184` (first checkpoint never completes inside 2 min; the coordinator then hits the 100s `checkpoint.timeout`) and `:247` (`only observed 0`/`2` new checkpoints in the 90s window). Both JDK 8 and JDK 11 legs are affected (dev runs `34801745423` and `34821874806`).
   
   ## Root cause (verified against current `dev` source)
   
   Execution chain for one barrier under backpressure:
   
   1. `CheckpointBarrierTriggerOperation#runInternal` hands `SourceSeaTunnelTask#triggerBarrier` to the task group's async executor, which calls `SourceFlowLifeCycle#triggerBarrier` and blocks on `synchronized (collector.getCheckpointLock())`.
   2. The reader thread is inside `SourceReader#pollNext`, which by contract holds that same lock for the whole call. `FakeSourceReader#pollNext` emits up to `MAX_ROWS_PER_POLL = 4096` rows per call, and each `SeaTunnelSourceCollector#collect` -> `sendRecordToNext` blocks on the bounded intermediate queue (`ArrayBlockingQueue`, capacity 2048) while the sink drains at ~500 rows/s. One poll therefore holds the lock for ~8 s.
   3. `SourceFlowLifeCycle#collect` releases the lock when `pollNext` returns, executes `Thread.sleep(0L)`, and re-enters `pollNext`. HotSpot monitors do not hand off to the parked waiter on exit; the exiting thread that immediately re-acquires wins nearly every time. `Thread.sleep(0L)` only yields the CPU and does not change that race.
   4. The barrier is injected only when the scheduler happens to favour the injector at a release point, i.e. after a random integer number of ~8 s polls. The dev log for job `1150683685079482369` shows exactly that shape: checkpoint durations of 20 s, 34 s, 8.5 s and 36 s against a no-starvation baseline of ~6 s (2048-row intermediate queue plus the 1024-row `MultiTableSinkWriter` queue at 500 rows/s).
   
   #12313 makes the E2E fixture avoid the race by sizing FakeSource splits so every split completes in one poll and its explicit `Thread.sleep(1000L)` runs outside the lock; that PR itself notes the engine-side unfair handoff as pre-existing and out of its scope. This PR is that engine-side fix. Any production source whose `pollNext` is long relative to the checkpoint interval (large batches, slow downstream, JDBC/file readers with big fetch sizes) is exposed to the same starvation; #11489 already worked around it inside `FakeSourceReader` by batching, which is why the lock hold is ~8 s rather than the whole split.
   
   ## Fix
   
   - New package-private `SourceCheckpointLockHandoff` (`seatunnel-engine-server`, `task.flow`): an injector announces itself before contending for the lock and withdraws in `finally`; the reader, at the point where it holds no lock, waits (1 ms slices, accounted as source idle time when observability is enabled) until no injector is announced before starting the next poll.
   - `SourceFlowLifeCycle#triggerBarrier` wraps its `synchronized` block with `injectorArriving()` / `injectorFinished()`.
   - `SourceFlowLifeCycle#collect` replaces the ineffective `Thread.sleep(0L)` after a non-empty poll with `checkpointLockHandoff.awaitInjectors()`.
   - No change to `Collector`, `SourceReader`, any connector, checkpoint serialization, restore, or barrier ordering. The barrier still travels through the same lock and the same `sendRecordToNext` call, after `addState` and `ack`, exactly as before.
   
   ### Semantics and safety
   
   - Old behaviour: barrier injection latency is unbounded and depends on scheduler luck. New behaviour: bounded by the poll in flight. Data order, ack order and state snapshot content are unchanged.
   - Deadlock-free by construction: the reader waits only while holding no lock; an injector never waits for the reader; an injector blocked on the full intermediate queue while forwarding the barrier still makes progress because the sink keeps draining. The `finally` guarantees a failed injection (for example `snapshotState` throwing) cannot leave the reader parked.
   - Hot-path cost when no barrier is pending: one volatile read per non-empty poll (`awaitInjectors` returns 0 immediately).
   - Empty polls are unaffected (they already sleep 100 ms outside the lock); `prepareClose` and schema-change phases are unaffected (they run after the handoff point and do not hold the lock).
   - Task cancellation still interrupts the reader thread; the wait propagates `InterruptedException` like the previous sleep did.
   - The periodic `FlushSignal` from `onTimerTick` also takes the checkpoint lock; it is intentionally left out of the handoff (it is not a barrier and is not latency-critical), keeping the change to the barrier path only.
   
   ## Tests
   
   - New `SourceCheckpointLockHandoffTest` (pure unit test, no cluster):
     - no injector pending: `awaitInjectors` returns immediately (no added latency on the hot path);
     - pending state tracks multiple injectors independently (checkpoint and savepoint triggered back to back);
     - a reader re-acquiring the lock in a tight loop yields to an injector within at most the poll in flight (measured in poll cycles, not wall-clock);
     - a parked reader resumes when the injector finishes, including after a failed injection;
     - a parked reader honours interrupt (task cancellation).
   - Existing E2E coverage that exercises the barrier-vs-busy-source path: `BackpressureSlowSinkIT`, `SavepointBusySourceBarrierIT`, plus the whole `engine-v2-it` suite.
   - Local: `./mvnw spotless:apply -pl seatunnel-engine/seatunnel-engine-server -nsu -Dmaven.gitcommitid.skip=true` only. Compilation, unit tests and E2E are verified by this PR's GitHub CI, per this initiative's no-local-build policy.
   
   ## Files
   
   - `seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/flow/SourceFlowLifeCycle.java` (handoff wiring, comments updated)
   - `seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/flow/SourceCheckpointLockHandoff.java` (new)
   - `seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/task/flow/SourceCheckpointLockHandoffTest.java` (new)
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them [seatunnel]

Posted by "davidzollo (via GitHub)" <gi...@apache.org>.
davidzollo commented on PR #12316:
URL: https://github.com/apache/seatunnel/pull/12316#issuecomment-6394269422

   Updated in c5462a14a078f39ca206edf01937af6fe0c65dc1 to address the remaining review points.
   
   Timer flushes now use the same announce/finally-withdraw handoff as barriers and recheck closure under the collector monitor. The helper documents cross-poll progress and polling limits, and retains the replaced sleep call's interrupted-thread behavior even on the no-pending fast path. Test registration precedes sampling, with unconditional owned-thread cleanup.
   
   The existing test class now exercises actual SourceFlowLifeCycle/collector barrier and timer wiring, serialized state and snapshot/state/ack/forward order, failures and queued ticks behind a closing barrier. BackpressureSlowSinkIT retains its unchanged single-split workload and all original checkpoint/queue assertions, running with timer flushing both disabled and enabled; the timer variant checks actual worker flush-counter progress. No #12313 fixture workaround is included.
   
   Scoped Spotless and static whitespace checks passed, and the final source/test patch received independent review. The PR description now reflects the actual scope and limits. Remote readback confirms this head, four intended files, no POM delta and no conflict. Current-head GitHub CI remains required; this is not runtime or merge clearance.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them [seatunnel]

Posted by "goutamadwant (via GitHub)" <gi...@apache.org>.
goutamadwant commented on PR #12316:
URL: https://github.com/apache/seatunnel/pull/12316#issuecomment-5841704369

   I tried to reproduce the `BackpressureSlowSinkIT` flake locally, to compare this PR and #12313 alone and together.
   
   Setup: macOS, a loaded 10-core host, one fresh JVM per run. Base was `dev` at `deb16a3c3`. Each head was the PR diff(s) applied to that commit.
   
   | variant | JDK 8 | JDK 11 (`-XX:ActiveProcessorCount=2`) |
   |---|---|---|
   | base | 0 / 8 | 0 / 8 (+ 0 / 3 with `ActiveProcessorCount=1` and `nice 19`) |
   | this PR | 0 / 8 | 0 / 8 |
   | #12313 | 0 / 8 | 0 / 8 |
   | both | 0 / 8 | 0 / 7 |
   
   Base never failed for me, so this is not red-to-green evidence for the IT. It only shows that neither change breaks it.
   
   **Handoff alone:** to check the mechanism I wrote a small harness around `SourceCheckpointLockHandoff`. A reader holds the monitor for 5 ms per poll, and I counted how many polls an injector waits for the monitor (200 trials each).
   
   - `Thread.sleep(0)` (current `dev`): about 25% of trials waited more than one poll; the worst case was 8-10 polls.
   - this PR: every trial got the lock within 1-2 polls.
   
   So the handoff does what the description says.
   
   **Throughput:** I ran a 5M-row FakeSource to InMemory batch job with `checkpoint.interval = 200`, alternating `dev` and this PR, in two batches.
   
   - Batch 1, 7 pairs, heavily loaded host: median 66.5 s on `dev`, 68.1 s with this PR.
   - Batch 2, 5 pairs, quieter host: median 72.0 s and 72.2 s.
   
   I read that as no measurable difference, not as a clean benchmark. The fast path is one `AtomicInteger` read per poll. The reader only parks while an injector is registered, and it would be blocked on the monitor anyway in that case. The `finally` release looks right.
   
   One limit, if I read it correctly: the handoff only helps between `pollNext` calls. A single `pollNext` that blocks on a full queue for seconds still holds the lock for that time. That is the case #12313 avoids by sizing splits under `MAX_ROWS_PER_POLL`. With #12313's fixture, though, the IT no longer exercises the long back-to-back lock hold, so it would keep passing even if this handoff regressed. If both land, it may be worth keeping one variant of the test on the original `split.num = 1` workload so this change stays covered.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them [seatunnel]

Posted by "DanielLeens (via GitHub)" <gi...@apache.org>.
DanielLeens commented on PR #12316:
URL: https://github.com/apache/seatunnel/pull/12316#issuecomment-5846335176

   Thanks for the thorough pass — I went back through the current head against each point rather than taking my own prior conclusions for granted, and I want to respond to all five with where I actually landed.
   
   **Issues 1 & 2 (timer flush signal path not covered by the handoff)**: you're right, and I should have caught this myself. I re-traced it: `onTimerTick` (`SourceFlowLifeCycle.java:204-214`) calls `collector.sendFlushSignal(...)`, which goes through `sendRecordToNext` and `synchronized (checkpointLock)` (`SeaTunnelSourceCollector.java:410`) — the identical monitor `triggerBarrier` registers against, but `onTimerTick` never calls `injectorArriving()`/`injectorFinished()`. So the reader's `awaitInjectors()` has no visibility into a pending flush tick, and that tick is exposed to exactly the unfair-reentry race this PR eliminates for barriers. It's pre-existing behavior, not a regression from this diff, but since `timerFlushWorker` is a shared, node-wide pool, a tick losing that race for several multi-second polls does pin a shared thread longer than necessary, and it's a gap in what this PR set out to fix. I'll wrap `onTimerTick`'s `sendFlushSignal` call in the same `injectorArrivi
 ng()` / `try { ... } finally { injectorFinished(); }` pattern in the next revision — likely via a small shared helper on `SourceCheckpointLockHandoff` so both call sites can't drift apart again — rather than just documenting the gap away.
   
   **Issue 3 (sampling order in `injectorAcquiresLockWithinOnePollCycle`)**: confirmed, and your fix is better than what I originally proposed. I had flagged the same test in my 09-15 review and suggested widening the tolerance or raising `POLL_HOLD_MS`, which only shrinks the window. Working through it again with your suggested swap — announce via `injectorArriving()` first, then sample `completedPolls` — actually removes the race: once the injector has registered, the reader's very next `awaitInjectors()` call is guaranteed to see it and park before it can re-acquire the lock for an unannounced extra poll, so there's no gap left to sample around. I'll make that swap and correct the comment above it.
   
   **Issue 5 (javadoc wording)**: agreed, "an injector never waits for the reader" is only true in the deadlock-avoidance sense and reads like a latency claim on its own. I'll tighten that sentence and add an explicit note on which `checkpointLock` contenders are (and, until Issue 1 lands, aren't) registered with the handoff, so this doesn't have to be inferred from the call sites.
   
   **Issue 4 (sleep-poll vs. a signalled wait)**: this one I'd like to hold as a follow-up rather than fold into this PR. The design point is fair — a `wait`/`notifyAll` (or `LockSupport.park`/`unpark`) handoff would resume the reader immediately instead of on the next 1ms slice — but it trades a very small, well-understood latency cost for a different correctness surface to reason about (missed-notify ordering between `injectorFinished()` and a reader that hasn't started waiting yet). Given the documented cost is already bounded and this PR is meant to stay a minimal, narrowly-scoped fix, I'd rather land the flush-path coverage and the test fix first and revisit the wait mechanism separately if there's ever measured evidence the 1ms granularity matters in practice. Happy to hear if you disagree on the priority.
   
   I'll push a commit covering Issues 1, 2, 3 and 5 next; once that's up I'd like you to take another look specifically at the flush-path wiring, since that's the part that's genuinely new rather than a restatement of what I'd already checked.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them [seatunnel]

Posted by "DanielLeens (via GitHub)" <gi...@apache.org>.
DanielLeens commented on PR #12316:
URL: https://github.com/apache/seatunnel/pull/12316#issuecomment-5846335036

   Thank you for taking the time to build an independent harness and reproduce this rather than just reading the description — that's exactly the kind of check I was hoping for.
   
   The harness numbers line up with what I traced through the code: `Thread.sleep(0)` on `dev` losing the race roughly a quarter of the time with a multi-poll tail, versus this PR bounding it to 1-2 polls every time. And I read the throughput comparison the same way you do — the fast path is one atomic read per poll with no allocation, so a difference in the noise on a loaded host is what I'd expect, not evidence either way on its own.
   
   You're also right about the boundary of what this fixes: the handoff only creates a yield point *between* `pollNext` calls, so a single call that blocks for seconds on its own (a large JDBC split, for instance) is unaffected — that's the same limitation I called out in my own review, and it's exactly why #12313's fixture (bounding rows per poll) and this PR are complementary rather than overlapping fixes for the same symptom.
   
   Your suggestion to keep one IT variant on the original `split.num = 1` workload is a good one, and I agree with the reasoning: if #12313's fixture lands and the IT no longer produces a long back-to-back lock hold, this handoff's own regression coverage would quietly disappear even though the code is still there. I'll add that variant in the next revision so the two fixes don't end up canceling out each other's test coverage.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them [seatunnel]

Posted by "nzw921rx (via GitHub)" <gi...@apache.org>.
nzw921rx commented on PR #12316:
URL: https://github.com/apache/seatunnel/pull/12316#issuecomment-6462868947

   ## SeaTunnel benchmark comparison
   
   - Baseline: `dev` at `cec3276740d989c8cb67c7b8c37e0a817e728059` (2 runs)
   - Candidate: `PR #12316` at `d6d2e8ab1007b1ce2ab67770d3fa5cab1d172084` (2 runs)
   - Suite: `SeaTunnelPipelineBenchmark`
   - Java: `17.0.21`
   - Runner image: `ubuntu24-20261026.354.1`
   - CPU: `AMD EPYC 9V74 80-Core Processor`
   
   > Baseline and candidate ran alternately on the same worker.
   
   ### JMH comparison
   
   > `B` = Baseline, `C` = Candidate. Score is the median benchmark result; CV measures variability and Error represents the relative JMH confidence interval, both aggregated as medians across runs.
   > Score Change is direction-adjusted so positive is favorable; CV and Error changes are relative changes.
   
   | Benchmark | Parameters | Score B | Score C | Score Change | CV B | CV C | CV Change | Error B | Error C | Error Change | Unit |
   | --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |
   | `Pipeline.sourceSink` | `rate=600k, p=4, payload=256, work=64` | 456,176.13 | 460,259.60 | +0.90% | 0.58% | 0.77% | +33.44% | 2.23% | 2.97% | +33.44% | ops/s |
   | `Pipeline.sourceTransformSink` | `rate=600k, p=4, payload=256, work=64` | 451,105.22 | 453,264.82 | +0.48% | 0.83% | 1.19% | +43.10% | 3.19% | 4.57% | +43.10% | ops/s |
   | `Pipeline.sourceTransformSinkWithObservability` | `rate=600k, p=4, payload=256, work=64` | 460,496.53 | 457,603.21 | -0.63% | 0.77% | 0.82% | +6.36% | 2.98% | 3.17% | +6.36% | ops/s |
   | `Pipeline.sourceTransformSinkWithObservabilityAndTrace` | `rate=600k, p=4, payload=256, work=64` | 456,651.69 | 456,960.68 | +0.07% | 0.86% | 1.03% | +19.88% | 3.32% | 3.98% | +19.88% | ops/s |
   | `Pipeline.sourceTransformSinkWithTrace` | `rate=600k, p=4, payload=256, work=64` | 457,157.06 | 460,570.10 | +0.75% | 0.93% | 1.23% | +32.24% | 3.59% | 4.74% | +32.24% | ops/s |
   
   ### Pipeline comparison
   
   Cells show `baseline → candidate (adjusted change)`; positive change is favorable.
   `Payload` is characters per row and `Growth` is a unitless ratio. `Valid` includes measurement samples only; warmup samples are excluded.
   Percentiles beyond the measurable range are shown as lower bounds, for example `>60,000`.
   
   #### `source-sink`
   
   Parameters: `rate=600k, p=4, work=64`
   
   | Payload (chars) | Throughput (rows/s) | P50 (ms) | P95 (ms) | P99 (ms) | Max (ms) | Growth (ratio) | Valid (samples) |
   | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |
   | 256 | 587,371.56 → 598,995.70 (+1.98%) | 50 → 50 (+0.00%) | 96 → 96 (+0.00%) | 100 → 100 (+0.00%) | 102 → 102 (+0.00%) | 1.000 → 1.000 (+0.00%) | ✅ 50/50 → ✅ 50/50 |
   
   #### `source-transform-sink`
   
   Parameters: `rate=600k, p=4, work=64`
   
   | Payload (chars) | Throughput (rows/s) | P50 (ms) | P95 (ms) | P99 (ms) | Max (ms) | Growth (ratio) | Valid (samples) |
   | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |
   | 256 | 585,651.59 → 585,137.71 (-0.09%) | 50 → 50 (+0.00%) | 96 → 96 (+0.00%) | 100 → 100 (+0.00%) | 104 → 104 (-0.48%) | 1.000 → 1.000 (+0.00%) | ✅ 50/50 → ✅ 50/50 |
   
   #### `source-transform-sink-observability`
   
   Parameters: `rate=600k, p=4, work=64`
   
   | Payload (chars) | Throughput (rows/s) | P50 (ms) | P95 (ms) | P99 (ms) | Max (ms) | Growth (ratio) | Valid (samples) |
   | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |
   | 256 | 590,493.11 → 587,891.31 (-0.44%) | 50 → 51 (-2.00%) | 96 → 96 (+0.00%) | 100 → 100 (+0.50%) | 104 → 104 (+0.00%) | 0.995 → 0.995 (+0.00%) | ✅ 50/50 → ✅ 50/50 |
   
   #### `source-transform-sink-observability-trace`
   
   Parameters: `rate=600k, p=4, work=64`
   
   | Payload (chars) | Throughput (rows/s) | P50 (ms) | P95 (ms) | P99 (ms) | Max (ms) | Growth (ratio) | Valid (samples) |
   | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |
   | 256 | 588,068.49 → 587,544.88 (-0.09%) | 50 → 51 (-0.99%) | 96 → 96 (+0.00%) | 100 → 100 (+0.00%) | 104 → 105 (-0.48%) | 0.990 → 0.990 (+0.00%) | ✅ 50/50 → ✅ 50/50 |
   
   #### `source-transform-sink-trace`
   
   Parameters: `rate=600k, p=4, work=64`
   
   | Payload (chars) | Throughput (rows/s) | P50 (ms) | P95 (ms) | P99 (ms) | Max (ms) | Growth (ratio) | Valid (samples) |
   | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |
   | 256 | 587,544.88 → 595,133.12 (+1.29%) | 50 → 50 (+0.00%) | 96 → 96 (+0.00%) | 100 → 100 (+0.00%) | 104 → 104 (-0.48%) | 1.000 → 1.000 (+0.00%) | ✅ 50/50 → ✅ 50/50 |
   
   ---
   Benchmark comparison did not result in performance degradation
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them [seatunnel]

Posted by "DanielLeens (via GitHub)" <gi...@apache.org>.
DanielLeens commented on PR #12316:
URL: https://github.com/apache/seatunnel/pull/12316#issuecomment-6138979567

   CI retry result: fork run 36327199671 reached attempt 2. The prerequisite `Dependency licenses` job reran today and passed, but GitHub retained the requested Windows unit-test job and the other downstream jobs as `cancelled` with their original September completion timestamps, so the workflow concluded `cancelled` again without actually producing a new result for the target job. The one-rerun budget is now exhausted. Source remains unchanged, the PR is conflict-free and formally APPROVED; CI still requires a fresh workflow/head event (or explicit authorization for a broader rerun) to obtain a non-cancelled Build result.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them [seatunnel]

Posted by "nzw921rx (via GitHub)" <gi...@apache.org>.
nzw921rx merged PR #12316:
URL: https://github.com/apache/seatunnel/pull/12316


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them [seatunnel]

Posted by "davidzollo (via GitHub)" <gi...@apache.org>.
davidzollo commented on PR #12316:
URL: https://github.com/apache/seatunnel/pull/12316#issuecomment-6412367685

   The current-head CI compile failure was caused by the new test importing FlushSignal from the task-record package. d6d2e8ab1007b1ce2ab67770d3fa5cab1d172084 corrects the import to the existing org.apache.seatunnel.api.signal.FlushSignal type used by the real collector. This is an import-only correction: production behavior and assertions are unchanged. Scoped server Spotless and the exact diff/whitespace checks passed, and the correction received independent review. The resulting head still requires GitHub compile, unit and integration execution; the prior failed run is not a result for this new head.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them [seatunnel]

Posted by "DanielLeens (via GitHub)" <gi...@apache.org>.
DanielLeens commented on PR #12316:
URL: https://github.com/apache/seatunnel/pull/12316#issuecomment-5678693760

   *Posting this as a plain issue comment rather than a `gh pr review` — GitHub does not let an author submit a formal review on their own PR. I reviewed this the same way I'd review anyone else's `seatunnel-engine` change: full diff, full call-chain trace, no benefit of the doubt for authorship.*
   
   # What Problem Does This PR Solve?
   
   - **User pain point**: Under sustained backpressure, a checkpoint or savepoint barrier injected via `SourceFlowLifeCycle#triggerBarrier` can be starved for a long, effectively unbounded number of reader poll cycles. The reader thread holds `collector.getCheckpointLock()` while emitting each record inside `SourceReader#pollNext`, releases it, and — because Java's intrinsic monitors are unfair — almost always wins the race to reacquire it for the next poll before a parked barrier-injector thread gets a turn. The previous mitigation, `Thread.sleep(0L)` after a non-empty poll, only yields the CPU; it does not change who wins the monitor race, so it did not bound the starvation. This was observed as `BackpressureSlowSinkIT` timing out on `dev` (per my prior root-cause note on this flake).
   - **Fix approach**: Add `SourceCheckpointLockHandoff`, a small cooperative-handoff primitive: a barrier injector calls `injectorArriving()` before contending for the lock and `injectorFinished()` in a `finally` block after releasing it; the reader thread, at the point between polls where it holds no lock, calls `awaitInjectors()` and spin-waits (1ms `Thread.sleep` slices) until no injector is registered before starting its next poll.
   - **One-sentence summary**: Turns the previously-unfair, potentially-unbounded race for the checkpoint lock into an explicit handoff that guarantees a barrier injector acquires the lock within one poll cycle of announcing itself, instead of possibly losing the race indefinitely.
   
   # 1. Code Change Review
   
   ## 1.1 Core Logic Analysis
   
   **Core changes**:
   - New file `SourceCheckpointLockHandoff.java` (102 lines): an `AtomicInteger pendingInjectors` counter with `injectorArriving()`/`injectorFinished()`/`hasPendingInjector()`/`awaitInjectors()`.
   - `SourceFlowLifeCycle.java`: `collect()` now calls `checkpointLockHandoff.awaitInjectors()` (instead of `Thread.sleep(0L)`) right after a non-empty poll, outside the checkpoint lock; `triggerBarrier(Barrier)` now wraps its existing `synchronized (collector.getCheckpointLock())` block in `injectorArriving()` / `try { ... } finally { injectorFinished(); }`.
   
   Before (`collect()`):
   ```java
   Thread.sleep(0L);
   ```
   After:
   ```java
   long handoffWaitNs = checkpointLockHandoff.awaitInjectors();
   if (metricsEnabled) {
       sourceIdleNs.inc(handoffWaitNs);
   }
   ```
   Before (`triggerBarrier`):
   ```java
   synchronized (collector.getCheckpointLock()) {
       ...
       collector.sendRecordToNext(new Record<>(barrier));
   }
   ```
   After:
   ```java
   checkpointLockHandoff.injectorArriving();
   try {
       synchronized (collector.getCheckpointLock()) {
           ...
           collector.sendRecordToNext(new Record<>(barrier));
       }
   } finally {
       checkpointLockHandoff.injectorFinished();
   }
   ```
   
   **Key findings**:
   - The normal path reaches this code on every source poll cycle for every running source subtask: `awaitInjectors()` is called unconditionally after every non-empty `pollNext()`, and `injectorArriving()`/`injectorFinished()` wrap every `triggerBarrier` call, i.e. every checkpoint and savepoint. This is core scheduling-path code, not a rare recovery branch.
   - `awaitInjectors()`'s own contract is respected at its call site: its Javadoc requires the caller to hold no lock, and `SourceFlowLifeCycle.collect()` calls it strictly after `reader.pollNext(collector)` has already returned (i.e. after any lock the reader took inside `pollNext` has already been released) — I traced this and it is correct, no deadlock is introduced.
   - `injectorFinished()` is unconditionally reached via `finally`, even when `barrier.prepareClose(...)`, `reader.snapshotState(...)`, `runningTask.addState(...)`, `runningTask.ack(...)`, or `collector.sendRecordToNext(...)` throws — so a failed injection cannot permanently park the reader. Verified there is exactly one `injectorArriving()`/`injectorFinished()` pair, with no early return between them.
   - `AtomicInteger` correctly supports the documented "more than one injector" case (a checkpoint and a savepoint barrier close together) — increments/decrements are safe under concurrent callers, and `hasPendingInjector()` correctly reflects "at least one still pending" until every announced injector has withdrawn.
   
   **In-depth correctness analysis — the residual bound this fix actually provides**: I want to be precise about what "bounded by a single poll" means, because I think the class Javadoc could be misread as a stronger guarantee than it actually is, and I'd rather flag my own doc wording than let it stand ambiguous.
   
   `SourceReader#pollNext` is documented as "generate the **next batch** of records" (not one record), and at least one connector — `JdbcSourceReader#pollNext` (`seatunnel-connectors-v2/connector-jdbc/.../JdbcSourceReader.java:67-95`) — wraps its **entire per-split read loop** (`while (!inputFormat.reachedEnd()) { output.collect(seaTunnelRow); }`) inside one `synchronized (output.getCheckpointLock())` block, i.e. it takes the lock once for the whole split rather than once per row. For that connector shape, `awaitInjectors()` cannot help *during* a single `pollNext()` call — the reader thread is inside `reader.pollNext(collector)`, not at the handoff call site, for the full duration of that split. What this fix actually bounds is the previously-unbounded compounding across **multiple consecutive poll cycles** (the reader winning the race poll after poll after poll, which is exactly what I traced as the mechanism behind the `BackpressureSlowSinkIT` flake — a test source that re
 turns from `pollNext()` frequently). For a connector whose single `pollNext()` call can itself run for minutes (e.g. a very large JDBC split under a slow downstream), checkpoint-barrier latency for that specific poll is not improved by this PR — it is unchanged from before, and was already a pre-existing property of holding the lock for the whole split, not something this PR regresses.
   - This means the fix is fully correct and effective for the flake it targets and for any connector that calls `collect()` once (or a few times) per `pollNext()` invocation, which covers most non-batch-oriented sources. It does not, and does not claim in the code, extend to eliminating lock hold time *within* a single large-batch poll.
   
   ## 1.2 Compatibility Impact
   
   **Fully compatible.** No config option, API, checkpoint/savepoint state format, or serialization is touched — this is a purely in-memory, intra-process concurrency primitive scoped to one `SourceFlowLifeCycle` instance's lifetime (a fresh `SourceCheckpointLockHandoff` per instance, no cross-restart state to migrate). The only observable side effect is `sourceIdleNs` metric: the handoff wait is now counted as idle time, whereas the previous `Thread.sleep(0L)` contributed nothing to that metric. This makes the metric more accurate (the reader genuinely is idle while ceding to an injector) but is a small, backward-compatible semantic refinement worth calling out explicitly since some existing dashboards/alerts calibrated to the old idle-time baseline could see a small upward shift during checkpoint injection windows — not a functional regression, no action required, but worth an explicit mention here for anyone auditing metric-based SLOs.
   
   ## 1.3 Performance / Side-Effect Analysis
   
   - Fast path (no pending injector): `awaitInjectors()` does one `AtomicInteger.get()` (a volatile read) and returns — negligible overhead added to every poll cycle, no allocation.
   - Slow path (injector pending): the reader spin-waits via `Thread.sleep(1L)` in a loop until the injector withdraws; bounded by how long the injector needs to hold the lock (documented as "normally finishes within a few milliseconds"), so worst-case added reader latency per checkpoint is small and self-limiting — it is not busy-spinning (no CPU burn between the 1ms sleeps).
   - No new locks, no new blocking I/O, no new retry logic, no new resource that needs releasing — the change is additive coordination state (`AtomicInteger`) around locking that already existed.
   - Concurrency safety: reasoned through above (finally-guarded release, atomic counter, no deadlock at the call sites as they exist today). I did not find a scenario where `pendingInjectors` can leak positive (go permanently non-zero without a corresponding live injector), since the only increment/decrement pair is co-located in `triggerBarrier` with the decrement in `finally`.
   
   ## 1.4 Error Handling and Logging
   
   Not applicable to the new class — `injectorArriving`/`injectorFinished`/`hasPendingInjector` cannot throw; `awaitInjectors()` correctly declares and propagates `InterruptedException` so that task-cancellation interrupts surface to the caller instead of being swallowed (verified by the new `waitingReaderHonoursInterrupt` test). No new logging added; none needed for this scope.
   
   **Issue 1: Test assertion window in `injectorAcquiresLockWithinOnePollCycle` is not fully immune to scheduling jitter, despite the comment's claim**
   - **Location**: `seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/task/flow/SourceCheckpointLockHandoffTest.java:106-108` (the `pollsBeforeInjector.set(completedPolls.get()); handoff.injectorArriving();` pair inside the injector thread body)
   - **Problem description**: The test comment states "The injector's acquisition is measured in reader poll cycles, so the assertion does not depend on wall-clock scheduling noise." That's the intent, but the two statements sampling `pollsBeforeInjector` and then calling `injectorArriving()` are not executed atomically with respect to the reader thread. If the injector thread is descheduled (GC safepoint, CI host contention) for longer than one `POLL_HOLD_MS` (100ms) between those two lines, the reader can complete an extra poll cycle in that gap, and `pollsWaited = pollsWhenInjectorAcquired - pollsBeforeInjector` (asserted `<= 1` at line ~139) would be inflated to 2+, failing the test even though the production handoff logic behaved correctly.
   - **Potential risk**: A narrow, environment-dependent flaky-test risk on loaded/shared CI runners — not a masked production bug (the assertion failure would be a false negative on the test's own timing tolerance, not evidence of the handoff misbehaving). Given the two statements are adjacent with no I/O or lock contention between them, the probability is low but not zero, especially under GC pressure with many parallel forked test JVMs.
   - **Best improvement**: Either (a) widen the tolerance slightly (e.g. `pollsWaited <= 2`) with a comment acknowledging scheduling slack, or (b) increase `POLL_HOLD_MS` to reduce the relative likelihood of a stray scheduling gap exceeding it, or (c) have `SourceCheckpointLockHandoff` (test-only overload, or a small test seam) return the poll-count sample atomically with the announcement so the measurement genuinely has no gap. I'd lean toward (b) as the lowest-risk change.
   - **Severity**: Medium (per Section 5.10.2 test-stability classification: "Risk present" — could cause intermittent failure, does not block merge, but should be tightened)
   - **Raised by another reviewer**: No
   
   No other issues, blocking or non-blocking, found in the production code.
   
   # 2. Code Quality Assessment
   
   ## 2.1 Coding Standards
   
   `SourceCheckpointLockHandoff` has a thorough class-level Javadoc covering the mechanism, the deadlock-safety argument, and the `finally`-release contract; every public/package method has its own Javadoc stating pre/postconditions (notably `awaitInjectors()`'s "the caller must not hold the checkpoint lock" precondition, which is the one precondition that actually matters for correctness). The new field/constant (`WAIT_SLICE_MS`, `pendingInjectors`) both have Javadoc explaining *why* their values/semantics are what they are, not just restating the declaration. This meets the project's documentation bar for concurrency-relevant fields well.
   
   ## 2.2 Test Coverage and Test Stability
   
   `SourceCheckpointLockHandoffTest.java` covers: no-op fast path, independent multi-injector counting, the core "bounded by one poll cycle" guarantee under real concurrent threads, resume-on-finish, and interrupt propagation. The class Javadoc explicitly ties the test back to the `BackpressureSlowSinkIT` regression it guards against, which is good practice.
   
   **Test-stability conclusion (Section 5.10.2)**:
   - `awaitReturnsImmediatelyWhenNoInjectorIsPending`, `pendingStateTracksEveryInjectorIndependently`: pure, single-threaded, deterministic. Stable.
   - `waitingReaderResumesWhenInjectorFinishes`: two threads, but the negative assertion window (reader must *not* resume within `5*WAIT_SLICE_MS+50ms`) is safe because nothing decrements the counter until the main thread explicitly does so later — no race, deterministic. Stable.
   - `waitingReaderHonoursInterrupt`: single-thread interrupt semantics, deterministic. Stable.
   - `injectorAcquiresLockWithinOnePollCycle`: real two-thread concurrency test bounded by a 10-second `JOIN_TIMEOUT_MS` safety net (so a failure surfaces as an assertion failure, not a CI hang) — but has the scheduling-jitter exposure described in **Issue 1** above.
   
   **Overall stability rating: Risk present.** The one identified pattern (Issue 1) is a genuine, if low-probability, source of intermittent failure specific to this new test; it does not indicate a flaw in the production fix itself, and the test correctly bounds its own worst case with a join timeout rather than risking a hang. Recommend tightening per Issue 1's suggestion before or shortly after merge.
   
   ## 2.3 Documentation Updates
   
   Not applicable — no user-visible/config-visible behavior change, so no `docs/en`/`docs/zh` update is required. (I did consider whether the metric-semantics note in 1.2 warrants a docs update; given it's a refinement of an existing internal metric's precision rather than a new/renamed metric or a config change, I don't think it clears the bar for `docs/en`/`docs/zh`, but I'm flagging my reasoning here in case a reviewer disagrees.)
   
   # 3. Architectural Soundness
   
   ## 3.1 Elegance of the Solution
   
   **Precise fix**, with the scope caveat documented in 1.1: it targets the actual mechanism of the starvation (unfair monitor re-acquisition across poll boundaries) without changing the public `Collector#getCheckpointLock()` contract, and without resorting to a blanket sleep/backoff. It is not a long-term solution to "bound lock hold time within one very large poll" (that would require either finer-grained locking inside long-running connector loops or a fundamentally different backpressure signal), but it correctly and completely solves the problem it set out to solve — the cross-poll starvation.
   
   ## 3.2 Maintainability
   
   The new class is small, single-purpose, and its Javadoc explicitly documents the deadlock-safety invariant future maintainers need to preserve ("the caller must not hold the checkpoint lock" / "release in `finally`"). The two call sites are minimal and easy to audit against that invariant.
   
   ## 3.3 Extensibility
   
   If a future connector pattern needs finer-grained yielding (e.g. mid-batch, for the JDBC-style single-lock-per-split case discussed in 1.1), `SourceCheckpointLockHandoff` could be extended with a second call site inside such a loop without changing its public contract — the design doesn't foreclose that.
   
   ## 3.4 Historical-Version Compatibility
   
   No checkpoint/savepoint state, API, or config surface is touched; nothing to migrate across upgrades.
   
   # 4. Issue Summary
   
   | # | Issue | Location | Severity |
   |---|-------|----------|----------|
   | 1 | Scheduling-jitter exposure in `injectorAcquiresLockWithinOnePollCycle`'s sampling window (test-stability "Risk present") | `SourceCheckpointLockHandoffTest.java:106-108` | Medium |
   
   # 5. Merge Recommendation
   
   ### Conclusion: Ready to merge after fixes
   
   1. **Blockers — must be fixed**: None in the production code. I'm holding this to "ready after fixes" rather than a bare LGTM only because of Issue 1's test-stability classification (Section 5.10.2 requires a `Risk present` finding to be listed as non-blocking-but-should-be-addressed, and I'd rather tighten a new test's timing assumption before it has a chance to flake on a loaded CI runner than fix it reactively later).
   2. **Recommended fixes — non-blocking**: Issue 1 — widen the tolerance or increase `POLL_HOLD_MS` in `SourceCheckpointLockHandoffTest`.
   
   **Overall assessment**: The production fix is correct and precisely scoped to the race it targets (I traced both call sites against `awaitInjectors()`'s no-lock-held precondition and found no deadlock risk, and confirmed the `finally`-guarded release makes starvation-of-the-reader impossible even on a failed injection). I want to be explicit about the one scope limitation I found: for connectors that hold the checkpoint lock for an entire large `pollNext()` batch (JDBC being a concrete example I verified in this codebase), this fix bounds cross-poll starvation but does not shrink the lock-hold time of one very large poll — that's an accurate, not overstated, claim once you read "bounded by a single poll" precisely, but I'd have appreciated it being spelled out in the class Javadoc, and I'm noting it here for anyone using this PR as a reference for checkpoint-latency guarantees going forward. Net: correct, well-tested, compatible fix; one non-blocking test-hardening item (Issue 1
 ) I'd like addressed before or shortly after merge.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them [seatunnel]

Posted by "SEZ9 (via GitHub)" <gi...@apache.org>.
SEZ9 commented on PR #12316:
URL: https://github.com/apache/seatunnel/pull/12316#issuecomment-6308433149

   Thanks @davidzollo for the detailed verification and @nzw921rx for the LGTM.
   
   Before merging I'd like to close out the open points from the earlier review pass, since I don't see follow-up on them yet:
   
   1. **Timer flush path in `SourceFlowLifeCycle`** — the handoff currently wraps only `triggerBarrier`. The timer-driven `FlushSignal` still contends on the same unfair monitor without calling `injectorArriving`/`injectorFinished`, and the reader-side wait in `collect()` only yields to registered injectors, so a pending timer flush keeps its pre-existing unbounded starvation exposure and can pin the shared `timerFlushWorker` thread. Could you either route the timer flush through the same announce/withdraw pair, or explain why that contender is intentionally left out?
   
   2. **`injectorAcquiresLockWithinOnePollCycle`** — `completedPolls` is sampled before `injectorArriving()`, so the reader can start a fresh poll in that window and `pollsWaited <= 1` can fail under scheduling noise. Please sample after announcing (or widen the bound and document why).
   
   3. **`awaitInjectors` sleep loop** — the `Thread.sleep(1)` polling ties reader resumption to OS timer granularity rather than to `injectorFinished()`. A park/unpark-style wakeup would be preferable; if you'd rather keep the sleep for simplicity, a short comment on the trade-off is fine.
   
   4. **`SourceCheckpointLockHandoff` class javadoc** — "an injector never waits for the reader" is easy to misread as a latency guarantee; please clarify that it is a progress/non-blocking statement, and state explicitly whether the timer flush contender is covered by the handoff (ties back to item 1).
   
   On CI: run 36327199671 concluded `cancelled` again on the retry, so we still have no non-cancelled Build result for this head. Pushing the changes above should trigger a fresh workflow and give us a real result — please ping me when it's up.
   
   <!-- streview-comment:1927 -->


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Zeta] Hand the source checkpoint lock to barrier injectors instead of racing them [seatunnel]

Posted by "SEZ9 (via GitHub)" <gi...@apache.org>.
SEZ9 commented on PR #12316:
URL: https://github.com/apache/seatunnel/pull/12316#issuecomment-6459401910

   Thanks @davidzollo for the explanation of d6d2e8ab1007b1ce2ab67770d3fa5cab1d172084. I have not verified that diff myself, so I am treating the import-only description as stated intent for now; a pointer to the hunk would help me confirm it.
   
   Status of the earlier review points against this head:
   
   - **PR12316-F1 / F2 (timer FlushSignal path and reader-side wait):** the PR author's own self-assessment in this thread (explicitly not a self-approval, static reading only) describes `onTimerTick` as wrapping its `synchronized(checkpointLock)` body with `injectorArriving()` / `injectorFinished()` the same way `triggerBarrier` does, which would also make `awaitInjectors()` yield to a pending timer flush. If that is accurate at the current head, both findings are resolved. Since an import-only fix would not have changed this on its own, please confirm with a short pointer to the hunk so I can close them.
   - **PR12316-F3 (`injectorAcquiresLockWithinOnePollCycle`):** if the assertions are unchanged, the `completedPolls` sample is still taken before `injectorArriving()`. Please either move the sample after registration or make the bound tolerant of one extra poll; a scheduling-dependent `pollsWaited <= 1` is likely to flake eventually.
   - **PR12316-F4 (`Thread.sleep(1)` loop in `awaitInjectors`):** still non-blocking. If you prefer to keep the polling loop for simplicity, a one-line comment noting that resumption latency is bounded by timer granularity is sufficient.
   - **PR12316-F5 (class javadoc):** please reword "an injector never waits for the reader" so it reads as an ordering/cooperation guarantee rather than a latency guarantee, and add a sentence stating whether the timer flush contender is covered by the handoff.
   
   On CI, the latest follow-up on this thread reports the Build check on head d6d2e8ab1007 as completed and green; I have not checked it independently, so I am taking that at face value. Once F3 and F5 are addressed and F1/F2 are confirmed, I have no further concerns from my side.
   
   <!-- streview-comment:2085 -->


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org