You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by "nzw921rx (via GitHub)" <gi...@apache.org> on 2026/04/13 03:46:17 UTC

Re: [I] [STIP-23] [Feature][Zeta] Engine-level timer flush support for Sink connectors [seatunnel]

nzw921rx commented on issue #10717:
URL: https://github.com/apache/seatunnel/issues/10717#issuecomment-4233603438

   ## Motivation
   
   Currently, when a Sink connector needs **wall-clock-driven periodic flush** with **fail-fast error propagation**, there are only two options at the connector level — both are problematic:
   
   | Approach | Problem |
   |----------|---------|
   | Background `ScheduledExecutorService` inside the connector | Races with checkpoint / schema-change paths; failures may be silently delayed. |
   | Time check inside `writeRecord` | Cannot trigger when there is no incoming data (idle source). |
   
   We need the **engine** to inject a "flush intent" on the **same consume chain** that processes records, barriers, and schema changes — in a controlled order, without disrupting checkpoint semantics.
   
   ## Goals
   
   | ID | Goal |
   |----|------|
   | G1 | **Checkpoint barrier (`Ck`) semantics remain first-class**: consistency, alignment, `prepareCommit` / `ack` are still anchored to `Ck`. |
   | G2 | **Schema change (`Sc`) and flush signal (`F`) are second-class**: both are non-checkpoint control-plane events, processed with the same ordering principles. |
   | G3 | **No private timer threads inside connectors**: timing is managed by an engine-hosted, task-bound scheduler; **flush runs only on the thread that consumes `F`**. |
   | G4 | **Fail-fast**: flush failures propagate immediately, identical to the write path. |
   | G5 | **Opt-in capability**: connectors declare via `enable_timer_flush`; 2PC Sinks (`containAggCommitter == true`) are hard-guarded by the engine, not supported in Phase 1. |
   
   ## Non-Goals
   
   - No change to the `writeRecord` / `prepareCommit` / `close` lifecycle — `F` is a supplementary trigger, not a new commit protocol.
   - No coverage of Flink / Spark translation layer in this phase.
   - No engine-level unification of `batch_size` (consistent with #10717 Non-Goals).
   - Phase 1 does NOT support Exactly-Once Sinks (2PC Sinks are hard-guarded by the engine, see 2PC guard mechanism in Configuration Model).
   
   ## Design
   
   ### Configuration Model
   
   Timer flush configuration has two levels: **env level** (Task level) and **connector level** (opt-in switch).
   
   **Env-level parameter** — defined in the `env` block of the job config, applies to the entire Task:
   
   ```java
   // New addition to EnvCommonOptions.java
   public static Option<Long> SINK_FLUSH_INTERVAL =
           Options.key("sink.flush.interval")
                   .longType()
                   .defaultValue(0L)
                   .withDescription(
                           "The interval (in milliseconds) for engine-level timer flush "
                                   + "on Sink tasks. Default 0 means disabled. "
                                   + "Values less than 100ms will trigger a WARN log "
                                   + "and be rejected (treated as disabled). "
                                   + "Only effective for Sink connectors that opt in via "
                                   + "enable_timer_flush = true.");
   ```
   
   Validation logic:
   
   ```java
   private long validateFlushInterval(long intervalMs) {
       if (intervalMs <= 0) {
           return 0;
       }
       if (intervalMs < 100) {
           log.warn(
                   "sink.flush.interval={}ms is less than 100ms, this may cause "
                           + "excessive TimerFlushSignal injection and impact performance. "
                           + "Recommended minimum is 100ms. taskLocation [{}]",
                   intervalMs,
                   taskLocation);
       }
       return intervalMs;
   }
   ```
   
   Job config example:
   
   ```hocon
   env {
     job.mode = STREAMING
     checkpoint.interval = 60000
     sink.flush.interval = 5000
   }
   ```
   
   **Connector-level parameter** — each Sink connector declares whether it accepts engine timer flush, following the `SupportSaveMode` opt-in pattern:
   
   ```java
   // New addition to connector Options class
   public static final Option<Boolean> ENABLE_TIMER_FLUSH =
           Options.key("enable_timer_flush")
                   .booleanType()
                   .defaultValue(false)
                   .withDescription(
                           "Whether this Sink registers for engine-level timer flush. "
                                   + "When true and env sink.flush.interval is set, "
                                   + "the engine will periodically inject TimerFlushSignal "
                                   + "into the record stream for this Sink.");
   ```
   
   Connector config example:
   
   ```hocon
   sink {
     Elasticsearch {
       hosts = ["http://localhost:9200"]
       index = "my_index"
       enable_timer_flush = true
     }
   }
   ```
   
   **Activation rules:**
   
   | `env.sink.flush.interval` | Connector `enable_timer_flush` | `containAggCommitter` | Result |
   |---------------------------|-------------------------------|-----------------------|--------|
   | >= 100ms | `true` | `false` | Engine starts timer for this Sink task, injects `F` at the specified interval |
   | >= 100ms | `true` | `true` (2PC Sink) | **Refused**, engine logs WARN, behavior is identical to current |
   | >= 100ms | `false` (default) | Any | This Sink does not participate in timer flush, behavior is identical to current |
   | 0 (default) or not set | Any | Any | No timer is started, behavior is identical to current |
   | 1~99ms | `true` | `false` | **Activated but engine logs WARN**, warning that interval is too small and may cause excessive `F` injection |
   
   All three conditions must be met **simultaneously** to activate timer flush:
   1. `env.sink.flush.interval` is set
   2. Connector `enable_timer_flush = true`
   3. `containAggCommitter == false` (non-2PC Sink)
   
   **2PC guard mechanism:**
   
   `SinkFlowLifeCycle` already has the `containAggCommitter` field, which is `true` when `SeaTunnelSink.createAggregatedCommitter()` returns non-empty. The engine checks this field during timer flush initialization — a 2PC Sink is refused even if `enable_timer_flush = true`, and a warning log is emitted:
   
   ```java
   // Timer flush activation logic in SinkFlowLifeCycle
   private void maybeStartTimerFlush(long flushIntervalMs, boolean enableTimerFlush) {
       if (flushIntervalMs <= 0 || !enableTimerFlush) {
           return;
       }
       if (containAggCommitter) {
           log.warn(
                   "Sink [{}] has AggregatedCommitter (2PC), timer flush is not supported. "
                           + "Ignoring enable_timer_flush=true. taskLocation [{}]",
                   sinkAction.getName(),
                   taskLocation);
           return;
       }
       // Start ScheduledExecutorService, register periodic F enqueue
   }
   ```
   
   This ensures:
   - Users have global control over the entire job (via env)
   - Connectors declare opt-in via `enable_timer_flush`
   - 2PC Sinks are hard-guarded by the engine — even misconfiguration will not activate timer flush
   - Existing jobs with no configuration changes have zero impact
   
   ### Foundational Consensus: Signal Hierarchy and Second-Class Citizens
   
   This design treats `Sc` (Schema Change) and `F` (Flush Signal) uniformly as **second-class citizens**, which serves as the foundational consensus:
   
   **First-class citizen — `Ck` (Checkpoint Barrier)**
   
   The existing `Barrier` / `CheckpointBarrier` in Zeta, which participates in the global checkpoint protocol and defines transaction and snapshot boundaries. `Ck` is the consistency anchor; its semantics must NOT be overridden or replaced by any other signal.
   
   **Second-class citizen — `Sc` (Schema Change)**
   
   The existing `SchemaChangeEvent` in Zeta, a non-checkpoint control-plane event inserted in-order alongside data records `R` in the record stream, processed sequentially by the engine and the Sink. After `prepareClose` is set, it is no longer delivered to downstream stages (consistent with `RecordEventProducer` drop policy for non-Barrier events). `Sc` does NOT alter checkpoint boundary semantics and does NOT independently serve as a commit point.
   
   **New in this proposal — `F` (Flush Signal)**
   
   This design adds `F` to the existing two-tier model, at the same level as `Sc` (second-class citizen). `F` is an **engine-synthesized control `Record`**, concrete type `TimerFlushSignal`, which triggers a "flush only, not a checkpoint" action at the Sink. `F` follows the same ordering principles and `prepareClose` drop policy as `Sc`.
   
   **Conceptual queue illustration:**
   
   <img width="1086" height="467" alt="Image" src="https://github.com/user-attachments/assets/0ccaf0eb-2c29-472b-9bb5-e8b5660a4b3e" />
   
   ### Event Shape of `F`: Synthesized Control Record
   
   `F` is constructed by the engine as an internal-only payload of type `TimerFlushSignal`, wrapped in `Record<?>` and flows in the **same data plane** as `R` / `Sc` / `Ck`.
   
   **Interaction with Intermediate Disruptor:**
   - `F` is a non-Barrier event — it follows the existing `RecordEventProducer` / `RecordEventHandler` → `collector.collect` path.
   - After `prepareClose`, `F` is dropped (same as `R` / `Sc`).
   
   **Implementation requirement:**
   - Add an `instanceof` branch for `TimerFlushSignal` in `SinkFlowLifeCycle.received` (and any upstream relay points).
   - `F` must NEVER be passed to `SinkWriter.write(SeaTunnelRow)` as regular row data.
   
   **Timer scheduling:**
   - When the timer fires, the engine **publishes an `F`** from an enqueueable context (NOT a connector-internal unmanaged thread).
   - The wall-clock side MUST use a `ScheduledExecutorService` explicitly bound to the specific `SeaTunnelTask` / subtask that has timer flush enabled (see Lifecycle Management below).
   - The scheduler callback ONLY enqueues `F`; it NEVER executes flush. Actual flush is always executed on the thread consuming `F`.
   
   ### Engine Injection and Consumption Path
   
   **Sink side (mandatory handling point):**
   
   In `SinkFlowLifeCycle.received(Record<?>)`, add a `TimerFlushSignal` branch alongside the existing `Barrier` / `SchemaChangeEvent` / `write` branches:
   
   ```java
   @Override
   public void received(Record<?> record) {
       if (record.getData() instanceof Barrier) {
           // ... existing checkpoint barrier handling ...
       } else if (record.getData() instanceof SchemaChangeEvent) {
           // ... existing schema change handling ...
       } else if (record.getData() instanceof TimerFlushSignal) {
           // invoke the flush action registered by the connector
           // do NOT call writer.write()
       } else {
           // ... existing write path ...
       }
   }
   ```
   
   **Intermediate Disruptor tasks:**
   
   - `F` as a non-Barrier event: after `prepareClose` is set, the Producer no longer enqueues (consistent with `R` / `Sc`).
   - `Barrier` path is unchanged: always publish + Handler collect (consistent with current implementation).
   
   ### Lifecycle Management of the Timer
   
   A `ScheduledExecutorService` MUST be created for **each task** that has timer flush enabled. The timer lifecycle distinguishes between **graceful shutdown** and **restore recovery**:
   
   **Startup:**
   
   | Event | Action |
   |-------|--------|
   | Task is ready and starts consuming data (initial start) | Create `ScheduledExecutorService`, call `scheduleAtFixedRate` to start the timer |
   | New task instance is ready after restore | Create a **new** `ScheduledExecutorService` bound to the new instance, call `scheduleAtFixedRate` again |
   
   **Graceful shutdown (job completion / user cancellation):**
   
   | Event | Action |
   |-------|--------|
   | `prepareClose` is set | Timer callback detects `prepareClose == true`, stops enqueuing new `F` |
   | Task `close` | Call `executor.shutdown()`, wait for submitted timer callbacks to complete (callbacks only perform enqueue checks, extremely fast), then release the thread pool. Already-enqueued `F` is consumed normally by the consume thread |
   
   **Restore recovery (failure recovery / replace):**
   
   | Event | Action |
   |-------|--------|
   | Task instance is marked as disposed (failure triggers restore / replace) | Call `executor.shutdownNow()`, immediately interrupt the timer thread, cancel all pending schedules. Old executor is disposed together with the old task instance |
   | New task instance is created and ready | Create a brand new `ScheduledExecutorService`, bind to the new task instance, restart the timer. References to the old executor MUST NOT be reused by the new instance |
   
   **Constraints:**
   - The executor MUST NOT outlive the task or be shared across different task instances.
   - Single-threaded daemon thread pool per task to avoid unordered concurrent enqueuing and to not prevent JVM shutdown. Thread naming MUST include `taskId` / `jobId` / `flushCount` for troubleshooting.
   - Connectors are FORBIDDEN from creating their own unmanaged `ScheduledExecutorService` for timer flush.
   - Graceful shutdown uses `shutdown()` (wait for completion); restore recovery uses `shutdownNow()` (immediate interruption).
   
   ### Ordering and Priority Rules
   
   **F vs. Ck (Checkpoint Barrier):**
   
   `F` must NOT be inserted at a position that breaks barrier alignment semantics. The timer thread **must acquire `checkpointLock` before enqueuing `F`**, sharing the same lock as `triggerBarrier()` and `sendRecordToNext()` to ensure mutual exclusion among all three.
   
   Existing lock mechanism in the engine:
   - `SourceSeaTunnelTask.init()` creates `checkpointLock = new Object()`
   - `SeaTunnelSourceCollector.sendRecordToNext()` delivers records via `synchronized(checkpointLock)`
   - `SourceFlowLifeCycle.triggerBarrier()` injects barriers via `synchronized(collector.getCheckpointLock())`
   
   The timer thread enqueuing `F` must follow the same path:
   
   ```java
   // Timer callback enqueue logic
   private void onTimerFired() {
       synchronized (checkpointLock) {
           if (prepareClose) {
               return;
           }
           // Enqueue F while holding checkpointLock,
           // mutually exclusive with triggerBarrier() and sendRecordToNext()
           enqueueFlushSignal();
       }
   }
   ```
   
   This guarantees:
   - `Ck` takes priority: while `triggerBarrier()` holds the lock, the timer thread blocks and cannot insert `F`
   - No `F` sandwiched between two halves of a `Ck`
   - No unsynchronized concurrent access to Sink state
   
   **F vs. prepareClose:**
   
   - After `prepareClose` is set: no new `F` is delivered.
   - Already-enqueued `F` is consumed to a position consistent with the existing `R` / `Sc` close protocol.
   
   **F vs. Sc (when adjacent):**
   
   `Sc` and `F` originate from different sources (`Sc` from the Source reader, `F` from the timer thread). Both are serialized through the same `checkpointLock` when enqueuing. **Their relative order is determined by lock acquisition order — no artificial intervention is applied.**
   
   Phase 1 only involves At-Least-Once semantics. `Sc` and `F` are both second-class citizens, and correctness is maintained regardless of which is consumed first:
   - `Sc` first: schema change is applied before flush — flushed data conforms to the new schema
   - `F` first: current buffered data is flushed before schema change — flushed data conforms to the old schema, which is equally correct
   
   **Backpressure:**
   
   When downstream backpressure causes the RingBuffer to approach capacity, the scheduler MUST **pause further `F` enqueuing** until downstream resumes consumption. The wall-clock thread must NOT execute flush or block for extended periods (consistent with the "enqueue only" principle).
   
   The current `RecordEventProducer.onData()` uses `ringBuffer.next()` which is a blocking call (blocks the caller when the RingBuffer is full). The timer thread must NEVER use that path. Backpressure detection is implemented via the LMAX Disruptor `RingBuffer` non-blocking API:
   
   **Disruptor path** (`RingBuffer<RecordEvent>`, capacity `RING_BUFFER_SIZE = 1024`):
   
   ```java
   // Timer callback enqueue logic (runs on the ScheduledExecutorService timer thread)
   private void onTimerFired(RingBuffer<RecordEvent> ringBuffer,
                             IntermediateQueueFlowLifeCycle flowLifeCycle) {
       if (flowLifeCycle.getPrepareClose()) {
           return;
       }
       // Non-blocking: tryNext() returns sequence if slot available,
       // throws InsufficientCapacityException if full
       try {
           long sequence = ringBuffer.tryNext();
           try {
               RecordEvent event = ringBuffer.get(sequence);
               event.setRecord(new Record<>(TimerFlushSignal.INSTANCE));
           } finally {
               ringBuffer.publish(sequence);
           }
       } catch (InsufficientCapacityException e) {
           // RingBuffer is full — drop this F, retry on next timer tick
       }
   }
   ```
   
   **BlockingQueue path** (`IntermediateBlockingQueue`):
   
   ```java
   private void onTimerFired(BlockingQueue<Record<?>> queue,
                             IntermediateQueueFlowLifeCycle flowLifeCycle) {
       if (flowLifeCycle.getPrepareClose()) {
           return;
       }
       // Non-blocking: offer() returns true if enqueued, false if full
       queue.offer(new Record<>(TimerFlushSignal.INSTANCE));
       // Returns false when full — drop this F, retry on next timer tick
   }
   ```
   
   The core principle is the same for both paths: **use a non-blocking API to attempt enqueue; on failure, drop this `F`, do not block, do not retry, do not execute flush on the timer thread.**
   
   ## Public Interfaces
   
   ### New API: `SinkTimerHandle`
   
   ```java
   /**
    * Handle for connectors to register wall-clock-driven flush.
    * Exposed via SinkWriter.Context or as a standalone SPI.
    */
   public interface SinkTimerHandle {
   
       /**
        * Register a periodic flush action. The engine will inject a TimerFlushSignal
        * into the record stream at the specified interval. The flushAction is invoked
        * on the task's consume thread when the signal is consumed — never on the
        * timer thread itself.
        *
        * <p>The flushAction should call the connector's existing flush/bulk-write
        * logic. It does NOT replace prepareCommit.
        *
        * @param intervalMs flush interval in milliseconds
        * @param flushAction the flush callback to execute
        */
       void registerTimerFlush(long intervalMs, Runnable flushAction);
   }
   ```
   
   ### New Internal Class: `TimerFlushSignal`
   
   An engine-internal marker class carried as the payload of `Record<?>`. Not part of the public connector API.
   
   ### Modified Class: `SinkFlowLifeCycle`
   
   The `received(Record<?>)` method gains a new `instanceof TimerFlushSignal` branch (see Design section above).
   
   ### Modified Class: `RecordEventProducer` / `RecordEventHandler`
   
   No behavioral change — `F` is a non-Barrier event and naturally follows the existing drop-after-prepareClose path.
   
   ## Compatibility
   
   ### Backward Compatibility
   
   - **No existing config options are removed or renamed.**
   - **No existing API contracts are broken.** `SinkWriter.write`, `prepareCommit`, `snapshotState`, and `close` remain unchanged.
   - Connectors that do not call `registerTimerFlush` behave exactly as they do today — zero impact.
   - The `TimerFlushSignal` is engine-internal; connectors never see it directly.
   
   ### Exactly-Once / 2PC Compatibility
   
   **Phase 1 explicitly does NOT support 2PC scenarios.** Timer flush targets non-2PC connectors only (`containAggCommitter == false`); 2PC compatibility is deferred to future iterations.
   
   | Connector / Mode | Phase 1 Support | Notes |
   |-----------------|----------------|-------|
   | JDBC (`is_exactly_once = false`, default) | **Yes** (opt-in) | Phase 1 primary use case, non-XA mode, `containAggCommitter == false` |
   | JDBC (`is_exactly_once = true`, XA transactions) | No (future iteration) | With XA enabled, `containAggCommitter == true`, hard-guarded by engine |
   | Doris / StarRocks 2PC | No (future iteration) | `containAggCommitter == true`, hard-guarded by engine |
   | Mongo transactions | No (future iteration) | Requires additional verification of flush vs. transaction boundary interaction |
   | Other non-2PC connectors (Elasticsearch, Paimon, etc.) | **Yes** (opt-in) | `containAggCommitter == false` is the only requirement |
   
   ## Implementation Plan
   
   | Phase | Scope |
   |-------|-------|
   | Phase 1 | `TimerFlushSignal` class, `SinkTimerHandle` SPI, `SinkFlowLifeCycle.received` branch, lifecycle-bound `ScheduledExecutorService`, backpressure-aware enqueue gating, concurrency tests with checkpoint coordination, unit tests, JDBC non-XA connector adoption |
   | Phase 2 | 2PC scenario support (JDBC XA, Doris / StarRocks 2PC), other connector adoption (Elasticsearch, Paimon), E2E tests, documentation |
   


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

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

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