zhangshenghang opened a new issue, #13360:
URL: https://github.com/apache/seatunnel/issues/13360

   ## Search before asking
   
   - [x] I had searched in the 
[issues](https://github.com/apache/seatunnel/issues?q=is%3Aissue) and found no 
similar design proposal. Related but distinct: #2274 (original checkpoint 
design), #12849 / #12850 (acknowledgement & statistics fixes), #12361 (CDC 
reader-side OOM). None of them offload state persistence from the master.
   
   ## Motivation
   
   In the current Zeta checkpoint implementation, **all state bytes transit the 
master's JVM heap**:
   
   1. Each task serializes its state into `List<byte[]>` in the barrier path 
and buffers it in `SeaTunnelTask#checkpointStates` until all cycles are 
acknowledged.
   2. `TaskAcknowledgeOperation` ships the full byte payloads to the master.
   3. The master's `PendingCheckpoint` accumulates every subtask's bytes until 
all acks arrive.
   4. On completion, `CheckpointCoordinator#completePendingCheckpoint` 
re-serializes the whole `CompletedCheckpoint` (a second full copy), writes one 
pipeline-level blob to storage from the master, and keeps the byte-carrying 
object in `latestCompletedCheckpoint` until the next checkpoint completes 
(default 300s).
   
   Structural problems:
   
   | # | Problem |
   |---|---|
   | 1 | Master memory scales **O(state bytes)**: pending copy + retained copy 
+ re-serialization copy ≈ 2–3× snapshot size per pipeline, × pipeline count |
   | 2 | State takes **two network hops** (worker → master → storage); ack 
payloads can reach hundreds of MB |
   | 3 | All checkpoint IO funnels through the master (**single writer, single 
node**) |
   | 4 | Large `byte[]` are G1 humongous objects promoted to the master's old 
gen (Full GC pressure) |
   | 5 | State-size metrics count arrays instead of bytes, so monitoring 
understates real sizes |
   
   STIP-6 (#2274) was designed around the assumption *"Apache SeaTunnel will 
not have a super large state"*. CDC initial snapshots break that assumption: 
the enumerator state alone (`SnapshotPhaseState`: assigned splits + chunk 
watermarks, growing with progress) is documented at **10–500 MB per pipeline**, 
multiplied by pipeline count and parallelism.
   
   ## Goals
   
   1. Master checkpoint memory **O(metadata)** instead of O(state bytes)
   2. Parallel, **single-hop** persistence from workers
   3. **Zero protocol change**: barrier alignment, exactly-once two-phase 
commit, schema-change flow and pipeline-level checkpoint granularity are 
untouched
   4. **Zero config break**: existing `seatunnel.engine.checkpoint.storage.*` 
options keep their names and defaults; v1 on-disk format remains restorable
   5. Safe rollout: the new path is the **default**; a deprecated escape hatch 
restores the old behavior
   
   ## Non-Goals
   
   - Async snapshots (moving serialization/IO off the barrier thread) — 
follow-up
   - Incremental checkpoints / cross-version chunk sharing — follow-up; the 
handle indirection layer enables them
   - Unaligned checkpoints — unnecessary with Zeta's bounded queues 
(backpressure blocks the source instead)
   
   ## Proposed Design
   
   ### Overview
   
   ```
   worker (per TaskGroup)                                   storage
     barrier passes the task (protocol unchanged)
      serialize state -> byte[] (unchanged)
      writer:
        total <= inline threshold (20KB) -> InlineStateHandle (zero disk IO)
        otherwise -> write chunk (tmp -> rename) -------> 
<ns>/<jobId>/<pipelineId>/chk-N/subtask-*.chunk
      byte[] released immediately; only handles are buffered
     ack carries handles only (KB-sized)
                             |
   master (CheckpointCoordinator)
     PendingCheckpoint accumulates handles (KB-sized)
     all acked -> assemble small _metadata file ---------> chk-N/_metadata   
(atomic commit point)
     latestCompletedCheckpoint = metadata-only object
     completion notice still carries only the checkpoint id (already true today)
   ```
   
   Four structural changes: master disk writes drop from O(state) to O(KB); ack 
messages drop from MB-scale to KB-scale; the master no longer holds state 
bytes; humongous arrays disappear from the master heap.
   
   ### StateHandle abstraction
   
   One model serves both the new path and the deprecated one (the old path is 
expressed as "all handles inline", which is byte-for-byte equivalent to today):
   
   ```java
   /** Persistent reference to one subtask's state. */
   public interface StateHandle extends Serializable {
       /** Deterministic and unique: 
{jobId}/{pipelineId}/chk-{id}/subtask-{actionId}-{index} */
       String handleId();
       /** True size in bytes, measured at the write site (fixes metric 
accuracy). */
       long getStateSize();
       /** Fetch the subtask's state segments on restore; inline handles are 
zero-IO. */
       byte[][] readStates() throws Exception;
       /** Idempotent delete; no-op for inline handles. */
       void discard() throws Exception;
   }
   
   /** Small state: bytes embedded, persisted later inside _metadata (or the v1 
blob on the old path). */
   public final class InlineStateHandle implements StateHandle { byte[][] 
inlineBytes; }
   
   /** Large state: reference to a chunk file. */
   public final class FileChunkStateHandle implements StateHandle { String 
location; long size; }
   ```
   
   Existing types are generalized (no behavioral fork):
   
   | Type | Today | After |
   |---|---|---|
   | `ActionSubtaskState.state` | `List<byte[]>` | `List<StateHandle>` |
   | `TaskAcknowledgeOperation.states` | byte payloads | handles |
   | `PendingCheckpoint` / `CompletedCheckpoint` | bytes | handles |
   
   ### Chunk file format
   
   Exactly one file per subtask per checkpoint (bounds the file count to the 
subtask count):
   
   ```
   [entryCount: int] { [length: int][bytes] }*
   ```
   
   ### `_metadata` file format (the commit point)
   
   ```
   [MAGIC "STCKMD": 6B][version: int = 2][flags: int][payloadLen: int][CRC32: 
int]
   [ProtoStuff-serialized CompletedCheckpoint, whose state lists are 
StateHandles]
   ```
   
   - Reuses the existing `ProtoStuffSerializer` and object graph (checkpoint 
id, type, timestamps, action states, statistics).
   - The trailing CRC is the integrity line of defense for object stores 
without atomic rename (see storage semantics below).
   - **The existence of `_metadata` is the single criterion that a checkpoint 
completed.**
   
   ### Storage SPI extension (non-breaking)
   
   ```java
   /** Implemented by localfile / hdfs. Third-party plugins that don't 
implement it
    *  simply keep the old behavior (see configuration & deprecation). */
   public interface ChunkSupportStorage extends CheckpointStorage {
       FileChunkStateHandle writeChunk(ChunkDescriptor desc, byte[][] states);
       byte[][] readChunk(FileChunkStateHandle handle);
       void writeMetadata(MetadataEnvelope envelope);        // tmp -> rename 
(S3: direct write + CRC)
       MetadataEnvelope readMetadata(String location);       // CRC-validated
       List<Long> listCompletedCheckpointIds(String jobId, String pipelineId);
   }
   ```
   
   ### Flow: worker-side write-through
   
   `SeaTunnelTask#addState` becomes write-through instead of buffer-until-ack:
   
   1. Barrier passes each `FlowLifeCycle` (protocol, locks, 
source/sink/enumerator logic unchanged).
   2. Serialization still produces `List<byte[]>` (unchanged).
   3. Writer decides: total ≤ threshold → inline handle; otherwise write 
`{path}.tmp` → flush → rename to `{path}` and return a file handle.
   4. The byte array reference is dropped immediately; `checkpointStates` 
stores handles. The worker's byte-holding window shrinks from "the whole 
checkpoint cycle" to "serialization + write".
   5. The enumerator task (`SourceSplitEnumeratorTask`, index = -1 — typically 
the single largest state in CDC) and sink committer states go through the same 
channel with no special-casing.
   6. Ack idempotency keeps using the existing `notYetAcknowledgedTasks` check 
(Hazelcast operation retries are safe).
   
   ### Flow: master-side collection & commit
   
   1. Ack (KB-sized) arrives → `acknowledgeHandle` under the 
`PendingCheckpoint` lock semantics (aligned with #12850).
   2. All-acked → `completePendingCheckpoint` (same trigger point and 
synchronization):
      - old path: today's v1 blob logic, kept verbatim;
      - new path: assemble the envelope and write `chk-N/_metadata.tmp` → 
rename → `_metadata`.
   3. `latestCompletedCheckpoint` becomes a metadata-only object (retention 
cost ≈ 0); the whole-blob re-serialization disappears because the serialized 
graph contains only handles.
   
   ### Flow: restore (dual-format probing + parallel fetch)
   
   1. Job restart → `getLatestCheckpoint(jobId, pipelineId)`:
      - scan v2 `chk-*/_metadata`, take the max id, validate CRC (on failure, 
try the next older one);
      - if no v2 exists, fall back to today's v1 blob scan, deserialize and 
wrap as inline handles.
   2. Build a handle-only `CompletedCheckpoint` and reuse the existing 
`restoreTaskState` distribution.
   3. Restore operations carry each task's own handles (KB-sized); workers 
fetch their own chunks (`InlineStateHandle` = zero IO). Every worker only pulls 
its own subtasks, so restore is parallel cluster-wide by construction.
   
   Master failover / coordinator recreation is unchanged: 
`CheckpointCoordinatorState` carries only status + message, never state bytes.
   
   ### Flow: cleanup protocol
   
   | Object | Rule | Action |
   |---|---|---|
   | Over-retention | beyond `max-retained` completed ids | discard every file 
handle inside the oldest `chk-N/`, then remove the dir (idempotent) |
   | Orphan dirs | `chk-*` without `_metadata`, mtime > now − 
2×checkpoint-timeout | remove the whole dir |
   | tmp leftovers | `*.tmp` older than the threshold | remove |
   | Terminal job | existing `deleteCheckpoint(jobId)` semantics (incl. 
retain-after-job-cancelled) | extended to remove the v2 tree |
   
   Executed periodically by the master's checkpoint thread (same place as 
today's retention cleanup). Safety boundary: only `^chk-[0-9]+$` dirs and 
engine-generated file names are ever touched.
   
   ### Disk layout & storage semantics
   
   ```
   <namespace>/                                            (existing config 
unchanged)
   ├── <jobId>/<ts>_<rand>_<pipelineId>_<chkId>.blob      v1 legacy (read-only 
compatibility)
   └── <jobId>/<pipelineId>/
       ├── chk-105/
       │   ├── _metadata
       │   ├── subtask-<actionId>-0.chunk
       │   └── subtask-<actionId>-(-1).chunk               enumerator state
       └── chk-106/…
   ```
   
   | Store | Rename semantics | Commit guarantee |
   |---|---|---|
   | localfile / NFS | atomic | tmp → rename |
   | HDFS | atomic | tmp → rename (reuses the existing `HdfsStorage` pattern) |
   | S3 / OSS / COS / GCS | no atomic rename (copy+delete) | `_metadata` 
written directly (multipart) + CRC validation on restore; crash leftovers 
`.tmp` are reclaimed by cleanup |
   
   ### Configuration & deprecation lifecycle
   
   | Option | Value | Notes |
   |---|---|---|
   | `seatunnel.engine.checkpoint.state-write-mode` | **`worker` (default)** / 
`master` | `master` is the deprecated old path, kept as an escape hatch |
   | `seatunnel.engine.checkpoint.state-inline-threshold` | int, default 
`20480` (20KB) | aligned with Flink's `state.backend.fs.memory-threshold` |
   
   - **Capability detection**: with the default `worker` mode, if the 
configured storage plugin does not implement `ChunkSupportStorage`, the 
coordinator automatically degrades to the old path for that job and logs a WARN 
(no user action needed; third-party plugins keep working during the deprecation 
window).
   - Workers reuse the same `checkpoint.storage` config section (each node 
already loads `seatunnel.yaml` independently; only the master consumes it 
today). With `worker` mode active, deployment validates the section exists on 
every node and fails fast naming the node if missing.
   - Option description carries: *"`master` is deprecated and will be removed 
in a future version. Storage plugin implementations should implement 
`ChunkSupportStorage`."*
   - Lifecycle: version N introduces it (default `worker`, `master` deprecated) 
→ observation window → version M removes the old path and the option itself, 
documented in `docs/en/introduction/concepts/incompatible-changes.md` with 
migration guidance for custom plugin authors.
   
   ### Threading model
   
   | Executor | Duty | Concurrency |
   |---|---|---|
   | task thread (barrier path) | serialize + writer (inline or chunk) | one 
thread per TaskGroup, sequential by construction |
   | master operation thread | `acknowledgeHandle` | `PendingCheckpoint` lock 
(per #12850) |
   | master checkpoint thread | `_metadata` write, retention/orphan cleanup | 
`completePendingCheckpoint` synchronized (as today) |
   | worker restore | `readChunk` + deserialize | per task, parallel by 
construction |
   
   ### Failure semantics (crash-point by crash-point, equivalent to today)
   
   | Crash point | Leftover | Behavior |
   |---|---|---|
   | worker while serializing | none | task failover; master aborts on timeout |
   | worker while writing a chunk | `*.tmp` | same; tmp reclaimed by cleanup |
   | worker after chunk, before ack | orphan `chk-N` | timeout abort; orphan 
cleanup |
   | ack transport retry | none | deduped by `notYetAcknowledgedTasks` 
(idempotent) |
   | master before/while writing `_metadata` | orphan or `*.tmp` | new master 
restores from the previous complete `_metadata` |
   | `_metadata` corruption (S3 partial write) | — | CRC fails → fall back to 
the next older retained version |
   | chunk missing on restore | — | version incomplete → fall back to previous 
version (recommend `max-retained >= 3`) |
   | storage unavailable | — | write fails → checkpoint fails (same semantics 
as today) |
   
   ### Special paths
   
   | Path | Handling |
   |---|---|
   | Savepoint | same mechanism and directory rule (chk-id); orthogonal to 
#11962 (savepoint storage separation) |
   | Schema-change checkpoint | `checkpointType` stored verbatim in 
`_metadata`; barrier/timeout flow unchanged |
   | Sink 2PC commit info | KB-scale → inline; aggregated commit path unchanged 
|
   | CheckpointIDCounter | carries no state bytes; unchanged |
   | Pipeline-level granularity | per-pipeline coordinator/directory; the 
STIP-6 differentiator is fully preserved |
   
   ### Observability
   
   | Metric | Meaning |
   |---|---|
   | `checkpoint_state_size_bytes` | true bytes at the write site (replaces the 
array-count metric) |
   | `checkpoint_chunk_write_duration_ms` / `_bytes` | worker direct-write cost 
|
   | `checkpoint_metadata_write_duration_ms` | master commit cost |
   | `checkpoint_orphan_cleaned_bytes` | cleanup effectiveness |
   | `checkpoint_pending_handles` | pending-window handle count |
   
   ## Relationship to Flink
   
   Directly borrowed (battle-tested for a decade): TM writes state / JM keeps 
only handles; `InlineStateHandle` ≈ `ByteStreamStateHandle`, 
`FileChunkStateHandle` ≈ `FileStateHandle`; `_metadata` as the commit point; 
the 20KB inline threshold; per-node parallel restore; handle-based retention 
pruning.
   
   Deliberate deviations (Zeta constraints): no location pre-allocation in the 
trigger (Zeta's barrier flows with the data; paths are derived 
deterministically instead); no async snapshot phase yet (states are 
`snapshotState()` POJOs with no anchorable immutable structure — follow-up); no 
incremental sharing yet (low benefit for current state shapes — follow-up on 
top of the handle layer).
   
   Not adopted: unaligned-checkpoint in-flight persistence (no pain point with 
bounded queues). Preserved: pipeline-level checkpoint granularity.
   
   ## Compatibility
   
   - User-facing options unchanged except the two additions above.
   - v1 format remains restorable (dual-format probing on restore). Older 
binaries cannot read v2 — the normal forward-compatibility boundary; 
checkpoints simply re-accumulate during the upgrade window.
   - Third-party `CheckpointStorage` plugins: no compile break; they keep the 
old behavior via capability detection until they implement 
`ChunkSupportStorage`.
   - Protocol, exactly-once, savepoint and schema-change semantics unchanged.
   
   ## Alternatives considered
   
   | Alternative | Why rejected |
   |---|---|
   | Compress the v1 blob only | does not change the O(state) scaling, only the 
constant |
   | Off-heap master buffer | still single-writer, two hops, plus off-heap 
management complexity |
   | Streaming write from the master without full collection | requires 
reworking ack consistency; larger blast radius than the benefit |
   | Connector-side state slimming only | treats the symptom; the engine's 
O(state) path remains |
   
   ## Open Questions
   
   1. Inline threshold: 20KB (Flink-aligned) vs 64KB?
   2. When worker nodes miss the storage config section: fail fast (proposed) 
vs auto-degrade to the old path for that job?
   3. Orphan cleanup ownership: master periodic task (proposed) vs 
storage-plugin self-management?
   4. Do we want an offline v1→v2 migration tool for users with very large 
retained histories?
   5. Should the deprecation window also cover a `Both` mode writing v1+v2 
simultaneously for extra safety, or is default-worker + v1-readable sufficient?
   
   ## Are you willing to submit a PR?
   
   - [x] Yes
   


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

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to