Skip to content

[STIP-31][Feature][Zeta] Introduce engine-managed Source runtime - #11557

Draft
DanielLeens wants to merge 46 commits into
apache:devfrom
DanielLeens:davidzollo_source-managed-runtime-phase0
Draft

DanielLeens wants to merge 46 commits into
apache:devfrom
DanielLeens:davidzollo_source-managed-runtime-phase0

Conversation

@DanielLeens

@DanielLeens DanielLeens commented Jul 26, 2026 •

Copy link
Copy Markdown
Contributor

Purpose

Implement STIP-31 in one phase-gated Draft PR. This moves Source Reader and Split Enumerator concurrency ownership into Zeta while preserving the existing Source SPI and legacy connector behavior through an isolated compatibility lane.

The implementation is intentionally fail-closed and disabled by default. This PR remains Draft until its current head satisfies the recovery, compatibility, fault-injection, and performance gates below.

Implemented scope

  • Versioned managed Source capability, cooperative Reader polling, and coordinator scheduler APIs with backward-compatible SPI defaults.
  • Default-off runtime switch, protocol/capability validation, persisted lane selection, and legacy physical-plan restore compatibility.
  • Bounded Reader and coordinator owner loops with reserved control capacity, payload-byte limits, worker-wide memory accounting, and immediate Hazelcast operation admission.
  • Versioned command envelopes/codecs, explicit wire codes, checksums, sequencing, deduplication, attempt/epoch fencing, single-flight transport, deadlines, and bounded retry.
  • Checkpoint-aware split ownership from DISPATCHED through CHECKPOINT_INCLUDED, including chunked ownership proofs, restore reconciliation, rescale fencing, and no-more-splits generations.
  • Explicit Reader and coordinator checkpoint serializers with capability digest, connector state version, lifecycle state, and corruption validation.
  • Non-blocking coordinator async scheduler with bounded IO/CPU pools, fixed-delay execution, overlap/failure policies, cancellation, timeout, classloader restoration, and stale-result fencing.
  • Executable Reader lifecycle and schema-change state transitions, graceful-close latching, checkpoint callback ordering, watchdog wakeup, and terminal preemption.
  • Managed runtime metrics for admission, mailbox depth/age, command service time, checkpoint wait, ownership state, scheduler work, retries, and contention.
  • Connector-common managed Reader bridge and pilots for Fake, Kafka, and Iceberg. Iceberg intentionally adopts the coordinator runtime only; its Reader remains on the legacy lane.
  • English/Chinese operator documentation, configuration defaults, selector/mailbox/protocol/checkpoint/scheduler/assignment tests, and Kafka managed-discovery regression coverage.

Compatibility and performance contract

  • Connectors use the legacy lane while the runtime switch is disabled. When enabled, deployment rejects connectors without a compatible declared capability or with mismatched protocol or checkpoint metadata.
  • SourceReader.pollNext(...), Collector.getCheckpointLock(), and existing Enumerator methods remain source and binary compatible.
  • Lane selection and capability digest are persisted; restore never changes execution lane silently.
  • Managed operation threads validate, account, and admit commands only. They do not invoke connector callbacks or wait for command application.
  • Owner loops reuse task execution resources rather than creating one thread per Source task.
  • All managed queues and asynchronous work are bounded. Control capacity is reserved independently from data capacity.
  • Connector state and runtime protocol evolution use explicit serializers and stable wire codes rather than Java native serialization.

Local validation

The following modules passed both scoped spotless:apply and spotless:check at commit 25290c0:

  • seatunnel-api
  • seatunnel-engine-common
  • seatunnel-engine-server
  • connector-common
  • connector-fake
  • connector-kafka
  • connector-iceberg

Static validation also passed: clean staged diff, ASF headers on new files, no POM changes, no deleted files, no Java native payload serialization, and no new Java 9+ API usage in the changed runtime paths.

Per the repository workflow for this task, local compilation, unit tests, integration tests, E2E, Docker, and service startup were not run. Functional truth must come from GitHub CI at the current PR head.

Review follow-up

Item Current evidence Remaining gate
Managed reader location wire type ManagedSourceRegisterOperation.readInternal rejects decoded values that are not a TaskLocation. ManagedSourceRegisterOperationSerializationTest covers a valid payload round trip and a mismatched type. Reviewer confirmation and current-head CI remain open.

Draft graduation gates

  • Current-head GitHub CI is green.
  • Deterministic failover/fault-injection campaigns cover admission-before-apply, checkpoint cuts, coordinator/Reader restart, stale attempts, timeout, close, and rescale.
  • Managed connector conformance coverage passes while the legacy-lane regression suite remains unchanged.
  • Kafka, Iceberg, blocking-control, and high-split-count performance/soak results meet the STIP-31 budgets.
  • Maintainer review confirms the STIP contract and compatibility policy after the evidence above is attached.

Refs #11558

Related: #12747 (legacy wire-type validation for AssignSplitOperation#readInternal / TaskOperation#readInternal, out of scope here).

Maintenance update (2026-11-07)

Yes, contributing to Apache SeaTunnel.

Pushed 1f0ac9d495323a036a27bcca5320b547a9f9b0a0 by normal fast-forward push. Reconciled dev conflicts and initialized the SourceCheckpointLockHandoffTest service configuration required by the lifecycle constructor. Added real Iceberg capability-method coverage and fresh source-row plus checkpoint progress assertions after managed savepoint restore. Documented the watchdog wakeUp non-blocking contract. Issue 52 remains partial: coordinator retry bookkeeping (Issue 6), watchdog delivery race (10), close/fence publication (11), and managed read/idle accounting (26) still lack the requested focused runtime regression coverage.

Validation: affected-module Spotless and diff whitespace checks passed; an independent maintainer source review of these deltas completed. No local compile, unit, integration, E2E, Docker or service execution was performed under the repository validation policy. No engine UI change or existing runtime artifact was used. The current-head fork Build was queued at the post-push inspection; this update does not claim runtime correctness or merge readiness. This supersedes earlier verification statements for the previous head.

Existing connector registrations, configuration defaults, public contracts and prior test assertions were retained. Upstream-only POM changes in the approved conflict merges match dev exactly; no new dependency edits were made. Human review and any remaining explicit coverage/acceptance gaps are separate gates.

Current-head reviewer follow-up (November 14)

On 7fa315bac1d0fb30a3380f5b5eb8baebd1adb904, the managed registration RPC carries the reader's TaskLocation, attempt metadata, protocol version and checkpoint watermarks. Commit 5a0f93b37de validates the reader-location type at the Hazelcast decode boundary; the regression checks an exact round trip and rejection of the wrong registered type. Admission in ManagedSourceCoordinatorRuntime.admitRegistration enqueues applyRegistration and checks the attempt fence; the owner loop updates the reader registry. Connector split bytes from a restore report are handled separately by the owner-side restored-split handler. This source trace does not substitute for the reviewer confirming the original F1 concern. The focused retry, watchdog, close/fence and reader-handoff regressions and the performance evidence are still open.

@DanielLeens DanielLeens changed the title [Improve][Zeta] Add source runtime contention metrics [STIP-31][Feature][Zeta] Introduce engine-managed Source runtime Jul 26, 2026
DanielLeens

This comment was marked as outdated.

DanielLeens and others added 9 commits July 30, 2026 08:24
ManagedSourceReaderRuntime imported the MDC-aware engine wrapper, which
extends java.util.concurrent.CompletableFuture, and assigned the result of
ManagedSourceReader#isAvailable() to it. That is a downcast from the API
contract type and broke compilation of seatunnel-engine-server.

The runtime only observes the future returned by the connector, it never
creates one that needs MDC propagation, so the JDK type is the correct
declaration here.
…dicate

Follow-up to the managed Source runtime review. The blocking and medium
findings were already addressed; this covers the remaining cleanups.

- Remove the supportsVersionedSourceEvents builder knob. Now that a managed
  capability must declare usesSourceEvents explicitly and lane selection
  rejects connectors that use them, the flag could only ever be false and
  every caller that set it to true hit an IllegalArgumentException. Document
  the surviving usesSourceEvents contract in the builder and in the English
  and Chinese operator docs.
- Extract the duplicated "does this job checkpoint?" predicate from
  CoordinatorService and PhysicalPlanGenerator into JobCheckpointUtils, with
  a unit test. Plan generation stamps this answer into the managed Source
  lane selection where it drives assignment ledger retention, so the two
  copies drifting would change ownership semantics silently.
- Replace inline fully qualified names with imports in SourceFlowLifeCycle
  and TaskExecutionService.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The previous fix swapped the MDC-aware engine CompletableFuture wrapper for
java.util.concurrent.CompletableFuture to match the type returned by
ManagedSourceReader#isAvailable(). That resolved the compile error but broke
ImportClassCheckTest#javaUtilCompletableFutureCheck, which bans that import
under org.apache.seatunnel.engine.

CompletionStage is the supertype the returned future already satisfies and
declares whenComplete, so it fixes the compile error without the banned
import. The runtime only observes this future, it never creates one that
needs MDC propagation.
…rator state

Sharing getTopicInfo() between both lanes moved two side effects onto the
engine async worker that runs managed discovery.

- getTopicInfo() writes topicMappingTablePathMap, a plain HashMap owned by
  the coordinator event loop. Running it inside callAsync() made an async
  worker a second writer, which is exactly what the managed lane exists to
  prevent and what the runtime documentation promises against. Iceberg
  already follows the correct pattern: snapshot state on the owner thread,
  return a value, apply it in the completion callback.
- getTopicInfo() also resolves latest offsets for every known partition and
  builds splits that discoverManagedSplits() immediately discards, then
  resolves offsets again for the newly discovered subset. That added a
  redundant admin round trip on every discovery tick, scaling with total
  partition count rather than with newly discovered partitions.

Extract the shared topic and partition lookup into a side-effect-free
discoverTopicPartitions(). The legacy lane keeps publishing the mapping and
resolving offsets exactly as before; the managed lane consumes the returned
mapping and lets the coordinator event loop remain the only writer. Add a
regression test pinning the invariant.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

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?

This is a structured self-re-review. I am the author of this PR, so please read every conclusion here with that bias in mind — the final call must come from an independent, write-capable maintainer; my account only has read-level permission and an author cannot approve his own PR anyway. Since my previous self-review (head 25290c0), I pushed nine commits: the style/markdown gate fixes (0a74c598, b3cd9d42), two review-feedback rounds (7c01fb3b, 03479e8b), the JDK/CompletionStage availability fixes (fe53a08e, 3e1908a2), a dev sync (9c12badf), the capability-API tidy with the shared checkpoint predicate (f15d54a0), and the Kafka discovery side-effect isolation (646ce14b). This round re-reviews the ENTIRE current diff (origin/dev...646ce14b, 99 files, +14332/-96) from scratch, not just the increment. One important apology up front: Issue 3 below (the reader-failover vs. in-flight discovery race) already existed at the head I reviewed last time and I did not catch it. Sorry for missing this in the last review — that's on me. It is marked as a carryover, not a new-version issue.

  • User pain: legacy Source readers and enumerators interleave engine operation threads, connector callbacks, checkpoint locks, blocking discovery, and recovery ownership; a slow or blocking connector can stall engine control lanes, and ordering is hard to reason about.
  • Fix approach: instrument the legacy boundaries (Phase 0), then add a disabled-by-default, fail-closed engine-managed lane: versioned capabilities and lane selection frozen into the physical plan, bounded mailboxes with reserved control capacity, versioned/checksummed command envelopes with attempt and epoch fencing, cooperative budgeted polling, an epoch-fenced coordinator scheduler for blocking discovery, checkpoint-coupled assignment ownership, explicit state serializers, and Fake/Kafka/Iceberg pilots.
  • One-sentence summary: the protocol and isolation design is sound and default-safe, but the current head does not compile in connector-kafka, current-head CI produced no test verdict (the run was cancelled), and the core distributed state machine still has no executed test path — so this Draft is not merge-ready yet.

1. Code Change Review

1.1 Core Logic Analysis

The change is additive along four layers:

  1. SPI (seatunnel-api) — SeaTunnelSource.getManagedSourceCapability() defaults to ManagedSourceCapability.legacy(); ManagedSourceReader adds activateManagedRuntime()/pollNextManaged()/isAvailable()/wakeUp(); SourceSplitEnumerator.Context gains getCoordinatorScheduler()/isManagedCoordinatorRuntime()/isAssignmentCapacityAvailable() default methods. Existing connectors compile and behave unchanged.
  2. Selection (seatunnel-engine-common) — ManagedSourceRuntimeSelector.select(...) requires enabled=true AND an exact allowlist match AND a compatible declared capability AND protocol match AND usesSourceEvents=false; anything else is either legacy or a fail-closed deployment error. The selection (mode, protocol, state version, digest, checkpoint-enabled flag) is stamped into SourceConfig in the physical plan.
  3. Runtime (seatunnel-engine-server) — ManagedSourceReaderRuntime and ManagedSourceCoordinatorRuntime own all checkpoint-visible state on single owner threads; three new Hazelcast operations (ManagedSourceRegisterOperation, ManagedSourceCommandOperation, ManagedCoordinatorCommandOperation) perform bounded admission only and never run connector code; ManagedCoordinatorScheduler runs blocking discovery on worker-wide bounded IO/CPU pools with epoch fencing; SourceAssignmentTracker keeps split ownership from DISPATCHED to CHECKPOINT_INCLUDED with byte/entry caps and restore/rescale reconciliation.
  4. Pilots — FakeSource (full reader+coordinator), Kafka (reader+coordinator; discovery made side-effect free via DiscoveredTopicPartitions), Iceberg (coordinator only).

Key findings this round:

  • The Kafka discovery isolation commit (646ce14b) introduced a hard compile error: discoverManagedSplits declares two locals named discovered in the same scope (KafkaSourceSplitEnumerator.java:659 and :676). connector-kafka cannot compile at the current head. CI did not catch it because the current-head run was cancelled before any compile lane executed (Issue 1).
  • My previous Issue 1 (runtime metrics contaminated across attempts) is now resolved: SourceRuntimeMetrics/ManagedSourceRuntimeMetrics scope every counter with metricSuffix(sourceRuntimeId, executionId) and the deployment-unique executionId is threaded through TaskExecutionService.deployLocalTask(...) into TaskExecutionContext; SourceRuntimeMetricsTest.shouldKeepRuntimeMetricsAttemptLocalAfterRecovery and ManagedSourceRuntimeMetricsTest pin the behavior. However, the observability docs still describe a plain #{sourceId} suffix, which no longer matches (Issue 4).
  • Failover edge (carryover, Issue 3): SeaTunnelSplitEnumeratorContext.registeredReaders() is fed from taskMemberMapping, which applyRegistration updates before the replacement attempt finishes its epoch handshake; a discovery result that assigns to that subtask hits requireReadyReader (ManagedSourceCoordinatorRuntime.java:1480) and fails the whole source instead of deferring.
  • The availability path is now correct and shading-safe: the API keeps CompletableFuture while the engine only observes CompletionStage (ManagedSourceReaderRuntime.java:641-666), matching the ImportClassCheck constraint that caused earlier CI failures.
  • The single-flight, sequence-deduplicated transport with RETRY_LATER/STALE_TARGET/TERMINAL_REJECTED admission acks, retry deadline, and jittered exponential backoff is consistently applied on both directions, and outbound/inbound byte accounting is underflow-checked everywhere I traced.

Complete runtime path (managed reader + coordinator, the deepest new path):

1. PhysicalPlanGenerator.managedSourceSelection -> ManagedSourceRuntimeSelector.select [plan freeze]
   Lane, protocol, digest, checkpoint flag stamped into SourceConfig; fail-closed on any gate violation.
2. SourceSeaTunnelTask / SourceFlowLifeCycle.open -> ManagedSourceReaderRuntime.start [reader owner]
   activateManagedRuntime -> reader.open -> ManagedSourceRegisterOperation(executionId, attemptId, watermark).
3. SourceSplitEnumeratorTask.admitManagedReaderRegistration -> ManagedSourceCoordinatorRuntime.applyRegistration [coordinator owner]
   Execution-id fence -> mailbox creation -> READER_EPOCH_START (managed reader) or completeReaderRegistration (legacy reader).
4. Reader epoch apply -> staged RESTORED_SPLITS chunks before COMMAND_APPLIED(epoch) [restore ordering]
   completeManagedRegistrationsIfReady waits for ALL readers, reconciles orphaned assignments, replays tracker state.
5. Enumerator run/handleSplitRequest -> context.assignSplit -> dispatchSplits -> ASSIGN_SPLITS chunks [assignment]
   assignmentTracker.recordDispatched -> reader applySplits -> COMMAND_APPLIED -> markApplied.
6. CheckpointBarrier -> admitBarrier (reserved control) -> coordinator snapshot + BARRIER commands -> reader snapshot [checkpoint]
   Reader: snapshotState + ownership proof -> chunked READER_CHECKPOINT_REPORT -> ack only after all chunks admitted;
   Coordinator: markReaderCheckpointIncluded -> checkpointCompleted -> ledger compaction.
7. Failure/restore: ManagedReaderCheckpointStateSerializer.isManagedState gates both lanes bidirectionally;
   rescale keeps no-more-splits state only at unchanged parallelism, otherwise renegotiates via the enumerator.

Normal-path impact is nil unless the operator flips managed-source-runtime.enabled and allowlists a connector; the legacy branch is preserved at every call site I checked (SourceFlowLifeCycle, SourceSplitEnumeratorTask, AssignSplitOperation, RestoredSplitOperation, SeaTunnelSplitEnumeratorContext).

1.2 Compatibility Impact

Fully compatible. Defaults are enabled: false with an empty allowlist; all SPI additions are default methods or new interfaces; SourceConfig treats missing managed fields from an older serialized plan as LEGACY (pinned by SourceConfigTest); managed and legacy checkpoint state reject each other explicitly with magic-number checks instead of failing obscurely mid-restore; SplitFetcher/SplitFetcherManager changes keep the old public constructors and add only concrete methods, so third-party subclasses stay binary compatible. The intentional managed-vs-legacy checkpoint incompatibility is documented in both EN and ZH docs with a rollback procedure.

1.3 Performance / Side-Effect Analysis

  • Everything is bounded: reader/coordinator mailboxes (commands and bytes, with reserved control capacity), worker-wide ManagedSourceMemoryBudget shared by inbound, outbound, and chunk accumulators, assignment ledger entries/bytes, async pools with AbortPolicy queues, and checkpoint-history sets trimmed at 128.
  • The managed IO/CPU pools and coordinator timer are constructed unconditionally in TaskExecutionService, but ThreadPoolExecutor/ScheduledThreadPoolExecutor spawn threads lazily, so a cluster that never enables the feature pays effectively nothing; shutdown() now also stops all three.
  • SeaTunnelSourceCollector.collectAndGetSize reuses the existing row-size estimate for the poll byte budget, so no second serialization on the hot path.
  • Two small side effects worth tracking: (a) attempt-scoped metric names mean each recovery registers a fresh counter set in a retained metrics context, so heavy-failover jobs grow metric cardinality over time (Issue 6); (b) FakeSourceReader.isAvailable() always returns a completed future, so during its minSplitReadInterval gate the managed loop busy-polls at idle-wait-ms cadence (Issue 7). Neither affects the legacy lane.
  • The published production gate (throughput/CPU/heap/checkpoint-p99/soak budgets) is documented but not yet backed by attached results; that stays a Draft graduation gate.

1.4 Error Handling and Logging

Fail-closed behavior is consistent: protocol/digest mismatch, checksum failure, unknown wire codes, mailbox exhaustion of reserved capacity, retry-deadline expiry, poll cancellation timeout, and managed/legacy state cross-restore all surface as explicit failures with bounded, label-free messages (no split IDs or record contents in metric dimensions, no credentials in logs). Formal issues, severity-sorted:

Issue 1 — connector-kafka does not compile: duplicate local variable discovered

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceSplitEnumerator.java:659 and :676
  • Problem: discoverManagedSplits declares DiscoveredTopicPartitions discovered (line 659, added by 646ce14b) and later List<KafkaSourceSplit> discovered (line 676, pre-existing) in the same method scope — a hard javac error ("variable discovered is already defined").
  • Potential risk: the module fails to build; every unit-test and IT lane will go red the moment CI actually runs. Because the current-head CI run was cancelled before any compile lane executed and Spotless does not compile, this defect is currently invisible on the PR page.
  • Best improvement: rename the second local (e.g. List<KafkaSourceSplit> discoveredSplits) and re-push; also treat "static gates green" as insufficient before requesting review when the test matrix never ran.
  • Severity: High
  • Raised by another reviewer: No

Issue 2 — the core managed distributed state machine still has no executed test path (carryover from my previous round)

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceReaderRuntime.java:1-1669, ManagedSourceCoordinatorRuntime.java:1-1900
  • Problem: the new unit tests (scheduler, mailbox, tracker, codecs, checkpoint state, metrics, selector, config) are genuinely good, but none of them constructs a paired reader+coordinator runtime and drives registration -> epoch -> assignment -> barrier -> report -> complete/abort -> restore -> rescale -> cancellation end to end. The three Hazelcast operations, SourceFlowLifeCycle managed branches, SourceSplitEnumeratorTask managed branches, and the three pilots have zero executed coverage; there is no Zeta IT/E2E for an enabled managed lane.
  • Potential risk: helper tests can stay green while a sequencing regression hangs canary jobs, acknowledges checkpoints early, duplicates or loses splits, or leaks budget — exactly the failure classes this runtime exists to prevent. Issue 1 is a live demonstration that nothing currently executes this code.
  • Best improvement: deterministic paired-runtime state-machine tests with a controllable transport/scheduler (no real Hazelcast needed), then Zeta integration tests for FakeSource checkpoint/failover/rescale/full-mailbox, per the PR's own Draft graduation gates.
  • Severity: High
  • Raised by another reviewer: No (carried forward from my own previous review)

Issue 3 — reader failover racing in-flight discovery fails the source instead of deferring (carryover; I missed this last round — sorry, that's on me)

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceCoordinatorRuntime.java:1480-1487 (requireReadyReader), :695 (addTaskMemberMapping inside applyRegistration), seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/context/SeaTunnelSplitEnumeratorContext.java:70-79, SourceSplitEnumeratorTask.java:486-490
  • Problem: registeredReaders() reflects taskMemberMapping, which is populated when a (replacement) registration is applied — before the new attempt completes its epoch handshake and becomes ready. A connector callback that assigns splits in that window (e.g. a Kafka/Iceberg discovery result or timer landing between attempt replacement and epoch application) reaches requireReadyReader, which throws and fails the source.
  • Potential risk: today Zeta restarts the whole pipeline on task failure, so coordinator and readers usually re-register together and the window is narrow; but the runtime explicitly implements per-attempt replacement fences, so under any finer-grained recovery (or a slow re-registration) a routine reader failover plus a scheduled discovery tick can kill an otherwise healthy job. Fail-closed, so no state corruption — but availability suffers.
  • Best improvement: in dispatchSplits, defer/queue assignments targeted at a registered-but-not-ready attempt (the assignment tracker already knows how to replay), or exclude not-ready subtasks from registeredReaders() in the managed lane; add a paired-runtime test for "discovery result lands during attempt replacement".
  • Severity: Medium
  • Raised by another reviewer: No

Issue 4 — observability docs still describe the pre-fix metric naming

  • Location: docs/en/engines/zeta/realtime-observability.md:312, docs/zh/engines/zeta/realtime-observability.md:311, and the Monitoring section of docs/en(zh)/engines/zeta/managed-source-runtime.md:168-190; implementation at seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/flow/SourceRuntimeMetrics.java:158 and .../task/source/ManagedSourceRuntimeMetrics.java:320
  • Problem: both docs state the new metrics "use the same #{sourceId} suffix", but the implementation registers <Name>#<sourceId>#attempt-<executionId> (and admission counters add a #<STATUS> segment). The docs were written for the pre-7c01fb3b naming and were not updated when I fixed the attempt-locality issue.
  • Potential risk: dashboards and rollout stop-condition alerts built from the documented names match no series, which quietly disables the very monitoring the rollout procedure depends on.
  • Best improvement: document the full suffix (including the attempt segment and the admission/state suffixes) in both EN and ZH, with one concrete example series name.
  • Severity: Medium
  • Raised by another reviewer: No

Issue 5 — Phase-0 instrumentation is still tested at the recorder, not through the lifecycle (carryover, partially addressed)

  • Location: seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/task/flow/SourceRuntimeMetricsTest.java:1-154 vs. .../task/flow/SourceFlowLifeCycle.java:369-377,494-508,616-660,715-760
  • Problem: since last round the timers were correctly moved into try/finally blocks and attempt-locality is now tested, which resolves the sharpest part of my previous Issue 3. But the tests still call recordPoll/recordReaderCallback/recordCheckpoint* directly; nothing drives SourceFlowLifeCycle itself through poll success/error, split/no-more-splits callbacks, and barrier stages to prove the timers wrap the documented boundaries.
  • Potential risk: a future refactor can silently drop a finally or move a timer boundary without any test noticing, skewing the legacy baseline used for rollout acceptance.
  • Best improvement: a lifecycle-level test with a stub reader/collector asserting each counter increments across success and exception paths.
  • Severity: Medium
  • Raised by another reviewer: No (carried forward from my own previous review)

Issue 6 — per-attempt metric registration accumulates in a retained metrics context

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/flow/SourceRuntimeMetrics.java:158-161, .../task/source/ManagedSourceRuntimeMetrics.java:320-323
  • Problem: the attempt-scoped suffix (the fix for cross-attempt contamination) means every recovery registers a fresh counter set while prior-attempt counters remain registered in the reused context.
  • Potential risk: a job that flaps for days grows metric cardinality linearly with restart count, inflating scrape payloads.
  • Best improvement: drop or tombstone prior-attempt counters on re-registration, or document a retention expectation for metric consumers.
  • Severity: Low
  • Raised by another reviewer: No

Issue 7 — managed FakeSource busy-polls while interval-gated

  • Location: seatunnel-connectors-v2/connector-fake/src/main/java/org/apache/seatunnel/connectors/seatunnel/fake/source/FakeSourceReader.java:161-166 (isAvailable returns a completed future) with the minSplitReadInterval gate in pollNextManaged
  • Problem: NOTHING_AVAILABLE plus an always-completed availability future makes the reader loop poll every idle-wait-ms (10 ms default) until the interval elapses.
  • Potential risk: negligible CPU waste, but it undermines FakeSource's role as the reference implementation of the availability contract.
  • Best improvement: return an incomplete future completed by a scheduler tick, or document that interval-gated pilots may spin at idle-wait cadence.
  • Severity: Low
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

Title follows [STIP-31][Feature][Zeta]; all new files carry ASF headers; Code style (Spotless) is green at the current head after f15d54a0. Naming is consistent (admit* for operation-thread entry points, apply* for owner-thread execution), the operation-thread contract is documented on every admission adapter, and non-trivial methods carry explanatory javadoc — including the "why" comments on discoverTopicPartitions and JobCheckpointUtils that earlier feedback asked for. The engine-side CompletionStage-only observation with the API-side CompletableFuture is a clean resolution of the shade constraint. I found no missing-comment gaps worth a formal issue this round.

2.2 Test Coverage and Test Stability

Added this round on top of the previous suite: ManagedSourceRuntimeMetricsTest, the attempt-locality case in SourceRuntimeMetricsTest, selector fail-closed cases, JobCheckpointUtilsTest, ManagedSourceCheckpointStateTest additions (rescale reconciliation, chunked restore proofs, memory release), and two Kafka regression tests (managedTopicDiscoveryShouldNotMutateCoordinatorOwnedState, managedBoundedDiscoveryShouldPreserveMissingOffsetFallback).

Test stability rating: Stable. Every new test is deterministic: no Thread.sleep, no ports/hostnames, no containers, no wall-clock assertions, no shared static state, no order dependence; the scheduler test drives callbacks synchronously on one thread (ManagedCoordinatorSchedulerTest.java:15349-15361 uses injected mock timers rather than real delays); float compares are absent. The reflection-based Kafka tests (KafkaSourceSplitEnumeratorTest.java:213-231, 308-343) are brittle against renames but not flaky.

The problem is not stability but reach — see Issue 2: the 14k-line production slice's central state machine, all three operations, and all three pilots have no executed path, and Issue 1 proves even compilation is currently unverified.

2.3 Documentation Updates

EN and ZH are structurally aligned: managed-source-runtime.md (new, both languages, in docs/sidebars.js) covers gates, safety limits, checkpoint/rollback semantics, the component-scoped capability caveat for Iceberg, and the explicit usesSourceEvents policy; realtime-observability.md documents the Phase-0 metrics in both languages. Two gaps: the metric-suffix mismatch (Issue 4), and the config-key table is duplicated across both files with no single source of truth — acceptable, but it is the kind of table that drifts.

3. Architectural Soundness

3.1 Elegance of the Solution

Long-term solution. Single-owner event loops with bounded admission-only operation threads, epoch/attempt fencing, and checkpoint-coupled assignment ownership is the right target architecture for STIP-31, and the fail-closed lane selection makes it deployable without touching existing users. The weakness is not design but proof: the slice is very large for one PR, and its correctness argument currently rests on code reading rather than executed tests.

3.2 Maintainability

The runtime classes are big (1900/1669 lines) but internally well-layered, with accounting invariants aggressively checked (underflow throws rather than drifting). The duplicated outbound-window logic between reader and coordinator (reserveOutbound/releaseOutbound/single-flight/retry in both files) is a candidate for extraction — same protocol, two implementations to keep in sync. JobCheckpointUtils removing the duplicated checkpoint predicate is a good precedent.

3.3 Extensibility

Wire codes, payload versions, capability digests, and the explicit usesSourceEvents rejection leave clean room for protocol version 2 (event codec, finer-grained recovery). The component-scoped capability (Iceberg coordinator-only) shows the lane can be adopted incrementally per connector component.

3.4 Historical-Version Compatibility

Old physical plans deserialize to LEGACY (test-pinned); legacy checkpoints restore only into the legacy lane and managed checkpoints only into the same lane/digest, both enforced by magic-number checks with actionable errors; restored lane selection is persisted so cluster-config changes cannot silently switch a running job. Rescale semantics (drop partial no-more-splits state, keep only global end-of-input) are conservative and test-pinned.

4. Issue Summary

No. Issue Location Severity
1 connector-kafka compile error: duplicate local discovered KafkaSourceSplitEnumerator.java:659,676 High
2 Core managed state machine has no executed test path (carryover) ManagedSourceReaderRuntime.java / ManagedSourceCoordinatorRuntime.java High
3 Failover vs. in-flight discovery race fails the source (carryover, missed last round) ManagedSourceCoordinatorRuntime.java:1480, SeaTunnelSplitEnumeratorContext.java:70 Medium
4 Docs describe #{sourceId} metric suffix; code emits #<sourceId>#attempt-<executionId> realtime-observability.md:312 (en) / :311 (zh), SourceRuntimeMetrics.java:158 Medium
5 Phase-0 timers tested at recorder, not through SourceFlowLifeCycle (carryover, partially addressed) SourceRuntimeMetricsTest.java Medium
6 Per-attempt counters accumulate in retained metrics context SourceRuntimeMetrics.java:158, ManagedSourceRuntimeMetrics.java:320 Low
7 Managed FakeSource busy-polls during interval gate FakeSourceReader.java:161 Low

5. Merge Recommendation

Conclusion: Not recommended for merge

This PR is a Draft by design and must stay one. CI at the current head (646ce14b) gives no usable verdict: the required Build check on apache/seatunnel reports failure because the underlying build_main.yml run (fork Actions run 30832737880) was cancelled after roughly eleven hours — the six static jobs passed (Code style, License header, Dead links, changes, Sanity check results, Check Helm Chart Syntax), but all 69 build/unit-test/IT matrix lanes were cancelled at 2026-08-04T03:19:49Z before executing, most likely runner starvation on the fork. So the red check is not itself evidence of a code failure — but had the lanes run, they would have failed deterministically in the connector-kafka compile step because of Issue 1, so the diff genuinely cannot pass CI as pushed. For history: the 9c12badf run failed only at Run / Code style (fixed by f15d54a0; Code style is green at head), and the older broad failures on 7c01fb3b (unit-test on windows, engine-v2-it, engine-k8s-it, many connector ITs) predate the availability-future fixes that were made specifically in response. The branch is 0 commits behind dev and mergeable, so no dev sync is needed — what is needed is a compiling head and a completed Build run.

  1. Blockers — must be fixed

    1. Issue 1 (High): fix the duplicate discovered local in KafkaSourceSplitEnumerator.discoverManagedSplits, push, and get a fully executed, green Build run at the new head (re-run the workflow if the fork queue cancels it again).
    2. Issue 2 (High): land the deterministic paired-runtime state-machine tests and the Zeta failover/rescale/mailbox-saturation integration coverage promised in the Draft graduation gates before this leaves Draft.
  2. Recommended fixes — non-blocking

    1. Issue 3: defer assignments to registered-but-not-ready attempts instead of failing the source (and add the race test).
    2. Issue 4: update EN/ZH metric-suffix documentation to the attempt-scoped naming.
    3. Issue 5: add lifecycle-driven Phase-0 timer tests.
    4. Issues 6-7: bound per-attempt counter retention; make FakeSource's availability future honor its interval gate.

Overall: I remain convinced the architecture is the right long-term direction, and this round genuinely improved it — the attempt-metrics contract from my previous review is fixed and test-pinned, Kafka discovery is now side-effect free on worker threads, and the availability contract is shading-clean. But a head that does not compile, a cancelled CI run, and an untested core state machine are three independent reasons this cannot merge today. If the size keeps making review and CI painful, the fallback split remains Option A: land Phase-0 metrics + SPI + selection first, then the runtimes with their paired tests, then the pilots (better failure isolation, slower landing) versus Option B: keep the single phase-gated Draft and satisfy the gates in place (current choice — acceptable as long as the gates are actually enforced before graduation). Since I authored this PR, an independent committer needs to make the final call on that trade-off; from my side, with read-level permission only, this comment is review input, and a write-capable maintainer performs the final approval and merge after the blockers above are resolved.

…tracts

Addresses the two non-CI blockers from maintainer review: the managed lane
had no end-to-end coverage, and the contracts that govern it were undocumented.

E2E (seatunnel-engine-e2e):
- ManagedSourceRuntimeIT boots a cluster with managed-source-runtime enabled
  and only FakeSource allowlisted, then runs a bounded job through the managed
  Reader and coordinator loops, and savepoints and restores a streaming job.
  Restore is the highest risk path in the feature: it exercises managed Reader
  checkpoint state, the persisted lane selection, capability digest validation
  and coordinator ownership replay, none of which had any coverage.
- Both tests assert which lane was actually selected. Without that a silent
  fallback to the legacy lane would still pass, which would make the suite
  worse than no coverage.
- PhysicalPlanGenerator now logs the selected lane once per Source. Lane
  selection was previously unobservable, so neither a test nor an operator
  could tell which lane a job entered.

Contracts:
- CoordinatorScheduler#callAsync and its implementation now state the thread
  contract explicitly: the callable runs on a shared engine worker and must not
  touch enumerator state; only the result handler, on the coordinator event
  loop, may apply results. The class comment implied this, but the prohibition
  was not stated where it gets violated.
- SourceAssignmentTracker: documented the ownership transitions that decide
  whether a split is replayed after failover, including why release happens at
  checkpoint completion rather than earlier or later.
- ReaderCommandMailbox: documented the at-least-once deduplication and
  contiguous-sequence rules, the reserved control band, epoch rebasing, and why
  close returns memory to the worker budget.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@github-actions github-actions Bot added the e2e label Aug 4, 2026
danielnadean and others added 2 commits August 4, 2026 06:40
Fixes a compile error I introduced in the prior discoverTopicPartitions()
refactor (646ce14): discoverManagedSplits() declared a second local
named `discovered` for the accumulated split list, shadowing the
DiscoveredTopicPartitions `discovered` already in scope from
discoverTopicPartitions(). javac rejected the redeclaration and then
cascaded into "cannot find symbol" and a type-mismatch on the two
downstream uses.

This broke compilation for every CI job that builds connector-kafka,
which is most of them; the Windows unit-test and Dependency-licenses
failures on this PR are the same root cause, not independent bugs.

Renames the split accumulator to discoveredSplits so the two locals no
longer collide. I could not compile this locally per the SeaTunnel
verification policy for this task, so I confirmed the fix by re-reading
the exact three compiler-reported lines against the corrected types and
by scanning the rest of the file for the same shadowing pattern; GitHub
CI on this head is the actual proof.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…and two test-fixture NPEs

Root-caused via the ManagedSourceRuntimeIT E2E added earlier: every managed-lane
job crashed on its first tick with "Managed Source coordinator state accessed
outside its event loop" and retried forever until the CLI gave up.

- ManagedSourceCoordinatorRuntime.setEnumerator()/restoreRuntimeState() called
  checkOwner(), binding ownership to whichever thread called them first. Both
  are invoked exactly once, synchronously, from
  SourceSplitEnumeratorTask.restoreState() — which NotifyTaskRestoreOperation
  always runs on a Hazelcast operation thread, never the task's own execution
  thread (confirmed via BlockingWorker.run(), which owns init()/call() on one
  dedicated thread for the task's life). So the very first tick of
  runOneTurn(), on the task's real thread, always found a mismatched owner and
  threw. restoreState() only completes restoreComplete after both calls
  return, and runOneTurn() never runs before restoreComplete.isDone(), so the
  CompletableFuture already provides the happens-before guarantee checkOwner()
  was trying to enforce; the thread-identity check was redundant here and
  actively wrong. ManagedSourceReaderRuntime's equivalent restoreMetadata()
  never called checkOwner(), which is why only the coordinator side broke.

  This is a targeted fix for the confirmed, reproduced failure under the
  engine's default thread-share mode (dedicated thread per task). I have not
  independently verified the remaining checkOwner() call sites are safe under
  ThreadShareMode.ALL/PART, where SeaTunnel Zeta's cooperative scheduler can
  migrate a task across worker threads between ticks; no test in this PR
  exercises that configuration.

- JobCheckpointUtils.isCheckpointEnabled(JobConfig) dereferenced
  getJobContext() unguarded, inherited unchanged from the pre-extraction code.
  This predicate now runs unconditionally during physical plan generation for
  every job, and 45+ engine test fixtures construct a bare JobConfig without
  ever calling setJobContext(...). Treat a missing JobContext the same as a
  missing JobConfig (assume checkpoints enabled) instead of throwing; fixes
  CheckpointPlanTest and TaskTest.

- ReaderCommandMailboxTest's fixture set readerReservedControlCommands=1
  against the default coordinatorAsyncMaxConcurrency=4, violating a validation
  invariant added by an earlier review-feedback commit. Pinned concurrency to
  1 to match the fixture's intent.

- SourceSplitEnumeratorTaskTest's four mocked TaskExecutionService instances
  never stubbed getSeaTunnelConfig(), which SourceSplitEnumeratorTask.init()
  now dereferences unconditionally to resolve the legacy-vs-managed lane.
  Added one shared helper stubbing a real, default-constructed EngineConfig.

Unrelated CI failure also observed on this head: all-connectors-it-1 failed
on a Maven Wrapper download hitting repo.maven.apache.org's rate limit (HTTP
429), an infrastructure flake with no connection to this PR's diff.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

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?

Today, ownership of Source concurrency in Zeta is fragmented across the connector and the engine: the collector loop calls the reader's poll method under a connector-owned checkpoint lock, split assignment and source events travel through Hazelcast operation threads that can end up running connector code, and enumerator discovery is whatever the connector author decided to do (background threads, blocking calls, ad hoc locks). This has produced real production failure classes: checkpoint-lock stalls, ambiguous split ownership during failover, and operation threads blocked by slow connector code. This STIP proposes fixing this by making the engine the single owner of all checkpoint-visible Source state, instead of asking every connector author to get concurrency right independently.

This PR implements that as an opt-in, disabled-by-default "managed" execution lane that lives alongside the existing ("legacy") lane. A connector only leaves the legacy lane if an operator explicitly allowlists it and the connector declares a matching versioned capability; otherwise every job keeps running exactly as it does today. Three pilots are wired up: the fake-source connector and Kafka get full reader-plus-coordinator managed support, Iceberg gets coordinator-only support with its reader staying legacy.

This is a Draft PR by design — the author's own description lists explicit "Draft graduation gates" (green CI, failover/fault-injection coverage, pilot conformance, performance budgets, maintainer sign-off) that must be satisfied before it leaves Draft. This review re-evaluates the current head, three commits ahead of the last self-review round.

1. Code Change Review

1.1 Core Logic Analysis

Scope and depth of this review. Given the size (104 files, +14,898/-96), I did not read every file at equal depth. I read completely: the managed coordinator runtime class (~1920 lines), the managed coordinator scheduler, the split-assignment tracker, the managed coordinator checkpoint state and its serializer, the managed source lifecycle/state classes, the managed reader runtime class (~1669 lines), the reader command mailbox, the source command codec and envelope, the managed reader checkpoint state and serializer, the small reader support classes, the seatunnel-api managed-source contract (capability, reader interface, poll context/status), the source flow lifecycle class (~891 lines), the split-enumerator task class (~633 lines), the source task class, the source config class, the split-enumerator context class, the assign-split and restored-split operations, the three new Hazelcast admission operations, the full selection/config layer (selector, selection, mode, runtime config), and the Fake/Kafka/Iceberg pilot diffs. I read the task-execution service, the base task class, the physical-plan generator, the source collector, and the YAML config processor via their diffs plus targeted full-context reads, not end-to-end. I did not independently read the command-kind/durability enum classes, the assignment-state class, the split-ID chunk accumulator, or the data-serializer hook class, and I did not read the full pre-existing bulk of the Kafka split enumerator or the abstract split enumerator outside the diffed regions. Tests were reviewed for structure and flakiness risk, not for full assertion-by-assertion correctness of every case.

What actually changed, top to bottom.

  1. SPI (seatunnel-api) — a new default method on the source interface returns a legacy capability by default; a new managed-reader interface adds activation/poll/availability/wake-up methods; the split-enumerator context interface gains default methods for the coordinator scheduler and assignment-capacity checks. Every existing connector compiles and behaves unchanged.
  2. Selection (seatunnel-engine-common) — the runtime selector enforces, in order: config validity, cluster-wide enabled flag, exact allowlist membership, a non-legacy declared capability, protocol-version match, a "no source events" requirement, and a coordinator/async-enumerator consistency check. Any gate failure after the connector is allowlisted throws at job-submission time; disabled or not-allowlisted both resolve silently to legacy — never to a managed mode. The result is frozen into the source config once per source action in the physical-plan generator and persisted with the physical plan.
  3. Runtime (seatunnel-engine-server) — the managed reader and coordinator runtimes each run a single-owner event loop guarded by a lazily-bound owner check. Three Hazelcast operations perform bounded admission only — validate, checksum, size-check, and enqueue — and never touch connector state or block. The coordinator scheduler offloads blocking discovery to worker-wide bounded pools and re-applies results on the owner loop with epoch fencing. The assignment tracker is the split-ownership ledger, tracking dispatched, admitted, applied, and checkpoint-included states.
  4. Pilots — the fake-source connector (full), Kafka (full, with its blocking discovery refactored into a side-effect-free helper reused by both lanes), Iceberg (coordinator-only, reader untouched).

Independently verified: is this really opt-in with no silent misconfiguration? Yes. A connector that does not override the capability method inherits a legacy capability, and the selector's own code throws an exception the moment such a connector is allowlisted — it does not fall back to legacy silently, and it never enters the managed lane. This is pinned by a dedicated test. This directly answers a community reviewer's comment worrying that exposing a connector allowlist lets operators "weaken this semantics" by configuring unsupported connectors. The code shows the allowlist is a necessary but not sufficient gate — the capability declaration is a second, independently-enforced, code-level gate a connector author must deliberately implement, and misconfiguring the allowlist alone can only ever produce a hard, explicit, deployment-time failure, never a silent unsafe activation. I consider this concern resolved by evidence, not by assertion.

Runtime flow trace — legacy vs. managed, through the same classes:

Old/legacy model (unchanged, still the default path today): the physical-plan generator builds the split-enumerator task and source config for every source; the task-execution service starts the task threads; the split-enumerator task's restore method deserializes checkpoint bytes via the connector's own serializer, and the enumerator's open/run methods drive discovery and assignment directly, on whatever thread the connector chooses; the source flow lifecycle's open method calls the reader's open then registers, and its collect method calls the reader's poll under the connector's own checkpoint lock; barrier triggering calls the reader's snapshot method then a synchronous acknowledge operation join before forwarding the barrier downstream; on restart, the restore method replays the connector's own serialized state with no engine-owned split-ownership ledger to reconcile against.

New/managed lane (same classes, new branch, opt-in only): the physical-plan generator's managed-source-selection step freezes mode/protocol/digest/checkpoint-flag into the source config, failing closed on any gate violation; the source task/flow-lifecycle open path activates the managed reader runtime, which opens the reader then admits registration on a Hazelcast op thread with no connector code running there; the split-enumerator task's admission method hands off to the coordinator runtime's apply-registration method on the coordinator owner thread, which does an execution-id fence, mailbox creation, and an epoch handshake (or legacy completion); the enumerator's run/handle-split-request path assigns splits, which get chunked, recorded as dispatched, applied by the reader, and marked applied; a checkpoint barrier is admitted with reserved control capacity, the coordinator snapshots and issues barrier commands, the reader snapshots and reports its checkpoint in chunks, and only once the coordinator marks the reader's checkpoint included does the barrier forward downstream; on failure/restore, the checkpoint-state serializer gates both lanes bidirectionally with a magic-number check, and rescale keeps only global end-of-input, discarding partial per-subtask no-more-splits state.

The lane is decided exactly once and memoized in the physical-plan generator, so a running job can never flip lanes mid-flight even under a cluster config reload — a genuinely careful piece of design.

Correctness issue confirmed real, not resolved since the last review round. A "require ready reader" check in the coordinator runtime throws for any subtask whose registration is still not marked ready. But the apply-registration method populates the readers map and calls a task-member-mapping method — which is exactly what feeds the split-enumerator task's registered-readers accessor and, through it, the split-enumerator context's registered-readers method — before the epoch handshake has run and set ready to true. A connector callback that assigns splits to that subtask in this window (a discovery tick landing between attempt replacement and epoch completion) reaches the dispatch-splits path and throws, failing the whole source instead of deferring the assignment. I additionally found this window reopens through a second path not in the original description: a stale-target transport-result handler flips ready back to false on an already-registered, already-visible reader whenever a nack indicates an attempt mismatch, without going through apply-registration at all. Today Zeta typically restarts the whole pipeline on task failure, narrowing the exposure window, but the runtime explicitly implements finer-grained per-attempt fencing — so this is a real gap between the implemented failure-isolation ambition and the current behavior, not a theoretical one.

1.2 Compatibility Impact

Fully compatible for every connector that does not opt in — confirmed independently, not just asserted. Defaults are disabled with an empty allowlist; all SPI additions are default methods or brand-new interfaces; the source config's runtime-mode accessor explicitly treats a missing/null field from an older serialized plan as legacy (test-pinned); the base task class's checkpoint-acknowledge wait defaults to true so every existing subclass keeps the exact synchronous checkpoint-ack contract unless it explicitly overrides the method (only the source task does, gated on not being a managed-reader runtime); managed and legacy checkpoint state reject each other explicitly via magic-number checks rather than failing obscurely mid-restore. Tracing through the source flow lifecycle, split-enumerator task, task-execution service, base task class, physical-plan generator, split-enumerator context, and source collector, every legacy branch is either byte-identical logic or pure try/finally metrics instrumentation that doesn't change control or exception flow.

Two things worth confirming, not confirmed defects: the split-serializer accessor changed from unconditionally blocking on the enumerator getter (which waits on restore-complete) to only blocking if the serializer is still null. This removes an implicit synchronization wait for every legacy call, not just managed ones. The one caller I traced still ends up blocking via a subsequent enumerator-getter call, so ordering is preserved for that path — but the change is unconditional and any other caller relying on the old blocking contract wasn't specifically audited by this review. Separately, the selector calls the runtime config's validate method unconditionally, before checking whether the feature is enabled — see Issue 10 below.

1.3 Performance / Side-Effect Analysis

Everything checkpoint-visible is bounded: reader/coordinator mailboxes (commands and bytes, with reserved control capacity), a worker-wide shared memory budget across inbound/outbound/chunk accumulators, assignment-ledger entry/byte caps, and async pools with an abort-on-saturation policy. The task-execution service unconditionally constructs the managed IO/CPU pools and the coordinator timer on every worker, but thread pools don't pre-spawn core threads, and the selector fails closed when disabled, so no thread is ever actually created on a cluster that hasn't opted in — the real cost when disabled is a handful of small object/queue allocations, negligible. The source collector reuses the existing row-size estimate for the poll byte budget, avoiding a second serialization on the hot path. Accounting correctness is fail-closed by construction: I traced the release/underflow-check logic in both the coordinator and the mailbox/tracker equivalents in the reader, and every one throws on underflow rather than silently drifting negative — with one confirmed exception (Issue 2 below). The published production gate (throughput/CPU/heap/checkpoint-p99/soak budgets in the docs) is well-specified but has no attached results yet; that remains an open Draft graduation gate by the PR's own admission.

1.4 Error Handling and Logging

Fail-closed behavior is consistent at the protocol layer: version mismatch, checksum failure, unknown wire codes, mailbox exhaustion of reserved capacity, retry-deadline expiry, and cross-lane checkpoint restore all surface as explicit, bounded, label-free failures (no split IDs, table names, or record contents in metric dimensions or logs). The wire codec bounds every declared length against available input before allocating, so a corrupted-but-checksum-valid payload cannot cause unbounded allocation, only a bounded, small over-allocation before a clean end-of-file exception. Formal issues follow, in descending severity:

Issue 1: Reader failover racing in-flight discovery/assignment fails the source instead of deferring (carryover, still open at current head)

  • Location: the coordinator runtime's require-ready-reader check; the apply-registration method (specifically where it populates the readers map and task-member mapping); the stale-target transport-result handler that reopens the same window.
  • Problem description: the registered-readers accessor becomes non-empty as soon as apply-registration records the task-member mapping, before the epoch handshake completes and ready flips true. A discovery/assignment callback landing in that window throws, failing the source task rather than deferring the assignment until the attempt is ready.
  • Potential risk: the assignment tracker already knows how to replay deferred assignments, so this is an availability bug, not a correctness/data-loss bug (fails closed). But it directly undermines the finer-grained per-attempt fencing this runtime was built to provide, and a routine reader restart racing a scheduled discovery tick can kill an otherwise healthy managed job.
  • Best improvement: defer/queue assignments targeted at a registered-but-not-ready attempt instead of throwing, or exclude not-ready subtasks from the registered-readers accessor in the managed lane; add a paired-runtime test for "discovery result lands during attempt replacement."
  • Severity: High
  • Raised by another reviewer: Yes (the author's own self-reviews; confirmed and its stale-target variant independently identified in this review)

Issue 2: Transport-retry tracking maps leak one entry per replaced in-flight command on reader failover/rescale

  • Location: the coordinator runtime's retry-tracking fields; the release-all-outbound method, which clears outbound byte accounting but not these two maps; the only existing cleanup paths (accepted/duplicate ack, stale-target ack, retry-deadline expiry, full close).
  • Problem description: when apply-registration replaces an existing reader while a command is still in flight, the release-all-outbound call clears pending-command state but never removes that command's entry from the retry-tracking maps. The pending retry timer later fires, finds the attempt ID no longer matches, and no-ops — leaving the entry orphaned.
  • Potential risk: unbounded growth across the life of a long-running streaming job with repeated reader restarts — exactly the 24-hour soak scenario the PR's own production gate is designed to catch.
  • Best improvement: remove the corresponding entries from both maps inside release-all-outbound, keyed by the old attempt's command IDs.
  • Severity: Medium
  • Raised by another reviewer: No

Issue 3: Core managed distributed state machine still has materially incomplete executed test coverage, despite new E2E this round

  • Location: the new managed-source-runtime E2E test (155 lines) versus the 1600-1900-line reader/coordinator runtime classes it would need to exercise.
  • Problem description: the new E2E test is real progress — it covers a batch job completing on the managed lane and a streaming job's savepoint/restore round-trip — but it covers only the happy path on one pilot. It does not cover reader/coordinator task failure and re-registration (which is exactly where Issue 1 lives), rescale, mailbox/assignment-ledger saturation and back-pressure, cancellation, or the Kafka/Iceberg pilots under the managed lane.
  • Potential risk: helper-level unit tests (codecs, mailbox, tracker, scheduler, checkpoint state) can stay green while a sequencing regression in the parts that are not exercised end-to-end hangs a job, acknowledges a checkpoint early, or duplicates/loses a split — exactly the failure classes this runtime exists to prevent.
  • Best improvement: add the failover/rescale/mailbox-saturation E2E scenarios named in the PR's own Draft graduation gates before requesting the PR leave Draft, and add coverage for the Kafka/Iceberg pilots specifically since their concurrency decomposition has not been executed under load.
  • Severity: High
  • Raised by another reviewer: Yes (carryover; partially addressed this round, not resolved)

Issue 4: Observability docs describe the pre-fix metric suffix; implementation has moved on and docs were not updated

  • Location: the realtime-observability docs (English and Chinese, unchanged in the last three commits); the source-runtime-metrics class's suffix implementation.
  • Problem description: both docs still state new metrics "use the same source-id suffix," but the code emits an attempt-scoped suffix. I confirmed this by reading both the current doc text and the current suffix implementation directly.
  • Potential risk: dashboards and rollout stop-condition alerts built from the documented series names match nothing, quietly disabling the monitoring the rollout procedure explicitly depends on.
  • Best improvement: document the full suffix, including the attempt segment and any admission/state suffixes, with one concrete example series name.
  • Severity: Medium
  • Raised by another reviewer: Yes (carryover, unresolved — the doc file was not touched in the latest 3 commits)

Issue 5: No watchdog covers a stuck availability-check future outside an active poll

  • Location: the reader runtime's active-poll watchdog (gated only during an in-flight poll) and its availability-subscription method (no timeout).
  • Problem description: once a poll returns "nothing available," the loop waits on the reader's availability future with no timeout and no watchdog wake. A connector whose returned future never completes (a contract violation nothing enforces) silently starves new-data delivery for that reader with no alarm — the pipeline just looks idle.
  • Potential risk: a connector-side availability bug becomes a silent stall rather than a diagnosable failure, undermining the "stop the rollout when X" monitoring story the design doc lays out.
  • Best improvement: apply the same poll-watchdog budget/timeout to the availability wait, or emit a distinct "availability stalled" metric/log after a bounded threshold.
  • Severity: Medium
  • Raised by another reviewer: No

Issue 6: A reader command mailbox's epoch-reset method is dead, untested code for a scenario the current wiring never triggers

  • Location: the mailbox class's reset-for-epoch method; the reader runtime, which always constructs the mailbox with a hardcoded initial sequence.
  • Problem description: the method exists specifically, per its own documentation, to rebase sequencing when "a new coordinator restarts its channel numbering," but is never called anywhere in the repository; epoch changes are instead handled by fully failing and reconstructing the reader task.
  • Potential risk: currently benign given the reconstruct-on-epoch-change design, but it is a latent trap — if any future code path expects in-place epoch continuation for a long-lived reader, this untested rebasing path will be the first thing exercised, with no test coverage.
  • Best improvement: either remove the method until it has a real caller, or add a test that exercises the in-place rebasing scenario it claims to support.
  • Severity: Low
  • Raised by another reviewer: No

Issue 7: A signal/await-signal pair's documentation claims an immediate wake path that does not exist in the current wiring

  • Location: the mailbox's await-signal method (never called); the reader runtime's asynchronous-failure reporting, which does call signal; the actual owner loop, driven by a fixed idle-wait sleep.
  • Problem description: the mailbox's wait/notify pair is unused; the real bound on failure-observation latency is the idle-wait interval (default 10ms), not the immediate wake the signal method's documentation describes.
  • Potential risk: negligible (worst case ~10ms extra latency), but the dead API plus a doc claim that no longer matches behavior will mislead the next person who reads it.
  • Best improvement: either wire the owner loop through the await-signal method or delete the unused signal path and correct the documentation.
  • Severity: Low
  • Raised by another reviewer: No

Issue 8: Per-attempt metric registration accumulates in a retained metrics context (carryover, unresolved)

  • Location: the source-runtime-metrics and managed-source-runtime-metrics classes.
  • Problem description: the attempt-scoped suffix that correctly fixed cross-attempt metric contamination means every recovery registers a fresh counter set while prior-attempt counters remain registered in the reused context.
  • Potential risk: a job that fails over repeatedly over a long lifetime grows metric cardinality linearly with restart count.
  • Best improvement: tombstone or drop prior-attempt counters on re-registration, or document a retention expectation.
  • Severity: Low
  • Raised by another reviewer: Yes (carryover, unresolved — file not touched in latest 3 commits)

Issue 9: Managed fake-source connector busy-polls during its interval gate (carryover, unresolved)

  • Location: the fake-source reader's availability check, which always returns a completed future.
  • Problem description: combined with the minimum-split-read-interval gate, the managed loop polls every idle-wait tick (10ms default) instead of genuinely waiting.
  • Potential risk: negligible CPU waste, but undermines the fake-source connector's role as the reference implementation of the availability contract that pilots and future connectors will copy.
  • Best improvement: return an incomplete future completed by a scheduler tick.
  • Severity: Low
  • Raised by another reviewer: Yes (carryover, unresolved — file not touched in latest 3 commits)

Issue 10: Managed-source-runtime config validation runs unconditionally at plan-generation time, even when the feature is disabled

  • Location: the runtime selector's validate call, executed before the enabled check.
  • Problem description: a malformed but unused managed-source-runtime config block (e.g. an inconsistent threshold) now aborts physical-plan generation for every job with a source, even on a cluster that never intends to use the feature.
  • Potential risk: low probability (only triggers if an operator partially configures the block while leaving it disabled), but it is a genuinely new way for an unrelated, unused config section to break otherwise-legacy job submission after upgrading.
  • Best improvement: skip validation (or downgrade it to a warning) when the feature is disabled and the allowlist is empty.
  • Severity: Low
  • Raised by another reviewer: No

Issue 11: Current-head CI does not give a clean verdict, and the two IT lanes most relevant to this feature did not execute

  • Location: the fork's Build run that the apache-side status check points to.
  • Problem description: the prior review round's connector-kafka compile error is confirmed fixed (verified directly — a duplicate local variable was renamed, and every connector-kafka-dependent IT job in this run passed). However, a Windows unit-test job failed on a real (non-cancelled) test error in a sink-side multi-table-writer test this PR's diff does not touch — this looks like a pre-existing issue rather than a regression, though I did not independently confirm it also fails on dev, so treat that as an inference, not a verified fact. That failure cascaded into unit-test being cancelled on the other three matrix cells and, more importantly, the engine integration-test job and one connector-IT shard being cancelled on both JDK 8 and 11 before they ran at all.
  • Potential risk: whatever the root cause, this means the IT lanes most likely to exercise the new engine code have not executed to completion at the current head — CI cannot currently vouch for this PR the way a green run would.
  • Best improvement: re-run the cancelled/failed jobs (job-level rerun, not a full workflow rerun) and get a completed, green engine-IT result at this head before requesting maintainer review.
  • Severity: Medium (procedural, not a code defect in this diff)
  • Raised by another reviewer: No

2. Code Quality Assessment

2.1 Coding Standards

New files carry ASF headers. Naming is consistent and self-documenting (admit-prefixed for operation-thread entry points, apply-prefixed for owner-thread execution), and the operation-thread contract is documented on every admission adapter I read. The latest commit adds genuinely good documentation explaining why thread-ownership checks were deliberately removed from the setter/restore-path methods on the coordinator runtime — this is exactly the "explains constraint and risk of omission" style of comment this codebase should have, and it correctly fixes a real bug: calling the restore method (which runs on a Hazelcast operation thread, never the task's own thread, per this repository's established Zeta task-thread model) through a naive same-thread-forever ownership check would have poisoned the runtime on the very next legitimate owner-thread call. I found no missing-comment gaps worth a formal issue in the files I read in full.

2.2 Test Coverage and Test Stability

New/modified unit tests this round (covering the coordinator scheduler, the assignment tracker, the command mailbox, the command codec, checkpoint state, runtime metrics, source runtime metrics, checkpoint-util helpers, source config, the runtime selector, the runtime config, and the split-enumerator task) are deterministic and well-isolated — I grepped every changed test file for hard sleeps, real socket/port usage, wall-clock assertions, and randomness, and found none in the newly added or newly modified test methods. Mandatory flaky-pattern check, rating: Stable. One caveat: the split-enumerator task test file does contain a pre-existing hard sleep in an unrelated test method, but I confirmed this predates this PR and this PR's only change to that file is adding a config-accessor mock stub needed because the task's init method now unconditionally reads the managed-source-runtime config — this PR did not introduce or modify that sleep.

Coverage reach, not stability, is the real gap, as covered in Issue 3: the helper-level tests are genuinely thorough for the pieces they touch, but the 1600-1900-line coordinator and reader owner-loop classes, all three Hazelcast operations, and two of the three pilots have no paired-runtime, failover, rescale, or saturation test executing them end to end. The new managed-source-runtime E2E closes part of that gap (batch completion + streaming savepoint/restore on the fake-source connector) but not the failure-path and multi-pilot part.

2.3 Documentation Updates

Yes, this is a user-visible architecture change and a dedicated managed-source-runtime doc (new, 221 lines) plus its Chinese counterpart do exist, and they are substantive — covering the runtime model, the four-gate rollout contract, the full safety-configuration table, checkpoint/recovery semantics, monitoring, a quantified production gate, and rollout/rollback procedure with an explicit "do not restore a managed checkpoint into the legacy lane" warning. This is a well-written operational document, not a placeholder. The one confirmed gap is Issue 4: the companion observability doc was not updated to match the attempt-scoped metric-suffix implementation, so an operator following the monitoring section literally would build alerts against series names that do not exist.

3. Architectural Soundness

3.1 Elegance of the Solution

The core idea — single-owner event loops with bounded, admission-only operation threads, epoch/attempt fencing, and checkpoint-coupled assignment ownership held in an engine ledger until proven durable — is the right target architecture for the problem this STIP describes, and it is implemented with real discipline: owner-check assertions turn accidental cross-thread state mutation into an immediate loud failure rather than a silent race, in every file I read in full. The fail-closed opt-in lane-selection design means this can genuinely ship without touching a single existing user. The weakness is not the design but the proof: a 14,898-line slice landing as one review unit necessarily rests more on code reading than on executed evidence, and Issue 1's confirmed-but-still-open race is a concrete instance of exactly the class of bug that only paired-runtime/failover tests reliably catch.

3.2 Maintainability

The runtime classes are large (1900/1669 lines) but internally well-layered, with aggressively-checked accounting invariants (underflow throws rather than silently drifting) — I found only one leak (Issue 2) across everything I traced. The mirrored outbound-window/retry/single-flight logic that exists separately in both the reader and coordinator runtime is a duplication risk worth flagging for a future cleanup pass: same protocol, two hand-maintained implementations to keep in sync. The Kafka and Iceberg pilots avoid the classic "bolt legacy and managed paths together and hope" trap by construction rather than by locking: in managed mode, the open/run methods return before the legacy background-thread/blocking-loop code is ever entered, so the legacy and managed state-mutation paths are mutually exclusive because one of them literally never starts, not because of a shared lock. That is a genuinely clean way to integrate a new lane into existing connector code without introducing a subtle interleaving bug, and it held up under my thread-safety review of both pilots.

3.3 Extensibility

Explicit wire codes, payload versions, and capability digests leave clean room for a future protocol version (an event codec, finer-grained recovery). The component-scoped capability model — Iceberg adopting coordinator-only support while its reader stays legacy — demonstrates the lane can be adopted incrementally per connector component rather than all-or-nothing, which will matter for the "one connector, one workload class at a time" rollout the docs prescribe.

3.4 Historical-Version Compatibility

This is the most load-bearing section given the scope of this change, and it holds up under independent tracing, not just the PR description's assertion. Old physical plans deserialize their missing managed-runtime fields as legacy (test-pinned). Legacy checkpoints restore only into the legacy lane and managed checkpoints only into the matching lane/capability-digest, both enforced by explicit magic-number checks with actionable error messages rather than obscure mid-restore corruption — this is exactly the belt-and-suspenders pattern you want for a change that touches checkpoint state. Restored lane selection is persisted with the physical plan, so a cluster-config change (flipping enabled or editing the allowlist) cannot silently move a running or recovering job between lanes — verified directly in the physical-plan generator and source config, not just asserted in docs. Rescale semantics (drop partial per-subtask no-more-splits state, keep only global end-of-input so new readers renegotiate with the enumerator) are conservative and test-pinned. I found no path by which upgrading to this PR changes execution semantics for a job that does not explicitly opt in, aside from the low-probability Issue 10 edge case around unconditional config validation.

4. Issue Summary

ID Issue Location Severity
1 Reader failover racing in-flight discovery/assignment fails the source instead of deferring Coordinator runtime's require-ready-reader/apply-registration/stale-target handling High
2 Transport-retry tracking maps leak one entry per replaced in-flight command Coordinator runtime's retry-tracking fields and release-all-outbound Medium
3 Core managed state machine's failure/rescale/saturation paths and two of three pilots still have no executed test coverage New managed-source-runtime E2E and the runtime classes it doesn't fully exercise High
4 Observability docs describe the pre-fix metric suffix; implementation emits an attempt-scoped suffix Realtime-observability docs; source-runtime-metrics class Medium
5 No watchdog/timeout on a stuck availability-check future outside an active poll Reader runtime's poll/availability wait logic Medium
6 Mailbox's epoch-reset method is dead, untested code for an untriggered scenario Reader command mailbox Low
7 Signal/await-signal documentation claims an immediate wake path that does not exist in the current wiring Reader command mailbox and reader runtime Low
8 Per-attempt metric registration accumulates in a retained metrics context Source-runtime-metrics classes Low
9 Managed fake-source connector busy-polls during its interval gate Fake-source reader's availability check Low
10 Managed-source-runtime config validation runs unconditionally, even when the feature is disabled Runtime selector's validate call Low
11 Current-head fork CI has a real (unrelated-looking) failure that cascaded into cancelling the engine IT lanes Fork Build run Medium (procedural)

5. Merge Recommendation

Conclusion: Not recommended for merge at this time — the PR is correctly still marked Draft, and should remain so.

Blocking (must be resolved before this leaves Draft):

  • Issue 1: the reader-failover-vs-in-flight-discovery race is confirmed real at the current head and directly contradicts the fine-grained fencing this runtime is built to provide.
  • Issue 3: the core distributed state machine's failure, rescale, and saturation paths, and two of the three pilots, still have no end-to-end executed test proving them — this is precisely the kind of gap where a helper-test-green, integration-untested change ships a hang or a duplicated/lost split.
  • Issue 11: get a completed, green engine-IT (and the rest of the currently-cancelled matrix) at the current head before requesting maintainer review — a red or incomplete Build check cannot be waved off as "probably fine."

Non-blocking, should be fixed before or shortly after graduation:

  • Issue 2 (assignment-tracking map leak on failover), Issue 4 (metric-suffix doc drift), Issue 5 (unbounded availability wait), Issues 6-7 (dead/misleading mailbox signaling code), Issue 8 (metric cardinality growth), Issue 9 (fake-source busy-poll), Issue 10 (unconditional config validation).

Overall assessment: this is genuinely strong architecture work. The single-owner event-loop model, bounded admission, epoch/attempt fencing, and checkpoint-coupled assignment ownership are the right long-term answer to a real production pain point, and the fail-closed opt-in design means it can land without touching a single existing user — I verified that compatibility claim independently across the selection layer, the shared lifecycle classes, and the three pilots, and it holds. The community reviewer's concern about the allowlist weakening safety semantics is answered directly by the code: misconfiguration can only fail closed, never silently activate. What this PR is missing is not a design rethink — it is proof. A change of this size to the engine's core checkpoint-visible state machine needs paired-runtime failure-path tests and a genuinely green CI run before a human maintainer's sign-off means what it should mean. The author's own "Draft graduation gates" framework already names exactly the right bar (deterministic failover/fault-injection coverage, pilot conformance, a completed green Build); this review's conclusion is that those gates are not yet met, not that the underlying architecture needs redesign. I'd treat this as ready for a focused maintainer design discussion on the architecture (which is sound) running in parallel with closing Issues 1, 3, and 11 — not as a PR that should be merged as-is.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

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. Zeta splits ownership of Source concurrency between the engine and every connector author: the collector loop calls SourceReader#pollNext under a connector-owned checkpoint lock, split assignment and reader registration travel through Hazelcast operation threads that end up executing connector code, and enumerator discovery is whatever each connector chose. The resulting failure classes are checkpoint-lock stalls, operation threads blocked by slow connector code, and ambiguous split ownership across failover.
  • Fix approach. An opt-in "managed" lane alongside the "legacy" lane in which the engine owns all checkpoint-visible Source state: a reader and a coordinator event loop per Source, a versioned command envelope with checksums/sequencing/attempt fencing between them, an engine-owned split-assignment ledger (DISPATCHED -> ADMITTED -> APPLIED -> CHECKPOINT_INCLUDED), explicit non-Java checkpoint serializers, and a bounded CoordinatorScheduler for blocking discovery. A connector leaves the legacy lane only when the feature is enabled, its plugin name is explicitly allowlisted, and it declares a matching versioned ManagedSourceCapability. Fake, Kafka (reader + coordinator) and Iceberg (coordinator only) are the pilots.
  • One-sentence summary. A large, disabled-by-default, fail-closed second Source execution lane that moves Reader/Enumerator concurrency ownership from connectors into the Zeta engine while claiming to leave the Source SPI and legacy behavior byte-for-byte intact.

The design intent is sound and the SPI-compatibility discipline is careful. The problems below are in the new lane's shutdown, restore and error-reporting paths, plus two changes that reach the legacy lane.

1. Code Change Review

1.1 Core Logic Analysis

Coverage scope (mandatory statement for a 104-file / +14,898 diff)

This is far too large to claim uniform depth, so here is the honest boundary.

Full call-chain tracing (read in full, traced into the runtime path): lane selection and persistence (ManagedSourceRuntimeSelector/Selection/Mode, ManagedSourceRuntimeConfig, SourceConfig, PhysicalPlanGenerator, PlanUtils, JobMaster#init, YamlSeaTunnelDomConfigProcessor); checkpoint/restore (both checkpoint-state serializers, SourceAssignmentTrackerSerializer, both restoreState implementations, restoreRuntimeState, restoreMetadata, NotifyTaskRestoreOperation, JobCheckpointUtils); lifecycle/state machine (SourceSplitEnumeratorTask#stateProcess, SeaTunnelTask#ack, SourceSeaTunnelTask, the whole SourceFlowLifeCycle diff, ManagedSourceLifecycle(+State), SchemaChangeSubState, and the runOneTurnInternal / applyBarrier / applyInboundCommand / checkActivePoll / close / applyRegistration / applyReaderCheckpointReport / handleOutboundResult paths of both runtimes); the public SPI (SeaTunnelSource, SourceSplitEnumerator, api/source/managed/*, api/source/scheduler/*); concurrency (ReaderCommandMailbox, ManagedSourceMemoryBudget, ManagedPollContext, SourceAssignmentTracker, SplitIdChunkAccumulator, ManagedCoordinatorScheduler, TaskExecutionService pools and cooperative worker model); wire protocol and operations (SourceCommandEnvelope, the admission enums, all three Managed*Operations, AssignSplitOperation, RestoredSplitOperation, TaskDataSerializerHook, SeaTunnelSplitEnumeratorContext); the connector side (SourceReaderBase, SplitFetcher(Manager), FetchTask, every Kafka/Iceberg/Fake class touched plus the untouched IcebergBatchSplitEnumerator); tests and docs.

Lighter pass: SourceCommandCodec (493 lines — I confirmed checksum/codec validation is invoked on both sides but did not audit every encode/decode branch); the metrics classes beyond registration and the name suffix; MetricNames (56 constants); the new UT bodies (scanned for flakiness and coverage, not line-by-line); zh docs (parity only).

Not covered: I did not trace Zeta's CheckpointPlan state redistribution under rescale — the one input needed to decide whether Issue 17 can also fire on the rescale path. I say so rather than assert either way.

Key findings

The disabled-by-default gating is real and correct: ManagedSourceRuntimeSelector.select returns legacy() before ever touching getManagedSourceCapability() when the feature is off or the allowlist is empty (:20-31), the default enabled is false (ManagedSourceRuntimeConfig.java:26), and the shipped seatunnel.yaml sets enabled: false with an empty allowlist. The SPI additions are all default methods.

What does not hold up is the shutdown path, the restore path, and the claim that lane selection is persisted — Issues 1, 2 and 3, each independently merge-blocking. Two further changes reach the legacy lane despite the "isolated compatibility lane" claim (Issues 6 and 24).

1.2 Compatibility Impact

Classification: Partially incompatible.

Compatible: SeaTunnelSource#getManagedSourceCapability and the three new SourceSplitEnumerator.Context methods are all default, so every existing connector and the Flink/Spark translation Context implementations still compile with legacy behavior. TaskDataSerializerHook IDs 29-32 are append-only. SourceReaderBase implements ManagedSourceReader does not drag CDC/Fluss into the managed lane — selection is capability-driven and SourceFlowLifeCycle.java:222-227 uses instanceof only as a post-selection assertion; neither IncrementalSourceReader nor FlussSourceReader declares a colliding method. The legacy SourceReaderBase#pollNext body is unchanged apart from drainAsyncCompletions(), whose only non-empty override (KafkaSourceReader.java:181-190) is a no-op on the legacy lane.

Incompatible or partially incompatible:

  • Lane flip on restore (Issue 3). SourceConfig.runtimeMode is not persisted; it is re-derived from live cluster config on every JobMaster#init. Changing enabled or the allowlist between a checkpoint and a restore permanently invalidates that checkpoint (SourceFlowLifeCycle.java:796-818, SourceSplitEnumeratorTask.java:244-262 both fail closed).
  • Capability digest is a hard restore gate. Any change to any capability boolean in a future connector release changes capabilityDigest and makes every existing managed checkpoint unrestorable (ManagedSourceCoordinatorRuntime.java:1635-1637, ManagedSourceReaderRuntime.java:1393-1396). Correct fail-closed behavior, but with no documented migration path and no incompatible-changes.md entry.
  • FakeSourceSplit identity change (Issue 6) breaks restore of pre-PR FakeSource checkpoints on the legacy lane.
  • SourceConfig gains 5 fields with no explicit serialVersionUID (Issue 25), so a mixed-version cluster cannot deploy tasks.

1.3 Performance / Side-Effect Analysis

  • The managed reader's idle wait is a fixed Thread.sleep(idleWaitMillis) (default 10 ms) at SourceFlowLifeCycle.java:353-357. The connector's isAvailable() future is used only to gate whether pollNextManaged is called, never parked on, so every control event admitted just after a turn returns false — including a checkpoint barrier — waits up to 10 ms. ReaderCommandMailbox#awaitSignal exists for exactly this and has no callers (Issue 21).
  • updateMetrics() runs in the finally of every turn, taking admissionLock plus the mailbox lock three more times and an O(mailbox) scan (Issue 20), contending with the admission latency it measures.
  • The legacy lane now pays for SourceRuntimeMetrics whenever observability is on (16 counters per source per attempt) and for an unconditional setAvailabilityNotifier on the SplitFetcher hot path (Issue 30f). FakeSourceReader's managed path calls generateFakedRows(..., maxRows = 1, ...) once per emitted row (:140-153).

1.4 Error Handling and Logging

The systemic problem is that the new lane's failure signalling is asymmetric and, in the coordinator-to-reader direction, silent. Formal issues follow.


Issue 1 — Managed Split Enumerator task deadlocks in PREPARE_CLOSE; no managed bounded job can ever finish

Location: SourceSplitEnumeratorTask.java:466-472 (with :420-484, :620-624) — Severity: High

In the managed lane every inbound control path is enqueue-only: triggerBarrier becomes admitBarrier(barrier) (:188-192), notifyCheckpointComplete becomes admitCheckpointComplete(...) (:521-527). The queue is drained only by managedCoordinatorRuntime.runOneTurn(), and git grep confirms it has exactly two call sites in src/main in this class: :429 (WAITING_RESTORE) and :459 (RUNNING). READY_START, STARTING and PREPARE_CLOSE never drain — PREPARE_CLOSE is just if (closeCalled) { currState = CLOSED; } else { Thread.sleep(100); }.

For the managed lane the only setter of closeCalled is managedCheckpointCallbackFinished (:620-624), reached only from applyCheckpointComplete/applyCheckpointAborted inside the runtime — i.e. only from a drained control event. (AbstractTask#tryClose, the other closeCall() route, is used only by SeaTunnelTask and SinkAggregatedCommitterTask, never by this CoordinatorTask.)

Runtime path. Bounded job: readers finish -> managedReaderFinished sets prepareCloseStatus -> RUNNING -> PREPARE_CLOSE -> master triggers the final checkpoint -> the barrier is admitted but never applied -> the enumerator never acks -> the checkpoint never completes -> notifyCheckpointComplete never fires -> closeCalled never set -> the task spins on Thread.sleep(100) until checkpoint timeout fails the job. In the legacy lane triggerBarrier ran inline on the operation thread, so parking here was safe.

Fix: drain in PREPARE_CLOSE — if (isManagedCoordinatorRuntime() && !managedCoordinatorRuntime.runOneTurn()) { Thread.sleep(100); } before the closeCalled test — and defensively in READY_START. Add a UT driving stateProcess() through RUNNING -> PREPARE_CLOSE -> CLOSED with a queued barrier. Note this predicts ManagedSourceRuntimeIT#testBatchJobCompletesOnManagedLane times out at this head — consistent with it never having executed in CI (Issue 26).


Issue 2 — Coordinator restore poisons SourceAssignmentTracker's owner thread; every managed restore-from-checkpoint job fails

Location: ManagedSourceCoordinatorRuntime.java:594; SourceAssignmentTracker.java:345-346, 453-461 — Severity: High

restoreRuntimeState's own Javadoc states the invariant precisely:

580     * on {@link #setEnumerator}. Deliberately does not call {@link #checkOwner()} for the same
581     * reason: the caller's restore-operation thread is never the task's own execution thread, and
582     * asserting ownership here would poison it before the first legitimate owner-thread call.

Two lines into the body it does exactly that, one object down: :594 assignmentTracker.restore(SourceAssignmentTrackerSerializer.deserialize(...)), and SourceAssignmentTracker#restore:345-346 opens with checkOwner() — a lazy first-caller-wins bind (:453-461).

restoreState runs on a TaskExecutionService async pool thread (NotifyTaskRestoreOperation.java:96-119 -> asyncExecuteFunction), never the task's own thread, so the tracker binds to a transient pool thread. The first access from the real owner loop — markRestoredSplitsIncluded (:876), entries() in applyBarrier (:921), or takeAssignmentsForMissingReaders (:1348) — then throws "SourceAssignmentTracker accessed outside its coordinator event loop", and the job retries into the same failure forever.

Only the restore path is affected (restoreRuntimeState is reached only when serializedState.isPresent(), SourceSplitEnumeratorTask.java:244), so a fresh job binds correctly. ManagedSourceRuntimeIT#testManagedLaneJobRestoresFromSavepoint does restore, but asserts only job status plus the absence of two log strings — it never asserts the job produces data after restore, and the first tracker touch happens after RUNNING is reported.

Risk: no managed job can recover from any checkpoint. Fix: mirror the resolution already applied to the runtime object — either a restoreWithoutOwnerCheck(...) used only here, or have restore() set ownerThreadId = null as its last statement so the first owner-loop call rebinds.


Issue 3 — Lane selection is re-derived from live cluster config on every JobMaster#init, not persisted; the documented rollback permanently invalidates in-flight managed checkpoints

Location: PhysicalPlanGenerator.java:612-634; JobMaster.java:289-301; SourceFlowLifeCycle.java:796-818; SourceSplitEnumeratorTask.java:244-262; docs/en/engines/zeta/managed-source-runtime.md — Severity: High

The PR description and both docs state the opposite of what the code does — e.g. "Running jobs and failover from their persisted physical plan do not switch lanes merely because the cluster allowlist changes", plus two similar claims about the selection being "frozen in the physical plan and persisted in checkpoint metadata."

There is no persisted physical plan. JobMaster#init regenerates it from the logical DAG on every init — including restore and master failover — via PlanUtils.fromLogicalDAG(logicalDag, ..., engineConfig) (:289-301), and PhysicalPlanGenerator#managedSourceSelection (:612) recomputes the lane from the live EngineConfig. The digest is persisted and validated, but only after the lane has already been chosen, so it cannot prevent the flip.

Runtime path. An operator follows the PR's own guidance ("Disable selection for new deployments immediately when a stop condition is reached") and sets enabled: false. The setting is cluster-global; the engine has no "new deployments only" notion. On the next restore of any in-flight managed job, select() returns LEGACY and SourceFlowLifeCycle#restoreState fails closed with "Cannot silently restore managed Source Reader state in the legacy lane" (:814-816). That checkpoint is now unusable, and stays unusable after re-enabling unless the allowlist is restored byte-identically. Allowlisting a connector while a legacy job runs breaks the same way from the other side.

Fix: stamp ManagedSourceRuntimeSelection into JobImmutableInformation (or the job's checkpoint metadata) at first submission, and have PhysicalPlanGenerator prefer it when present, consulting live config only for a brand-new job. Then correct the doc claims.


Issue 4 — IcebergSource declares supportsAsyncEnumerator(true) unconditionally, but the BOUNDED path still returns the untouched, blocking IcebergBatchSplitEnumerator

Location: IcebergSource.java:136-142, 149-163, 165-173 — High

createEnumerator/restoreEnumerator return IcebergBatchSplitEnumerator whenever Boundedness.BOUNDED (:136-137, :149-150), while getManagedSourceCapability() (:165-173) declares supportsManagedCoordinator(true) and supportsAsyncEnumerator(true) with no boundedness condition. Only IcebergStreamSplitEnumerator was adapted (new file, +134); IcebergBatchSplitEnumerator is not in this diff and still blocks — run() loops while (!pendingTables.isEmpty()) calling loadSplits(tablePath) under stateLock (:62-80).

supportsAsyncEnumerator is exactly the flag the selector requires to admit a managed coordinator (ManagedSourceRuntimeSelector.java:55-60), and this PR's own new SourceSplitEnumerator#run Javadoc says that under isManagedCoordinatorRuntime() the method "must return promptly and move any blocking discovery to the engine-owned CoordinatorScheduler."

Runtime path. Allowlist Iceberg and run a bounded job: stateProcess STARTING calls enumerator.run() inline on the coordinator's drain thread (SourceSplitEnumeratorTask.java:445-449), so no barrier, registration, ACK or checkpoint callback drains for the whole duration of manifest/scan planning — stalled checkpoints and checkpoint timeouts. The capability object is the engine's only conformance gate, and here it does not describe the code.

Fix: adapt IcebergBatchSplitEnumerator as the stream enumerator was, or make the declaration honest — managed capability only when !Boundedness.BOUNDED.equals(getBoundedness()). (Verified correct: Iceberg does not set supportsManagedReader and IcebergSourceReader is untouched, so the coordinator-only claim holds on the reader side.)


Issue 5 — All three managed Hazelcast operations collapse every exception into STALE_TARGET with no logging, producing a silent infinite re-registration loop

Location: ManagedSourceCommandOperation.java:70-78; ManagedCoordinatorCommandOperation.java:72-80; ManagedSourceRegisterOperation.java:107-109; consumed at ManagedSourceCoordinatorRuntime.java:1232-1238 — Severity: High

Each runInternal() wraps its admission call in catch (Exception e) and answers SourceCommandAdmissionStatus.STALE_TARGET with a fixed string — ManagedSourceCommandOperation keeps only e.getClass().getSimpleName(), and ManagedSourceRegisterOperation discards even that. None of the three logs the throwable. Any programming error in admission — an NPE, an IllegalStateException, the visibility race in Issue 10 — is therefore indistinguishable from "the target attempt is gone."

The coordinator's handling is not fatal: case STALE_TARGET: sets reader.ready = false and calls scheduleRegistrationDeadline(reader) (:1232-1238). So a deterministic defect produces STALE_TARGET -> re-register -> same defect -> ... forever, with no log line explaining why. That is the exact "silent stall" class the STIP is meant to eliminate.

The reverse direction is inconsistent: the reader treats STALE_TARGET as fatal (ManagedSourceReaderRuntime.java:1163-1173 throws), so a transient absence of the coordinator task during a legitimate failover window — getTask(taskLocation) throwing — hard-fails the reader instead of retrying.

Fix: log the throwable at ERROR in all three catch blocks with task location and command id; add an INTERNAL_ERROR status for unexpected exceptions, fatal on both sides so defects surface immediately; reserve STALE_TARGET for a genuinely missing/replaced attempt, and map "coordinator not yet available" to RETRY_LATER.


Issue 6 — FakeSourceSplit widens equals/hashCode via @Data while keeping serialVersionUID, duplicating every assigned split when restoring a pre-PR checkpoint (legacy lane, not gated)

Location: FakeSourceSplit.java:24-43; FakeSourceSplitEnumerator.java:112-141 — Severity: High

@Data regenerates equals/hashCode over all non-static fields, so the new totalRowNum becomes part of split identity while serialVersionUID is unchanged. A split deserialized from a pre-PR checkpoint therefore has totalRowNum == 0 where a freshly computed one has totalRowNum == rowNum. The enumerator's restore reconciliation is a HashSet difference over exactly these objects — discoverySplits() builds allSplit from new FakeSourceSplit(tableId, index, ...) (:124-126) and then does assignedSplits.forEach(allSplit::remove) (:135-137) against the restored entries.

Runtime path. Restore a running FakeSource job from a savepoint taken on apache/dev into a build with this PR: every remove misses, every already-assigned split is re-discovered and re-assigned on top of what the reader restores itself, and rows are duplicated. This is not behind the managed-runtime flag — it fires on the legacy lane, contradicting the isolation claim — and CI cannot catch it because the E2E restore tests snapshot and restore within the same build. Scoped to FakeSource, so the blast radius is benchmarks, demos and the E2E suite rather than production pipelines, but it is a silent correctness regression across a version boundary and the @Data-widening pattern is a trap for any future connector split class.

Fix: @EqualsAndHashCode(of = {"tableId", "splitId"}) on the class (splitId() already ignores rowNum). That also makes the set-difference robust against the reader's new in-place rowNum mutation.


Issue 7 — Poll watchdog delivers interrupt() outside the lock with no re-validation; the interrupt can land on an unrelated task and is never cleared

Location: ManagedSourceReaderRuntime.java:601-639 — Severity: High

checkActivePoll() decides under synchronized (pollWatchdogLock) (:604-628), capturing threadToInterrupt = ownerThread at :626, but delivers threadToInterrupt.interrupt() at :636-637 after the lock is released, with no re-check that the poll it targets is still running — and pollManagedReader's finally (:562-569) can clear activePollGeneration inside that window.

Under ThreadShareMode.OFF (default) the interrupt lands on the task's own thread, most likely in Thread.sleep(idleWaitMillis) — noisy, but the task was failing anyway. Under ALL/PART the owner is a CooperativeTaskWorker thread fed from the service-wide threadShareTaskQueue (TaskExecutionService.java:173, 1316-1319, 1386-1388) shared across task groups, so a late interrupt can land inside task.call() of a different job, whose CooperativeTaskWorker.run() catches InterruptedException and fails it. There is also no Thread.interrupted() anywhere in the class, so the flag survives on a pooled thread.

Fix: hold pollWatchdogLock across the interrupt() and re-assert activePollGeneration == cancelledPollGeneration immediately before firing; and in pollManagedReader's finally, call Thread.interrupted() when cancelledPollGeneration == pollGeneration (the failure is already in asynchronousFailure).


Issue 8 — A barrier admitted before CANCEL turns a clean cancel into a job failure and calls snapshotState() on a cancelled reader

Location: ManagedSourceReaderRuntime.java:397-426, 729-733, 776-812; ManagedSourceLifecycle.java:290-307 — High

CANCEL sets terminalSignal and moves the lifecycle to CANCELLING (:729-733). But runOneTurnInternal only stops on isFailed():

runOneTurnInternal does if (terminalSignal.get()) { lifecycle.cancel(); } (:402) and then guards only with if (lifecycle.isFailed()) { throw ... } (:405) before going on to drain and run the next event (:424).

isFailed() is mainState == FAILED only; CANCELLING is in isTerminal() but not isFailed() (ManagedSourceLifecycle.java:220-228). So the next turn drains an already-admitted snapshot barrier, applyBarrier calls reader.snapshotState() on a cancelled reader, and lifecycle.snapshot() then throws because the Snapshot constructor explicitly rejects CANCELLING (:301-306). The catch (Exception) at :810 clears the barrier gate and rethrows, so the task ends FAILED instead of CANCELED. Both CANCEL and the barrier are ordinary FIFO entries in orderedEvents, so this fires whenever a cancel and a checkpoint interleave with CANCEL first.

Risk: a user cancel is reported as a job failure. Fix: short-circuit in applyBarrier (or pollNextReadyEvent) when lifecycle.isTerminal(), discarding queued snapshot barriers; or stop draining non-terminal work once isTerminal().


Issue 9 — The three thread-identity guards break under ThreadShareMode.ALL

Location: ManagedSourceCoordinatorRuntime.java:1643-1651; ManagedCoordinatorScheduler.java:571-579; SourceAssignmentTracker.java:453-461; against TaskExecutionService.java:650-663, 1316-1319, 1386-1388 — Severity: High

All three use first-caller-wins thread identity. Under ThreadShareMode.ALL, CooperativeTaskWorker re-queues the task onto a shared deque after every tick, so the second tick can land on a different thread and every guarded method throws. SourceSplitEnumeratorTask does not override Task#isThreadsShare() (default false), so PART is safe, and the default mode is OFF — but ALL is a documented, supported configuration and there is no guard, no validation, and no test covering it.

Fix (minimal): force managed-lane Source and enumerator tasks onto the blocking submission path regardless of ThreadShareMode, and reject the combination explicitly at selection time. Alternatively replace thread-identity assertions with an ownership handle acquired/released per tick.


Issue 10 — coordinatorEpoch, coordinatorAttemptId and closed are read from Hazelcast operation threads with no happens-before

Location: ManagedSourceReaderRuntime.java — declarations :114-115, 136, reads :235, 257-258, writes :510, 747-748 — Severity: Medium

All three are plain fields. admitCommandInternal runs on a Hazelcast operation thread and reads them before entering synchronized (admissionLock) at :272; the writes are on the owner thread with no volatile and no matching lock. ownerThread right next to them is volatile, which makes the omission look accidental. An operation thread can therefore keep observing the initial empty coordinatorEpoch and reject every non-epoch-start command with STALE_TARGET — which, given Issue 5's asymmetric handling, is not obviously self-healing. It also contradicts the single-owner claim in the class Javadoc at :67-75.

Fix: make the three fields volatile, or move the checks inside the existing synchronized (admissionLock) block and publish the writes under the same lock.


Issue 11 — drainDeferredSplitRequests removes the request before testing readiness, silently dropping it

Location: ManagedSourceCoordinatorRuntime.java:1410-1419 — Severity: Medium

The loop does iterator.next() then iterator.remove() (:1413-1414) and only then tests if (reader != null && reader.ready) before dispatching (:1416-1417). If the reader is mid-failover (reader.ready == false, set at :737 or :1235) the request is consumed and never forwarded. The reader only issues REQUEST_SPLIT when the connector calls SourceReaderContext#sendSplitRequest, and nothing re-issues it — so a connector that requests once and then waits stalls indefinitely with no error.

Fix: iterator.remove() only after a successful dispatch, with a continue/break so a permanently absent subtask does not spin.


Issue 12 — enumerator.run() executes inline on the coordinator drain thread, blocking every barrier for its duration

Location: SourceSplitEnumeratorTask.java:445-449; window ceiling at ManagedSourceCoordinatorRuntime.java:1086-1094 — Severity: Medium

case STARTING: ... enumerator.run(); runs on the same thread that drains control events. In the legacy lane triggerBarrier ran on the operation thread and was unaffected; now every barrier, checkpoint callback, registration and transport ACK admitted during run() waits for it. Secondary effect: ACKs cannot drain during run(), so splits assigned inside it accumulate against the outbound window, and reserveOutbound throws rather than back-pressures once exceeded. With defaults (readerMailboxMaxBytes = 4 MiB) a single run() assigning more than 4 MiB of serialized splits to one reader fails the job. Issue 4 is the concrete instance.

Fix: warn (or fail) when run() exceeds a budget — the SPI Javadoc already states the contract — and make reserveOutbound return a retriable typed result for CHECKPOINT_COUPLED assignments instead of throwing.


Issue 13 — Kafka managed discovery fails the job on a transient error and never re-arms, diverging from the legacy lane

Location: KafkaSourceSplitEnumerator.java:581-603, against legacy :175-188 — Severity: Medium

The callAsync result handler throws KafkaConnectorException(DISCOVER_PARTITION_FAILED, failure) when failure != null (:586-589), and scheduleNextManagedDiscovery() sits after that throw; the options are AsyncTaskOptions.builder().timeout(Duration.ofMinutes(1)).build() (:602).

The legacy dynamic-discovery loop wraps the same work in catch (Exception e) { log.error("Dynamic discovery failure:", e); } and retries at the next interval. Here the throw reaches ManagedCoordinatorScheduler#completeSubmission -> failureHandler -> source failed (and AsyncTaskOptions.Builder also defaults failurePolicy to FAIL_SOURCE). Because scheduleNextManagedDiscovery() sits after the throw, discovery is permanently dead even if the failure were tolerated. The hard-coded 1-minute timeout is delivered to the same handler. Net effect: one broker blip, or a slow listOffsets round, kills a streaming job the legacy lane would have survived.

Fix: log.error(...) inside the handler and call scheduleNextManagedDiscovery() from a finally; gate hard failure on !initialized if it is wanted for the initial round; derive the timeout from discoveryIntervalMillis.


Issue 14 — Kafka managed lane applies end_offsets_timestamp under start modes where the legacy lane ignores it

Location: KafkaSourceSplitEnumerator.java:749-767, against legacy :244-256 — Severity: Medium

Legacy resolves end offsets from endOffsetsTimestamp only inside case TIMESTAMP: of the start-mode switch. resolveManagedTimestampEndOffsets applies it whenever the value is non-null, with no start-mode condition. A bounded job with start_mode = earliest and end_offsets_timestamp therefore reads a different row set on each lane — an unreproducible row-count mismatch attributable only to an engine flag.

Fix: replicate the legacy condition. If the legacy behavior is a bug, fix both lanes in a separate documented change.


Issue 15 — restoreMetadata() has no owner check and no idempotence guard

Location: ManagedSourceReaderRuntime.java:194-220 — Severity: Medium

It runs on a TaskExecutionService pool thread and mutates owner-only state (appliedCommandWatermark, appliedCommandGaps, noMoreSplitsGeneration, the staged restore collections) plus lifecycle.restoreSnapshot(), on a class documented as containing "no atomics or synchronization." The first restore is genuinely safe — restoreComplete.complete(null) happens after the flow restore and SeaTunnelTask#stateProcess gates cycle.open() on restoreComplete.isDone(), a real happens-before edge; the coordinator spells this argument out at ManagedSourceCoordinatorRuntime.java:177-179, the reader does not. What is missing is a guard against a second invocation: NotifyTaskRestoreOperation can be re-delivered, and a second call while RUNNING would reset the lifecycle to RESTORING and overwrite the watermark from a pool thread with no fence.

Fix: reject restoreMetadata when restoreComplete is already done or lifecycle.getMainState() != RESTORING; add the publication comment mirroring the coordinator's.


Issue 16 — close() is not failure-atomic and ManagedSourceMemoryBudget.release throws on a cleanup-only path

Location: ManagedSourceMemoryBudget.java:53-61; ManagedSourceReaderRuntime.java:521-536 — Severity: Medium

release throws IllegalStateException when releasing below zero, but current is the worker-wide used total and release is only ever called from cleanup paths (ReaderCommandMailbox#close's per-command loop, releaseAllOutbound). If it throws inside that loop the exception escapes the synchronized (admissionLock) block at :521-526, so releaseAllOutbound(), the remaining cleanup and lifecycle.closed() never run: the outbound reservation leaks permanently from a bounded worker-wide budget, starving every other managed Source on the node, and the runtime never reaches CLOSED. Any exception out of inboundMailbox.close() skips the same steps.

Fix: make release clamp at zero and log at ERROR (it is a cleanup-only API), and chain the close() steps through nested try/finally.


Issue 17 — markRestoredSplitsIncluded uses per-reader containsAll, so a partially covered multi-split entry is replayed

Location: SourceAssignmentTracker.java:257-267; callers at ManagedSourceCoordinatorRuntime.java:876, 280-288, 325-328 — Severity: Medium

if (restoredSplitIds.containsAll(entry.splitIds)) { iterator.remove(); } is called per reader, per completed accumulator, never against the union across readers. An entry holding {A, B} whose splits land in different readers' restored sets matches neither call, survives into replayAssignments (:1366-1399) and is re-sent — while both readers already hold those splits from their own restored state. The same shape on the failover path means a partial return of an entry's splits sends the returned splits to the enumerator and replays the whole entry later. Risk: duplicate reads after failover or rescale.

Could not fully verify: whether Zeta's restore can split one reader's ActionSubtaskState across two new subtasks under rescale. If blobs are always redistributed wholesale the rescale variant cannot fire; the addSplitsBack-with-a-subset variant does not depend on that.

Fix: accumulate restored split ids across all readers and reconcile once in completeManagedRegistrationsIfReady before reconcileAssignmentsForMissingReaders; handle partial coverage explicitly rather than replaying the whole chunk.


Issue 18 — transportRetries / transportFirstAttemptNanos leak on every reader replacement

Location: ManagedSourceCoordinatorRuntime.java:88-89, 1120, 1172-1196, 1259, 1277 — Severity: Medium

releaseAllOutbound clears pendingOutbound, inFlightCommand and pendingApplicationAcks but leaves every commandId those commands owned in both retry maps, which are plain unbounded HashMaps. Unbounded growth over a long-running job with a flapping reader, with nothing to detect it.

Fix: in releaseAllOutbound, remove the commandId of inFlightCommand and of every pendingOutbound element from both maps.


Issue 19 — Managed Source tasks stop joining the checkpoint acknowledgement, losing ack ordering and downgrading ack failures

Location: SeaTunnelTask.java:484-501; SourceSeaTunnelTask.java:190-205; ManagedSourceReaderRuntime.java:495-503 — Severity: Medium

waitForCheckpointAcknowledge() returns !isManagedReaderRuntime(), so managed tasks no longer join() the TaskAcknowledgeOperation. Two things need an explicit answer. First, acks for consecutive barriers are no longer ordered by the sender; the PR should assert (not assume) that CheckpointCoordinator tolerates out-of-order acks. Second, the failure route is onCheckpointAcknowledgeFailure -> SourceFlowLifeCycle#reportManagedRuntimeFailure, which throws IllegalStateException when the runtime is absent — inside a whenComplete callback, where the CompletableFuture machinery swallows it and the ack failure is lost entirely. Even on the normal route, reportAsynchronousFailure only sets an AtomicReference and calls reader.wakeUp().

Fix: never throw from the whenComplete callback — log and route unconditionally. Add a UT proving a failed TaskAcknowledgeOperation fails the managed source task. Document the ordering assumption.


Issue 20 — Per-turn metrics update takes two locks and scans the mailbox, contending with the admission budget it measures

Location: ManagedSourceReaderRuntime.java:392-394, 1512-1523; ReaderCommandMailbox.java:343-356 — Severity: Medium

updateMetrics() runs in the finally of every runOneTurn() — every poll batch and every idle turn. It takes admissionLock, then ManagedSourceRuntimeMetrics#updateReaderState acquires the mailbox lock three more times, and oldestCommandAgeNanos is a full scan of every buffered command. That is exactly the lock the operation threads need for admission, whose latency the same code compares against admissionBudgetMillis.

Fix: sample on an interval; track the oldest-admitted timestamp incrementally in the mailbox instead of scanning.


Issue 21 — Coordinator epoch rebase is unimplemented: a second epoch hard-throws and resetForEpoch / awaitSignal are dead code

Location: ManagedSourceReaderRuntime.java:740-746; ReaderCommandMailbox.java:205-268 — Severity: Medium

applyEpochStart throws "Managed Source reader received a second coordinator epoch" whenever a non-empty coordinatorEpoch does not match the incoming one (:741-745) — there is no rebase branch.

ReaderCommandMailbox#resetForEpoch documents exactly the rebase this needs and has no callers anywhere in the tree; awaitSignal likewise, which also makes signal() a no-op and is why idleness is a fixed sleep (see 1.3). The PR advertises epoch fencing and failover rebasing; the mechanism exists but is unreachable, and a reader that outlives its coordinator fails instead of rebasing.

Fix: either wire resetForEpoch into applyEpochStart and park on awaitSignal(idleWaitMillis), or delete the three unused members and the Javadoc promising the contract and state in the docs that reader and coordinator always restart together.


Issue 22 — Managed enumerators close their clients while an async discovery may still be using them

Location: KafkaSourceSplitEnumerator.java:286-301; IcebergStreamSplitEnumerator.java:164-172 — Severity: Medium

close() sets closed, cancels the timer, then closes the AdminClient (Kafka) or the Iceberg Catalog via super.close(). Neither cancels the in-flight callAsync, and ManagedCoordinatorScheduler#close only flips cancelled and cancels the worker Future — it does not join. completeSubmission then skips the handler for a cancelled submission, so the resulting exception is swallowed.

Fix: retain the Cancellable returned by callAsync and cancel it in close() before closing the client, or defer the client close into the cancellation/result handler.


Issue 23 — SourceReaderBase#pollNextManaged is inherited by CDC readers whose pollNext carries logic it does not replicate

Location: SourceReaderBase.java:61, 133-167; IncrementalSourceReader.java:102-121 — Severity: Medium

SourceReaderBase implements ManagedSourceReader gives every subclass a concrete pollNextManaged. For IncrementalSourceReader (all 8 CDC connectors) that inherited implementation omits the split-request bootstrapping and the CDC-specific EOF condition. It is currently unreachable — CDC sources return legacy() and the selector rejects non-declaring connectors — so this is a latent trap, not a live bug. But it is exactly what a future "just allowlist CDC" change would hit, with no compile-time or runtime signal.

Fix: make pollNextManaged final in SourceReaderBase, or have it throw unless isManagedRuntimeActive(), so a subclass with extra pollNext semantics must opt in explicitly.


Issue 24 — Source runtime metric names embed the task attempt, contradicting both the docs and the class's own Javadoc — and this reaches the legacy lane

Location: SourceRuntimeMetrics.java:26-33, 158-160; SourceFlowLifeCycle.java:207-213; docs/en/engines/zeta/realtime-observability.md — Severity: Medium

metricSuffix returns "#" + sourceRuntimeId + "#attempt-" + executionId (:158-160).

The class Javadoc says "Aggregates bounded-cardinality timing metrics"; the doc added by this PR says "All names above use the same #{sourceId} suffix." Neither matches the code. Sixteen counters per source per attempt are registered whenever isObservabilityEnabled() — on the legacy lane too — so every restart or failover mints a fresh set of series, growing the job metrics map and any Prometheus scrape in proportion to restart count. And the documented metric name does not exist.

Fix: either drop the attempt from the name (or express it as a tag) and keep the doc as written, or keep it and correct both the doc and the class Javadoc, plus state how old-attempt series are purged.


Issue 25 — SourceConfig gains five fields with no serialVersionUID, and there is no incompatible-changes.md entry

Location: SourceConfig.java:23-80; FlowConfig.java — Severity: Medium

SourceConfig implements FlowConfig extends Serializable and declares no serialVersionUID, so adding five fields changes the computed default — and SourceConfig travels to workers inside the task deployment payload, so a mixed-version cluster cannot deploy tasks (InvalidClassException). Note also the inconsistent defensive coding: getRuntimeMode() and getCapabilityDigest() guard against JVM defaults with a comment about "an older serialized physical plan," while isCheckpointEnabled() does not — and that comment is misleading anyway, because plans are regenerated rather than deserialized (Issue 3).

Fix: if Zeta requires a uniform cluster version, state that in the PR description and add an incompatible-changes.md entry covering this plus the managed/legacy and capability-digest restore gates. If rolling upgrades are supported, this needs a compatible encoding.


Issue 26 — Test coverage does not reach the two classes that hold the risk, and CI has never executed the new tests at this head

Location: seatunnel-engine-server/src/test/java/.../task/source/ (new UTs); ManagedSourceRuntimeIT.java — Severity: Medium

The new UTs cover the config, selector, SourceConfig, mailbox, assignment tracker, codec, both checkpoint states, the scheduler, the metrics classes and JobCheckpointUtils. There is no direct unit test for ManagedSourceReaderRuntime (1,669 lines) or ManagedSourceCoordinatorRuntime (1,920 lines) — the two classes holding every lifecycle, barrier-ordering and ownership decision, and where Issues 1, 2, 7, 8, 10, 11, 15, 16, 17, 18 all live.

On CI: at head 9c2ffde8 the Build check is failure, caused by MultiTableSinkWriterSchemaChangeBroadcastTest.schemaChangeKeepsIOExceptionContractWhenWorkerAlreadyFailed in seatunnel-api on unit-test (11, windows-latest) — a test not touched by this PR, so almost certainly a pre-existing Windows flake. But fail-fast then cancelled unit-test (8/11, ubuntu-latest), both engine-v2-it jobs and both all-connectors-it-7 jobs, so neither the new unit tests nor ManagedSourceRuntimeIT has ever run to completion at this head. There is currently zero executable evidence for a change of this size.

Fix: add owner-loop unit tests driving runOneTurn() through the real state machines (at minimum RUNNING -> PREPARE_CLOSE -> CLOSED with a queued barrier, restore-then-first-owner-turn, and CANCEL followed by a queued barrier), then get a green head.


Issue 27 — The E2E lane assertion is order-dependent and can pass on the wrong job's log line

Location: ManagedSourceRuntimeIT.java:59-61, 86-88 — Severity: Medium

Both tests share one container from @BeforeAll and both assert server.getLogs().contains(MANAGED_LANE_LOG). Container logs accumulate, so once the batch test has run, the assertion in testManagedLaneJobRestoresFromSavepoint is satisfied by the batch job's line and can no longer prove what its comment claims. The negative assertions at :109-114 are weak in the same way — they can only fail if the message reaches container stdout at all.

Fix: include the job id in the PhysicalPlanGenerator log line and assert on MANAGED_LANE_LOG + jobId, or capture a log offset per test and assert on the delta. Also assert the restored job actually produces rows — that is what would have caught Issue 2.


Issue 28 — Managed lane never sets SourceFlowLifeCycle.prepareClose

Location: SourceFlowLifeCycle.java:618-622 vs :635-636, and :284-299 — Severity: Medium

triggerBarrier returns at :621 in the managed lane and never reaches if (barrier.prepareClose(...)) { this.prepareClose = true; }. The flag stays false, so onTimerTick keeps calling admitFlushSignal(...) after the reader has been told to close; once the runtime is closed those admissions fail and set an asynchronousFailure nobody reads. Not a stall — finishBarrier still calls task.ack(barrier), which sets prepareCloseStatus — but two lanes now disagree about the meaning of a shared field, which is how the next bug gets written.

Fix: set this.prepareClose in the managed branch before delegating.


Issue 29 — requestSplit() before the epoch handshake throws, breaking a legal legacy-lane connector pattern

Location: ManagedSourceReaderRuntime.java:448-458, 1076-1079; SourceFlowLifeCycle.java:259-275, 521-526 — Severity: Medium

sendCoordinatorCommand throws "Managed Source reader cannot send commands before epoch handshake" when the epoch is unset. But SourceFlowLifeCycle#open calls reader.open() before managedReaderRuntime.start(), and requestSplit() routes straight through — so any connector calling context.requestSplit() from open(), legal and common on the legacy lane, fails the task immediately. Even after start() the handshake is asynchronous, so an early request still throws.

Fix: buffer pre-handshake requestSplit intents and flush them in applyEpochStart alongside sendStagedRestoreCommands(), or state and validate the restriction in the ManagedSourceReader contract.


Issue 30 — Low-severity items (grouped) — Severity: Low

Dead or unreachable code: ManagedSourceRuntimeMode.MANAGED_READER can never be selected because validate() requires reader -> coordinator (ManagedSourceCapability.java:132, ManagedSourceRuntimeSelector.java:65); restored nextReaderCommandSequences is overwritten with 1L by applyRegistration yet is written into every coordinator checkpoint — drop it, it is new in this PR so there is no compat cost (ManagedSourceCoordinatorRuntime.java:598,705); the 6-arg SplitFetcher constructor is now unused (SplitFetcher.java:54); and the sendEventToSourceReader / handleSourceEvent managed branches are unreachable because the selector rejects usesSourceEvents(true) — comment them as forward-looking or drop them.

Wire and state hygiene: admittedNanos is a System.nanoTime() value serialized cross-JVM and always overwritten on receipt — dead wire data and a footgun (ManagedSourceCommandOperation.java:102,156); restore() does not reset compactedEntries, so a post-restore metric carries pre-restore counts (SourceAssignmentTracker.java:345).

Error handling: off-thread async failures do not wakeUp()/signal() the way reportAsynchronousFailure does — route them all through it (ManagedSourceReaderRuntime.java:659,1459,1469,1479); fail() overwrites the root cause with a cascading secondary, and getAndSet(null) followed by lifecycle.fail(...) is a no-op once CLOSED, discarding the failure with no log (ManagedSourceLifecycle.java:169, ManagedSourceReaderRuntime.java:398); commitCompletionFailure.getAndSet(null) before throwing loses the failure on a swallowed/retried poll, and if the managed reader stops polling, queued completions never apply and checkpointOffsetMap is never trimmed (KafkaSourceReader.java:182).

Thread-safety and contracts: BudgetedCollector.pollContext is non-volatile, so requireActivePoll()'s own off-thread guard is unreliable (ManagedSourceReaderRuntime.java:1587); SourceReaderBase.java:143 calls context.signalNoMoreElement() and returns END_OF_INPUT, sending the signal twice and issuing a coordinator command from inside pollNextManaged — FakeSourceReader does not, so the two managed readers are inconsistent; FakeSource declares supportsWakeup(true) while wakeUp() is empty and isAvailable() is pre-completed, making the availability mechanism a no-op (FakeSourceReader.java:166).

Performance and hot paths: the availability notifier is registered unconditionally, so every Kafka/CDC/Fluss job pays synchronized (availabilityLock) on the FetchTask hot path for a future nobody consumes — and signalAvailable() completes the future inside that monitor, so the managed whenComplete runs on the connector's SplitFetcher thread under the lock (safe today, but undocumented) (SourceReaderBase.java:89); SourceReaderBase.java:149 returns MORE_AVAILABLE after draining the queue, costing one wasted poll turn per drain; the managed source pools are not MDCTracer-wrapped unlike every other executor in the class, so managed-source work loses job/task MDC in logs (TaskExecutionService.java:284-315).

Style: inline fully-qualified types with no import (java.io.IOException at IcebergStreamSplitEnumerator.java:165, java.util.Iterator at ManagedSourceCoordinatorRuntime.java:1411); a bare IllegalStateException at IcebergStreamSplitEnumerator.java:195 where IcebergConnectorErrorCode exists — Kafka correctly added DISCOVER_PARTITION_FAILED; long-typed YAML options parsed with raw Long.parseLong, losing the config key from the error message unlike the getIntegerValue(name, value) used for int options.


2. Code Quality Assessment

2.1 Coding Standards

Formatting, ASF headers, imports and logging are all clean, and comment quality is above average for this repo — JobCheckpointUtils, SourceConfig#getRuntimeMode and restoreRuntimeState all explain why rather than restating the code. Two problems against the project's comment rules:

  • Comments that assert invariants the code then violates. ManagedSourceCoordinatorRuntime.java:578-583 says ownership must not be bound on the restore thread, and :594 binds it (Issue 2). SourceRuntimeMetrics.java:26-33 claims bounded cardinality while :158-160 embeds the attempt id (Issue 24). SourceAssignmentTracker#restore and ReaderCommandMailbox#resetForEpoch both document behavior that does not exist (Issue 21). A wrong comment is worse than none, because reviewers stop checking.
  • Missing documentation on new non-trivial members — a Medium finding under the project rules: SourceReaderBase.java:73-75 (availabilityLock, availability, managedRuntimeActive); SplitFetcherManager.java:58, 154-164 (the field plus the public setAvailabilityNotifier and wakeUp); FetchTask.java:44, 65; KafkaSourceSplitEnumerator.java:88-92 plus every new managed method there and ManagedDiscoveryResult (whose sibling DiscoveredTopicPartitions is documented); IcebergStreamSplitEnumerator.java:60-65, 174-257 (every new field and method, including no note that snapshotState deliberately skips stateLock in the managed lane); FakeDataGenerator.java:142; FakeSourceSplit.java:33 (totalRowNum vs rowNum — total vs remaining; given Issue 6 that omission is load-bearing). All are coordinator-thread-confined or hot-path members — exactly the category the rules say must carry an ownership/constraint comment.

2.2 Test Coverage and Test Stability

Stability rating: Risk present.

Positive: the new unit tests contain no Thread.sleep, no wall-clock assertions, no shared static state, no hard-coded ports and no unseeded randomness — I scanned every new test file. The E2E uses Awaitility.await().atMost(2, MINUTES).untilAsserted(...) rather than sleeps (ManagedSourceRuntimeIT.java:122-138), which is the right pattern. The SourceSplitEnumeratorTaskTest diff is purely additive Mockito stubbing; I diffed it line by line against apache/dev and can confirm no existing test or assertion was weakened anywhere in this PR.

Risk evidence: ManagedSourceRuntimeIT.java:86-88 is order-dependent on an accumulating shared container log (Issue 27) and can pass without proving what it claims; :109-114 can only fail if the message reaches container stdout; and ~3,600 lines of owner-loop logic have no direct unit test while the E2E has never run in CI (Issue 26).

2.3 Documentation Updates

Both docs/en and docs/zh are added with matching content, sidebars.js is updated, and the operator guidance (rollout order, stop conditions, production-gate matrix) is unusually thorough. Three corrections: the lane-persistence claim is wrong in three places (Issue 3), the metric suffix is wrong (Issue 24), and there is no docs/en/introduction/concepts/incompatible-changes.md entry for the managed/legacy restore gate, the capability-digest gate, or the SourceConfig serialization change (Issue 25).

3. Architectural Soundness

3.1 Elegance of the Solution

Long-term solution, correctly shaped, incompletely executed. The architecture is the right one: a versioned capability handshake, an explicit non-Java wire format with stable codes and checksums, an engine-owned assignment ledger with an explicit ownership state machine, engine-owned bounded pools instead of connector threads, and a hard fail-closed boundary between lanes. Requiring the coordinator lane whenever the reader lane is on (so barriers and checkpoint callbacks share one ordered domain) is the correct simplification, and rejecting usesSourceEvents connectors at selection time rather than at first event is exactly right. The gap is that the steady-state path is well developed while the transition paths — shutdown, restore, cancel, epoch change — are not; Issues 1, 2, 8 and 21 are all transitions.

3.2 Maintainability

Two 1,700–1,900 line classes with hand-rolled event loops, mailbox, retry/deadline machine, chunking and thread-ownership assertions is a lot of surface to carry. Defensible for this problem, but it raises the bar on tests — and those two classes currently have none. The checkOwner() pattern is my main structural concern: a lazy first-caller-wins bind is silently correct in the common case and silently wrong in exactly the cases that matter (Issues 2 and 9). An explicit attachToOwnerLoop() called once from the first runOneTurn(), with an "owner not yet attached" error for earlier callers, would make both impossible by construction — and would also close the related trap where a connector calling getCoordinatorScheduler() or isAssignmentCapacityAvailable() from enumerator.open() binds ownership to the restore thread, which the new CoordinatorScheduler API actively invites.

3.3 Extensibility

Good. runtimeProtocolVersion + connectorStateVersion + capabilityDigest give three independent evolution axes, wire codes are explicit, the serializers are versioned with magic + checksum, and TaskDataSerializerHook IDs are append-only. Adding a versioned SourceEvent codec in protocol v2 is a clean additive step. The one gap is that a capability-flag change is currently an unrecoverable restore break with no migration story (see 1.2).

3.4 Historical-Version Compatibility

Covered in 1.2: the SPI is fully compatible; the restore and deployment paths are not (Issues 3, 6, 25), and none of it is documented as incompatible.

4. Issue Summary

No. Issue Location Sev
1 Enumerator deadlocks in PREPARE_CLOSE; control events never drained SourceSplitEnumeratorTask.java:466 High
2 Restore binds assignment-tracker owner to the restore thread; all managed restores fail ManagedSourceCoordinatorRuntime.java:594, SourceAssignmentTracker.java:345 High
3 Lane selection re-derived from live config, not persisted; rollback invalidates checkpoints PhysicalPlanGenerator.java:612, JobMaster.java:289 High
4 Iceberg declares supportsAsyncEnumerator but BOUNDED path blocks IcebergSource.java:136,165 High
5 Managed ops swallow all exceptions into unlogged STALE_TARGET -> silent retry loop ManagedSourceCommandOperation.java:70 +2 High
6 FakeSourceSplit identity widened; pre-PR restore duplicates splits (legacy lane) FakeSourceSplit.java:24 High
7 Watchdog interrupt() outside the lock; no re-validation; flag never cleared ManagedSourceReaderRuntime.java:601 High
8 Barrier after CANCEL -> snapshotState() on cancelled reader -> FAILED not CANCELED ManagedSourceReaderRuntime.java:402 High
9 Thread-identity guards break under ThreadShareMode.ALL ManagedSourceCoordinatorRuntime.java:1643 +2 High
10 Epoch/attempt/closed read cross-thread without volatile ManagedSourceReaderRuntime.java:114,235 Med
11 Deferred split request dropped when the reader is not ready ManagedSourceCoordinatorRuntime.java:1410 Med
12 enumerator.run() inline on the drain thread blocks all barriers SourceSplitEnumeratorTask.java:445 Med
13 Kafka managed discovery fails the job on transient errors, never re-arms KafkaSourceSplitEnumerator.java:581 Med
14 Kafka managed lane applies end_offsets_timestamp outside TIMESTAMP mode KafkaSourceSplitEnumerator.java:749 Med
15 restoreMetadata() lacks owner check and idempotence guard ManagedSourceReaderRuntime.java:194 Med
16 close() not failure-atomic; budget release throws on cleanup -> worker-wide leak ManagedSourceMemoryBudget.java:53 Med
17 Per-reader containsAll replays partially covered ledger entries SourceAssignmentTracker.java:257 Med
18 Transport retry maps leak on reader replacement ManagedSourceCoordinatorRuntime.java:1172 Med
19 Checkpoint ack no longer joined; failure thrown inside whenComplete and swallowed SeaTunnelTask.java:484 Med
20 Per-turn metrics update double-locks and scans the mailbox ManagedSourceReaderRuntime.java:392 Med
21 Epoch rebase unimplemented; resetForEpoch/awaitSignal dead; idleness a fixed sleep ManagedSourceReaderRuntime.java:740 Med
22 Enumerators close clients while async discovery may be in flight KafkaSourceSplitEnumerator.java:286 Med
23 pollNextManaged inherited by CDC readers without their pollNext semantics SourceReaderBase.java:61 Med
24 Metric names embed the task attempt; contradicts docs and own Javadoc; hits legacy lane SourceRuntimeMetrics.java:158 Med
25 SourceConfig +5 fields, no serialVersionUID; no incompatible-changes.md entry SourceConfig.java:23-80 Med
26 No unit tests for the 3,600 lines of owner-loop logic; CI never ran them at this head new UT dir, ManagedSourceRuntimeIT.java Med
27 E2E lane assertion order-dependent on an accumulating shared container log ManagedSourceRuntimeIT.java:86 Med
28 Managed lane never sets SourceFlowLifeCycle.prepareClose SourceFlowLifeCycle.java:618 Med
29 requestSplit() before the epoch handshake throws ManagedSourceReaderRuntime.java:1076 Med
30 Grouped low-severity items (a–q) see Issue 30 Low

5. Merge Recommendation

Conclusion: Not recommended for merge

To be clear about what that means: I am not rejecting the design. The architecture is well shaped, the SPI compatibility discipline is genuinely careful, and the operator documentation is better than most features in this repo ship with. This is about the current head being demonstrably non-functional on its own primary paths, plus two regressions that escape the isolation the PR claims. The PR is also still a Draft with all of the author's own graduation gates unmet, so read this as maintainer input on the increment rather than a merge decision.

1. Blockers — must be fixed

  • Issue 1 (High) — managed enumerator deadlocks in PREPARE_CLOSE; no managed bounded job can complete and no savepoint can finish. This alone means the feature does not work end to end today.
  • Issue 2 (High) — coordinator restore poisons the assignment tracker's owner thread; no managed job can recover from any checkpoint or savepoint. The code's own Javadoc, two lines above the offending call, states the invariant being broken.
  • Issue 3 (High) — lane selection is re-derived from live cluster config on every JobMaster#init, so following the PR's own documented rollback step permanently invalidates in-flight managed checkpoints. Persist the selection with the job and correct the three doc claims.
  • Issue 4 (High) — Iceberg's capability declaration does not match its bounded enumerator. The capability object is the engine's only conformance gate; it must not lie.
  • Issue 5 (High) — the three managed operations convert every exception, including programming errors, into an unlogged STALE_TARGET: an undiagnosable retry loop in one direction, spurious fatal failures in the other.
  • Issue 6 (High) — FakeSourceSplit's widened equals/hashCode duplicates splits when restoring a pre-PR checkpoint. This is on the legacy lane and is not gated by the feature flag, contradicting the isolation claim.
  • Issue 7 (High) — the watchdog can deliver an interrupt to an unrelated task under ThreadShareMode.ALL/PART and never clears the flag.
  • Issue 8 (High) — a barrier queued behind CANCEL calls snapshotState() on a cancelled reader and reports FAILED instead of CANCELED.
  • Issue 9 (High) — the thread-identity guards are incompatible with the supported ThreadShareMode.ALL. At minimum, reject the combination explicitly.
  • Issue 26 (Medium, but treat as a gate) — CI has never executed the new unit tests or ManagedSourceRuntimeIT at this head. The Build failure is an unrelated pre-existing Windows flake in MultiTableSinkWriterSchemaChangeBroadcastTest (seatunnel-api, not touched here) that fail-fast-cancelled every ubuntu and IT job. A green head is a precondition for any further review round — and Issues 1 and 2 predict ManagedSourceRuntimeIT will not pass once it does run. Please also add direct unit tests for the two owner loops; every High above except 3, 4 and 6 lives in code with no test at all.

Also: mergeStateStatus is DIRTY / mergeable is CONFLICTING. The conflict is confined to docs/sidebars.js, which is mechanical, but the branch needs a rebase before CI results mean anything.

2. Recommended fixes — non-blocking

Issues 10–25 and 27–29 should be addressed before the feature graduates from experimental; several (10, 11, 16, 17, 18, 19) are latent correctness or leak issues that will be much harder to diagnose once the lane is enabled anywhere. Issue 30 is cleanup.

On @nzw921rx's point about the connector allowlist — I partly agree, and my own analysis strengthens the concern rather than the switch. I would keep an explicit allowlist: for an experimental engine change of this size an operator gate separate from what the connector claims is worth having, and the "fail fast if the connector doesn't support it" behavior you ask for is already implemented (ManagedSourceRuntimeSelector.java:32-39 throws when an allowlisted connector declares no managed capability). But the deeper worry — that this knob's semantics are weaker than they look — is correct, and Issue 3 is the concrete reason: because the lane is re-derived from that same config on every restore, the allowlist silently gates checkpoint recoverability rather than being a rollout convenience. Persisting the selection with the job (Issue 3's fix) is what makes the switch safe to keep, so I would resolve the comment that way rather than by removing the switch.

Overall assessment

The right architecture, roughly 80% built. What is missing is the transition machinery — shutdown, restore, cancel, epoch change — which is exactly where Issues 1, 2, 8 and 21 sit. My strong suspicion is that these survived because the lane has never actually run: the E2E that would exercise all four has never executed in CI.

I do not think there is a materially better Option B for the overall design. Splitting the delivery would help a lot, though. This PR bundles (a) legacy-lane observability instrumentation, (b) the new SPI surface, (c) the engine runtime, and (d) three connector pilots. Landing (a) and (b) first — both small, additive and independently reviewable — would shrink (c) to something a maintainer can hold in their head and let the pilots land one at a time behind an already-proven runtime. It would also have surfaced Issues 6 and 24, both legacy-lane changes currently hidden inside a 15,000-line managed-lane PR.

One structural suggestion that prevents two Highs by construction rather than convention: replace the lazy checkOwner() first-caller-wins bind with an explicit attachToOwnerLoop() invoked once from the first runOneTurn(), and have the guards throw a clear "coordinator loop has not started" error for any earlier caller. That closes Issue 2, makes Issue 9 diagnosable, and removes the trap where a connector touching the new CoordinatorScheduler API from enumerator.open() silently binds ownership to the wrong thread.

Thanks for the care that went into the documentation and the compatibility gating — the fail-closed posture and the explicit capability handshake are the right instincts, and they are why the remaining problems are localized rather than systemic.

davidzollo and others added 2 commits August 10, 2026 21:56
…Mockito stubbing

The previous fix stubbed getSeaTunnelConfig() as
when(...).thenReturn(seaTunnelConfig()) where the helper itself started a
second stubbing on a SeaTunnelConfig mock. Java evaluates the thenReturn
argument after when() has opened a stubbing and before thenReturn closes
it, so the nested when() threw UnfinishedStubbingException and failed all
four tests deterministically. Earlier CI attempts never reached this
module because unrelated modules failed first, which masked the bug until
attempt 4.

Use a real, default-constructed SeaTunnelConfig instead of a mock. Its
EngineConfig is an inline field initializer whose managed-source config
defaults to the disabled legacy lane, and the constructor only builds an
in-memory Hazelcast Config without loading YAML, so no stubbing is needed
at all.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

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. Zeta splits ownership of Source concurrency between the engine and every connector author: the collector loop calls SourceReader#pollNext under a connector-owned checkpoint lock, split assignment and reader registration travel through Hazelcast operation threads that end up executing connector code, and enumerator discovery is whatever each connector chose. The resulting failure classes are checkpoint-lock stalls, operation threads blocked by slow connector code, and ambiguous split ownership across failover.
  • Fix approach. An opt-in "managed" lane alongside the "legacy" lane in which the engine owns all checkpoint-visible Source state: a reader and a coordinator event loop per Source, a versioned command envelope with checksums/sequencing/attempt fencing between them, an engine-owned split-assignment ledger (DISPATCHED -> ADMITTED -> APPLIED -> CHECKPOINT_INCLUDED), explicit non-Java checkpoint serializers, and a bounded CoordinatorScheduler for blocking discovery. A connector leaves the legacy lane only when the feature is enabled, its plugin name is explicitly allowlisted, and it declares a matching versioned ManagedSourceCapability. Fake, Kafka (reader + coordinator) and Iceberg (coordinator only) are the pilots.
  • One-sentence summary. Same conclusion as my last round: this is a well-shaped, disabled-by-default second Source execution lane whose steady-state protocol is careful, but whose shutdown, restore, cancel and error-reporting paths are still broken, and CI has still never run the one test that would prove otherwise.

Re-review note

Two commits landed since my last review (head 9c2ffde8): a test-only fix (75baafb15, rewrites a Mockito helper in SourceSplitEnumeratorTaskTest that had an UnfinishedStubbingException) and a merge from dev (2da2feed6) that resolves a conflict in docs/sidebars.js. I diffed 9c2ffde8..2da2feed6 restricted to seatunnel-engine, seatunnel-connectors-v2, seatunnel-api and seatunnel-e2e, and separately git diff dev...HEAD for just the test file: the only production or test-behavior change in this window is the 19-line Mockito fix. Every other file that shows up in a naive diff between the two heads (e.g. IcebergSinkCDCIT.java, Flink20Container.java, the new hugegraph E2E fixtures) came in from dev itself and is not part of dev...HEAD — i.e. not part of this PR's diff at all. I re-verified this by re-reading the current source at the exact line numbers cited in my prior High-severity findings (Issues 1, 2, 3, 6, 7 below) rather than re-deriving them from scratch, and all five are present byte-for-byte as before. Given that, I am carrying forward the full finding set from my 4896649794 review with re-verified locations, rather than re-doing a blind full re-read of 15,000 lines that I already know did not change. I found no new issue this round, so there is no carryover apology needed this time — everything below was already on record.

What did change materially is CI, and it changed for the better in one place and is still inconclusive in the place that matters most. See section 1.4 / Issue 26.

1. Code Change Review

1.1 Core Logic Analysis

Scope of this round. Full re-verification against current line numbers for every High-severity issue (1–9); the Medium/Low issues (10–30) are carried forward from the 4896649794 full read since the underlying files are unchanged, and I additionally re-confirmed the diff boundary claim above with git diff rather than trusting the PR's own commit messages.

Runtime path for the two worst bugs (Issues 1 and 2), unchanged from last round:

Bounded managed job, normal shutdown (Issue 1):
  readers finish -> managedReaderFinished() sets prepareCloseStatus
    -> SourceSplitEnumeratorTask: RUNNING -> PREPARE_CLOSE
    -> master triggers final checkpoint barrier
    -> triggerBarrier() -> admitBarrier(barrier)   [enqueue only]
    -> PREPARE_CLOSE case: closeCalled? no -> Thread.sleep(100) [loops forever]
    -> managedCoordinatorRuntime.runOneTurn() is NEVER called from PREPARE_CLOSE
    -> queued barrier is never drained/applied
    -> enumerator never ACKs -> checkpoint never completes
    -> notifyCheckpointComplete() never fires -> closeCalled never set
    -> job spins until checkpoint timeout fails it

Managed job restore-from-checkpoint (Issue 2):
  NotifyTaskRestoreOperation runs on a TaskExecutionService pool thread (never the task's own thread)
    -> SourceSplitEnumeratorTask.restoreState()
    -> ManagedSourceCoordinatorRuntime.restoreRuntimeState(bytes)
       [Javadoc: "Deliberately does not call checkOwner() ... the caller's
        restore-operation thread is never the task's own execution thread"]
    -> assignmentTracker.restore(...)
       -> SourceAssignmentTracker#restore() calls checkOwner() FIRST LINE
       -> binds ownerThreadId to the transient pool thread
    -> job proceeds to RUNNING; owner loop's first real touch
       (markRestoredSplitsIncluded / applyBarrier / takeAssignmentsForMissingReaders)
    -> checkOwner() throws "accessed outside its coordinator event loop"
    -> job retries into the same failure forever

Key findings (unchanged from last round, re-verified):

  1. The disabled-by-default gating is real: ManagedSourceRuntimeSelector.select returns legacy() before ever touching getManagedSourceCapability() when the feature is off or the allowlist is empty, the default enabled is false, and the shipped seatunnel.yaml sets enabled: false with an empty allowlist. Every SPI addition is a default method, so this remains genuinely safe for every existing connector today.
  2. The transition paths — shutdown, restore, cancel, epoch change — are still broken, and are exactly the paths a disabled-by-default feature's own test suite has never been able to exercise, because that suite has never finished running in CI (see Issue 26 update below).
  3. Two changes still reach the legacy lane despite the "isolated compatibility lane" framing: FakeSourceSplit's widened equals/hashCode (Issue 6) and the per-attempt metric cardinality (Issue 24).
  4. docs/sidebars.js merge conflict from my last review is resolved cleanly — engines/zeta/managed-source-runtime is correctly present in the sidebar, and mergeStateStatus is now MERGEABLE/no conflict (it was DIRTY/CONFLICTING at my last review). That specific note from my prior "Also:" callout is closed.
  5. Nothing in the actual runtime, SPI, connector or serializer code changed, so every Medium/Low finding from the last round (Issues 10–25, 27–30) applies unmodified at the current head; I re-point their locations below without re-litigating the analysis, since re-deriving conclusions from unchanged source would not add information.

1.2 Compatibility Impact

Classification: Partially incompatible. Unchanged from last round — nothing that bears on compatibility was touched.

Compatible: SeaTunnelSource#getManagedSourceCapability and the three new SourceSplitEnumerator.Context methods are all default, so every existing connector and the Flink/Spark translation Context implementations still compile with legacy behavior. TaskDataSerializerHook IDs 29–32 are append-only. SourceReaderBase implements ManagedSourceReader does not drag CDC/Fluss into the managed lane — selection is capability-driven, and neither IncrementalSourceReader nor FlussSourceReader declares a colliding method.

Incompatible or partially incompatible (all still present, re-verified against current line numbers):

  • Lane flip on restore (Issue 3). SourceConfig.runtimeMode is not persisted; JobMaster#init (JobMaster.java:288-300) unconditionally calls PlanUtils.fromLogicalDAG(..., engineConfig) with the live cluster EngineConfig on every init, including restore and master failover, and PhysicalPlanGenerator#managedSourceSelection (PhysicalPlanGenerator.java:611-634) recomputes the lane from it every time. The new code comment at that call site ("decided once, here, and then persisted with the physical plan") describes only the per-generation cache (computeIfAbsent), not cross-restart persistence — the physical plan itself is regenerated from the logical DAG on every init, so nothing survives a restart. Changing enabled or the allowlist between a checkpoint and a restore still permanently invalidates that checkpoint.
  • Capability digest is a hard restore gate, correct fail-closed behavior but still with no documented migration path and no incompatible-changes.md entry.
  • FakeSourceSplit identity change (Issue 6) still breaks restore of pre-PR FakeSource checkpoints on the legacy lane, confirmed present verbatim at FakeSourceSplit.java:24-43 (@Data regenerates equals/hashCode over totalRowNum, serialVersionUID unchanged).
  • SourceConfig still has 5 fields with no explicit serialVersionUID (Issue 25).

1.3 Performance / Side-Effect Analysis

Unchanged from last round; every item was in code that did not move:

  • The managed reader's idle wait is still a fixed Thread.sleep(idleWaitMillis) (default 10 ms); ReaderCommandMailbox#awaitSignal still has no callers (Issue 21).
  • updateMetrics() still runs in the finally of every turn, taking admissionLock plus the mailbox lock three more times and doing an O(mailbox) scan (Issue 20).
  • The legacy lane still pays for SourceRuntimeMetrics whenever observability is on, and for an unconditional setAvailabilityNotifier on the SplitFetcher hot path (Issue 30f).

1.4 Error Handling and Logging

The systemic problem is unchanged: the new lane's failure signalling is asymmetric and, in the coordinator-to-reader direction, silent. All issues below are carried forward from my 4896649794 review with re-verified path:line locations; none has been touched by the two commits since then. I am keeping the original numbering so this stays diffable against the previous review rather than renumbering for no reason.


Issue 1 — Managed Split Enumerator task deadlocks in PREPARE_CLOSE; no managed bounded job can ever finish

Location: SourceSplitEnumeratorTask.java:466-472 (with :420-484, :620-624) — Severity: High — Status: still open, re-verified this round

In the managed lane every inbound control path is enqueue-only: triggerBarrier becomes admitBarrier(barrier) (:188-192), notifyCheckpointComplete becomes admitCheckpointComplete(...) (:521-527). The queue is drained only by managedCoordinatorRuntime.runOneTurn(), which has exactly two call sites in this class: WAITING_RESTORE and RUNNING. PREPARE_CLOSE is still just if (closeCalled) { currState = CLOSED; } else { Thread.sleep(100); } — confirmed unchanged at the current head.

The only setter of closeCalled on the managed path is managedCheckpointCallbackFinished, reached only from applyCheckpointComplete/applyCheckpointAborted inside the runtime, i.e. only from a drained control event.

Runtime path. Bounded job: readers finish -> RUNNING -> PREPARE_CLOSE -> master triggers the final checkpoint -> the barrier is admitted but never applied -> the enumerator never acks -> the checkpoint never completes -> closeCalled never set -> the task spins on Thread.sleep(100) until checkpoint timeout fails the job.

Fix: drain in PREPARE_CLOSE — if (isManagedCoordinatorRuntime() && !managedCoordinatorRuntime.runOneTurn()) { Thread.sleep(100); } before the closeCalled test. Add a UT driving stateProcess() through RUNNING -> PREPARE_CLOSE -> CLOSED with a queued barrier.


Issue 2 — Coordinator restore poisons SourceAssignmentTracker's owner thread; every managed restore-from-checkpoint job fails

Location: ManagedSourceCoordinatorRuntime.java:594; SourceAssignmentTracker.java:345-346, 453-461 — Severity: High — Status: still open, re-verified this round

restoreRuntimeState's own Javadoc states the invariant precisely ("Deliberately does not call checkOwner()... the caller's restore-operation thread is never the task's own execution thread"), and two lines into the body it does exactly that, one object down: assignmentTracker.restore(...), and SourceAssignmentTracker#restore opens with checkOwner() — a lazy first-caller-wins bind. I re-read both methods verbatim at the current head; nothing here moved.

restoreState runs on a TaskExecutionService async pool thread, never the task's own thread, so the tracker binds to a transient pool thread. The first access from the real owner loop then throws "SourceAssignmentTracker accessed outside its coordinator event loop", and the job retries into the same failure forever.

Risk: no managed job can recover from any checkpoint. Fix: mirror the resolution already applied to the runtime object — either a restoreWithoutOwnerCheck(...) used only here, or have restore() set ownerThreadId = null as its last statement so the first owner-loop call rebinds.


Issue 3 — Lane selection is re-derived from live cluster config on every JobMaster#init, not persisted; the documented rollback permanently invalidates in-flight managed checkpoints

Location: PhysicalPlanGenerator.java:611-634; JobMaster.java:288-300; SourceFlowLifeCycle.java:796-818; SourceSplitEnumeratorTask.java:244-262; docs/en/engines/zeta/managed-source-runtime.md — Severity: High — Status: still open, re-verified this round

The docs still claim the opposite of what the code does (lane selection "frozen in the physical plan and persisted in checkpoint metadata"). There is still no persisted physical plan: JobMaster#init regenerates it from the logical DAG on every init via PlanUtils.fromLogicalDAG(logicalDag, ..., engineConfig), and PhysicalPlanGenerator#managedSourceSelection recomputes the lane from the live EngineConfig every time. I checked whether the new logging added around this call site (which I had not specifically quoted last round) changes the persistence story — it does not; it only logs the selection, it does not stamp it anywhere durable. The digest is persisted and validated, but only after the lane has already been (re-)chosen.

Runtime path. An operator sets enabled: false per the PR's own "disable selection for new deployments immediately" guidance. The setting is cluster-global. On the next restore of any in-flight managed job, select() returns LEGACY and SourceFlowLifeCycle#restoreState fails closed. That checkpoint is now unusable until the allowlist is restored byte-identically.

Fix: stamp ManagedSourceRuntimeSelection into JobImmutableInformation (or the job's checkpoint metadata) at first submission, and have PhysicalPlanGenerator prefer it when present, consulting live config only for a brand-new job. Then correct the doc claims.


Issue 4 — IcebergSource declares supportsAsyncEnumerator(true) unconditionally, but the BOUNDED path still returns the untouched, blocking IcebergBatchSplitEnumerator

Location: IcebergSource.java:136-142, 149-163, 165-173 — Severity: High — Status: still open (files unchanged; not re-read line-by-line this round, no reason to expect drift given the diff-boundary proof above)

createEnumerator/restoreEnumerator still return IcebergBatchSplitEnumerator whenever Boundedness.BOUNDED, while getManagedSourceCapability() still declares supportsManagedCoordinator(true) and supportsAsyncEnumerator(true) unconditionally. IcebergBatchSplitEnumerator is untouched by this PR and still blocks under stateLock.

Fix: adapt IcebergBatchSplitEnumerator as the stream enumerator was, or restrict the capability declaration to !Boundedness.BOUNDED.equals(getBoundedness()).


Issue 5 — All three managed Hazelcast operations collapse every exception into STALE_TARGET with no logging, producing a silent infinite re-registration loop

Location: ManagedSourceCommandOperation.java:70-78; ManagedCoordinatorCommandOperation.java:72-80; ManagedSourceRegisterOperation.java:107-109; consumed at ManagedSourceCoordinatorRuntime.java:1232-1238 — Severity: High — Status: still open

Unchanged: each runInternal() wraps admission in catch (Exception e) and answers a fixed STALE_TARGET, none logs the throwable, and the reverse direction is inconsistent — the reader treats STALE_TARGET as fatal, so a transient absence of the coordinator task during legitimate failover hard-fails the reader instead of retrying.

Fix: log the throwable at ERROR in all three catch blocks; add an INTERNAL_ERROR status for unexpected exceptions, fatal on both sides; reserve STALE_TARGET for a genuinely missing/replaced attempt.


Issue 6 — FakeSourceSplit widens equals/hashCode via @Data while keeping serialVersionUID, duplicating every assigned split when restoring a pre-PR checkpoint (legacy lane, not gated)

Location: FakeSourceSplit.java:24-43; FakeSourceSplitEnumerator.java:112-141 — Severity: High — Status: still open, re-verified this round with a full re-read of the file

I re-read the file at the current head. @Data still regenerates equals/hashCode over all non-static fields including the new totalRowNum, serialVersionUID is still the same -3321891887156360959L, and the restore reconciliation in FakeSourceSplitEnumerator is still a HashSet difference over these objects. This fires on the legacy lane, unconditionally on the feature flag — it is the clearest example of the PR's "isolated compatibility lane" claim not holding.

Fix: @EqualsAndHashCode(of = {"tableId", "splitId"}) on the class.


Issue 7 — Poll watchdog delivers interrupt() outside the lock with no re-validation; the interrupt can land on an unrelated task and is never cleared

Location: ManagedSourceReaderRuntime.java:601-639 — Severity: High — Status: still open, re-verified this round with a full re-read of the method

I re-read checkActivePoll() at the current head: it still decides under synchronized (pollWatchdogLock), captures threadToInterrupt = ownerThread inside the lock, but still calls threadToInterrupt.interrupt() after the lock is released with no re-check that the poll it targets is still running. Under ThreadShareMode.ALL/PART the owner can be a shared CooperativeTaskWorker thread fed from the service-wide queue, so a late interrupt can land inside a different job's task. There is still no Thread.interrupted() anywhere in the class.

Fix: hold pollWatchdogLock across the interrupt() and re-assert the poll generation immediately before firing; clear the interrupt flag in pollManagedReader's finally when the poll was the cancelled one.


Issue 8 — A barrier admitted before CANCEL turns a clean cancel into a job failure and calls snapshotState() on a cancelled reader

Location: ManagedSourceReaderRuntime.java:397-426, 729-733, 776-812; ManagedSourceLifecycle.java:290-307 — Severity: High — Status: still open

Unchanged: runOneTurnInternal only stops on isFailed(), which does not include CANCELLING; a barrier queued behind CANCEL is still drained, applyBarrier still calls snapshotState() on a cancelled reader, and the Snapshot constructor still rejects CANCELLING, so the task ends FAILED instead of CANCELED.

Fix: short-circuit in applyBarrier/pollNextReadyEvent once lifecycle.isTerminal(), discarding queued snapshot barriers.


Issue 9 — The three thread-identity guards break under ThreadShareMode.ALL

Location: ManagedSourceCoordinatorRuntime.java:1643-1651; ManagedCoordinatorScheduler.java:571-579; SourceAssignmentTracker.java:453-461; against TaskExecutionService.java:650-663, 1316-1319, 1386-1388 — Severity: High — Status: still open

Unchanged: all three guards use first-caller-wins thread identity, which breaks once CooperativeTaskWorker re-queues the task onto a shared deque under ThreadShareMode.ALL. No guard, no validation, no test covers this documented, supported configuration.

Fix (minimal): force managed-lane Source and enumerator tasks onto the blocking submission path regardless of ThreadShareMode, and reject the combination explicitly at selection time.


Issues 10–25, 27–29 — carried forward unchanged (Medium)

None of the underlying files changed between my last review and this head, so I am not re-typing the full analysis; only the location index, for traceability:

# Issue Location
10 Epoch/attempt/closed read cross-thread without volatile ManagedSourceReaderRuntime.java:114,235
11 Deferred split request dropped when the reader is not ready ManagedSourceCoordinatorRuntime.java:1410
12 enumerator.run() inline on the drain thread blocks all barriers SourceSplitEnumeratorTask.java:445
13 Kafka managed discovery fails the job on transient errors, never re-arms KafkaSourceSplitEnumerator.java:581
14 Kafka managed lane applies end_offsets_timestamp outside TIMESTAMP mode KafkaSourceSplitEnumerator.java:749
15 restoreMetadata() lacks owner check and idempotence guard ManagedSourceReaderRuntime.java:194
16 close() not failure-atomic; budget release throws on cleanup -> worker-wide leak ManagedSourceMemoryBudget.java:53
17 Per-reader containsAll replays partially covered ledger entries SourceAssignmentTracker.java:257
18 Transport retry maps leak on reader replacement ManagedSourceCoordinatorRuntime.java:1172
19 Checkpoint ack no longer joined; failure thrown inside whenComplete and swallowed SeaTunnelTask.java:484
20 Per-turn metrics update double-locks and scans the mailbox ManagedSourceReaderRuntime.java:392
21 Epoch rebase unimplemented; resetForEpoch/awaitSignal dead; idleness a fixed sleep ManagedSourceReaderRuntime.java:740
22 Enumerators close clients while async discovery may be in flight KafkaSourceSplitEnumerator.java:286
23 pollNextManaged inherited by CDC readers without their pollNext semantics SourceReaderBase.java:61
24 Metric names embed the task attempt; contradicts docs and own Javadoc; hits legacy lane SourceRuntimeMetrics.java:158
25 SourceConfig +5 fields, no serialVersionUID; no incompatible-changes.md entry SourceConfig.java:23-80
27 E2E lane assertion order-dependent on an accumulating shared container log ManagedSourceRuntimeIT.java:86
28 Managed lane never sets SourceFlowLifeCycle.prepareClose SourceFlowLifeCycle.java:618
29 requestSplit() before the epoch handshake throws ManagedSourceReaderRuntime.java:1076
30 Grouped low-severity items (dead code, wire/state hygiene, error handling, thread-safety, perf, style) see prior round

Issue 26 (updated this round) — Test coverage does not reach the two classes that hold the risk, and CI has still never executed the managed-lane E2E to completion

Location: seatunnel-engine-server/src/test/java/.../task/source/ (new UTs); ManagedSourceRuntimeIT.java; CI run for head 2da2feed6 — Severity: Medium, treated as a merge gate — Status: partially improved, core gap still open

What improved. All four unit-test matrix jobs (Java 8/11 x ubuntu/windows) now pass, including the Windows job whose MultiTableSinkWriterSchemaChangeBroadcastTest failure previously fail-fast-cancelled most of the matrix. That confirms the 75baafb15 Mockito fix works and this specific CI blocker from my last review is closed.

What is still open, and why. I pulled the fork's own Actions run for the current head (https://github.com/DanielLeens/seatunnel/actions/runs/31451018144, which the apache-side "Build" check for this PR points to). Two jobs failed directly, and both are unrelated to this PR:

  • all-connectors-it-8 (11, ubuntu-latest): IcebergSinkCDCIT.testMysqlCdcCheckDataE2e failed with ParameterResolutionException — the test container setup's wget for zstd-jni-1.5.5-5.jar from repo1.maven.org got "Unable to establish SSL connection" (exit code 4). This is a network flake in a container-provisioning script, not a code path this PR touches — IcebergSinkCDCIT.java is not part of dev...HEAD for this PR at all (it was modified independently on dev and merged in unchanged by this PR).
  • all-connectors-it-3 (8, ubuntu-latest): PostgresCDCIT.testPostgresCdcSnapshotOnlyAndCommittedOffsetStartupModes failed with org.awaitility.core.ConditionTimeoutException: expected: <1> but was: <0> within 1 minutes. connector-cdc-postgres is untouched by this PR's diff, and Postgres CDC readers stay on the legacy lane unconditionally (they never declare a managed capability), so this cannot be an effect of the change under review either.

Both of those are exactly the class of pre-existing CI flakiness my last review already flagged for the Windows unit-test job — infrastructure noise, not this diff.

The part that matters: both engine-v2-it (8, ubuntu-latest) and engine-v2-it (11, ubuntu-latest) — the only jobs that build and run ManagedSourceRuntimeIT, the sole end-to-end test of the managed lane's shutdown and restore paths — show conclusion: cancelled in this run, not success or failure. The total run took 6h16m for the "Build" umbrella check, which is suspiciously close to GitHub Actions' 6-hour per-job execution ceiling; my best supported inference (not a directly observed fact) is that the two connectors-it jobs ran long via Maven's reactor "banned from build" retries after their failures, and the workflow's overall budget was exhausted before engine-v2-it could complete, so GitHub cancelled it rather than letting it finish. I could not confirm the exact GitHub-side mechanism from the API alone, so I am flagging this as inference, not fact — but the observable fact that matters for this review is unambiguous either way: at every head of this PR to date, including this one, ManagedSourceRuntimeIT has never completed in CI.

That means Issues 1 and 2 above — a deadlock that stops every managed bounded job from finishing, and a poisoned owner-thread bind that breaks every managed restore — are still completely unverified by CI in either direction, in the one test suite designed to catch exactly them. I stand by my source-level tracing of both bugs (re-verified this round against the current head), but "the code says X will happen" and "CI confirmed X happens" are different levels of evidence, and this PR still only has the former for its two most severe findings.

Fix: same as before — add direct owner-loop unit tests for ManagedSourceReaderRuntime/ManagedSourceCoordinatorRuntime that do not depend on the flaky, slow, unrelated all-connectors-it jobs finishing first, and get a ManagedSourceRuntimeIT run to completion (success or failure) on this head. Right now the CI graph structure means an unrelated Iceberg/Postgres CDC problem can starve the one test that would tell us whether Issues 1 and 2 are real in practice, not just on paper.


2. Code Quality Assessment

2.1 Coding Standards

Unchanged from last round: formatting, ASF headers, imports and logging are clean, and comment quality is above average for this repo. The same two problems stand:

  • Comments that assert invariants the code then violates — ManagedSourceCoordinatorRuntime.java:578-583 says ownership must not be bound on the restore thread, and two lines later it is (Issue 2); SourceRuntimeMetrics.java:26-33 claims bounded cardinality while embedding the attempt id (Issue 24); SourceAssignmentTracker#restore and ReaderCommandMailbox#resetForEpoch both document behavior that does not exist (Issue 21). I would add one more from this round's re-read: the new comment at PhysicalPlanGenerator.java around the managedSourceSelection call site ("decided once, here, and then persisted with the physical plan") reads as a persistence claim but the physical plan is regenerated from scratch on every JobMaster#init — this is the same class of problem as Issue 3, on the comment that documents it.
  • Missing documentation on new non-trivial members — unchanged list from last round (SourceReaderBase.java:73-75, SplitFetcherManager.java:58,154-164, FetchTask.java:44,65, KafkaSourceSplitEnumerator.java:88-92 and every new managed method there, IcebergStreamSplitEnumerator.java:60-65,174-257, FakeDataGenerator.java:142, FakeSourceSplit.java:33).

2.2 Test Coverage and Test Stability

Stability rating: Risk present. Unchanged from last round for the reasons already given (no Thread.sleep/wall-clock/shared-static/hard-coded-port/unseeded-randomness patterns in any new UT; the SourceSplitEnumeratorTaskTest diff, now including the Mockito fix, is purely additive against apache/dev with no weakened assertion anywhere in this PR). The Mockito fix itself is a genuine, well-explained bug fix in test infrastructure, not a weakening — it replaces a mock that could never have worked (nested when() inside a thenReturn() argument throws deterministically) with a real object that exercises the actual default config path, which if anything is a stricter test than the broken mock it replaces.

New risk evidence this round, on top of the carried-forward Issue 27 (order-dependent E2E log assertion): the engine-v2-it cancellation documented in Issue 26 above means the E2E suite's stability is still unproven, not merely "risk present" from a code-reading perspective — it has literally never been given the chance to fail or pass at any head of this PR.

2.3 Documentation Updates

Unchanged: both docs/en and docs/zh are present with matching content and sidebars.js is now correctly wired (the merge conflict from my last review is resolved). The same three corrections are still outstanding: the lane-persistence claim is wrong (Issue 3, and see the comment note in 2.1), the metric suffix claim is wrong (Issue 24), and there is still no docs/en/introduction/concepts/incompatible-changes.md entry for the managed/legacy restore gate, the capability-digest gate, or the SourceConfig serialization change (Issue 25).

3. Architectural Soundness

3.1 Elegance of the Solution

Unchanged: long-term solution, correctly shaped, incompletely executed. The architecture — versioned capability handshake, explicit non-Java wire format, engine-owned assignment ledger, engine-owned bounded pools, hard fail-closed lane boundary — is the right one. The gap remains that the steady-state path is well developed while the transition paths (shutdown, restore, cancel, epoch change) are not; Issues 1, 2, 8 and 21 are all transitions, and none of them moved this round.

3.2 Maintainability

Unchanged: two 1,700–1,900 line classes with hand-rolled event loops, mailbox, retry/deadline machine, chunking and thread-ownership assertions, currently with zero direct unit tests. The checkOwner() lazy first-caller-wins pattern remains my main structural concern (Issues 2 and 9); an explicit attachToOwnerLoop() called once from the first runOneTurn() would make both classes of bug impossible by construction rather than by convention.

3.3 Extensibility

Unchanged: good. runtimeProtocolVersion + connectorStateVersion + capabilityDigest give three independent evolution axes, wire codes are explicit, serializers are versioned with magic + checksum, TaskDataSerializerHook IDs are append-only. The one gap is still that a capability-flag change is an unrecoverable restore break with no migration story.

3.4 Historical-Version Compatibility

Covered in 1.2, unchanged: the SPI is fully compatible; the restore and deployment paths are not (Issues 3, 6, 25), and none of it is documented as an incompatible change.

4. Issue Summary

No. Issue Location Sev Status this round
1 Enumerator deadlocks in PREPARE_CLOSE; control events never drained SourceSplitEnumeratorTask.java:466 High Open, re-verified
2 Restore binds assignment-tracker owner to the restore thread; all managed restores fail ManagedSourceCoordinatorRuntime.java:594, SourceAssignmentTracker.java:345 High Open, re-verified
3 Lane selection re-derived from live config, not persisted; rollback invalidates checkpoints PhysicalPlanGenerator.java:611, JobMaster.java:288 High Open, re-verified
4 Iceberg declares supportsAsyncEnumerator but BOUNDED path blocks IcebergSource.java:136,165 High Open, unchanged file
5 Managed ops swallow all exceptions into unlogged STALE_TARGET -> silent retry loop ManagedSourceCommandOperation.java:70 +2 High Open, unchanged file
6 FakeSourceSplit identity widened; pre-PR restore duplicates splits (legacy lane) FakeSourceSplit.java:24 High Open, re-verified
7 Watchdog interrupt() outside the lock; no re-validation; flag never cleared ManagedSourceReaderRuntime.java:601 High Open, re-verified
8 Barrier after CANCEL -> snapshotState() on cancelled reader -> FAILED not CANCELED ManagedSourceReaderRuntime.java:402 High Open, unchanged file
9 Thread-identity guards break under ThreadShareMode.ALL ManagedSourceCoordinatorRuntime.java:1643 +2 High Open, unchanged file
10 Epoch/attempt/closed read cross-thread without volatile ManagedSourceReaderRuntime.java:114,235 Med Open
11 Deferred split request dropped when the reader is not ready ManagedSourceCoordinatorRuntime.java:1410 Med Open
12 enumerator.run() inline on the drain thread blocks all barriers SourceSplitEnumeratorTask.java:445 Med Open
13 Kafka managed discovery fails the job on transient errors, never re-arms KafkaSourceSplitEnumerator.java:581 Med Open
14 Kafka managed lane applies end_offsets_timestamp outside TIMESTAMP mode KafkaSourceSplitEnumerator.java:749 Med Open
15 restoreMetadata() lacks owner check and idempotence guard ManagedSourceReaderRuntime.java:194 Med Open
16 close() not failure-atomic; budget release throws on cleanup -> worker-wide leak ManagedSourceMemoryBudget.java:53 Med Open
17 Per-reader containsAll replays partially covered ledger entries SourceAssignmentTracker.java:257 Med Open
18 Transport retry maps leak on reader replacement ManagedSourceCoordinatorRuntime.java:1172 Med Open
19 Checkpoint ack no longer joined; failure thrown inside whenComplete and swallowed SeaTunnelTask.java:484 Med Open
20 Per-turn metrics update double-locks and scans the mailbox ManagedSourceReaderRuntime.java:392 Med Open
21 Epoch rebase unimplemented; resetForEpoch/awaitSignal dead; idleness a fixed sleep ManagedSourceReaderRuntime.java:740 Med Open
22 Enumerators close clients while async discovery may be in flight KafkaSourceSplitEnumerator.java:286 Med Open
23 pollNextManaged inherited by CDC readers without their pollNext semantics SourceReaderBase.java:61 Med Open
24 Metric names embed the task attempt; contradicts docs and own Javadoc; hits legacy lane SourceRuntimeMetrics.java:158 Med Open
25 SourceConfig +5 fields, no serialVersionUID; no incompatible-changes.md entry SourceConfig.java:23-80 Med Open
26 Owner-loop classes still untested; managed-lane E2E has never completed in CI, at this head for a new (unrelated-infra) reason new UT dir, ManagedSourceRuntimeIT.java Med (gate) Partially improved (unit-test flake fixed) / core gap open
27 E2E lane assertion order-dependent on an accumulating shared container log ManagedSourceRuntimeIT.java:86 Med Open
28 Managed lane never sets SourceFlowLifeCycle.prepareClose SourceFlowLifeCycle.java:618 Med Open
29 requestSplit() before the epoch handshake throws ManagedSourceReaderRuntime.java:1076 Med Open
30 Grouped low-severity items (a–q) see Issue 30 Low Open

5. Merge Recommendation

Conclusion: Not recommended for merge

I am the author of this PR, and GitHub does not let an author approve or request changes on their own pull request, so my account can only leave a comment-type review regardless of the technical conclusion below — please read this with that bias disclosed, the same way I disclosed it in my last two self-review rounds. The final call has to come from an independent maintainer with write access.

Nothing about the technical picture changed this round. Since my last review, this PR gained one test-infrastructure fix and a routine dev sync; I verified that boundary with git diff rather than taking the commit messages' word for it, and every High-severity issue I traced last time is present, unmodified, at the same or trivially shifted line numbers today. This is about the current head still being demonstrably non-functional on its own primary transition paths (shutdown, restore), plus two regressions that still escape the isolation the PR claims (Issues 6, 24) — not about the design, which remains the right shape.

1. Blockers — must be fixed

  • Issue 1 (High) — managed enumerator still deadlocks in PREPARE_CLOSE; no managed bounded job can complete and no savepoint can finish. Re-verified against the current head.
  • Issue 2 (High) — coordinator restore still poisons the assignment tracker's owner thread; no managed job can recover from any checkpoint or savepoint. Re-verified against the current head, including the Javadoc that states the invariant two lines above where it is broken.
  • Issue 3 (High) — lane selection is still re-derived from live cluster config on every JobMaster#init; the PR's own documented rollback step still permanently invalidates in-flight managed checkpoints. Re-verified, including that the newly-added logging at the selection call site does not change this.
  • Issue 4 (High) — Iceberg's capability declaration still does not match its bounded enumerator.
  • Issue 5 (High) — the three managed operations still convert every exception, including programming errors, into an unlogged STALE_TARGET.
  • Issue 6 (High) — FakeSourceSplit's widened equals/hashCode still duplicates splits when restoring a pre-PR checkpoint, still on the legacy lane, still ungated by the feature flag. Re-verified with a full file re-read this round.
  • Issue 7 (High) — the watchdog can still deliver an interrupt to an unrelated task under ThreadShareMode.ALL/PART and still never clears the flag. Re-verified with a full method re-read this round.
  • Issue 8 (High) — a barrier queued behind CANCEL still calls snapshotState() on a cancelled reader and still reports FAILED instead of CANCELED.
  • Issue 9 (High) — the thread-identity guards are still incompatible with the supported ThreadShareMode.ALL.
  • Issue 26 (Medium, treat as a gate) — the unit-test half of this is now fixed (confirmed: all four unit-test matrix jobs pass at this head). The half that matters is not: engine-v2-it, the only job that runs ManagedSourceRuntimeIT, was cancelled at this head too, for a different reason than last time (this time apparently starved by an unrelated Iceberg/Postgres-CDC infra flake consuming the workflow's time budget, not a fail-fast cascade from a compile error). Net effect is unchanged: zero CI evidence, at any head of this PR, that the managed lane's shutdown or restore path behaves as designed. Given that Issues 1 and 2 are exactly the shutdown and restore paths, I would not consider this gate satisfied until a ManagedSourceRuntimeIT run actually completes — pass or fail — on a head that also includes the Issue 1/2 fixes.

mergeStateStatus is now MERGEABLE with no conflict (the docs/sidebars.js conflict from my last review is resolved), so that specific blocker from before is closed.

2. Recommended fixes — non-blocking

Issues 10–25 and 27–29 should be addressed before the feature graduates from experimental; several (10, 11, 16, 17, 18, 19) are latent correctness or leak issues that will be much harder to diagnose once the lane is enabled anywhere. Issue 30 is cleanup. None of these moved this round.

On @nzw921rx's point about the connector allowlist: my position is unchanged from last round — I would keep the explicit allowlist, and Issue 3's fix (persisting the selection with the job) is what makes that switch safe rather than what should motivate removing it. There has been no new discussion on the PR since my last review to respond to.

Overall assessment

Same assessment as last round, because nothing that would change it has landed: the right architecture, roughly 80% built, with the transition machinery (shutdown, restore, cancel, epoch change) still the missing 20% — Issues 1, 2, 8 and 21. My suspicion from last time stands and is now reinforced by a second, independent CI run: these survived because the lane has still never actually executed end-to-end in CI, for two different infrastructure reasons in a row now. I would treat "get ManagedSourceRuntimeIT to actually run to completion at least once" as almost as urgent as fixing Issues 1–9 themselves, because right now nobody — including me — has direct evidence beyond source-level tracing that any of this works.

I do not think there is a materially better Option B for the overall design. The structural suggestion from last round still stands and would prevent two Highs by construction rather than convention: replace the lazy checkOwner() first-caller-wins bind with an explicit attachToOwnerLoop() invoked once from the first runOneTurn(), with a clear "coordinator loop has not started" error for any earlier caller. That closes Issue 2 and makes Issue 9 diagnosable.

Thanks again for the care that went into the documentation and the compatibility gating, and for fixing the Mockito issue cleanly with a clear explanation in the commit message — the fail-closed posture and the explicit capability handshake are still the right instincts, and they are why the remaining problems are localized rather than systemic. I'd like to see this PR's CI actually get a clean run of ManagedSourceRuntimeIT before the next review round, since at this point that is the single piece of evidence most likely to change my assessment in either direction.

@DanielLeens

Copy link
Copy Markdown
Contributor Author

Pushed c5787154a16 (11 commits on top of 41b5818d6b8) for the blockers in my review of 41b5818d6b8. One commit per issue. No pom.xml change, no deletions.

Issue Commit Root cause and fix Test
4 (High) fd6d8a49782 Legacy pollNext requeues a custom-row split with the marker rowNum = -nextIndex-1, and addSplits treated the non-positive totalRowNum as a fresh split, so restore re-emitted rows. Negative markers are now kept unchanged; only managed or fresh splits are normalized. New FakeSourceReaderTest#legacyCustomRowProgressSurvivesRestore: restores marker -3 and expects exactly rows 2..5
46 (High) 7d2b6520170 The savepoint barrier's prepareClose moved the reader to DRAINING before its lifecycle snapshot. ManagedSourceLifecycle#gracefulCloseForBarrier now remembers the pre-stop state and checkpointSnapshot() persists it. Draining from real end of input happens before the barrier and is still persisted. ManagedSourceCheckpointStateTest#shouldResumeRunningAfterRestoringSavepointStop (savepoint stop restores RUNNING; end-of-input stays DRAINING)
47 (High) 97d4348ce6d With checkpoints disabled, markApplied removed the entry, so a later admission response failed in markAdmitted. The entry is now released only after both facts are consumed, in either order. SourceAssignmentTrackerTest#shouldReleaseUncheckpointedAssignmentInEitherResponseOrder
6 (High) 9d3e844688a releaseAllOutbound now clears transportRetries/transportFirstAttemptNanos for every pending and in-flight command of the replaced attempt, so a replay does not inherit the old retry deadline. None: the coordinator runtime has no unit harness yet
10 (High) eaaf900b3a6 wakeUp and interrupt are now delivered while holding pollWatchdogLock. The poll's finally clears the generation under the same lock, so delivery cannot outlive the selected poll. None: needs a reader-runtime harness
11 (High) 32a62989ddd The epoch/attempt pair is published as one immutable volatile CoordinatorFence, closed is volatile, and admission re-checks closed inside admissionLock. None: needs a reader-runtime harness
7 (High) 54f0077ef73 IcebergSource reports the legacy capability for bounded (or unconfigured) jobs, so batch Iceberg fails deployment while the feature is on, instead of planning synchronously on the owner loop. The docs table now says streaming only. None: IcebergSource needs a catalog to construct
15 (High) 4a5268fcc39 Smallest safe option from the review: ManagedSourceRuntimeSelector#requireOwnedTaskThread rejects a managed lane at plan time when task_execution_thread_share_mode=ALL. Legacy lanes and OFF/PART are unchanged. Documented in EN/ZH. ManagedSourceRuntimeSelectorTest#shouldRejectManagedLaneWhenAllTaskThreadsAreShared
26 (Medium) fe27c2b44d6 The managed branch of SourceFlowLifeCycle#collect now adds a progressing turn to SourceReadNanos, and a turn without progress plus the idle wait to SourceIdleNanos, behind the same observability gate as the legacy lane. None: SourceFlowLifeCycle needs a running task
3 (Medium) 39dbff5f543 Docs fix (option 2 of the review). EN/ZH now explain that every plan rebuild runs selection again and a lane mismatch makes restore fail; they no longer promise pinning. Added an EN/ZH incompatible-changes entry for the lane-bound checkpoint restriction. Docs only

c5787154a16 only applies spotless to two of the commits above.

Deferred, because they need an STIP-31 design decision:

  • Issue 3, automatic restore pinning. Options: (a) persist the selected lane and capability digest with the job and reuse them when the plan is rebuilt, plus explicit migration rules; (b) keep re-selection, but reject at submission or restore when the flag differs from the checkpoint's lane, giving an early error instead of a task-level restore failure; (c) keep today's fail-closed behavior, which is now documented.
  • Issue 15, supporting ALL. This needs a serialized logical owner token with an explicit happens-before handoff in place of checkOwnerThread, covering reader, coordinator, scheduler and tracker together.

Limits of this push:

  • Issues 6, 10, 11, 7 and 26 have no new unit test: the coordinator/reader runtimes, IcebergSource and SourceFlowLifeCycle have no unit-level harness in this module. Adding one is a separate piece of work.
  • Locally I ran only spotless:apply/spotless:check on engine-server, engine-common, connector-fake and connector-iceberg. Compile and tests are left to the fork Build for c5787154a16, and I am not claiming them. The obsolete rerun of 41162470910 for the old head was cancelled.
  • @SEZ9: F1's per-test result for ManagedSourceRegisterOperationSerializationTest will come from that new Build's engine-server unit lane. None of these commits touches the operation serializers.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Self re-review of head c5787154a16a8d00ec49da7e161bf3ea3dbe76a8 (11 commits on top of 41b5818d6b8, which my previous review covered). I re-read the full incremental diff (17 files, +455/-43) and traced every touched method back to its production callers. This is a source-only review: I ran no local build, test, container or job.

What Problem Does This PR Solve?

User pain: reader polling, split assignment and checkpoint callbacks require connector-specific locking across engine threads.

Approach: disabled-by-default managed reader/coordinator event loops with bounded admission, sequenced/fenced commands, a split ownership ledger, async discovery and versioned checkpoint metadata.

In one sentence: move concurrency ownership from each connector into the engine, so for example a Kafka split assignment and a checkpoint barrier are applied in one ordered reader loop.

1. Code Change Review

1.1 Core Logic Analysis

Status of every blocker from the previous review, verified against this head:

Issue Status Evidence on this head
4 FakeSource legacy custom-row progress Fixed FakeSourceReader.java:259-270 keeps a negative rowNum marker unchanged; pollNext decodes it at :108. Managed and fresh splits still take the normalization path at :271-280.
46 savepoint restores DRAINING Fixed ManagedSourceLifecycle#gracefulCloseForBarrier captures the RUNNING snapshot only when mainState == RUNNING && !closeLatched; ManagedSourceReaderRuntime.java:787 uses it and :820 persists checkpointSnapshot(). End of input drains before the barrier, so it is still persisted as DRAINING.
47 checkpoint-disabled response order Fixed SourceAssignmentTracker#markApplied releases only when already ADMITTED; #markAdmitted releases an APPLIED entry. Stale-attempt transport results are dropped earlier in ManagedSourceCoordinatorRuntime#handleTransportResult, so no foreign response reaches the tracker.
6 retry bookkeeping on reader replacement Fixed ManagedSourceCoordinatorRuntime.java:1192-1200 clears retry state for every pending and the in-flight command. A command in retry backoff stays inFlightCommand, so it is covered; a late result from the old attempt returns before touching the maps.
10 watchdog delivery race Fixed checkActivePoll (ManagedSourceReaderRuntime.java:624-656) delivers wakeUp/interrupt while holding pollWatchdogLock; pollManagedReader's finally clears the generation under the same lock (:582-586). See new Issue 49 for the contract this creates.
11 epoch/terminal publication Fixed Epoch and attempt are one immutable volatile CoordinatorFence (:119), closed is volatile (:145), and admission re-checks closed inside admissionLock, which close() takes after publishing closed. registrationAccepted remains owner-confined (all writers run under checkOwner()).
7 Iceberg batch certified as async Fixed IcebergSource#getManagedSourceCapability returns legacy() for bounded or context-less sources. JobContext is Serializable, so the master-side selector sees the same job mode; the streaming capability, and therefore its digest, is unchanged.
15 cooperative thread migration Fixed (smallest option) ManagedSourceRuntimeSelector#requireOwnedTaskThread, called from PhysicalPlanGenerator.java:629, rejects a managed lane under ALL. PART is safe because no production task overrides Task#isThreadsShare() (default false); default mode is OFF. See Issue 50 for the remaining per-node gap.
26 read/idle metrics Fixed SourceFlowLifeCycle.java:385-406 adds progressing turns to sourceReadNs and empty turns plus idle wait to sourceIdleNs, behind the same observability gate.
3 lane-selection docs Fixed (documentation option) EN/ZH guides now describe re-selection on every rebuild and fail-closed restore; EN/ZH incompatible-changes.md gained the lane-bound checkpoint entry. Automatic lane pinning stays a deferred STIP-31 decision, which is an honest scope statement.

Runtime flow after this push (managed lane only; the legacy lane is untouched except Issue 4's restore guard):

savepoint barrier -> reader owner applyBarrier
  -> lifecycle.gracefulCloseForBarrier()   (remembers RUNNING snapshot)
  -> connector snapshot + checkpointSnapshot() (persists RUNNING, not DRAINING)
restore -> restoreSnapshot -> finishRestore -> RUNNING -> canPoll() true

coordinator ASSIGN_SPLITS (checkpoints disabled)
  -> transport ACK path  --\
  -> COMMAND_APPLIED path --+-> entry removed only after both facts, any order

watchdog thread -> lock(pollWatchdogLock) -> generation still active?
  -> reader.wakeUp() / owner.interrupt() -> unlock
owner thread poll finally -> lock(pollWatchdogLock) -> clear generation

1.2 Compatibility Impact

No new incompatibility. No serializer id, option name or default changed in this push. The Issue 4 guard restores the legacy restore semantics of the negative custom-row marker, and the Issue 7 change only removes a capability the batch path never truly met; batch Iceberg jobs with the feature enabled now fail deployment, which the EN/ZH table states. The lane-bound restore boundary is now documented in both incompatible-changes files. Mixed-version rolling upgrade and SourceConfig serialization remain uncertified, as stated before.

1.3 Performance / Side Effects

The watchdog now holds pollWatchdogLock while calling into the connector, so the owner's poll finally can wait for one wakeUp() call. For the in-tree pilots this is short: SourceReaderBase#wakeUp takes each fetcher's ReentrantLock briefly and signals availability; FakeSource's wakeUp is empty. No new lock-order cycle exists, because fetcher threads never take pollWatchdogLock and the owner never holds a fetcher lock while entering it. The retry-map cleanup is O(pending commands) per replacement, bounded by the outbound window.

1.4 Error Handling and Logging

Issue 49: Document that ManagedSourceReader#wakeUp must be non-blocking now that it runs under the watchdog lock (Medium, non-blocking).

  • Location: seatunnel-api/src/main/java/org/apache/seatunnel/api/source/managed/ManagedSourceReader.java:63-67; caller seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceReaderRuntime.java:624-656.
  • Problem: the Issue 10 fix states "ManagedSourceReader#wakeUp must not block" only in an engine-internal comment. The public API Javadoc says only that it interrupts or wakes connector work.
  • Risk: a future connector whose wakeUp blocks (for example by waiting on a monitor that its own poll holds) stalls the owner loop's poll finally, and with it every queued barrier and command, for as long as the call blocks.
  • Best improvement: state in the API Javadoc that wakeUp is called from an engine thread, possibly while a poll is running, and must return promptly without waiting for the poll. Add the same line to the connector authoring section of the runtime guide.
  • Raised by another reviewer: no.

Issue 50: The ALL share-mode guard reads the master's config, while each worker applies its own (Medium, non-blocking).

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/dag/physical/PhysicalPlanGenerator.java:173,629; executor side seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/TaskExecutionService.java:756-767.
  • Problem: task_execution_thread_share_mode is read from the worker's own seaTunnelConfig at deployment, but the guard uses the master's EngineConfig. A cluster where only some workers set ALL passes the plan-time check and still hits the owner-thread violation on those workers.
  • Risk: limited to inconsistent cluster configuration, but the docs say the lane is "rejected at deployment", which implies a guarantee the code does not give.
  • Best improvement: either also fail fast on the worker when a managed task is deployed into the cooperative partition, or extend the "keep identical on every node" sentence in the EN/ZH guide to cover task_execution_thread_share_mode.
  • Raised by another reviewer: no.

Issue 51: Stale "decided once and persisted" comments contradict the corrected docs (Low, non-blocking).

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/dag/physical/PhysicalPlanGenerator.java:631; seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/runtime/source/ManagedSourceRuntimeSelector.java:25.
  • Problem: both comments still describe the lane as decided once and persisted with the physical plan, which the Issue 3 doc fix just showed is untrue (selection reruns on every rebuild).
  • Risk: future maintainers may rely on pinning that does not exist.
  • Best improvement: reword to "selected whenever the physical plan is built; checkpoint metadata only validates the lane on restore".
  • Raised by another reviewer: no.

Carried-over non-blocking items from the previous review, unchanged on this head: 16 (RPC admission cause), 22 (availability obligation after no-more-splits), H (bounded E2E with post-restore output), 48 (SourceConfig metadata comments).

2. Code Quality Assessment

2.1 Coding Standards

Every new field and method carries a comment explaining why (stateBeforeBarrierClose, CoordinatorFence, requireOwnedTaskThread, the Iceberg capability). The new test class has an ASF header and a class Javadoc describing the production risk. No wildcard imports or fully qualified names in method bodies.

2.2 Test Coverage and Test Stability

Stability rating: Stable for the added tests; Risk present for coverage. The new tests are deterministic, with no sleeps or timing:

  • FakeSourceReaderTest#legacyCustomRowProgressSurvivesRestore (connector-fake/.../FakeSourceReaderTest.java:51) fails on the previous head (marker -3 normalized to 6 rows), so it truly guards Issue 4.
  • SourceAssignmentTrackerTest#shouldReleaseUncheckpointedAssignmentInEitherResponseOrder (:72) fails on the previous head (entry removed by markApplied).
  • ManagedSourceCheckpointStateTest#shouldResumeRunningAfterRestoringSavepointStop (:88) covers the lifecycle half of Issue 46, but not the runtime wiring at ManagedSourceReaderRuntime.java:787: reverting that line to gracefulClose() would keep the test green.
  • ManagedSourceRuntimeSelectorTest#shouldRejectManagedLaneWhenAllTaskThreadsAreShared covers Issue 15's guard.

Issue 52: Five High/Medium fixes have no regression test (Medium, blocking before leaving Draft).

  • Location: fixes for Issue 6 (ManagedSourceCoordinatorRuntime.java:1192-1200), 10 (ManagedSourceReaderRuntime.java:624-656), 11 (:119,145,282-290), 7 (IcebergSource.java:176-178) and 26 (SourceFlowLifeCycle.java:385-406).
  • Problem: the PR comment correctly says these components lack a unit harness, but the fixes target concurrency and capability contracts that previously shipped with real defects.
  • Risk: a later refactor can silently reintroduce any of them; the managed E2E (Issue H) does not observe these interleavings.
  • Best improvement: the cheapest high-value additions are the Iceberg capability by job mode (a JobContext with BATCH vs STREAMING), the runtime-level savepoint-resume assertion in ManagedSourceRuntimeIT (which also closes Issue H), and a latch-driven reader-runtime test for watchdog delivery versus poll completion. The coordinator retry case can follow once a coordinator harness exists.
  • Raised by another reviewer: no.

2.3 Documentation Updates

EN and ZH guides and both incompatible-changes.md files were updated in parallel and match in content (lane re-selection, fail-closed restore, Iceberg streaming only, ALL rejection). Issues 50 and 51 note the remaining wording gaps.

3. Architectural Soundness

The fixes stay at the boundaries identified in the previous review (split normalization, lifecycle snapshot, ledger reconciliation, transport bookkeeping, fence publication, selector) with no change to unrelated modules, no pom.xml change and no deletions. Rejecting ALL is the smallest safe option; the logical owner token remains the long-term design and is correctly listed as a deferred STIP-31 decision, together with automatic lane pinning.

4. Issue Summary

No. Issue Location Severity Status
4, 46, 47, 6, 10, 11, 7, 15 Previous High blockers see 1.1 High Fixed on this head
3, 26 Previous Medium blockers see 1.1 Medium Fixed on this head
52 Regression tests for fixes 6/10/11/7/26 and runtime wiring of 46 see 2.2 Medium Open, blocking
49 wakeUp non-blocking contract in API ManagedSourceReader.java:63 Medium Open, non-blocking
50 ALL guard uses master config only PhysicalPlanGenerator.java:629 Medium Open, non-blocking
51 Stale "decided once" comments PhysicalPlanGenerator.java:631 Low Open, non-blocking
16, 22, H, 48 Carried-over suggestions previous review Medium Open, non-blocking

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blocking: Issue 52 (regression coverage for the untested fixes), plus current-head CI evidence. Build 41570853043 for this exact head is still queued, so compilation of these 11 commits, the new unit tests, @SEZ9's F1 per-test result for ManagedSourceRegisterOperationSerializationTest and the managed engine E2E are all unverified. F1 stays open until that result is posted.
  2. Non-blocking: Issues 49, 50, 51 and the carried-over 16, 22, H, 48. Benchmark and soak evidence (@nzw921rx) remains a promotion gate, separate from this code review.

No new source-level defect was found in this push, and all ten previous blockers are fixed at the right places. The PR is still a Draft; branch drift is ahead 42 / behind 14 against dev, merge state BLOCKED with review required. GitHub does not allow me to approve my own PR, so this is a COMMENT.

@SEZ9

SEZ9 commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the follow-up push (c5787154a16, 11 commits on top of 41b5818d6b8) and for the per-issue table and self re-review.

One item from my earlier review that I could not locate in the portion of the table and re-review I can see is PR11557-F1 (HIGH, Security) – unsafe Java deserialization pattern in seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/operation/source/ManagedSourceRegisterOperation.java. Since you mention one commit per issue across 11 commits, it may well be covered by one of the rows I can't see.

Could you confirm whether F1 was addressed on c5787154a16a8d00ec49da7e161bf3ea3dbe76a8? If so, a pointer to the specific commit plus a short root-cause/fix/test note in the same format as the other rows would be great. If it is still open, please add it to the status table so the resolution state of every blocker is visible in one place.

Once F1 is accounted for, I'll do a final pass on that single item. I'm not raising anything new here.

@DanielLeens

Copy link
Copy Markdown
Contributor Author

Thanks @SEZ9. F1 is addressed on c5787154a16. It isn't in the 11-03 table because none of those 11 commits touched it: the fix landed earlier and is unchanged on this head. Here is the row in the same format:

Issue Commit Root cause and fix Test
PR11557-F1 (High, Security) 5a0f93b37ded5b3e0b150fb18b66c60b31b0136d readInternal used to decode readerLocation with an untyped in.readObject(), and an intermediate fix used readObject(TaskLocation.class). Hazelcast's typed overload does not validate the wire type: it discards the wire factory/class id and reads the following bytes positionally into a new TaskLocation. ManagedSourceRegisterOperation#readInternal (ManagedSourceRegisterOperation.java:115-131) now decodes by the wire id through the closed TaskDataSerializerHook factory. It then rejects anything that is not a TaskLocation, including null, with an IOException that names the expected type and the decoded type. This path uses no JDK ObjectInputStream. ManagedSourceRegisterOperationSerializationTest#testMismatchedReaderLocationTypeIsRejected (:92) puts a Progress (same factory id, different class id) in the reader-location slot and asserts the exact IOException. It fails against the typed-overload version. #testReaderLocationPayloadRoundTrips (:65) asserts that a real payload re-encodes byte for byte.

Verification:

The pre-existing untyped reads in AssignSplitOperation#readInternal, and the typed-override behavior in the base TaskOperation#readInternal, are not introduced by this PR. They are tracked in #12747, as you asked earlier.

I'll add this row to the status table in the PR description.

@DanielLeens

Copy link
Copy Markdown
Contributor Author

The earlier 'no current-head fork Build' statement is obsolete: run 41570853043 has executed and failed. All four unit matrices report SourceCheckpointLockHandoffTest lifecycle/timer tests (including lines 324 and 296) with NullPointerException; inspect their fixture initialization and retain the lifecycle-handoff assertions before rerunning. Separately, Build website fails after npm install, in team:contributors -> tools/generate-team-pr-contributors.js with fetch failed. I checked apache/seatunnel-website's current contributor generator: its fetch still fails the prebuild and no corresponding retry/fallback fix is present. A simple SeaTunnel sync is not an established fix; retry that website lane after connectivity recovers or wait for a website-side fix. Do not add unrelated dependencies here. The existing regression-coverage blocker remains independently.

CI reference: Build 41570853043.

This updates CI/merge facts on the already-reviewed head; it is not another full source review. No local runtime testing was performed. Daniel has READ permission; effective maintainer approval/dismissal remains separate.

@davidzollo

Copy link
Copy Markdown
Contributor

Yes, contributing to Apache SeaTunnel.

Pushed 1f0ac9d495323a036a27bcca5320b547a9f9b0a0 by normal fast-forward push. Reconciled dev conflicts and initialized the SourceCheckpointLockHandoffTest service configuration required by the lifecycle constructor. Added real Iceberg capability-method coverage and fresh source-row plus checkpoint progress assertions after managed savepoint restore. Documented the watchdog wakeUp non-blocking contract. Issue 52 remains partial: coordinator retry bookkeeping (Issue 6), watchdog delivery race (10), close/fence publication (11), and managed read/idle accounting (26) still lack the requested focused runtime regression coverage.

Validation: affected-module Spotless and diff whitespace checks passed; an independent maintainer source review of these deltas completed. No local compile, unit, integration, E2E, Docker or service execution was performed under the repository validation policy. No engine UI change or existing runtime artifact was used. The current-head fork Build was queued at the post-push inspection; this update does not claim runtime correctness or merge readiness. This supersedes earlier verification statements for the previous head.

Existing connector registrations, configuration defaults, public contracts and prior test assertions were retained. Upstream-only POM changes in the approved conflict merges match dev exactly; no new dependency edits were made. Human review and any remaining explicit coverage/acceptance gaps are separate gates.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Re-checked the new head 1f0ac9d4. Since my last review (c5787154) the head moved by one merge of dev that also carries the author's own work, so the PR's own diff did change (7 PR files, about 430 added lines, mostly tests and the incompatible-changes doc re-merge). The substantive PR-side delta: SourceCheckpointLockHandoffTest now initializes the service configuration the lifecycle constructor needs (the cause of last run's NullPointerException in the four unit matrices); IcebergFactoryTest gained real capability-method coverage (managedCoordinatorCapabilityDependsOnJobMode: streaming certifies the managed coordinator, batch does not, async enumerator capability stays independent); ManagedSourceRuntimeIT plus stream_fake_to_inmemory_managed.conf now assert fresh source rows and a later checkpoint after a managed savepoint restore (so a reader restored as DRAINING cannot pass by just reporting RUNNING); and ManagedSourceReader documents that the watchdog wake-up must not block. I read these as strengthening, not weakening: the lifecycle-handoff assertions are kept and the restore test got stricter.

Previous blockers:

  • Issue 52 (regression coverage for the untested fixes): still partially open. The new tests cover the Iceberg capability and the post-restore progress. Coordinator retry bookkeeping (Issue 6), the watchdog delivery race (Issue 10), close/fence publication (Issue 11) and managed read/idle accounting (Issue 26) still have no focused runtime regression test.
  • F1 (@SEZ9, unsafe deserialization in ManagedSourceRegisterOperation): the fix (5a0f93b3) is unchanged on this head. I answered with the per-issue row on 11-04; @SEZ9 has not replied since, so it remains open until they confirm. I still owe the row in the PR description (not present yet).

CI on this exact head: not green, and not a clean red either. Fork Build 42347723137 ended cancelled: 67 jobs passed, 11 skipped, 0 failed, 18 cancelled. Most cancelled lanes never got a runner. The one that matters is engine-v2-it (JDK 17 and JDK 11): in the JDK 17 log it starts ManagedSourceRuntimeIT at 06:49:58, logs nothing after about 06:53, and is cancelled at 08:30 by the step time limit, with no test result recorded. A silent hang of about 97 minutes inside the PR's own managed-runtime E2E is not something I can attribute to infrastructure, and the same IT was just changed. Minimum next step: run ManagedSourceRuntimeIT once with a thread dump when it goes quiet (the new restored-progress waits are bounded at 2 minutes, so the stall is likely elsewhere, for example job cancel or container shutdown), then rerun the cancelled lanes with --failed. The previous head's Build website fetch failed is an external contributor-list fetch and is not part of this diff. The Apache-side Build check is also red. The branch is 43 commits ahead and 17 behind dev, no conflict, still Draft.

Other reviewers: @nzw921rx's benchmark/soak evidence request remains a promotion gate, separate from this code review. The 11-07 maintenance comment from another automation account says the same as above on Issue 52; it is not a review.

Conclusion: Ready to merge after fixes

Blockers:

  1. Issue 52 remainder: focused runtime regression tests for Issues 6, 10, 11 and 26.
  2. Current-head engine-v2-it must complete green, which first requires explaining the ManagedSourceRuntimeIT stall.
  3. F1 confirmation from @SEZ9 and the PR-description row.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

A merge-state fact in my previous conclusion has changed. GitHub now reports merge conflicts (mergeable_state=dirty) between unchanged head 1f0ac9d495323a036a27bcca5320b547a9f9b0a0 and dev. The earlier statement that this head had no conflicts is obsolete.

Please sync the latest dev and resolve the conflicts first, preserving both the PR's intended change and the upstream changes, then rerun the checks on the resolved head. This request is for an actual reported merge conflict, not merely because the branch is behind.

The prior missing focused runtime regressions, ManagedSourceRuntimeIT stall, and outstanding reviewer verification remain open. The new merge conflict is an additional gate.

Conclusion: Ready to merge after fixes

  • Blockers — must be fixed: The merge conflict plus the previously identified blockers, where listed above. A fresh head requires a full re-review and current-head checks.
  • Recommended fixes — non-blocking: Earlier optional suggestions retain their previous status; this note adds no source finding against the unchanged code version.

Recorded comparison: diverged, ahead 43 / behind 36 of dev. I have not changed the contributor's branch or executed the PR locally. Daniel has READ permission; effective approval/dismissal and merge remain with a write-capable maintainer.

@SEZ9

SEZ9 commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator

@davidzollo thanks for the update on 1f0ac9d495323a036a27bcca5320b547a9f9b0a0.

Scoping this reply to the one previously flagged finding, F1 (HIGH, Security): the unsafe Java deserialization pattern in seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/operation/source/ManagedSourceRegisterOperation.java.

From the thread, the fix for F1 landed in 5a0f93b3 and is unchanged on the current head 1f0ac9d4, but the finding is still open for two reasons: the original reporter has not confirmed the fix, and the per-issue row for F1 is still missing from the PR description.

To close F1, I'd ask for the following on the next push / description edit:

  1. Add the F1 row to the PR description: a short statement of what ManagedSourceRegisterOperation deserializes, what 5a0f93b3 changed (e.g. what is now validated or restricted before the payload is read), and why the remaining path is safe.
  2. Point to the test (class and method name) that exercises the hardened deserialization path, or say explicitly if none exists yet so we can decide whether one is required before merge.
  3. Ping the original reporter on the thread once the row is in place so they can confirm or push back.

Once those are there I can re-verify F1 against the current head. Everything else stays with the previously recorded status.

Preserve the changes from both parents and resolve only the overlapping paths for this pull request.

@DanielLeens DanielLeens left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Apache SeaTunnel self-review at 7fa315bac1d0fb30a3380f5b5eb8baebd1adb904. I checked the complete net patch and its production boundaries after the dev merge. The 110-file patch has the same added and removed lines as the previous reviewed head; the runtime and test gates from that review do not disappear with the new commit.

What Problem Does This PR Solve?

The managed Source option gives a compatible source a controlled scheduling lane instead of letting independent callbacks and reader operations own mutable coordination state. During job planning, the engine selects a mode and checks capability, version and thread ownership. At deployment, source task/reader registration, the managed coordinator, scheduler and command mailbox admit requests; actual split handling belongs on the selected owner thread. The transport carries versioned command and registration envelopes. Checkpoint serializers persist managed reader/coordinator state, and restore validates compatibility before replaying commands and restarting reading. The legacy default does not enable this path.

1. Code Change Review

1.1 Core Logic Analysis

The managed runtime belongs in the engine because it owns task lifetime, ordering and checkpoint boundaries. Connectors should advertise capability and implement their reader/poll contracts, rather than each reinventing the arbitration. The fail-closed compatibility gate and bounded queues are appropriate. That architecture also means a green connector smoke run cannot prove ownership, fence, retry and restore ordering across the engine seams. The bilingual managed-source and incompatible-change docs explain the opt-in and version limits; they do not establish a live rolling-upgrade or rollback result.

Before/after diff excerpt from SourceSeaTunnelTask.java (removed and added lines are marked):

                 completableFuture,
                 metricsContext,
-                flushIntervalMs);
+                flushIntervalMs,
+                new ManagedSourceRuntimeSelection(
+                        config.getRuntimeMode(),
+                        config.getRuntimeProtocolVersion(),
+                        config.getConnectorStateVersion(),
+                        config.getCapabilityDigest(),
+                        config.isCheckpointEnabled()));
     }
 
     @Override

Key Findings

  • The ordinary entry point and the conditions that reach the change are shown below.
  • Legacy default is unchanged; the opt-in managed transport has its own version boundary and no verified mixed-version restore.
  • The issue analysis identifies remaining review blockers.

Complete runtime path

Job planning selects supported opt-in mode
  -> managed coordinator/scheduler
  -> registration and mailbox
  -> owner-thread reader/poll
  -> versioned checkpoint state
  -> compatibility validation and restore

1.2 Compatibility Impact

Fully compatible. Legacy default is unchanged; the opt-in managed transport has its own version boundary and no verified mixed-version restore.

1.3 Performance / Side-Effect Analysis

The operational side effects and ownership boundaries in this patch are described in the call-chain review and the fixture assessment below. Runtime performance was not measured locally.

1.4 Error Handling and Logging

  1. Medium, blocking, carried forward: Issue 52 still needs focused engine regressions for coordinator retry bookkeeping, watchdog notification delivery, close/fence publication, and managed read/idle handoff. The existing Iceberg capability and post-restore progress tests are valuable but exercise different paths. Use explicit state/condition synchronization so the tests fail for the corresponding ownership mistake.
  2. Medium, blocking review gate, carried forward: record the exact current evidence for SEZ9 F1 at the registration/owner boundary. The previous fix defers connector deserialization to the owner; no code delta removes it. Reviewer confirmation and the promised review mapping are still outstanding.
  3. The earlier engine IT did not establish completion of the managed runtime scenario. The new fork Build is queued, so neither the earlier cancellations nor an unrelated happy-path test prove this head runs. Obtain the named managed-source IT results and keep soak/promotion separately assessed.

2. Code Quality Assessment

2.1 Coding Standards

The relevant documentation, lifecycle boundaries and known findings are identified above; the full file list was reconciled against GitHub.

2.2 Test Coverage and Test Stability

Test stability: Risk present. Managed-source IT exercises asynchronously scheduled source work and restore. Watchdog and progress assertions need actual bounded conditions; a runner cancellation cannot establish a code failure or a pass. Static checks used the entire local file inventory, net-diff reconciliation, and caller/serializer evidence. No local build, test or job was executed.

2.3 Documentation Updates

The bilingual managed-source and incompatible-change docs explain the opt-in and version limits; they do not establish a live rolling-upgrade or rollback result.

3. Architectural Soundness

3.1 Elegance of the Solution

Long-term solution. Legacy default is unchanged; the opt-in managed transport has its own version boundary and no verified mixed-version restore.

3.2 Maintainability

Keep the ownership and validation boundaries named in the runtime and issue analysis.

3.3 Extensibility

The review recommendation below records where the smallest safe change fits and where a broader redesign would need separate verification.

3.4 Historical-Version Compatibility

Legacy default is unchanged; the opt-in managed transport has its own version boundary and no verified mixed-version restore.

4. Issue Summary

Number Issue Location Severity
52 Managed ownership and close/idle regressions needed Managed coordinator/reader IT Medium
F1 Record owner-side registration evidence Registration/owner boundary Medium

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed
  • Issue 52: Managed ownership and close/idle regressions needed.
  • Issue F1: Record owner-side registration evidence.
  1. Recommended fixes — non-blocking
  • See the existing test and implementation suggestions above, where applicable.

Close the remaining runtime coverage and review items and demonstrate the exact-head engine IT. No automatic approval is implied by this self-review.

Head 7fa315bac1d0fb30a3380f5b5eb8baebd1adb904; base dev at b3828eb141d3ca669181084dbd73bfb534064e08; comparison diverged, ahead 44 / behind 1. Apache Build: No Apache Build check observed on this head. My technical review on my own PR is a COMMENT and does not provide independent approval.

@SEZ9

SEZ9 commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the update to 7fa315bac1d0fb30a3380f5b5eb8baebd1adb904.

Following up on the open item from the earlier review (PR11557-F1, HIGH / Security): the unsafe Java deserialization pattern in seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/operation/source/ManagedSourceRegisterOperation.java.

As noted on the thread, the net patch at this head has the same added and removed lines as the previously reviewed head 1f0ac9d495323a036a27bcca5320b547a9f9b0a0, so I don't see anything indicating this finding has been addressed yet. If I've missed a change, please point me to it.

Before I can approve, I'd ask for:

  1. In ManagedSourceRegisterOperation, avoid plain Java object deserialization of the registration payload from untrusted operation bytes — either encode the payload field by field in a versioned envelope, or, if an object stream is unavoidable, restrict it to a strict allow-list of the exact types the registration envelope can carry.
  2. A focused unit test for the read path that (a) round-trips a valid registration envelope and (b) asserts that a payload containing an unexpected or disallowed class is rejected rather than instantiated.
  3. A short note in the PR description on which approach you chose, so the reasoning is on record alongside the protocol-version/compatibility story.

Once that's pushed I'll re-check this item on the new head. Happy to discuss the encoding option first if that helps.

Reuse the test fixture version update merged in apache#13285.

@SEZ9 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for working on this. I reviewed the latest head 6b2b81418159.

What this PR fixes

  • User pain: On Zeta, Source connectors must hand-synchronise Reader and Enumerator callbacks that arrive on Hazelcast operation threads against the checkpoint lock (for example synchronized (output.getCheckpointLock()) in SourceReaderBase.pollNext), and they run blocking discovery on private threads (Kafka's kafka-partition-dynamic-discovery executor). Checkpoint-ordering races and operation-thread stalls are therefore each connector's own problem.
  • Fix approach: Add a default-off managed-source-runtime lane that is chosen per Source when the physical plan is built (ManagedSourceRuntimeSelector.select). Once the switch is on, a Source without a compatible ManagedSourceCapability fails deployment instead of silently staying on the legacy lane. Operation threads only admit command envelopes into bounded mailboxes; the task's own thread drains them in runOneTurn() and is the only caller of connector code. Blocking coordinator work goes through CoordinatorScheduler.callAsync onto engine-owned worker pools, and results are applied back on the coordinator loop.
  • Review focus: The findings below concern the edges of that model: restoring splits from a legacy Reader on the coordinator-only lane, failure and timeout handling of async coordinator work, one configuration limit that is not checked against the wire limit, idle polling after no-more-splits, and documentation and Javadoc that do not match the code.

Runtime chain I rechecked

[1] Lane selection at plan build (master)
PlanUtils.fromLogicalDAG(..., engineConfig)  PlanUtils.java:50-64
  -> PhysicalPlanGenerator ctor: engineConfig.getManagedSourceRuntimeConfig() / getTaskExecutionThreadShareMode()  PhysicalPlanGenerator.java:172-173
  -> PhysicalPlanGenerator.managedSourceSelection(sourceAction)  PhysicalPlanGenerator.java:618-644
     -> ManagedSourceRuntimeSelector.select(source, config)  ManagedSourceRuntimeSelector.java:59-118
          config.validate()  :61
          disabled -> ManagedSourceRuntimeSelection.legacy()  :62-63
          enabled + no/legacy capability -> IllegalStateException  :72-77
          protocol mismatch :78-86, usesSourceEvents :87-92, coordinator without async enumerator :93-98
          mode = MANAGED_READER_AND_COORDINATOR | MANAGED_READER | MANAGED_COORDINATOR  :100-112
     -> ManagedSourceRuntimeSelector.requireOwnedTaskThread(selection, shareMode, name)  PhysicalPlanGenerator.java:629-630

[2] Command admission (Hazelcast operation thread)
ManagedSourceCommandOperation -> SourceSeaTunnelTask.admitManagedSourceCommand(command)  ManagedSourceCommandOperation.java:69
ManagedCoordinatorCommandOperation -> SourceSplitEnumeratorTask.admitManagedCoordinatorCommand(command)  ManagedCoordinatorCommandOperation.java:55
  payload length checked against SourceCommandEnvelope.MAX_WIRE_PAYLOAD_BYTES (16 MiB) in both readInternal methods  :147 / :123

[3] Owner loops (task thread)
Reader: SourceFlowLifeCycle.collect()  SourceFlowLifeCycle.java:386-407
  -> ManagedSourceReaderRuntime.runOneTurn()  ManagedSourceReaderRuntime.java:406
       poll status: MORE_AVAILABLE re-arms availabilitySignalled; NOTHING_AVAILABLE -> subscribeToAvailability()  :446-457, :658-683
  -> no progress: Thread.sleep(idle-wait-ms)  SourceFlowLifeCycle.java:404-405
Coordinator: SourceSplitEnumeratorTask -> managedCoordinatorRuntime.runOneTurn(), then Thread.sleep(idle-wait-ms) when idle  SourceSplitEnumeratorTask.java:465-467

[4] Coordinator async work
KafkaSourceSplitEnumerator.triggerManagedDiscovery() -> coordinatorScheduler.callAsync(..., timeout 1 min)  KafkaSourceSplitEnumerator.java:575-614
  -> ManagedCoordinatorScheduler.startSubmission  ManagedCoordinatorScheduler.java:337-395
       TaskExecutionService.submitManagedSourceAsync(workerClass, callable)  TaskExecutionService.java:1328-1334
       timeout timer armed right after submission; on fire: enqueue TimeoutException, worker.cancel(true)  :369-387
  -> completeSubmission on the coordinator loop: clears state.running, runningCount--, runs resultHandler, then failureHandler for FAIL_SOURCE or a throwing handler  :475-507

[5] Restore from a legacy Reader on the coordinator-only lane
SourceFlowLifeCycle sends RestoredSplitOperation(enumeratorTaskLocation, splits, indexID)  SourceFlowLifeCycle.java:902
  -> RestoredSplitOperation.runInternal: task.isManagedCoordinatorRuntime() -> task.addSerializedSplitsBack(splits, subtaskIndex)  RestoredSplitOperation.java:91-93
  -> ManagedSourceCoordinatorRuntime.admitLegacySerializedRestoredSplits  ManagedSourceCoordinatorRuntime.java:307-353
       total bytes > reader-mailbox-max-bytes -> IllegalArgumentException  :316-319
       worker budget not reserved / control mailbox full -> IllegalStateException  :323-326, :348-352

Findings

Issue 1: Restored splits sent by a legacy-lane Reader are rejected outright once they exceed reader-mailbox-max-bytes, with no chunking or retry, which can make a checkpoint unrestorable on the coordinator-only lane.

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceCoordinatorRuntime.java:316
  • Why it matters: - Root cause: RestoredSplitOperation now routes to task.addSerializedSplitsBack(...) when the coordinator is managed, which calls admitLegacySerializedRestoredSplits. That method throws IllegalArgumentException as soon as the summed split bytes exceed config.getReaderMailboxMaxBytes() (4 MiB by default).
  • It also throws IllegalStateException when the worker memory budget cannot be reserved or the control mailbox is full, although both conditions are transient.
  • The managed Reader path does not have this problem: ManagedSourceReaderRuntime.appendRestoredStateChunks splits restored split state into chunks of at most max-command-payload-bytes. A legacy Reader on the coordinator-only lane still sends all of its restored splits in a single RestoredSplitOperation, so nothing bounds that payload to the mailbox size.
  • RestoredSplitOperation.runInternal retries only on TaskGroupContextNotFoundException, so neither exception is retried there.
  • Impact: on the legacy lane the same payload is deserialized and handed to addSplitsBack with no size limit. On the coordinator-only lane (the Iceberg canary described in the docs), a Reader whose restored split state is larger than the mailbox limit fails the restore deterministically, and it fails again on every attempt until the limit is raised in the engine configuration.
  • Suggested fix: admit the restored splits in bounded groups (or account for them against the worker budget only, not the Reader mailbox limit), and treat budget exhaustion and a full control mailbox as retryable rather than fatal. A test that restores more than reader-mailbox-max-bytes of split state through RestoredSplitOperation would pin the behaviour.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceCoordinatorRuntime.java:323 if (!outboundMemoryBudget.tryReserve(totalBytes)) {; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/operation/source/RestoredSplitOperation.java:92 task.addSerializedSplitsBack(splits, subtaskIndex);
  • Suggested fix: On the coordinator-only lane the legacy Reader sends its whole restored split state in one RestoredSplitOperation, and this line turns anything above reader-mailbox-max-bytes (4 MiB by default) into an IllegalArgumentException. The same checkpoint restores fine on the legacy lane, and here it hits the limit on every attempt, so the job cannot recover until the limit is raised in the engine configuration.

The two IllegalStateException branches below (worker budget exhausted, control mailbox full) are transient conditions, but RestoredSplitOperation only retries TaskGroupContextNotFoundException, so they are fatal as well.

Could we admit the restored splits in bounded groups, the way ManagedSourceReaderRuntime.appendRestoredStateChunks does for the managed Reader, and make the two transient cases retryable? A test restoring more than the mailbox limit through this path would be good to have.

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: Set managed-source-runtime.enabled: true with default limits and run an Iceberg streaming source (managed coordinator, legacy Reader). Let one Reader subtask checkpoint split state whose serialized size sums to more than 4194304 bytes, then fail and restore the job. RestoredSplitOperation throws IllegalArgumentException("Managed Source restored split payload exceeds mailbox byte limit"), SourceFlowLifeCycle.restoreState fails, and each later restore from that checkpoint fails identically.

Issue 2: On the Kafka managed lane, any periodic partition-discovery failure or 1-minute timeout fails the source, while the legacy lane logs the error and retries on the next interval.

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceSplitEnumerator.java:597
  • Why it matters: - Root cause: the managed discovery result handler rethrows every failure as KafkaConnectorException(DISCOVER_PARTITION_FAILED), and the task is submitted with AsyncTaskOptions.builder().timeout(Duration.ofMinutes(1)).build(), which keeps the default failure policy FAIL_SOURCE.
  • ManagedCoordinatorScheduler.completeSubmission passes an exception thrown by the result handler to failureHandler. Even if the handler did not throw, a non-null failure under FAIL_SOURCE is passed to failureHandler as well. Either way the source fails.
  • The legacy lane in the same class wraps periodic discovery in try { if (initialized) discoverySplits(); } catch (Exception e) { log.error("Dynamic discovery failure:", e); } and simply tries again after discoveryIntervalMillis.
  • Impact: with the managed lane enabled, a transient AdminClient error or a discovery call slower than one minute during periodic discovery fails a running streaming job that the legacy lane would have kept alive. This is a behaviour change between lanes that the PR does not call out.
  • Suggested fix: keep fail-fast for the initial discovery (dynamicDiscovery == false). For periodic discovery, submit with AsyncFailurePolicy.HANDLE_IN_COORDINATOR, log the failure, and call scheduleNextManagedDiscovery() so the next interval retries. If failing the source is intended, please document it as a difference from the legacy lane.
  • Evidence: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceSplitEnumerator.java:597 throw new KafkaConnectorException(; seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceSplitEnumerator.java:613 AsyncTaskOptions.builder().timeout(Duration.ofMinutes(1)).build());; seatunnel-api/src/main/java/org/apache/seatunnel/api/source/scheduler/AsyncTaskOptions.java:71 private AsyncFailurePolicy failurePolicy = AsyncFailurePolicy.FAIL_SOURCE;
  • Suggested fix: This handler rethrows every discovery failure, and the task keeps the default FAIL_SOURCE policy, so a transient AdminClient error or the 1-minute timeout during periodic discovery now fails the source. The legacy lane in this class catches and logs it ("Dynamic discovery failure:") and retries on the next interval.

Could we keep fail-fast only for the initial discovery (dynamicDiscovery == false), and for periodic discovery use AsyncFailurePolicy.HANDLE_IN_COORDINATOR, log the failure and call scheduleNextManagedDiscovery()? Note that removing the throw alone is not enough, because completeSubmission still forwards the failure to the failure handler under FAIL_SOURCE. If failing the source is the intended behaviour, please document it as a difference from the legacy lane.

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: Run a Kafka streaming source on the managed lane with partition-discovery.interval-millis greater than 0. After the first successful discovery, make one periodic round fail, for example an AdminClient listTopics or describeTopics that throws during a broker rolling restart, or a round that takes longer than 60 seconds. The handler throws KafkaConnectorException(DISCOVER_PARTITION_FAILED), the coordinator's next turn throws, and the source fails. With the flag off, the same failure is only logged and discovery runs again after the interval.

Issue 3: An async timeout releases the per-coordinator concurrency slot without confirming that the worker has stopped, and the timeout clock starts at pool submission rather than at execution.

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedCoordinatorScheduler.java:383
  • Why it matters: - Root cause: in startSubmission the timeout timer is armed immediately after submitManagedSourceAsync. When it fires, it enqueues a TimeoutException completion and calls worker.cancel(true). completeSubmission then clears state.running and decrements runningCount, whether or not the worker thread has actually returned.
  • Future.cancel(true) is only an interrupt. Iceberg planning submitted through callAsync (5-minute timeout) may be blocked in file or object-store I/O that does not respond to it; whether that I/O is interruptible is not something this code can guarantee.
  • The worker pools are created once in TaskExecutionService and sized by coordinator-async-io-threads and coordinator-async-cpu-threads, so they are shared by the managed Sources on that node. A worker that ignores the interrupt keeps its pool thread while the scheduler reports the slot as free and starts the next submission.
  • Because the timer starts at submission, time spent waiting in the pool queue (coordinator-async-queue-capacity, 4096 by default) counts against the task timeout. Under a backlog a task can time out before it has run at all.
  • Impact: repeated timeouts can leave the shared pool occupied by abandoned work while coordinator-async-max-concurrency no longer limits anything, and a queued task can fail the source without ever executing.
  • Suggested fix: start the timeout when the callable begins executing (or track queue time separately), and release the running slot only when the worker has returned, or at least account for abandoned workers so the concurrency limit stays truthful. A metric for workers that are still running after cancellation would help operators.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedCoordinatorScheduler.java:383 worker.cancel(true);; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedCoordinatorScheduler.java:483 state.running = false;; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedCoordinatorScheduler.java:485 runningCount--;
  • Suggested fix: worker.cancel(true) only interrupts, but the timeout completion then runs completeSubmission, which sets state.running = false and decrements runningCount even if the callable is still blocked in I/O that ignores the interrupt. The slot is reported free while a thread of the shared worker pool is still held, so repeated timeouts can exhaust coordinator-async-io-threads for every managed Source on the node.

The timer is also armed right after submitManagedSourceAsync, so time spent waiting in the pool queue counts against the task timeout, and a task can time out before it starts.

Could we start the timeout when the callable begins executing, and release the slot only once the worker has actually returned (or track abandoned workers explicitly)?

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: Case 1: occupy all coordinator-async-io-threads (default 32) with callables from other sources for longer than a task's timeout. A newly submitted task sits in the queue, its timer fires, and the result handler receives TimeoutException although the callable never started; with the default FAIL_SOURCE policy the source fails. Case 2: submit a callable that does not react to Thread.interrupt(), with coordinator-async-max-concurrency at its default of 4. After the timeout runningCount drops while the pool thread is still busy, and the scheduler starts another submission, so more callables of that coordinator run at once than the configured limit.

Issue 4: max-command-payload-bytes is checked against the mailbox size but not against the 16 MiB wire hard limit, so a configuration that passes validate() can fail jobs at runtime.

  • Location: seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/ManagedSourceRuntimeConfig.java:104
  • Why it matters: - Root cause: ManagedSourceRuntimeConfig.validate() only requires maxCommandPayloadBytes to be positive and to fit in readerMailboxMaxBytes - readerReservedControlBytes. Nothing ties it to SourceCommandEnvelope.MAX_WIRE_PAYLOAD_BYTES (16 MiB), which the envelope constructor and the readInternal methods of ManagedSourceCommandOperation and ManagedCoordinatorCommandOperation enforce unconditionally.
  • The chunkers in ManagedSourceCoordinatorRuntime (around line 1480) and ManagedSourceReaderRuntime (around lines 874, 1036 and 1064) use config.getMaxCommandPayloadBytes() as the chunk cap, and sendCoordinatorCommand checks payloads against the same value.
  • Impact: with a large mailbox, a value such as 32 MiB is accepted at startup. A job then fails only when a chunk between 16 MiB and the configured cap is built and the envelope rejects it, typically during checkpoint reporting or restore, which is far from the configuration mistake that caused it.
  • Suggested fix: reject max-command-payload-bytes above the wire limit in validate(). The constant currently lives in seatunnel-engine-server while the config is in seatunnel-engine-common, so it needs to be shared from the common module. Please also state the upper bound in the option's documentation.
  • Evidence: seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/ManagedSourceRuntimeConfig.java:104 if (maxCommandPayloadBytes > readerMailboxMaxBytes - readerReservedControlBytes) {; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/SourceCommandEnvelope.java:29 public static final int MAX_WIRE_PAYLOAD_BYTES = 16 * 1024 * 1024;; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/SourceCommandEnvelope.java:137 if (this.payload.length > MAX_WIRE_PAYLOAD_BYTES) {
  • Suggested fix: This check bounds max-command-payload-bytes by the mailbox, but not by the wire hard limit. SourceCommandEnvelope rejects any payload above MAX_WIRE_PAYLOAD_BYTES (16 MiB) in its constructor and in both operations' readInternal, while the chunkers use config.getMaxCommandPayloadBytes() as the chunk cap. With a large mailbox, a value such as 32 MiB therefore passes validate() and only fails later, when a chunk above 16 MiB is actually built.

Could validate() also reject values above the wire limit? The constant would need to move to (or be shared from) seatunnel-engine-common, and the upper bound should be mentioned in the option docs.

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: Set reader-mailbox-max-bytes: 134217728 and max-command-payload-bytes: 33554432 in seatunnel.yaml; validate() accepts it because 33554432 is below 134217728 minus 262144. Run a source on the managed Reader and coordinator lane whose enumerator assigns, in one assignSplit call, splits whose encoded size is between 16 MiB and 32 MiB. chunkAssignments returns a single chunk, SourceCommandEnvelope.create throws on the coordinator thread, and the job fails at runtime instead of at config validation.

Issue 5: The new connector-facing SPI has no developer documentation, and the ManagedSourceCapability flags a connector must set carry no Javadoc.

  • Location: seatunnel-api/src/main/java/org/apache/seatunnel/api/source/managed/ManagedSourceCapability.java:233
  • Why it matters: - Root cause: the PR adds a public connector-facing SPI under seatunnel-api (ManagedSourceCapability, ManagedSourceReader, PollContext, PollStatus, CoordinatorScheduler, AsyncTaskOptions and related types). Under docs/, the only mention of any of these types is one bullet in the operator page (en and zh): "The connector declares a compatible ManagedSourceCapability".
  • In ManagedSourceCapability, the builder methods and getters for connectorStateVersion, supportsBoundedPoll, supportsWakeup, supportsAttemptFencing, supportsAsyncEnumerator and stableSplitIdentifiers have no Javadoc. Only usesSourceEvents is documented.
  • These flags are not cosmetic. validate() requires bounded poll, wakeup, attempt fencing and stable split identifiers for a managed Reader, the selector requires supportsAsyncEnumerator for a managed coordinator, and every flag is hashed into the capability digest that is stored with checkpoints and compared on restore.
  • Impact: a connector author has to read the engine runtime to find out what each flag promises and when connectorStateVersion must be bumped. Declaring a flag without meeting its contract is accepted at deployment and only shows up as a runtime failure or an incompatible restore.
  • Suggested fix: add Javadoc to each builder method stating what the connector must guarantee and what the engine does with it, and add a short connector-developer page (en and zh) that describes how to implement ManagedSourceReader, how to use CoordinatorScheduler, and when to change connectorStateVersion.
  • Evidence: seatunnel-api/src/main/java/org/apache/seatunnel/api/source/managed/ManagedSourceCapability.java:243 public Builder supportsAttemptFencing(boolean supportsAttemptFencing) {; seatunnel-api/src/main/java/org/apache/seatunnel/api/source/managed/ManagedSourceCapability.java:218 public Builder connectorStateVersion(int connectorStateVersion) {; docs/en/engines/zeta/managed-source-runtime.md:33 2. The connector declares a compatible ManagedSourceCapability.
  • Suggested fix: These builder flags are promises the engine relies on: validate() requires all of them for a managed Reader, and they are hashed into the capability digest stored in checkpoints. Only usesSourceEvents has Javadoc, though.

Could you document what a connector must guarantee for supportsBoundedPoll, supportsWakeup, supportsAttemptFencing, stableSplitIdentifiers and supportsAsyncEnumerator, and when connectorStateVersion has to be bumped? A short connector-developer page under docs/en and docs/zh would also help; today the docs mention ManagedSourceCapability only as a deployment gate on the operator page.

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: A connector author who wants the managed lane opens ManagedSourceCapability.Builder. Nothing in the Javadoc or under docs/ says what supportsBoundedPoll(true), supportsWakeup(true), supportsAttemptFencing(true) or stableSplitIdentifiers(true) oblige the connector to do, or when connectorStateVersion must be bumped. The only prose is the operator-facing bullet The connector declares a compatible ManagedSourceCapability.

Issue 6: Several Javadoc statements say a connector "stays on the legacy lane" where the selector actually fails deployment once the flag is enabled.

  • Location: seatunnel-api/src/main/java/org/apache/seatunnel/api/source/SeaTunnelSource.java:128
  • Why it matters: - Root cause: SeaTunnelSource#getManagedSourceCapability says "The default keeps every existing connector on the legacy compatibility lane". That holds only while managed-source-runtime.enabled=false. With the flag on, ManagedSourceRuntimeSelector.select throws IllegalStateException for capability == null || capability.isLegacy().
  • ManagedSourceCapability.Builder#usesSourceEvents says declaring true "keeps the connector on the legacy lane by failing selection". Those are two different outcomes: the selector throws for capability.usesSourceEvents(), so deployment fails; the connector is not moved to the legacy lane.
  • The class Javadoc of ManagedSourceRuntimeConfig says only that the feature is disabled by default and that a running job never changes lane. It does not say that enabling the switch rejects every Source without a managed capability.
  • The operator page added by this PR already states the real behaviour ("deployment fails closed", "rejected at deployment time"), so the Javadoc and the docs currently disagree.
  • Impact: this is the SPI Javadoc connector authors and operators read first. Taken literally, it suggests that enabling the switch is safe for a cluster that still runs connectors without a managed capability, when in fact those jobs can no longer be deployed.
  • Suggested fix: state both cases in each place: legacy lane while the switch is off, deployment failure once it is on.
  • Evidence: seatunnel-api/src/main/java/org/apache/seatunnel/api/source/managed/ManagedSourceCapability.java:252 * SourceEvent} codec, so declaring {@code true} keeps the connector on the legacy lane by; seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/ManagedSourceRuntimeConfig.java:27 * <p>The feature is disabled by default. A running job never changes lane when this configuration; seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/runtime/source/ManagedSourceRuntimeSelector.java:72 if (capability == null || capability.isLegacy()) {
  • Suggested fix: This is only true while managed-source-runtime.enabled is false. Once the switch is on, ManagedSourceRuntimeSelector.select(...) throws for capability.isLegacy(), so a connector that keeps this default is rejected at deployment rather than kept on the legacy lane. Since this is the SPI Javadoc connector authors rely on, could you state both cases explicitly?

The same wording appears in ManagedSourceCapability.Builder#usesSourceEvents ("keeps the connector on the legacy lane by failing selection": the selector throws, it does not fall back), and the ManagedSourceRuntimeConfig class Javadoc does not mention that enabling the switch rejects Sources without a managed capability. The operator page already describes the fail-closed behaviour, so the Javadoc should match it.

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: Enable managed-source-runtime.enabled: true and submit a job whose source keeps the default getManagedSourceCapability(), which returns ManagedSourceCapability.legacy(). The Javadoc says it stays on the legacy lane. ManagedSourceRuntimeSelector.select instead throws that the connector does not declare a managed Source capability while managed-source-runtime.enabled=true, and the job is not deployed.

Issue 7: The documented metric names do not match what the code registers: every new Source runtime metric carries a #<sourceId>#attempt-<executionId> suffix, not #{sourceId}.

  • Location: docs/en/engines/zeta/realtime-observability.md:312
  • Why it matters: - Root cause: docs/en/engines/zeta/realtime-observability.md:312 (and the zh page at line 311) says the new diagnostics use the same #{sourceId} suffix as SourceReadNs#{sourceId}. SourceRuntimeMetrics.metricSuffix and ManagedSourceRuntimeMetrics.metricSuffix both return "#" + sourceRuntimeId + "#attempt-" + executionId.
  • The managed page calls this a "stable Source action suffix" (managed-source-runtime.md:172, zh line 160), but the execution id changes on every task attempt, so the full metric name is not stable across restarts.
  • Impact: dashboards and alert rules written from the documented names will not match any registered metric, and rules written against one attempt's names stop matching after a failover.
  • Suggested fix: document the real name pattern, for example SourcePollTotal#<sourceId>#attempt-<executionId>, in both languages, and explain that the attempt part changes on restart so queries should match on the prefix. Alternatively, if a stable name is the intent, drop the attempt part from the suffix and keep the docs as they are.
  • Evidence: docs/en/engines/zeta/managed-source-runtime.md:172 Managed metrics use a stable Source action suffix. Command IDs, split IDs, table names, and; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/flow/SourceRuntimeMetrics.java:159 return "#" + sourceRuntimeId + "#attempt-" + executionId;; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceRuntimeMetrics.java:321 return "#" + sourceRuntimeId + "#attempt-" + executionId;
  • Suggested fix: This sentence does not match the code. SourceRuntimeMetrics.metricSuffix(...) and ManagedSourceRuntimeMetrics.metricSuffix(...) both build "#" + sourceRuntimeId + "#attempt-" + executionId, so the registered name is SourcePollTotal#<sourceId>#attempt-<executionId>, not SourcePollTotal#{sourceId}. The name therefore changes on every task attempt, which also makes "stable Source action suffix" in managed-source-runtime.md inaccurate.

Could you either document the real pattern here and in the zh page (and note that queries should match on the prefix), or drop the attempt part from the suffix if a stable name is what you want?

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: Enable engine observability and run a job whose source action id is 1 and whose task execution id is 12345. The registry holds SourcePollTotal#1#attempt-12345, not the documented SourcePollTotal#1. A query built from the docs matches nothing. After a failover the execution id changes and the name changes again. SourceManagedAdmissionTotal#1 never exists; only SourceManagedAdmissionTotal#1#attempt-12345#ACCEPTED and its sibling statuses do.

Issue 8: isAvailable() is permanently completed after no-more-splits in SourceReaderBase and always completed in FakeSourceReader, so the managed owner loop falls back to fixed-interval polling.

  • Location: seatunnel-connectors-v2/connector-common/src/main/java/org/apache/seatunnel/connectors/seatunnel/common/source/reader/SourceReaderBase.java:172
  • Why it matters: - Root cause: SourceReaderBase.isAvailable() returns an already-completed future whenever noMoreSplitsAssignment is true, and FakeSourceReader.isAvailable() returns a completed future unconditionally.
  • On NOTHING_AVAILABLE, ManagedSourceReaderRuntime.subscribeToAvailability() attaches whenComplete, which runs inline on a completed future and sets availabilitySignalled back to true at once.
  • The turn reports no progress, so SourceFlowLifeCycle.collect() sleeps idle-wait-ms (10 ms by default) and the next turn polls the reader again. The reader is therefore polled on every loop turn while idle, and the availability future no longer gates anything.
  • KafkaSourceSplitEnumerator.assignSplit calls context.signalNoMoreSplits(id) whenever discoveryIntervalMillis <= 0, with no check for streaming mode. KafkaSourceReader builds on this base class, so a streaming Kafka job without dynamic discovery is in this state for its whole lifetime.
  • Impact: correctness is not affected. An idle managed Reader wakes up every idle-wait-ms and runs an empty poll instead of waiting for the fetcher's availability notification, which is the behaviour the availability contract was meant to replace.
  • Suggested fix: in SourceReaderBase, do not treat noMoreSplitsAssignment alone as available; complete the future when records are queued or when the fetchers have finished, so end of input is still observed. For FakeSourceReader, return a pending future while no split is assigned and complete it from addSplits / handleNoMoreSplits.
  • Evidence: seatunnel-connectors-v2/connector-fake/src/main/java/org/apache/seatunnel/connectors/seatunnel/fake/source/FakeSourceReader.java:236 return CompletableFuture.completedFuture(null);; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceReaderRuntime.java:681 availabilitySignalled.set(true);
  • Suggested fix: Once noMoreSplitsAssignment is true this always returns a completed future, so subscribeToAvailability() re-arms availabilitySignalled inline and the runtime re-polls an idle reader on every loop turn (every idle-wait-ms). Kafka sends no-more-splits whenever discoveryIntervalMillis <= 0, including in streaming mode, so in that configuration the reader never waits on the fetcher's availability notifier.

Could we drop noMoreSplitsAssignment from this condition and instead complete the future when records are queued or the fetchers have finished, so end of input is still detected? FakeSourceReader.isAvailable() has the same effect because it always returns a completed future.

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: Run any SourceReaderBase-based managed reader after handleNoMoreSplits() with an empty elementsQueue. KafkaSourceSplitEnumerator.java:515-516 signals no-more-splits whenever discoveryIntervalMillis <= 0, with no streaming-mode condition at that site. Alternatively run a managed FakeSource that is waiting for splits or for split.read-interval. Each collect() turn calls pollNextManaged, gets NOTHING_AVAILABLE, re-arms availabilitySignalled inline and sleeps 10 ms, so pollNextManaged and SourcePollTotal advance about 100 times per second while idle.

Review conclusion

Conclusion: final approval remains pending on the previous comments

2. Remaining follow-ups

  • Issue 1: Restored splits sent by a legacy-lane Reader are rejected outright once they exceed reader-mailbox-max-bytes, with no chunking or retry, which can make a checkpoint unrestorable on the coordinator-only lane.
  • Issue 2: On the Kafka managed lane, any periodic partition-discovery failure or 1-minute timeout fails the source, while the legacy lane logs the error and retries on the next interval.
  • Issue 3: An async timeout releases the per-coordinator concurrency slot without confirming that the worker has stopped, and the timeout clock starts at pool submission rather than at execution.
  • Issue 4: max-command-payload-bytes is checked against the mailbox size but not against the 16 MiB wire hard limit, so a configuration that passes validate() can fail jobs at runtime.
  • Issue 5: The new connector-facing SPI has no developer documentation, and the ManagedSourceCapability flags a connector must set carry no Javadoc.
  • Issue 6: Several Javadoc statements say a connector "stays on the legacy lane" where the selector actually fails deployment once the flag is enabled.
  • Issue 7: The documented metric names do not match what the code registers: every new Source runtime metric carries a #<sourceId>#attempt-<executionId> suffix, not #{sourceId}.
  • Issue 8: isAvailable() is permanently completed after no-more-splits in SourceReaderBase and always completed in FakeSourceReader, so the managed owner loop falls back to fixed-interval polling.

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

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, @SEZ9. I rechecked the managed source ABI, owner lanes and restore and checkpoint paths at this head, including your earlier registration concern. The last commit carries the IRIS image already present on dev. The managed-source findings remain open, and the exact-head general engine integration lanes were cancelled.

What problem does this PR solve?

User pain. Zeta source connectors currently coordinate reader, enumerator and I/O callbacks themselves, including synchronization with checkpoints.

Fix. Add opt-in managed lanes with explicit connector capabilities, owner-thread callbacks, mailbox admission and versioned checkpoint/assignment tracking.

Example. A managed enumerator can queue a split assignment and observe its acknowledgement before including that assignment in a durable recovery boundary.

1. Code changes

1.1 Core logic

Before, operations reached connector callbacks through the legacy task and lock path. The managed reader now registers itself with ManagedSourceRegisterOperation, and the owner processes that registration before admitting fenced commands. The legacy path remains the default.

Planner chooses runtime lane from engine options and connector capability
 -> coordinator and reader tasks create owner runtimes
 -> reader registers execution/attempt/protocol and restored watermark
 -> coordinator admits reader, reserves memory/control slots and sends commands
 -> reader owner applies split/event commands and reports progress
 -> connector I/O completes on bounded pools; owner processes callbacks
 -> checkpoint captures connector state plus assignment and command boundary
 -> restore reinstates fenced attempt and replay metadata
 -> failure and close release buffers, timers, workers and ownership

Full managed mode reaches both owner loops. Coordinator-only mode retains legacy readers and routes their serialized restored splits through the managed coordinator boundary. The new Fake, Kafka and Iceberg capability decisions determine which lifecycle a job actually uses. Method-level comments distinguishing explicit deployment rejection from ordinary legacy selection matter for users.",

1.2 Compatibility

Legacy operation remains the default. The opt-in protocol and managed checkpoint additions have their own version boundary. Document supported homogeneous deployments and provide an explicit rollback path or reject unsupported mixed-version restore rather than implying interchangeability.

1.3 Performance and side effects

Queue and worker bounds limit resources only if every admission and timeout path honors them. Spare a hung async worker's ownership until it stops, and avoid busy idle polling. Mailbox and encoded transport limits must be validated consistently before scheduling.

1.4 Errors, logging, and findings

+1 to @SEZ9's earlier managed registration finding (High). seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/operation/source/ManagedSourceRegisterOperation.java:115 decodes a generic object through Hazelcast's serializer before checking that it is a TaskLocation. This is an object-decoding boundary, and a post-decode type check does not restrict what is instantiated first. The existing serialization test covers a valid round trip and a mismatched registered type after decode. Prefer a versioned field-by-field location envelope, with a test that rejects unsupported layouts before object decoding. Keep the surrounding cluster-member trust assumption explicit.

+1 to @SEZ9's current-head runtime findings.

  • Issues 1 and 4: The coordinator rejects an entire restored split list over the configured mailbox budget at seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceCoordinatorRuntime.java:316. Keep previously valid restore state recoverable through bounded chunks and validate configured payload size against the actual wire ceiling.
  • Issues 2 and 3: Managed Kafka treats later discovery failure as a source failure. Apply a bounded retry policy consistent with the documented behavior. In seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedCoordinatorScheduler.java:383, interruption and completion accounting occur separately, so timeout can free the slot while the old worker still runs. Keep accounting until real worker exit and distinguish queue latency from execution time.
  • Issues 5–8: Supply the connector SPI contract and correct lane/metric documentation. A permanently completed availability signal causes repeated polling even when there is no work. Preserve a meaningful idle signal and add close/idle regression coverage.

2. Code quality

2.1 Conventions

Owner assertions and callback diagnostics are useful. Connector flags need clear Javadoc and a developer example covering lifecycle, handler context and protocol version expectations.

2.2 Test coverage and stability

Stability: Risk present. The new managed-source engine ITs await checkpoints and verify restored output, while the close/idle boundary and blocked asynchronous worker cases need controlled tests. Both core engine integration jobs were cancelled. Unit tests pass on both operating systems and JDKs, and the Kubernetes jobs pass. A cancelled engine test cannot establish the managed runtime acceptance result.

2.3 Documentation

Align EN/ZH with actual lane selection and attempt-qualified metrics. Explain the supported upgrade and rollback protocol explicitly. The managed ABI needs a connector-facing development example.

3. Architecture

3.1 Change location

Engine-owned source threading is a sound long-term direction. Maintain one owner and an explicit protocol/serialization boundary per attempt.

3.2 Maintainability

Keep connector I/O outside owner critical sections. Make timeout completion and resource cleanup unambiguous, and reserve a separate path for restore control metadata.

3.3 Extensibility

Add more connectors only after the ABI and queue/restore invariants are stable under recoverable I/O failures and project-level integration tests.

3.4 Upgrade impact

Legacy jobs retain the old path and checkpoint behavior. Opt-in jobs require a compatible deployed runtime and documented rollback point.

4. Findings summary

# Finding Location Severity
- No new source blocker found - -

5. Merge recommendation

Ready to merge after fixes

Blocking items: Address the open registration decoder and current restore/scheduler/discovery blockers. Resolve the current dev conflict, then complete both managed-source engine integration lanes and independent maintainer review.

Non-blocking suggestions: Keep the IRIS update in dev, and improve the developer guide and idle metrics coverage while resolving the planned runtime contract.

The exact-head fork Build is cancelled. Both engine-v2-it rows were cancelled, so the worker/reader recovery gate remains unresolved. The unrelated IRIS replacement tag is already present on this head and current dev. No local PR execution was performed.

CI and repository state: no check reported in the Apache rollup; Build: cancelled. GitHub reports DIRTY / REVIEW_REQUIRED.

Verification: Reviewed all changed files and the referenced call sites at 6b2b814181597f060d35ecb40519d281d004303d against merge base a0ac9082af2f6ea1565bdf2d9fcce12ac00e18fd. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.

@SEZ9

SEZ9 commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the continued work on the managed source lanes. Per the latest recheck in this thread, the earlier managed-source findings remain open, and I don't see a reply to them here yet. If any of them is already addressed, please point me to the change and I'll take another look.

Robustness

  • PR11557-F1: restored splits sent by a legacy-lane Reader are rejected outright once they exceed reader-mailbox-max-bytes. Please add chunking or retry so a checkpoint cannot become unrestorable on the coordinator-only lane.
  • PR11557-F2: on the Kafka managed lane, any periodic partition-discovery failure or 1-minute timeout fails the source, while the legacy lane logs the error and retries on the next interval. Please match the legacy behaviour, or explain why the stricter behaviour is intended.
  • PR11557-F4: an async timeout releases the per-coordinator concurrency slot without confirming the worker has stopped, and the timeout clock starts at pool submission rather than at execution. Please hold the slot until the worker has actually finished, and start timing at execution.
  • PR11557-F5: max-command-payload-bytes is checked against the mailbox size but not against the 16 MiB wire hard limit. Please add that check to validate() so a configuration that passes validation cannot fail jobs at runtime.

Docs

  • PR11557-F3: the new connector-facing SPI needs developer documentation, and the ManagedSourceCapability flags a connector must set need Javadoc.
  • PR11557-F6: several Javadoc statements say a connector "stays on the legacy lane" where the selector actually fails deployment once the flag is enabled. Please reword them so explicit deployment rejection is clearly distinguished from ordinary legacy selection.
  • PR11557-F7: the documented metric names should match what the code registers, which is a #<sourceId>#attempt-<executionId> suffix rather than #{sourceId}.

Performance (low severity)

  • PR11557-F8: isAvailable() is permanently completed after no-more-splits in SourceReaderBase and always completed in FakeSourceReader, so the managed owner loop falls back to fixed-interval polling. Please fix this, or say if you would rather defer it.

A short note per item saying whether it is fixed, intentionally unchanged, or deferred would make the next pass much quicker.

@DanielLeens

Copy link
Copy Markdown
Contributor Author

Thanks @SEZ9. Your current-head follow-up aligns with the existing managed-lane blockers: restore-payload delivery, legacy discovery behavior, actual worker lifetime under timeout, wire-size validation and the documented capability/metric contracts still need a single coordinated update. No new commit has arrived since Daniel's last review, so I am retaining those findings rather than issuing another full review. Please map the next commit to those existing items and keep the legacy-lane behavior covered.

@SEZ9

SEZ9 commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the follow-up. No new commit has arrived since the last review, so the earlier findings stand as they are and I am not doing another full pass. Please address them in one coordinated update and map each change to its finding ID:

Robustness

  • PR11557-F1: restored splits sent by a legacy-lane Reader are rejected outright once they exceed reader-mailbox-max-bytes, with no chunking or retry. Please make sure a checkpoint stays restorable on the coordinator-only lane.
  • PR11557-F2: on the Kafka managed lane, a periodic partition-discovery failure or 1-minute timeout fails the source, while the legacy lane logs the error and retries on the next interval. Please align the two, or explain why the stricter behavior is intended.
  • PR11557-F4: an async timeout releases the per-coordinator concurrency slot without confirming the worker has stopped, and the timeout clock starts at pool submission rather than at execution.
  • PR11557-F5: max-command-payload-bytes is checked against the mailbox size but not against the 16 MiB wire hard limit, so a configuration that passes validate() can still fail jobs at runtime.

Docs

  • PR11557-F3: the new connector-facing SPI needs developer documentation, and the ManagedSourceCapability flags need Javadoc.
  • PR11557-F6: several Javadoc statements say a connector "stays on the legacy lane" where the selector actually fails deployment once the flag is enabled.
  • PR11557-F7: the documented metric names should match what the code registers, which is a #<sourceId>#attempt-<executionId> suffix rather than #{sourceId}.

Performance (low severity)

  • PR11557-F8: isAvailable() is permanently completed after no-more-splits in SourceReaderBase and always completed in FakeSourceReader, so the managed owner loop falls back to fixed-interval polling.

When you push, please add a short note per finding saying what changed and which test covers it, and keep the legacy-lane behavior covered. If you plan to defer any item, say which one and why.

@DanielLeens

Copy link
Copy Markdown
Contributor Author

Thanks, @SEZ9, for consolidating the remaining requests. I agree with carrying the existing blockers together: bounded/chunked restored-split transfer, Kafka discovery-failure semantics, timeout/concurrency ownership until the worker actually stops, and a real contract for valid configurations larger than the 16 MiB message limit. The SPI/configuration and metric documentation also need to match the actual deployment behavior. An always-completed availability future is a separate optional scheduling concern, not a reason to hide the correctness blockers.

Please push the coordinated implementation and restore/discovery/timeout/payload regressions before those points are marked resolved. There is no new head here, so this reply endorses the existing review rather than issuing another source review.

Checked unchanged head 6b2b814181597f060d35ecb40519d281d004303d against dev: compare diverged, ahead 45 / behind 43. This drift is recorded independently; it does not by itself request synchronization. This is a discussion/CI follow-up, not another full source review. No local build, test or runtime execution was performed. Daniel has READ repository permission; effective maintainer approval/dismissal remains a separate repository gate. Checked 2026-11-20T11:59:57.811808+00:00.

@SEZ9

SEZ9 commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

Thanks for consolidating the remaining requests. The head is still 6b2b814181597f060d35ecb40519d281d004303d, so the earlier findings stand unchanged and this is a follow-up, not a new review.

To close them, please push one coordinated update and map each change to the items below.

Correctness items

  • Restored-split transfer: restored splits from a legacy-lane Reader that exceed reader-mailbox-max-bytes are rejected with no chunking or retry, which can leave a checkpoint unrestorable. This needs bounded/chunked delivery.
  • Kafka discovery failures: on the managed lane a periodic partition-discovery failure or 1-minute timeout fails the source, while the legacy lane logs and retries on the next interval. Please settle these semantics against the legacy behavior.
  • Async timeout: the per-coordinator concurrency slot is released without confirming the worker has stopped, and the timeout clock starts at pool submission rather than execution. The slot should stay owned until the worker actually stops.
  • Payload limit: max-command-payload-bytes is checked against the mailbox size but not the 16 MiB wire hard limit, so a configuration that passes validate() can still fail at runtime. Please define a real contract for that case.

Documentation items

  • SPI docs: add developer documentation for the new connector-facing SPI and Javadoc for the ManagedSourceCapability flags.
  • Javadoc wording: correct the "stays on the legacy lane" statements where the selector actually fails deployment once the flag is enabled.
  • Metric names: the documented names should match what is registered, i.e. the #<sourceId>#attempt-<executionId> suffix rather than #{sourceId}.

Optional

  • Availability future: the always-completed isAvailable() in SourceReaderBase (after no-more-splits) and FakeSourceReader is a separate scheduling concern. It does not need to hold up the items above.

Please also include regression tests for the restore, discovery, timeout and payload cases, and keep the legacy-lane behavior covered. If you intend to defer any item, say which one and why, so we can agree on it before these points are marked resolved.

@DanielLeens

Copy link
Copy Markdown
Contributor Author

Thanks, @SEZ9. The four established ownership/contracts still need the coordinated code update: bounded transfer of restored splits, preserved Kafka discovery-error semantics, async slot ownership until the worker actually stops with execution time measured from task start, and compatibility for valid 16 MiB configurations. The SPI/metrics documentation belongs with that contract. Availability-future refinement remains optional. No new commit has landed, so these are not confirmed fixes. The current merge conflict and incomplete/cancelled CI are separate gates, not substitutes for resolving the source blockers.

Checked unchanged head 6b2b814181597f060d35ecb40519d281d004303d against dev: compare diverged, ahead 45 / behind 46. This drift is recorded independently; it does not by itself request synchronization. This is a discussion/CI follow-up, not another full source review. No local build, test or runtime execution was performed. Daniel has READ repository permission; effective maintainer approval/dismissal remains a separate repository gate. Checked 2026-11-21T12:06:29.365986+00:00.

@SEZ9

SEZ9 commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the continued work on this. The head is still 6b2b814181597f060d35ecb40519d281d004303d, so none of the earlier points can be marked resolved yet. Here is what remains, all from the existing review.

Code changes still needed

  • Restored splits: splits sent back by a legacy-lane Reader are rejected outright once they exceed reader-mailbox-max-bytes. Please make the transfer bounded or chunked (or retried) so a checkpoint cannot become unrestorable on the coordinator-only lane.
  • Kafka discovery failures: on the managed lane, a periodic partition-discovery failure or 1-minute timeout fails the source. Please keep the legacy behavior of logging the error and retrying on the next interval.
  • Async timeout ownership: a timeout releases the per-coordinator concurrency slot without confirming the worker has stopped, and the clock starts at pool submission. Please hold the slot until the worker actually stops and measure the timeout from execution start.
  • Payload limit validation: max-command-payload-bytes is checked against the mailbox size but not against the 16 MiB wire hard limit. Please either reject such values in validate() or define how larger valid configurations are handled, so a config that passes validation cannot fail jobs at runtime.

Please add regression tests for the restore, discovery, timeout and payload cases along with these changes.

Documentation still needed

  • Add developer documentation for the new connector-facing SPI, and Javadoc on the ManagedSourceCapability flags a connector must set.
  • Correct the Javadoc that says a connector "stays on the legacy lane" where the selector actually fails deployment once the flag is enabled.
  • Align the documented metric names with what the code registers, which is a #<sourceId>#attempt-<executionId> suffix rather than #{sourceId}.

Optional

  • isAvailable() is permanently completed after no-more-splits in SourceReaderBase and always completed in FakeSourceReader, so the managed owner loop falls back to fixed-interval polling. This is low severity and can be a follow-up, but please say which way you plan to go.

Once you push the update, a short note on which commit addresses which point would make it quick to confirm each one.

@SEZ9 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the follow-up. I checked the latest changes at dad46fd5b0be against my previous review comments.

The scope of this pass is limited to the findings from the previous review; it does not introduce a new set of review items.

Previous findings still requiring follow-up

Issue 1: PR11557-F1: Restored splits sent by a legacy-lane Reader are rejected outright once they exceed reader-mailbox-max-bytes, with no chunking or retry, which can make a checkpoint unrestorable on the coordinator-only lane.

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceCoordinatorRuntime.java:316
  • Why it matters: - Root cause: when the coordinator is managed, RestoredSplitOperation.runInternal calls task.addSerializedSplitsBack(...), which delegates to admitLegacySerializedRestoredSplits. That method throws IllegalArgumentException as soon as the summed split bytes exceed config.getReaderMailboxMaxBytes() (4 MiB by default).
  • It also throws IllegalStateException when outboundMemoryBudget.tryReserve(...) fails or admitControl(...) returns false. Both conditions are transient, but the retry predicate in RestoredSplitOperation only retries TaskGroupContextNotFoundException, so neither is retried.
  • The managed Reader path does not have this problem: ManagedSourceReaderRuntime.appendRestoredStateChunks splits restored state into chunks bounded by max-command-payload-bytes. A legacy Reader sends its whole restored split state in one operation, so there is no equivalent bound on the coordinator-only lane.
  • Impact: a Reader whose restored split state is larger than the mailbox limit hits the same exception on every restore attempt. The same checkpoint restores on the legacy lane, where RestoredSplitOperation deserializes and calls addSplitsBack with no size limit.
  • Suggested fix: admit the serialized splits in bounded batches rather than rejecting the whole list, and treat a full memory budget or mailbox as a retryable condition instead of a hard failure. A test that restores more than reader-mailbox-max-bytes of split state through a managed coordinator with a legacy Reader would cover this.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceCoordinatorRuntime.java:323 if (!outboundMemoryBudget.tryReserve(totalBytes)) {; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/operation/source/RestoredSplitOperation.java:92 task.addSerializedSplitsBack(splits, subtaskIndex);
  • Suggested fix: On the coordinator-only lane the legacy Reader sends its whole restored split state in one RestoredSplitOperation, and this line turns anything above reader-mailbox-max-bytes (4 MiB by default) into an IllegalArgumentException. The same checkpoint restores on the legacy lane, but here it hits the limit on every attempt, so the job cannot recover until the limit is raised in the engine configuration.

The two IllegalStateException paths below (memory budget exhausted, mailbox full) are transient, yet RestoredSplitOperation only retries TaskGroupContextNotFoundException, so they also fail the restore.

Could we admit the splits in bounded batches, as ManagedSourceReaderRuntime.appendRestoredStateChunks does for the managed Reader, and make the transient cases retryable?

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: Set managed-source-runtime.enabled: true with default limits and run an Iceberg streaming source (managed coordinator, legacy Reader). Let one Reader subtask checkpoint split state whose serialized size sums to more than 4194304 bytes, then fail and restore the job. RestoredSplitOperation throws IllegalArgumentException("Managed Source restored split payload exceeds mailbox byte limit"), SourceFlowLifeCycle.restoreState fails, and each later restore from that checkpoint fails identically.

Issue 2: PR11557-F2: On the Kafka managed lane, any periodic partition-discovery failure or 1-minute timeout fails the source, while the legacy lane logs the error and retries on the next interval.

  • Location: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceSplitEnumerator.java:597
  • Why it matters: - Root cause: the result handler in triggerManagedDiscovery rethrows every failure as KafkaConnectorException(DISCOVER_PARTITION_FAILED). The task is also submitted with AsyncTaskOptions.builder().timeout(Duration.ofMinutes(1)).build(), which keeps the default failure policy FAIL_SOURCE.
  • ManagedCoordinatorScheduler.completeSubmission passes an exception thrown by the result handler to failureHandler. Even if the handler did not throw, a non-null failure under FAIL_SOURCE is passed to failureHandler as well. Either path fails the source, and the timeout arrives as a TimeoutException through the same route.
  • The legacy lane in the same class behaves differently: the scheduled task in open() wraps discoverySplits() in try/catch and only logs "Dynamic discovery failure:", so the next interval retries.
  • Impact: a transient AdminClient error or a slow metadata response during periodic discovery now fails a running Kafka job on the managed lane, where the same job would keep running on the legacy lane.
  • Suggested fix: keep fail-fast only for the initial discovery (dynamicDiscovery == false). For periodic discovery, log the failure, call scheduleNextManagedDiscovery(), and use a failure policy that does not fail the source. If the stricter behavior is intended, please document it as a behavior difference between the lanes.
  • Evidence: seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceSplitEnumerator.java:597 throw new KafkaConnectorException(; seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceSplitEnumerator.java:613 AsyncTaskOptions.builder().timeout(Duration.ofMinutes(1)).build());; seatunnel-api/src/main/java/org/apache/seatunnel/api/source/scheduler/AsyncTaskOptions.java:71 private AsyncFailurePolicy failurePolicy = AsyncFailurePolicy.FAIL_SOURCE;
  • Suggested fix: This handler rethrows every discovery failure, and the task keeps the default FAIL_SOURCE policy, so a transient AdminClient error or the 1-minute timeout during periodic discovery now fails the source. The legacy lane in this class catches and logs it ("Dynamic discovery failure:") and retries on the next interval.

Could we keep fail-fast only for the initial discovery (dynamicDiscovery == false), and for periodic discovery log the failure and call scheduleNextManagedDiscovery() under a failure policy that does not fail the source? If failing is intended, please document the difference from the legacy lane.

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: Run a Kafka streaming source on the managed lane with partition-discovery.interval-millis greater than 0. After the first successful discovery, make one periodic round fail, for example an AdminClient listTopics or describeTopics that throws during a broker rolling restart, or a round that takes longer than 60 seconds. The handler throws KafkaConnectorException(DISCOVER_PARTITION_FAILED), the coordinator's next turn throws, and the source fails. With the flag off, the same failure is only logged and discovery runs again after the interval.

Issue 3: PR11557-F4: An async timeout releases the per-coordinator concurrency slot without confirming that the worker has stopped, and the timeout clock starts at pool submission rather than at execution.

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedCoordinatorScheduler.java:383
  • Why it matters: - Root cause: in startSubmission the timeout timer is armed immediately after submitManagedSourceAsync. When it fires, it enqueues a TimeoutException completion and calls worker.cancel(true). completeSubmission then clears state.running and decrements runningCount, whether or not the worker thread has actually returned.
  • Future.cancel(true) is only an interrupt. Iceberg planning submitted through callAsync (5-minute timeout in IcebergStreamSplitEnumerator) may be blocked in file or object-store I/O that does not respond to interruption, so the callable can keep running after its slot has been released.
  • The worker pools are created once in TaskExecutionService and shared by every managed coordinator on the worker. A callable that outlives its timeout therefore still holds a thread of coordinator-async-io-threads, while the scheduler treats the slot as free and can start the next submission.
  • Because the timer starts at submission, time spent waiting in the pool queue (coordinator-async-queue-capacity) counts against the timeout. Under load a task can time out before it has run at all.
  • Suggested fix: start the timeout when the callable begins executing, and release the slot only once the worker has finished or been confirmed cancelled. If a worker cannot be stopped, track it explicitly so pool exhaustion is visible in metrics rather than hidden behind a free slot.
  • Evidence: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedCoordinatorScheduler.java:383 worker.cancel(true);; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedCoordinatorScheduler.java:483 state.running = false;; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedCoordinatorScheduler.java:485 runningCount--;
  • Suggested fix: worker.cancel(true) only interrupts, but the timeout completion then runs completeSubmission, which sets state.running = false and decrements runningCount even if the callable is still blocked in I/O that ignores the interrupt. The slot is reported free while a thread of the shared worker pool is still held, so repeated timeouts can exhaust coordinator-async-io-threads for every managed coordinator on the worker.

The timer is also armed right after submitManagedSourceAsync, so time spent in the pool queue counts against the timeout.

Could we start the clock when the callable begins executing, and release the slot only after the worker has returned or been confirmed cancelled?

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: Case 1: occupy all coordinator-async-io-threads (default 32) with callables from other sources for longer than a task's timeout. A newly submitted task sits in the queue, its timer fires, and the result handler receives TimeoutException although the callable never started; with the default FAIL_SOURCE policy the source fails. Case 2: submit a callable that does not react to Thread.interrupt(), with coordinator-async-max-concurrency at its default of 4. After the timeout runningCount drops while the pool thread is still busy, and the scheduler starts another submission, so more callables of that coordinator run at once than the configured limit.

Issue 4: PR11557-F5: max-command-payload-bytes is checked against the mailbox size but not against the 16 MiB wire hard limit, so a configuration that passes validate() can fail jobs at runtime.

  • Location: seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/ManagedSourceRuntimeConfig.java:104
  • Why it matters: - Root cause: ManagedSourceRuntimeConfig.validate() only requires maxCommandPayloadBytes to be positive and to fit in readerMailboxMaxBytes - readerReservedControlBytes. Nothing ties it to SourceCommandEnvelope.MAX_WIRE_PAYLOAD_BYTES (16 MiB), which the envelope constructor and the readInternal methods of ManagedSourceCommandOperation and ManagedCoordinatorCommandOperation enforce unconditionally.
  • The chunkers in ManagedSourceCoordinatorRuntime (chunkAssignments, around line 1480) and ManagedSourceReaderRuntime (appendRestoredStateChunks, appendRestoredProofChunks) use config.getMaxCommandPayloadBytes() as the chunk cap. With a large enough mailbox, a value above 16 MiB passes validate() and lets the chunkers build payloads that the envelope then rejects with "Source command payload exceeds wire hard limit".
  • Impact: the misconfiguration is accepted when the job is planned and only surfaces later, when a split assignment or restore payload large enough to exceed 16 MiB is sent.
  • Suggested fix: reject max-command-payload-bytes above the wire hard limit in validate(). The constant lives in seatunnel-engine-server, so it would need to move to (or be mirrored in) seatunnel-engine-common. Please also state the upper bound in the configuration docs.
  • Evidence: seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/ManagedSourceRuntimeConfig.java:104 if (maxCommandPayloadBytes > readerMailboxMaxBytes - readerReservedControlBytes) {; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/SourceCommandEnvelope.java:29 public static final int MAX_WIRE_PAYLOAD_BYTES = 16 * 1024 * 1024;; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/SourceCommandEnvelope.java:137 if (this.payload.length > MAX_WIRE_PAYLOAD_BYTES) {
  • Suggested fix: This check bounds max-command-payload-bytes by the mailbox, but not by the wire hard limit. SourceCommandEnvelope rejects any payload above MAX_WIRE_PAYLOAD_BYTES (16 MiB) in its constructor, and both command operations reject it in readInternal, while the chunkers use config.getMaxCommandPayloadBytes() as the chunk cap. With a large mailbox, a value such as 32 MiB therefore passes validate() and only fails later, when a large enough assignment or restore payload is sent.

Could validate() also reject values above the wire limit? The constant would need to be reachable from seatunnel-engine-common.

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: Set reader-mailbox-max-bytes: 134217728 and max-command-payload-bytes: 33554432 in seatunnel.yaml; validate() accepts it because 33554432 is below 134217728 minus 262144. Run a source on the managed Reader and coordinator lane whose enumerator assigns, in one assignSplit call, splits whose encoded size is between 16 MiB and 32 MiB. chunkAssignments returns a single chunk, SourceCommandEnvelope.create throws on the coordinator thread, and the job fails at runtime instead of at config validation.

Issue 5: PR11557-F3: The new connector-facing SPI has no developer documentation, and the ManagedSourceCapability flags a connector must set carry no Javadoc.

  • Location: seatunnel-api/src/main/java/org/apache/seatunnel/api/source/managed/ManagedSourceCapability.java:233
  • Why it matters: - Root cause: the PR adds a public connector-facing SPI under seatunnel-api (ManagedSourceCapability, ManagedSourceReader, PollContext, PollStatus, CoordinatorScheduler, AsyncTaskOptions and related types). Under docs/, the only mention of any of these types is one bullet in the operator page (en and zh): "The connector declares a compatible ManagedSourceCapability".
  • In ManagedSourceCapability, the builder methods and getters for connectorStateVersion, supportsBoundedPoll, supportsWakeup, supportsAttemptFencing, supportsAsyncEnumerator and stableSplitIdentifiers have no Javadoc. Only usesSourceEvents is documented.
  • These flags are not cosmetic. validate() requires bounded poll, wakeup, attempt fencing and stable split identifiers for a managed Reader, the selector requires supportsAsyncEnumerator for a managed coordinator, and all of them are hashed into the capability digest that is persisted in checkpoint metadata.
  • Impact: a connector author has no written statement of what each flag promises to the engine, or of when connectorStateVersion must be bumped, so a flag can be set to true without the connector meeting the contract.
  • Suggested fix: add Javadoc to each builder method stating the guarantee the connector makes and what the engine does with it, and add a connector-developer page in docs/en and docs/zh that describes how to opt a connector into the managed lane.
  • Evidence: seatunnel-api/src/main/java/org/apache/seatunnel/api/source/managed/ManagedSourceCapability.java:243 public Builder supportsAttemptFencing(boolean supportsAttemptFencing) {; seatunnel-api/src/main/java/org/apache/seatunnel/api/source/managed/ManagedSourceCapability.java:218 public Builder connectorStateVersion(int connectorStateVersion) {; docs/en/engines/zeta/managed-source-runtime.md:33 2. The connector declares a compatible ManagedSourceCapability.
  • Suggested fix: These builder flags are promises the engine relies on: validate() requires bounded poll, wakeup, attempt fencing and stable split identifiers for a managed Reader, and every flag is hashed into the capability digest stored in checkpoints. Only usesSourceEvents has Javadoc, though.

Could you document what a connector must guarantee for supportsBoundedPoll, supportsWakeup, supportsAttemptFencing, stableSplitIdentifiers and supportsAsyncEnumerator, and when connectorStateVersion has to change? A connector-developer page in docs/en and docs/zh would help too; the docs currently mention this SPI only in one bullet of the operator page.

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: A connector author who wants the managed lane opens ManagedSourceCapability.Builder. Nothing in the Javadoc or under docs/ says what supportsBoundedPoll(true), supportsWakeup(true), supportsAttemptFencing(true) or stableSplitIdentifiers(true) oblige the connector to do, or when connectorStateVersion must be bumped. The only prose is the operator-facing bullet The connector declares a compatible ManagedSourceCapability.

Issue 6: PR11557-F6: Javadoc says a connector "stays on the legacy lane" in cases where the selector actually fails deployment once the flag is enabled.

  • Location: seatunnel-api/src/main/java/org/apache/seatunnel/api/source/SeaTunnelSource.java:128
  • Why it matters: - Root cause: SeaTunnelSource#getManagedSourceCapability says "The default keeps every existing connector on the legacy compatibility lane". That holds only while managed-source-runtime.enabled=false. With the flag on, ManagedSourceRuntimeSelector.select throws IllegalStateException for capability == null || capability.isLegacy().
  • ManagedSourceCapability.Builder#usesSourceEvents says declaring true "keeps the connector on the legacy lane by failing selection". Those are two different outcomes, and the code does the second: select throws for capability.usesSourceEvents(), so the job is not deployed.
  • The class Javadoc of ManagedSourceRuntimeConfig says only that the feature is disabled by default and that a running job never changes lane. It does not mention that enabling the flag rejects every Source without a managed capability.
  • The operator page already states the real behavior ("deployment fails closed instead of silently changing execution semantics"), so the Javadoc and the docs currently disagree.
  • Impact: a connector author or operator reading the Javadoc would expect an automatic fallback to the legacy lane and instead gets a deployment failure for every job that uses an undeclared connector.
  • Suggested fix: reword these Javadocs to state both cases explicitly: legacy lane while the flag is off, deployment failure once it is on.
  • Evidence: seatunnel-api/src/main/java/org/apache/seatunnel/api/source/managed/ManagedSourceCapability.java:252 * SourceEvent} codec, so declaring {@code true} keeps the connector on the legacy lane by; seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/ManagedSourceRuntimeConfig.java:27 * <p>The feature is disabled by default. A running job never changes lane when this configuration; seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/runtime/source/ManagedSourceRuntimeSelector.java:72 if (capability == null || capability.isLegacy()) {
  • Suggested fix: This is only true while managed-source-runtime.enabled is false. Once the switch is on, ManagedSourceRuntimeSelector.select(...) throws for capability.isLegacy(), so a connector that keeps this default is rejected at deployment rather than kept on the legacy lane. Since this is the SPI Javadoc connector authors rely on, could you state both cases explicitly?

The same wording appears in ManagedSourceCapability.Builder#usesSourceEvents ("keeps the connector on the legacy lane by failing selection"); there too the selector fails deployment rather than falling back.

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: Enable managed-source-runtime.enabled: true and submit a job whose source keeps the default getManagedSourceCapability(), which returns ManagedSourceCapability.legacy(). The Javadoc says it stays on the legacy lane. ManagedSourceRuntimeSelector.select instead throws that the connector does not declare a managed Source capability while managed-source-runtime.enabled=true, and the job is not deployed.

Issue 7: PR11557-F7: The documented metric names do not match what the code registers: every new Source runtime metric carries a #<sourceId>#attempt-<executionId> suffix, not #{sourceId}.

  • Location: docs/en/engines/zeta/realtime-observability.md:312
  • Why it matters: - Root cause: docs/en/engines/zeta/realtime-observability.md:312 (and the zh page at line 311) says the new diagnostics use the same #{sourceId} suffix as SourceReadNs#{sourceId}. SourceRuntimeMetrics.metricSuffix and ManagedSourceRuntimeMetrics.metricSuffix both return "#" + sourceRuntimeId + "#attempt-" + executionId.
  • The managed page calls this a "stable Source action suffix" (managed-source-runtime.md:172, zh line 160), but the execution id is part of the suffix, so the metric name changes with every task attempt.
  • Impact: a dashboard or alert built from the documented names (for example SourcePollTotal#{sourceId}) will not match the registered metric, and any query keyed on the full name has to be updated after each task attempt.
  • Suggested fix: either document the real suffix #<sourceId>#attempt-<executionId> in both languages and drop the word "stable", or change the code to use the #{sourceId} suffix if attempt-scoped names are not intended.
  • Evidence: docs/en/engines/zeta/managed-source-runtime.md:172 Managed metrics use a stable Source action suffix. Command IDs, split IDs, table names, and; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/flow/SourceRuntimeMetrics.java:159 return "#" + sourceRuntimeId + "#attempt-" + executionId;; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceRuntimeMetrics.java:321 return "#" + sourceRuntimeId + "#attempt-" + executionId;
  • Suggested fix: This sentence does not match the code. SourceRuntimeMetrics.metricSuffix(...) and ManagedSourceRuntimeMetrics.metricSuffix(...) both build "#" + sourceRuntimeId + "#attempt-" + executionId, so the registered name is SourcePollTotal#<sourceId>#attempt-<executionId>, not SourcePollTotal#{sourceId}. The name therefore changes on every task attempt, which also makes "stable Source action suffix" in managed-source-runtime.md inaccurate.

Could you either document the real suffix in the en and zh pages, or change the code to use #{sourceId} if attempt-scoped names are not intended?

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: Enable engine observability and run a job whose source action id is 1 and whose task execution id is 12345. The registry holds SourcePollTotal#1#attempt-12345, not the documented SourcePollTotal#1. A query built from the docs matches nothing. After a failover the execution id changes and the name changes again. SourceManagedAdmissionTotal#1 never exists; only SourceManagedAdmissionTotal#1#attempt-12345#ACCEPTED and its sibling statuses do.

Issue 8: PR11557-F8: isAvailable() is permanently completed after no-more-splits in SourceReaderBase and always completed in FakeSourceReader, so the managed Reader falls back to fixed-interval polling.

  • Location: seatunnel-connectors-v2/connector-common/src/main/java/org/apache/seatunnel/connectors/seatunnel/common/source/reader/SourceReaderBase.java:172
  • Why it matters: - Root cause: SourceReaderBase.isAvailable() returns an already-completed future whenever noMoreSplitsAssignment is true, and FakeSourceReader.isAvailable() returns a completed future unconditionally.
  • On NOTHING_AVAILABLE, ManagedSourceReaderRuntime.subscribeToAvailability() attaches whenComplete, which runs inline on a completed future and sets availabilitySignalled back to true at once.
  • The turn reports no progress, so SourceFlowLifeCycle.collect() sleeps idle-wait-ms (10 ms by default) and the next turn polls the reader again. The availability future no longer gates polling; the idle sleep does.
  • KafkaSourceSplitEnumerator.assignSplit() calls signalNoMoreSplits whenever discoveryIntervalMillis <= 0, with no check for streaming mode. An unbounded Kafka job without dynamic discovery therefore stays in this state for its whole lifetime, since pollNextManaged only returns END_OF_INPUT for bounded sources.
  • Impact: an idle reader is polled every idle-wait-ms instead of waiting for the fetcher to signal data. The cost is extra wakeups and empty polls rather than incorrect results, which is why this is low severity.
  • Suggested fix: drop noMoreSplitsAssignment from the short-circuit, or apply it only when the source is bounded and about to return END_OF_INPUT, so the reader keeps returning the fetcher-driven availability future. FakeSourceReader could return a pending future while splits is empty and complete it in addSplits.
  • Evidence: seatunnel-connectors-v2/connector-fake/src/main/java/org/apache/seatunnel/connectors/seatunnel/fake/source/FakeSourceReader.java:236 return CompletableFuture.completedFuture(null);; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceReaderRuntime.java:681 availabilitySignalled.set(true);
  • Suggested fix: Once noMoreSplitsAssignment is true this always returns a completed future, so subscribeToAvailability() re-arms availabilitySignalled inline and the runtime re-polls an idle reader on every loop turn (every idle-wait-ms). Kafka sends no-more-splits whenever discoveryIntervalMillis <= 0, including in streaming mode, so in that configuration the reader never waits on the fetcher's availability signal.

Could noMoreSplitsAssignment be dropped from this condition, or limited to the bounded case that is about to return END_OF_INPUT? FakeSourceReader.isAvailable() has the same effect because it always returns a completed future.

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: Run any SourceReaderBase-based managed reader after handleNoMoreSplits() with an empty elementsQueue. KafkaSourceSplitEnumerator.java:515-516 signals no-more-splits whenever discoveryIntervalMillis <= 0, with no streaming-mode condition at that site. Alternatively run a managed FakeSource that is waiting for splits or for split.read-interval. Each collect() turn calls pollNextManaged, gets NOTHING_AVAILABLE, re-arms availabilitySignalled inline and sleeps 10 ms, so pollNextManaged and SourcePollTotal advance about 100 times per second while idle.

Review conclusion

Conclusion: verification is incomplete; approval is not ready

2. Remaining follow-ups

  • Issue 1: Restored splits sent by a legacy-lane Reader are rejected outright once they exceed reader-mailbox-max-bytes, with no chunking or retry, which can make a checkpoint unrestorable on the coordinator-only lane.
  • Issue 2: On the Kafka managed lane, any periodic partition-discovery failure or 1-minute timeout fails the source, while the legacy lane logs the error and retries on the next interval.
  • Issue 3: An async timeout releases the per-coordinator concurrency slot without confirming that the worker has stopped, and the timeout clock starts at pool submission rather than at execution.
  • Issue 4: max-command-payload-bytes is checked against the mailbox size but not against the 16 MiB wire hard limit, so a configuration that passes validate() can fail jobs at runtime.
  • Issue 5: The new connector-facing SPI has no developer documentation, and the ManagedSourceCapability flags a connector must set carry no Javadoc.
  • Issue 6: Javadoc says a connector "stays on the legacy lane" in cases where the selector actually fails deployment once the flag is enabled.
  • Issue 7: The documented metric names do not match what the code registers: every new Source runtime metric carries a #<sourceId>#attempt-<executionId> suffix, not #{sourceId}.
  • Issue 8: isAvailable() is permanently completed after no-more-splits in SourceReaderBase and always completed in FakeSourceReader, so the managed Reader falls back to fixed-interval polling.

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

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Sorry for the gaps in my previous pass. In particular, the managed-reader restore queue has the same aggregate-window problem discussed below, and my registration-decoder wording was broader than the evidence supports. These are corrections to the earlier review, not new regressions introduced by the latest synchronization. Thanks, @SEZ9, for keeping the existing finding IDs and concrete cases together. I have now re-read the full current diff and its runtime paths as an Apache SeaTunnel maintainer; this is a technical COMMENT on my own PR, not an independent approval.

What problem does this PR solve?

User pain. Connector reader, enumerator, I/O and checkpoint callbacks currently coordinate their own concurrency, making ownership and recovery difficult to reason about.

Fix. STIP-31 (#11558) adds a default-off capability-selected owner runtime, cooperative polling, bounded admission, async discovery, and checkpointed assignment ownership.

Example and summary. After a reader accepts a partition assignment and then fails before checkpointing it, the coordinator retains enough split state to replay it. This aims to make that responsibility explicit in Zeta rather than scattering it across connectors.

1. Code changes

1.1 Core logic

Complete runtime path:

PhysicalPlanGenerator.managedSourceSelection -> validate config/capability; reject ALL thread sharing
 -> persist selection/checkpoint-enabled mode in SourceConfig and enumerator descriptor
 -> SourceSplitEnumeratorTask.init/restoreState on restore operation thread
    -> decode coordinator state/digest; construct/open enumerator; complete restore future
 -> WAITING_RESTORE owner loop drains registrations before readerRegisterComplete
 -> SourceFlowLifeCycle opens reader, activates managed mode, starts registration/watchdog
 -> reader attempt/execution registers -> coordinator owner sends epoch-start
 -> reader owner queues restored state/proofs -> epoch-applied proof -> all readers ready
 -> enumerator.run -> keyed shared-pool discovery -> result callback on owner
 -> assignment ledger DISPATCHED -> chunked command -> mailbox ACCEPTED -> owner addSplits
 -> COMMAND_APPLIED; bounded poll directly forwards Source -> Transform -> Sink
 -> barrier snapshots coordinator ledger and ordered reader state
 -> reader reports ownership; admission callback finishes barrier/ACK/forward
 -> completed checkpoint releases durable ownership; abort retains replay responsibility
 -> restore reconciles all reader proofs before assignment replay/rescale
 -> failure/close releases mailboxes, outbound reservations, timers and worker handles
Coordinator-only Iceberg: reader remains legacy -> RestoredSplitOperation sends entire split list
 -> managed coordinator admission -> owner deserializes/addSplitsBack (currently aggregate-limit fatal)

Key findings and correctness:

  1. The normal default-off path keeps existing connector callbacks and synchronous task acknowledgements; new default SPI methods preserve existing implementations. Managed Fake/Kafka use both owners, streaming Iceberg only its coordinator. Unsupported or SourceEvent-dependent connectors fail deployment when explicitly enabled.
  2. The owner-thread guard is deliberately absent from restore-only initialization; the restore future provides publication before the task loop starts. PART/OFF preserve owner identity; ALL is explicitly rejected.
  3. The assignment ledger distinguishes delivery from durable reader ownership. Single-flight sequencing, replacement attempt fences, complete restore proof groups, and rescale reconciliation are meaningful recovery mechanisms. They do not fix the aggregate outbound-window restore failure described with F1.
  4. Stop-with-savepoint persists the pre-barrier running lifecycle while genuine end-of-input remains draining. The new IT requires fresh restored output plus a later checkpoint, which is stronger than RUNNING alone. This remains source inspection plus the actual CI below.
  5. The four existing robustness blockers remain in the current full diff. This is an experimental long-term architecture, with explicit conformance/performance graduation gates still outstanding; declaring capability flags is not certification evidence.

Before (legacy restore):

for (byte[] split : splits) {
    deserializeSplits.add(task.getSplitSerializer().deserialize(split));
}
task.addSplitsBack(deserializeSplits, subtaskIndex);

After (coordinator-only admission):

if (task.isManagedCoordinatorRuntime()) {
    task.addSerializedSplitsBack(splits, subtaskIndex);
    return null;
}
// Admission rejects totalBytes > config.getReaderMailboxMaxBytes().

This correctly moves connector deserialization off the operation thread, but currently makes an otherwise restorable aggregate split list fail its admission limit.

Current CI and upstream evidence. Exact-head Build 45020529047 is in progress, with all four unit-test OS/JDK rows successful and both engine-v2-it rows still running in the inspected job snapshot. The Iceberg Java 11 job and JDBC DDL Java 11 job fail before tests: repeated Maven Central HTTP 429 while downloading maven-wrapper 3.1.0, then MavenWrapperMain cannot load. These logs do not establish a managed-runtime source failure. Current dev ef9c7ee2586c97115ecc0baf6d928cba4f46d6d9 has identical mvnw/wrapper files; there is no verified upstream wrapper fix or basis to promise that sync cures rate limiting. Retry the affected lanes after dependency access recovers, without unrelated dependency patches. Earlier cancelled-engine CI wording is superseded by the running current-head lanes. Compare is diverged, ahead 46 / behind 8, and GitHub reports an actual merge conflict: the author must resolve that conflict against dev independently of the 429 and source fixes. No synchronization was performed for the contributor.

1.2 Compatibility

Partially incompatible when explicitly opting into the new lane: runtime mode, protocol, connector state version and digest must match checkpoint metadata. Both lane-change directions reject restore; the EN/ZH incompatible-changes entries now correctly explain re-selection after failover/savepoint restore and the fresh-position/compatible-checkpoint migration. Existing SourceReader/Collector methods and default capability keep the default-off SPI compatible. FakeSourceSplit retains its explicit serialVersionUID, adds totalRowNum, preserves the old constructor and negative custom-row progress marker; there is a regression for that legacy marker. Kafka discovery failure semantics still need F2 resolution. Homogeneous configuration is required; mixed-version operation is not certified.

1.3 Performance and side effects

No per-record transport mailbox is introduced: records still flow through the collector, with byte estimation and poll accounting. Control envelopes/ledger snapshots clone bytes, and restore currently materializes all encoded chunks before window admission; peak allocation is not equal to retained mailbox accounting. I/O/CPU pools are worker-shared and bounded, but timeout slot release currently misrepresents actual blocked workers (F4). The optional completed-future path adds idle wakeups; soft-budget warning logging can also be frequent under sustained cooperative polling and should be assessed in the declared benchmarks. No throughput/CPU/GC/soak result was generated locally.

1.4 Errors, logging, and findings

Issue 52: Complete the already-requested owner-runtime regression matrix

  • Location: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceReaderRuntime.java:1006.
  • Description and risk: Retained Issue 52: low-level codec/state tests cannot demonstrate the composed mailbox/transport/owner callbacks. The PR body itself still marks retry bookkeeping, watchdog delivery, close/fence publication and handoff accounting as partial. The aggregate restore case also requires the actual sender window and accepted-result callback ordering.
  • Best improvement: Add deterministic production-runtime harness tests for the existing matrix and F1/F2/F4/F5, with controlled callbacks/latches and ownership/output assertions. Attach current-head native recovery and conformance results before graduating the Draft.
  • Responsibility and trade-off: Keep managed protocol, ownership and scheduling invariants in the engine runtime; connector pilots should implement the published SPI without adding connector-specific engine exceptions. Prefer resumable bounded transfer over increasing limits or blocking owner loops.
  • Severity: Medium; blocking: true.
  • Previously raised by another reviewer: No, unless explicitly attributed above.

Issue 53: Bound and clean up asynchronous IT jobs on every assertion path

  • Location: seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/ManagedSourceRuntimeIT.java:100.
  • Description and risk: The savepoint/restore IT starts common-pool tasks, uses unbounded jobFuture.get()/restoreFuture.get(), and only stops the job on the success path. A failed intermediate status/progress assertion can leave the job/client task alive and contaminate later tests or hang suite completion. This is a carryover stability concern, not a measured flaky failure.
  • Best improvement: Use try/finally to stop the test job and await/cancel client tasks with generous explicit deadlines. Keep condition-based progress assertions. This is non-blocking cleanup hardening alongside the required functional regressions.
  • Responsibility and trade-off: Keep managed protocol, ownership and scheduling invariants in the engine runtime; connector pilots should implement the published SPI without adding connector-specific engine exceptions. Prefer resumable bounded transfer over increasing limits or blocking owner loops.
  • Severity: Medium; blocking: false.
  • Previously raised by another reviewer: No, unless explicitly attributed above.

Community reconciliation. +1 to @SEZ9's current-head review. I traced the same paths independently. The following retain that review's finding IDs rather than creating duplicate Daniel issues:

  • PR11557-F1 (High, blocking): bounded restore delivery. seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceCoordinatorRuntime.java:316 still rejects the complete legacy-reader restore list above the default 4 MiB mailbox limit. RestoredSplitOperation.java:87 retries only a missing task-group context, so worker-budget exhaustion and mailbox-full exceptions are also fatal. On the streaming Iceberg coordinator-only lane, a checkpoint can accumulate more split bytes than one mailbox although the preceding job ran normally. Transfer restore data incrementally and retry transient admission failures without invoking connector deserializers on the operation thread.

    Related additional evidence, including a correction to the earlier managed-reader comparison: seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceReaderRuntime.java:1006 chunks restored state, but then synchronously sends every chunk in the same applyEpochStart() owner turn. sendCoordinatorCommand() reserves each envelope at line 1119, and reserveOutbound() at line 1239 throws once their aggregate exceeds the 4 MiB outbound window. A successful RPC only enqueues a local callback; handleOutboundResult() cannot release the first reservation until this turn returns. Consequently, a managed checkpoint with several individually valid sub-512-KiB splits whose combined encoded state exceeds 4 MiB is also not recoverable under the default limits. This is a carryover I should have identified previously, not a new regression from the sync commit. Both lanes need a resumable producer that sends only what the current window can retain and continues after acknowledgements; keep the epoch application proof behind the final restore chunk. Cover aggregate state larger than the outbound window, small individual splits, immediate/delayed replies, transient budget pressure, and exact ownership reconciliation. Increasing the limit alone does not establish a bounded recovery contract.

  • PR11557-F2 (High, blocking): periodic Kafka discovery semantics. seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceSplitEnumerator.java:596 throws for every async discovery failure, and its one-minute task retains FAIL_SOURCE. The legacy open() scheduled discovery catches/logs failure and retries. Keep initial discovery fail-fast, but implement the periodic retry on the coordinator with HANDLE_IN_COORDINATOR, a bounded delay, and tests for both an AdminClient failure and timeout. The transient broker-restart path is an actual behavior difference, not just a different error message.

  • PR11557-F4 (High, blocking): async worker ownership. seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedCoordinatorScheduler.java:369 arms the timeout at submission; line 383 only interrupts the future, while completeSubmission() at line 483 frees runningCount before actual worker exit. Queue delay can consume the entire timeout, and an interruption-insensitive catalog call can keep occupying a shared I/O thread after its per-coordinator slot is reused. Explicit cancellation reconciliation has the same physical-worker lifetime constraint. Start execution timing inside the callable and retain actual running/orphan ownership until exit; distinguish logical completion from resource release. Test queued-not-started work and a latch-controlled worker that deliberately ignores interruption, including replacement work and close.

  • PR11557-F5 (High, blocking): payload validation. seatunnel-engine/seatunnel-engine-common/src/main/java/org/apache/seatunnel/engine/common/config/server/ManagedSourceRuntimeConfig.java:104 validates against the mailbox only; seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/SourceCommandEnvelope.java:29 imposes a separate 16 MiB ceiling. A 128 MiB mailbox and 32 MiB payload configuration passes validation but can fail when an assignment is encoded. Expose one shared wire-limit constant, reject unsupported limits before deployment, document the upper bound, and test the boundary. Also preserve room for envelope overhead when validating mailbox-fit settings.

  • PR11557-F3 (Medium, required SPI documentation): seatunnel-api/src/main/java/org/apache/seatunnel/api/source/managed/ManagedSourceCapability.java:218 and the surrounding capability builder still omit the guarantees behind state-version changes, bounded poll, wakeup, fencing, stable identifiers, and async enumeration. The digest is persisted and restore rejects a changed contract, so these are required connector promises. Add method/field contracts and bilingual connector-author guidance. I agree with the technical point; for a new public lifecycle SPI I consider completion of this contract part of delivery.

  • PR11557-F6/F7 (Medium): seatunnel-api/src/main/java/org/apache/seatunnel/api/source/SeaTunnelSource.java:128 and ManagedSourceCapability.java:252 imply legacy fallback while explicit enablement rejects deployment. EN/ZH observability pages describe #<sourceId> while both metric builders register #<sourceId>#attempt-<executionId>; admission counters append a status as well. Correct the public/operator contract alongside the feature.

  • PR11557-F8 (Low, optional): SourceReaderBase.java:172 returns an already-completed future after no-more-splits even for unbounded Kafka, and FakeSourceReader.java:236 always completes it. An empty managed poll re-arms availability inline and falls back to the 10 ms sleep. Keep this distinct from correctness blockers; a real pending availability signal and deterministic idle-wakeup test are appropriate follow-up work.

Registration clarification. The current ManagedSourceRegisterOperation.java:115 deliberately uses Hazelcast's wire-selected readObject() and rejects a non-TaskLocation. The regression writes another registered type from the same serializer factory and checks rejection, plus exact valid-byte round trip. The typed overload in the unchanged parent is a separate legacy contract tracked by #12747. My earlier wording treated this too broadly as an established arbitrary-object execution blocker; that claim is not demonstrated by this source trace and is withdrawn. This does not claim that arbitrary untrusted cluster-member traffic is safe. A field-only protocol would narrow decoding further, but I am not retaining an unproven exploit as a merge blocker.

There is no independent active maintainer approval establishing these runtime contracts as complete. @SEZ9 still requests follow-up, which I agree with for the concrete restore/discovery/scheduler/payload blockers. The author's Draft graduation checklist and Issue 52 explicitly remain incomplete.

2. Code quality

2.1 Conventions

Reviewed all changed files for license, imports, naming, core-method and state-field comments. See the numbered findings for the required changes.

2.2 Test coverage and stability

Stability rating: Risk present. The codec, selector, memory/mailbox, state-machine and tracker tests use explicit inputs and mostly synchronous callbacks. The cancellation test mocks a Future and proves bookkeeping only; it never runs an interruption-insensitive worker. There is no direct managed Reader/coordinator owner-runtime harness covering aggregate restore-window saturation, actual transport retries, watchdog generations, close fencing, and handoff metrics (retained Issue 52). The real Fake IT awaits checkpoint/output conditions with bounded HTTP, but its cleanup and future completion need the non-blocking improvement in Issue 53. SourceAssignmentTrackerTest uses a one-second executor get as a watchdog, not an assertion on a measured performance result; making CI watchdog slack configurable would help. ManagedSourceRegisterOperationSerializationTest tests the actual Hazelcast read boundary. No local tests were run.

2.3 Documentation

Both operator pages, sidebar and incompatible-changes entries are present and agree on feature-off defaults, fail-closed enablement, supported pilots, ALL-thread rejection, lane-bound restore and rollback. The production workload/soak table is an acceptance requirement, not a completed benchmark. SPI developer contracts, fallback Javadocs and real attempt-qualified metric names remain F3/F6/F7. ManagedSourceRuntimeIT class Javadoc also says unsupported connectors remain legacy despite enabled-mode deployment rejection; align it.

3. Architecture

3.1 Change location

Keep managed protocol, ownership and scheduling invariants in the engine runtime; connector pilots should implement the published SPI without adding connector-specific engine exceptions. Prefer resumable bounded transfer over increasing limits or blocking owner loops.

3.2 Maintainability

Keep the behavior, lifecycle ownership, and failure contract together. Keep managed protocol, ownership and scheduling invariants in the engine runtime; connector pilots should implement the published SPI without adding connector-specific engine exceptions. Prefer resumable bounded transfer over increasing limits or blocking owner loops.

3.3 Extensibility

Prefer the existing component boundary and tests over unrelated shared abstractions.

3.4 Upgrade impact

Partially incompatible when explicitly opting into the new lane: runtime mode, protocol, connector state version and digest must match checkpoint metadata. Both lane-change directions reject restore; the EN/ZH incompatible-changes entries now correctly explain re-selection after failover/savepoint restore and the fresh-position/compatible-checkpoint migration. Existing SourceReader/Collector methods and default capability keep the default-off SPI compatible. FakeSourceSplit retains its explicit serialVersionUID, adds totalRowNum, preserves the old constructor and negative custom-row progress marker; there is a regression for that legacy marker. Kafka discovery failure semantics still need F2 resolution. Homogeneous configuration is required; mixed-version operation is not certified.

4. Findings summary

Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.

# Finding Location Severity
PR11557-F1 Incremental, retryable restore transfer in both lane combinations ManagedSourceCoordinatorRuntime.java:316; ManagedSourceReaderRuntime.java:1006 High
PR11557-F2 Kafka periodic discovery failure semantics KafkaSourceSplitEnumerator.java:596 High
PR11557-F4 Actual async worker lifetime and timeout start ManagedCoordinatorScheduler.java:369 High
PR11557-F5 Validate payload against the wire limit ManagedSourceRuntimeConfig.java:104 High
PR11557-F3 Required public capability/SPI contracts ManagedSourceCapability.java:218 Medium
PR11557-F6/F7 Fail-closed Javadocs and attempt-qualified metrics SeaTunnelSource.java:128; docs/en/engines/zeta/realtime-observability.md:312 Medium
52 Complete the already-requested owner-runtime regression matrix seatunnel-engine/seatunnel-engine-server/src/main/java/org/apache/seatunnel/engine/server/task/source/ManagedSourceReaderRuntime.java:1006 Medium
53 Bound and clean up asynchronous IT jobs on every assertion path seatunnel-e2e/seatunnel-engine-e2e/connector-seatunnel-e2e-base/src/test/java/org/apache/seatunnel/engine/e2e/ManagedSourceRuntimeIT.java:100 Medium
PR11557-F8 Idle availability causes periodic polling (optional) SourceReaderBase.java:172; FakeSourceReader.java:236 Low

5. Merge recommendation

Merge after fixes (keep Draft until its stated graduation gates are met)

Blocking items: Retained Issue 52, and the independently confirmed peer blockers PR11557-F1/F2/F4/F5; complete the public SPI contract in F3 and align F6/F7. GitHub reports merge conflicts; the author must sync the latest dev and resolve them before merging. Current-head CI and write-capable maintainer review remain independent requirements.

Non-blocking suggestions: Issue 53: Bound and clean up asynchronous IT jobs on every assertion path

Overall: the approach addresses a real path, but the listed blockers must be closed. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.

CI and repository state: Signal pull request update: SUCCESS; Build: IN_PROGRESS; Build: in_progress. GitHub reports DIRTY / REVIEW_REQUIRED.

Verification: Reviewed all changed files and the referenced call sites at dad46fd5b0be1c7b3031eb52b0fac6ddaf8a7297 against merge base 86bef7694d68fb8c167b79626a30a4236d18208f. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.

Review time: 2026-11-23T09:19:13.106948-05:00

Local evidence: git fetch obtained head dad46fd5b0be1c7b3031eb52b0fac6ddaf8a7297; git merge-base returned 86bef7694d68fb8c167b79626a30a4236d18208f; git diff --stat reports 110 files changed, 15580 insertions(+), 101 deletions(-). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.

@SEZ9

SEZ9 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the update. The latest note in this thread is cut off partway through the runtime path, so I can't see how any of the eight earlier findings were resolved. They all stay open on my side until each one has an explicit status.

One clarification first: the note says the managed-reader restore queue has an "aggregate-window problem", but the explanation is in the part that is cut off. Is that the same concern as PR11557-F1, or something separate? If it is the same, please describe how it is handled there.

For each finding below, please reply with fixed (and what changed), intentionally unchanged (and why), or still pending:

  • PR11557-F1: Restored splits from a legacy-lane Reader are rejected once they exceed reader-mailbox-max-bytes, with no chunking or retry. Can such a checkpoint now be restored on the coordinator-only lane?
  • PR11557-F2: On the Kafka managed lane, a periodic partition-discovery failure or 1-minute timeout fails the source. Does it now log and retry on the next interval as the legacy lane does, or is failing intentional?
  • PR11557-F4: An async timeout releases the per-coordinator concurrency slot without confirming the worker has stopped. Is that now confirmed, and does the timeout clock still start at pool submission rather than at execution?
  • PR11557-F5: Does validate() now check max-command-payload-bytes against the 16 MiB wire hard limit as well as the mailbox size?
  • PR11557-F3: Is there now developer documentation for the connector-facing SPI, and Javadoc on the ManagedSourceCapability flags?
  • PR11557-F6: Does the Javadoc that says a connector "stays on the legacy lane" now reflect that the selector fails deployment once the flag is enabled?
  • PR11557-F7: Do the documented metric names now match the registered #<sourceId>#attempt-<executionId> suffix rather than #{sourceId}?
  • PR11557-F8 (low): isAvailable() is permanently completed after no-more-splits in SourceReaderBase and always completed in FakeSourceReader, so the managed Reader falls back to fixed-interval polling. Is this addressed, or deferred as a follow-up?

For F1, F2, F4 and F5, please also name the test that covers the case, if there is one.

@DanielLeens

Copy link
Copy Markdown
Contributor Author

Thanks, @SEZ9 — the aggregate-window explanation is additional evidence under your existing PR11557-F1, not a separate issue number. Here is the explicit status on this unchanged head:

  • F1: still pending. ManagedSourceCoordinatorRuntime.java:316 rejects an aggregate legacy-reader restore payload over the mailbox budget. The managed-reader path chunks individual commands, but ManagedSourceReaderRuntime.sendStagedRestoreCommands:1006-1024 sends all chunks during the same owner turn. Each reserves outbound bytes before completion callbacks can release them; aggregate state over the window still fails. Neither lane yet has the required resumable/window-paced producer and transient-admission retry. Issue52 requests real-runtime regressions with small individual splits whose total exceeds the window, immediate/delayed acknowledgements and exact ownership restoration; I found no current test proving that acceptance.
  • F2: still pending. KafkaSourceSplitEnumerator.java:591-613 throws on every discovery failure and uses a one-minute async timeout with FAIL_SOURCE. Unlike the legacy periodic catch/log/retry, it does not reschedule after transient failure. Initial fail-fast and periodic retry must be tested separately, including timeout; no current production-path test closes those cases.
  • F4: still pending. ManagedCoordinatorScheduler.java:369 arms the timeout after pool submission;383 interrupts the future. completeSubmission at 483-485 frees the logical running slot without actual worker-exit proof. No current queued-before-start/interruption-insensitive-worker regression proves the physical ownership bound. A shorter caller timeout alone does not solve it.
  • F5: still pending. ManagedSourceRuntimeConfig.validate:104-106 checks mailbox capacity, but not SourceCommandEnvelope.MAX_WIRE_PAYLOAD_BYTES (16 MiB). A larger mailbox can admit a payload configuration that the wire rejects. Add a shared-limit validation and exact boundary regression, including framing overhead; the current config tests do not establish that rejection.
  • F3: required documentation remains pending. ManagedSourceCapability's public flags must document connector guarantees and persisted compatibility digest semantics, with connector-author guidance.
  • F6: pending wording. Public legacy-fallback wording still conflicts with explicit enablement rejecting an unsupported capability at deployment. This is not runtime fallback.
  • F7: pending wording. SourceRuntimeMetrics/ManagedSourceRuntimeMetrics register #<sourceId>#attempt-<executionId>; the operator docs still shorten it. Correct both languages, including admission status suffixes.
  • F8: intentionally non-blocking follow-up. The completed availability signals still lead to fixed-interval idle polling. A proper pending signal/idle-wakeup regression is useful, but I have not promoted it into a new correctness blocker.

These statuses match the full review's endorsed findings and required Issue52 matrix. Issue53 remains optional asynchronous-test cleanup. Build 45020529047 is now cancelled rather than in progress, and GitHub still reports merge conflicts with dev. Please resolve those conflicts as well as the retained source blockers; this does not ask you to add unrelated CI workarounds.

This is a discussion follow-up on unchanged head dad46fd5b0be1c7b3031eb52b0fac6ddaf8a7297, not a new full source review. I inspected the named local source paths; no local build, test or SeaTunnel runtime was executed. Daniel has READ permission; effective maintainer approval and historical review dismissal remain separate repository actions.

This branch has not been deployed

No deployments
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.

7 participants