Skip to content

[Feature][Zeta] Add snapshot compaction for HDFS IMap WAL - #13364

Draft
dybyte wants to merge 5 commits into
apache:devfrom
dybyte:feature/log-compaction
Draft

dybyte wants to merge 5 commits into
apache:devfrom
dybyte:feature/log-compaction

Conversation

@dybyte

@dybyte dybyte commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Purpose of this pull request

Related to #10329. Alternative implementation to #10399.

This PR adds opt-in snapshot compaction for HDFS IMap storage.

  • Rotate WAL segments and periodically merge all sealed files with the previous snapshot within each writer region, without sorting records.
  • Preserve tombstones, expiration times, and original timestamps, with safe recovery during concurrent compaction.
  • Share one compaction executor and separate planning/storage interfaces for future extensions.

Compaction is disabled by default. Previous regions remain unchanged. English and Chinese documentation is included.

Does this PR introduce any user-facing change?

Yes. Adds opt-in WAL rotation and periodic snapshot compaction for HDFS IMap storage, configured through compaction.enabled, compaction.interval-seconds, and wal.segment-size.

Compaction is disabled by default, preserving existing behavior unless explicitly enabled.

How was this patch tested?

Passed Spotless, full Maven verify with UI skipped, focused unit tests, real HDFS recovery tests, and the two-node cluster restart E2E test.

Check list

@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 34da0bb1b05a.

What this PR fixes

  • User pain: the HDFS/local-file IMap store is an append-only WAL (IMapFileStorage -> WALDisruptor -> HdfsWriter). Every repeated write to the same key grows the region's single wal.txt, and restart replay has to read all of it (#10329).
  • Fix approach: with compaction.enabled=true, WALWriter uses the new SegmentedHdfsWriter instead of HdfsWriter. It rotates segment-%020d-wal.txt files once wal.segment-size bytes have been written and reports each successfully closed segment to RegionCompactionPlanner.
  • Compaction: one JVM-wide daemon thread in CompactionCoordinator runs a per-writer task every compaction.interval-seconds. WALCompactor folds the sealed segments and the previous snapshot into a 00000000000000000000-snapshot-<uuid>-wal.txt file holding the latest raw mutation per key, tombstones and expired puts included.
  • Publication: HdfsCompactionStorage.publish writes a temporary file, renames it, then replaces the .compaction-current token. Only after that are the inputs deleted.
  • Replay: WALReader retries up to five times when it sees a ConcurrentCompactionException or FileNotFoundException.
  • Scope: only storage.type=hdfs on an hdfs:// or file:/// file system is accepted. Regions left by earlier runs are neither compacted nor adopted. The default stays false.

Runtime chain I rechecked

WRITE PATH (compaction.enabled=true)
FileMapStore.init()  FileMapStore.java:71-76
  -> IMapFileStorageFactory.create()  IMapFileStorageFactory.java:39-43
    -> IMapFileStorage.initialize()  IMapFileStorage.java:122
         new CompactionConfig(configuration)  IMapFileStorage.java:130  (rejects interval or segment size <= 0, CompactionConfig.java:62)
         rejects storage.type != hdfs  IMapFileStorage.java:131-134
         region = UUID when enabled, System.nanoTime() otherwise  IMapFileStorage.java:155-158
         new WALDisruptor(fs, type, businessRootPath + region + '/', serializer, compaction)  IMapFileStorage.java:173-179
      -> new WALWorkHandler(..., compaction)  WALDisruptor.java:78
        -> new WALWriter(..., compaction)  WALWorkHandler.java:60-62
             new HdfsCompactionStorage(fs, serializer) + initialize(parentPath) writes the .compaction-current token  WALWriter.java:68-69
             new RegionCompactionPlanner(parentPath)  WALWriter.java:70
             new SegmentedHdfsWriter(segmentSize, planner)  WALWriter.java:71
             CompactionCoordinator.register(planner, storage, intervalSeconds)  WALWriter.java:78-80
FileMapStore.store()/delete()  FileMapStore.java:94-112  (boolean result of mapStorage.store/delete is ignored)
  -> IMapFileStorage.store()/delete() -> WALDisruptor.tryPublish(APPEND)
    -> WALWorkHandler.walEvent()  WALWorkHandler.java:81-92  (IOException is logged, request completes with false)
      -> SegmentedHdfsWriter.write()  SegmentedHdfsWriter.java:66-79
           writtenBytes >= segmentSize -> seal()  SegmentedHdfsWriter.java:76-78
           seal(): super.close(), planner.sealed(current), current = null  SegmentedHdfsWriter.java:81-91

COMPACTION PATH (shared thread "seatunnel-imap-compaction")
CompactionCoordinator.register() -> scheduleWithFixedDelay(task, interval, interval)  CompactionCoordinator.java:47-87
  -> Task.run() (synchronized)  CompactionCoordinator.java:102-123
       planner.plan() returns empty while no segment is sealed  RegionCompactionPlanner.java:48-58
       WALCompactor.compact(): read every input into LatestMutationAccumulator, throw on ambiguous expiration, publish  WALCompactor.java:33-44
         -> HdfsCompactionStorage.publish(): tmp file + hsync, rename, replace token  HdfsCompactionStorage.java:90-123
       planner.committed(plan, snapshot)  RegionCompactionPlanner.java:61-64
       deleteReplacedInputs()  CompactionCoordinator.java:125-131
       catch (Exception) -> WARN, retry on the next interval  CompactionCoordinator.java:118-122

SHUTDOWN PATH
FileMapStore.destroy() -> mapStorage.destroy(false)  FileMapStore.java:89-91
  -> IMapFileStorage.destroy() -> walDisruptor.close()  IMapFileStorage.java:293-306
    -> WALDisruptor.close()  WALDisruptor.java:111-122
         handler.stopCompaction() -> registration.close() -> Task.close() (synchronized, waits for an in-flight run)  WALDisruptor.java:112, CompactionCoordinator.java:72-85, 134-136
         publish CLOSED, disruptor.shutdown(5 s)  WALDisruptor.java:115-117
      -> WALWorkHandler CLOSED -> WALWriter.close() -> SegmentedHdfsWriter.close() seals the last segment after compaction has stopped  WALWriter.java:89-92, SegmentedHdfsWriter.java:94-101

READ PATH
IMapFileStorage.loadAll*/loadAllKeys()  IMapFileStorage.java:261-290
  -> WALReader.readLatestMutations(): up to 5 attempts on ConcurrentCompactionException/FileNotFoundException  WALReader.java:167-184
    -> DefaultReader.forEachData(): list WAL files under the business root, sort by path, re-check the .compaction-current tokens after reading

Findings

Issue 1: A single failed segment close in SegmentedHdfsWriter.seal() leaves the writer permanently broken: every later IMap mutation fails to persist, and the only signal is an ERROR log per write.

  • Location: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/wal/writer/SegmentedHdfsWriter.java:85
  • Why it matters: Root cause: seal() calls super.close() and rethrows on failure before it reaches current = null.
  • The next write() sees closed == false and current != null, so it skips openNextSegment() and calls super.write(bytes) on the stream whose close just failed.
  • Nothing ever resets current or reopens a segment, so the writer stays in that state for the rest of the storage instance's life.

Why it is reachable: the legacy HdfsWriter closes its stream only at shutdown. Rotation now closes a stream on the write path every wal.segment-size bytes, so one transient file-system error during close is enough.

Impact:

  • WALWorkHandler.walEvent catches the IOException, logs it and completes the request with false.
  • IMapFileStorage.store()/delete() return that false, but FileMapStore.store()/delete() ignore the return value.
  • Hazelcast therefore keeps accepting mutations in memory while nothing reaches the WAL. A later restart replays state that is missing everything written after the failed seal.

Suggested fix:

  • Reset the writer state when close fails, for example clear current in a finally block without reporting the segment to the planner, so the next write() opens a fresh segment.
  • Add a unit test that injects a close failure and asserts that the following write succeeds.
  • Evidence: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/wal/writer/SegmentedHdfsWriter.java:90 current = null;; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/wal/writer/SegmentedHdfsWriter.java:70 if (current == null) {; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/wal/writer/SegmentedHdfsWriter.java:74 super.write(bytes);
  • Suggested fix: If super.close() throws here we never reach current = null. The next write() then skips openNextSegment() and calls super.write(bytes) on the stream whose close just failed, and nothing ever resets that state, so every later write fails too.

The effect is wider than this class. WALWorkHandler only logs the IOException and completes the request with false, and FileMapStore.store()/delete() ignore that boolean. Hazelcast keeps running while nothing is persisted.

Could we clear current in a finally block, without reporting the segment to the planner, so the next write opens a new segment? A test that injects a close failure and checks the following write would be good to have.

  • Priority: P0 — must fix before merge
  • I traced this in the code.
  • When it happens: Set compaction.enabled: true with storage.type: hdfs. Write until writtenBytes >= wal.segment-size, and let out.close() fail on that rotation, for example a completeFile failure because the last block lacks replicas, or a NameNode failover. That store() returns false although the record is durable. Every later store()/delete() on that IMap writer then fails in super.write on the closed stream and is only logged by WALWorkHandler. Hazelcast sees a successful MapStore call, so those mutations are missing after a restart.

Issue 2: Rotation is size-only and the final segment is sealed only after compaction has stopped, so with the default 64 MiB segment a region that writes less than one full segment per process lifetime is never compacted.

  • Location: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/wal/writer/SegmentedHdfsWriter.java:76
  • Why it matters: Root cause: three behaviours combine.
  • A segment reaches the planner only when writtenBytes >= segmentSize (default 64L * 1024 * 1024). RegionCompactionPlanner.plan() returns Optional.empty() while no sealed file exists, so the compaction.interval-seconds tick does nothing until then.
  • The last segment is sealed in SegmentedHdfsWriter.close(). WALDisruptor.close() and WALWriter.close() both call stopCompaction() first, so that final planner.sealed(current) reaches a task that is already closed and cancelled.
  • IMapFileStorage.initialize creates a fresh UUID region on every start, and regions from earlier runs are not adopted (the PR description and the new docs both say so).

Impact:

  • An IMap that writes less than wal.segment-size in one process lifetime gets no compaction at all, and its files accumulate across restarts exactly as before.
  • For any region, the tail written after the last size-triggered seal is never compacted.
  • The feature exists to bound replay cost for repeatedly updated keys (#10329), but with the documented defaults it only helps high-volume regions.

Suggested fix:

  • Add a second sealing trigger, for example seal a non-empty active segment once it is older than the compaction interval.
  • Alternatively, lower the default segment size and state the size-only behaviour clearly in the docs.
  • Evidence: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/compaction/RegionCompactionPlanner.java:49 if (sealedFiles.isEmpty()) {; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/config/CompactionConfig.java:49 .defaultValue(64L * 1024 * 1024); seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/common/WALWriter.java:90 stopCompaction();
  • Suggested fix: Rotation is purely size-based, and RegionCompactionPlanner.plan() returns empty until a segment is sealed. With the 64 MiB default, an IMap that writes less than that in one process lifetime never seals a segment, so the interval tick never does anything for it.

The only other seal happens in close(), after stopCompaction() has already run. The next start creates a new UUID region and does not adopt the old one, so the previous run's files are never compacted either.

Could we add a time-based trigger, for example sealing a non-empty active segment once it is older than the compaction interval? Otherwise compaction only takes effect for high-volume regions.

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: Set compaction.enabled: true and leave wal.segment-size at the default 67108864. Run a master whose writer for one IMap, for example engine_runningJobInfo, appends less than 64 MiB before shutdown. No ...-snapshot-...-wal.txt file is ever produced in that region. On restart a new UUID region is created and the old one is replayed in full and never compacted.

Issue 3: One pair of same-millisecond, same-value mutations with different expiration times makes every compaction attempt for that region fail, with a full re-read and a WARN stack trace on each interval.

  • Location: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/common/WALCompactor.java:38
  • Why it matters: Root cause: LatestMutationAccumulator marks a key ambiguous when compareTo == 0 but the expiration times differ.
  • IMapDataComparator does not compare expiration. A tie therefore means the same key, the same millisecond timestamp, the same deleted flag and the same value class and bytes.
  • WALCompactor.compact then throws for the whole plan.

Impact:

  • The tied pair stays in the sealed inputs. Every later run re-reads the previous snapshot and all accumulated sealed segments, throws again, and logs IMap WAL compaction failed; retained inputs will be retried with a stack trace.
  • The ambiguity clears only when that same key receives a newer mutation in a sealed segment. If the key is never written again, the region is not compacted for the rest of the process lifetime, and sealed segments keep piling up.
  • The docs added in this PR describe the deferral, but not that it blocks the whole region or that it repeats on every interval.

Suggested fix:

  • Consider resolving the tie in the compactor instead of failing the plan. The accumulator already keeps the first record it read, and the plan lists the snapshot first and then the sealed segments in seal order.
  • If the deferral has to stay, limit it to the affected key or files so the rest of the region can still be compacted, and log it once without a stack trace.
  • Evidence: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/common/WALCompactor.java:38 if (accumulator.hasAmbiguousExpirationTimes()) {; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinator.java:121 log.warn("IMap WAL compaction failed; retained inputs will be retried", e);; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/wal/reader/DefaultReader.java:102 files.sort(Comparator.comparing(file -> file.getPath().toString()));
  • Suggested fix: This throws for the whole plan, and the ambiguous pair stays in the sealed inputs. On every interval we re-read the snapshot and all sealed segments, throw again, and log a WARN with a stack trace. It only clears if that exact key gets a newer mutation in a sealed segment. For a key that is never written again, one tied pair blocks compaction of the region for the rest of the process lifetime.

Is failing the whole plan necessary? The accumulator already keeps the first record it read on a tie, and the plan lists the snapshot first and then the segments in seal order. Could the snapshot simply keep that record?

If the deferral has to stay, please keep the rest of the region compactable and log the condition once without the stack trace.

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: In one compaction-enabled region, seal segments containing two puts of the same key with identical timestamp and value bytes but different expirationTime, and never write that key again. Every compaction.interval-seconds tick re-reads the previous snapshot plus all sealed segments, throws "Compaction deferred: equal WAL mutations have different expiration times", and logs IMap WAL compaction failed; retained inputs will be retried with a stack trace. No snapshot is published and no input is deleted for that IMap on that member until restart.

Issue 4: WALDisruptor.close() now waits without any bound for an in-flight compaction, so member shutdown is held up by a full snapshot rewrite or a hung HDFS call.

  • Location: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/disruptor/WALDisruptor.java:112
  • Why it matters: Root cause:
  • WALDisruptor.close() now calls handler.stopCompaction() before it publishes the CLOSED event.
  • That reaches the registration's close(), which calls task.close(). Task.run() and Task.close() are both synchronized on the task, so the caller waits until the current run has finished: reading every input, writing and hsyncing the snapshot, renaming it, replacing the token and deleting the inputs.
  • There is no timeout and no cancellation check inside run().

Impact:

  • FileMapStore.destroy() calls mapStorage.destroy(false), which calls walDisruptor.close(). A member stopping while its region is being compacted therefore waits for the whole run, or for as long as a degraded file system keeps one of those calls blocked.
  • The comment on WALWriter.stopCompaction() shows the wait is deliberate, to keep it outside the 5 s Disruptor deadline. Having no bound at all is the concern.

Suggested fix:

  • Bound the wait, and let run() check a stop flag between inputs so it can abandon the attempt early.
  • A failed or abandoned attempt already leaves its inputs readable, so giving up on the run should not lose data. Waiting for completion is only needed when the caller is about to delete the directory.
  • Evidence: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinator.java:102 public synchronized void run() {; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinator.java:134 private synchronized void close() {; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinator.java:77 future.cancel(false);
  • Suggested fix: stopCompaction() ends in Task.close(), which is synchronized against Task.run(). This call therefore waits, with no timeout, for the in-flight compaction to read all inputs, write and hsync the snapshot, and delete the inputs. On the FileMapStore.destroy() shutdown path a member cannot stop until that finishes, or for as long as a degraded HDFS keeps one of those calls blocked.

I understand the wait is deliberate, to stay outside the 5 s Disruptor deadline. Could it be bounded, with run() checking a stop flag between inputs? A failed attempt already leaves its inputs readable, so abandoning the run should be safe when the directory is not being deleted.

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: Enable compaction and call IMapFileStorage.destroy(false) (member shutdown) while that IMap's compaction Task.run() is inside WALCompactor.compact, for example mid-way through writing a large snapshot or blocked in an HDFS call. destroy does not return until that run finishes; the wait is unbounded.

Issue 5: Task.close() shares a monitor with the whole compaction run, so IMapFileStorage.destroy() and node shutdown can hang behind a long or stuck compaction.

  • Location: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinator.java:134
  • Why it matters: Root cause: Task.run() and Task.close() are both synchronized on the task, and run() performs the entire compaction inside that monitor.
  • The run reads the previous snapshot and all sealed segments, writes and hsyncs a new snapshot, renames it, replaces the token and deletes the inputs.
  • WALDisruptor.close() now calls handler.stopCompaction() before publishing the CLOSED event, so IMapFileStorage.destroy() blocks until that run finishes.

Impact:

  • Before this PR, WALDisruptor.close() was limited by disruptor.shutdown(5, SECONDS). With compaction enabled, the time to close now depends on the size of the plan and on file-system responsiveness, with no upper limit.
  • A blocked HDFS call inside run() blocks shutdown of that IMap store indefinitely.

Suggested fix:

  • Do not hold the task monitor across I/O. Use a volatile stop flag that run() checks between inputs and before publishing, and have close() wait for a bounded time.
  • Keep the full wait only for destroy(true), where the region directory is deleted afterwards.
  • Evidence: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinator.java:134 private synchronized void close() {; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinator.java:78 task.close();; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/disruptor/WALDisruptor.java:112 handler.stopCompaction();
  • Suggested fix: close() shares the monitor with run(), so WALDisruptor.close() → stopCompaction() blocks for the entire in-flight compaction: reading the snapshot and all sealed segments, write and hsync, rename, token swap, deletes. With large plans or a stuck HDFS call, IMapFileStorage.destroy() and member shutdown wait without bound. Before this PR the close path was capped by the 5 s Disruptor shutdown.

Could run() check a volatile stop flag between inputs and before publishing, with close() waiting only for a bounded time? The unbounded wait seems necessary only for destroy(true), where the directory is deleted afterwards.

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: Set compaction.enabled: true on an hdfs-backed IMap and let at least one segment be sealed. While the seatunnel-imap-compaction thread is inside Task.run() for that writer (for example, reading several 64 MiB segments plus the previous snapshot, or blocked in a slow NameNode/DataNode call during publish), call IMapFileStorage.destroy(...). The calling thread parks on the Task monitor at task.close() until run() returns. No timeout applies, the CLOSED event has not been published, and isClosed is still false.

Issue 6: An OutOfMemoryError (or any other Error) in the compaction task stops compaction for that IMap without a log line, while the writer keeps rotating segments.

  • Location: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinator.java:118
  • Why it matters: Root cause:
  • WALCompactor.compact() loads the latest raw mutation of every distinct key in the plan into one heap accumulator. That includes key and value bytes, tombstones and expired puts, and there is no size bound or pre-check.
  • Task.run() catches only Exception.

Impact:

  • An OutOfMemoryError or any other Error escapes run(). A task scheduled with scheduleWithFixedDelay is not executed again after it throws.
  • The throwable is held only by the ScheduledFuture, which is used solely for cancel, so nothing is logged.
  • SegmentedHdfsWriter keeps sealing segments into RegionCompactionPlanner.sealedFiles, which is never drained again. The region returns to unbounded WAL growth with no signal to the operator.
  • The comment in the catch block says a failed attempt must not cancel future attempts. That guarantee does not hold for Error.

Suggested fix:

  • Catch Throwable in Task.run() and log it at ERROR, so the failure is visible and later attempts still run.
  • Consider a guard on input size or key count before loading a plan into memory.
  • Evidence: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinator.java:65 executor.scheduleWithFixedDelay(; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/common/WALCompactor.java:34 LatestMutationAccumulator accumulator = new LatestMutationAccumulator(null);; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/common/WALCompactor.java:36 storage.read(input, accumulator::accept);
  • Suggested fix: catch (Exception e) does not cover Error. WALCompactor holds the latest mutation of every key in the plan on heap with no bound, so an OutOfMemoryError here is realistic. When it escapes run(), scheduleWithFixedDelay drops all future executions of this task and nothing is logged, because the future is only ever used for cancel. Meanwhile SegmentedHdfsWriter keeps sealing segments into sealedFiles, which is never drained again.

Please catch Throwable and log it at ERROR, so the comment below ("must not cancel future scheduled attempts") holds for errors as well.

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: Enable compaction on an IMap whose current region holds more distinct keys and latest values than the free heap of the master JVM. On the next tick storage.read(input, accumulator::accept) throws OutOfMemoryError; any other Error inside run(), such as NoClassDefFoundError or StackOverflowError, has the same effect. The error bypasses catch (Exception e), no WARN or ERROR line is written, and the periodic task for that writer never fires again. SegmentedHdfsWriter continues to seal 64 MiB segments into the region, which are never compacted or deleted until the member restarts.

Issue 7: The wal.segment-size docs do not say that this option decides whether compaction runs at all: only size-sealed segments are compacted, so with the 64 MiB default a low-volume IMap region is never compacted.

  • Location: docs/en/engines/zeta/state-storage-and-recovery.md:216
  • Why it matters: Root cause, from the code:
  • SegmentedHdfsWriter.write seals a segment only when writtenBytes >= segmentSize. There is no time-based or interval-based rotation.
  • RegionCompactionPlanner.plan() returns Optional.empty() while no segment is sealed, so the compaction.interval-seconds tick does nothing until a full segment exists.
  • WALDisruptor.close() calls handler.stopCompaction() before the writer seals its last segment, and regions from earlier runs are never adopted. The tail of each run is therefore never compacted.

What the docs say:

  • The option tables describe wal.segment-size only as a rotation size.
  • The prose in state-storage-and-recovery.md says compaction merges only closed segments and that the active segment is not compacted. It does not say that a segment closes only on reaching this size.

Impact: a reader who enables compaction.enabled with the documented defaults will reasonably expect compaction every 300 seconds. A region that writes less than 64 MiB during one process lifetime gets none.

Suggested fix:

  • Add one sentence to the wal.segment-size row or the paragraph below it. It should say that a segment is closed only after it reaches this size, and that a region is compacted only once it has at least one closed segment.
  • Advise lowering the value for low-volume IMaps.
  • Mirror the sentence in the two deployment pages and in the zh docs.
  • Evidence: docs/en/engines/zeta/hybrid-cluster-deployment.md:356 | wal.segment-size| long |67108864 (64 MiB) | WAL rotation size in bytes when compaction is enabled; must be greater than zero. |; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/wal/writer/SegmentedHdfsWriter.java:76 if (writtenBytes >= segmentSize) {; seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/disruptor/WALDisruptor.java:112 handler.stopCompaction();
  • Suggested fix: Could we spell out how this option gates compaction? SegmentedHdfsWriter seals a segment only once writtenBytes >= segmentSize, and RegionCompactionPlanner.plan() returns empty until a segment is sealed. With the documented defaults, a region that writes less than 64 MiB in one run is never compacted, and the last segment is sealed only after stopCompaction() on close.

Please add a sentence saying that a segment closes only when it reaches this size, that a region is compacted only once it has at least one closed segment, and that low-volume IMaps need a smaller value. The same note belongs in the deployment pages and the zh docs.

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: A user copies the documented block (compaction.enabled: true, compaction.interval-seconds: 300, wal.segment-size: 67108864) on a cluster whose IMap writers each append less than 64 MiB per run. No snapshot is ever produced and no log line explains why. The docs do not state that the segment size is the threshold that decides whether compaction runs at all.

Issue 8: The "upgrade all members before enabling" and rollback constraints appear only in state-storage-and-recovery.md; the two deployment pages where users copy the YAML do not carry the warning.

  • Location: docs/en/engines/zeta/separated-cluster-deployment.md:308
  • Why it matters: Root cause:
  • This PR documents in state-storage-and-recovery.md that older releases cannot safely load while compaction is running. It also says all members using IMap persistence must be upgraded before enabling it, and that compaction must be disabled and allowed to finish before a rollback.
  • The new "Optional WAL compaction" blocks in hybrid-cluster-deployment.md and separated-cluster-deployment.md show the enabling YAML and the option table. They link onward only "for capacity and recovery considerations".
  • The zh state page carries the same warning. The zh deployment pages contain the YAML and table but no upgrade or rollback wording.

Impact: someone enabling the option from a deployment page during a rolling upgrade, or rolling back afterwards, has no hint on that page that mixed versions are unsafe while compaction runs. The constraint is an operational precondition, and the link text does not suggest it is one.

Suggested fix:

  • Add a short warning directly below the option table in both deployment pages, en and zh. It should say to enable compaction.enabled only after every member using IMap persistence runs a compaction-aware release, and to disable it and let any running compaction finish before rolling back.
  • Link the warning to the detailed section.
  • Evidence: docs/en/engines/zeta/separated-cluster-deployment.md:308 | wal.segment-size| long |67108864 (64 MiB) | WAL rotation size in bytes when compaction is enabled; must be greater than zero. |; docs/en/engines/zeta/state-storage-and-recovery.md:237 stable files. However, older releases cannot safely load while compaction is running. Upgrade all
  • Suggested fix: The upgrade and rollback constraint ("older releases cannot safely load while compaction is running") is documented only in state-storage-and-recovery.md, but this page is where most users will copy the YAML from. The link below only mentions "capacity and recovery considerations".

Could you add a short warning right below the table, here and in the hybrid page and both zh pages? It should say to enable compaction.enabled only after all members using IMap persistence are on a compaction-aware release, and to disable it and let any running compaction finish before rolling back.

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: Open docs/en/engines/zeta/hybrid-cluster-deployment.md at "Optional WAL compaction" (lines 341-365) and copy the three properties into map-store.properties during a rolling upgrade. Nothing on that page, or on the separated-cluster page or either zh page, says to upgrade every member first or to disable and drain compaction before rollback. That requirement is reachable only by following the link to state-storage-and-recovery.md and reading lines 237-240.

Review conclusion

Conclusion: can merge after the blocking items are fixed

1. Blocking items

  • Issue 1: A single failed segment close in SegmentedHdfsWriter.seal() leaves the writer permanently broken: every later IMap mutation fails to persist, and the only signal is an ERROR log per write.

2. Remaining follow-ups

  • Issue 2: Rotation is size-only and the final segment is sealed only after compaction has stopped, so with the default 64 MiB segment a region that writes less than one full segment per process lifetime is never compacted.
  • Issue 3: One pair of same-millisecond, same-value mutations with different expiration times makes every compaction attempt for that region fail, with a full re-read and a WARN stack trace on each interval.
  • Issue 4: WALDisruptor.close() now waits without any bound for an in-flight compaction, so member shutdown is held up by a full snapshot rewrite or a hung HDFS call.
  • Issue 5: Task.close() shares a monitor with the whole compaction run, so IMapFileStorage.destroy() and node shutdown can hang behind a long or stuck compaction.
  • Issue 6: An OutOfMemoryError (or any other Error) in the compaction task stops compaction for that IMap without a log line, while the writer keeps rotating segments.
  • Issue 7: The wal.segment-size docs do not say that this option decides whether compaction runs at all: only size-sealed segments are compacted, so with the 64 MiB default a low-volume IMap region is never compacted.
  • Issue 8: The "upgrade all members before enabling" and rollback constraints appear only in state-storage-and-recovery.md; the two deployment pages where users copy the YAML do not carry the warning.

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

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for contributing to Apache SeaTunnel! I reviewed the complete current diff and followed its entry points and failure paths. The items below need attention before merging; I hope the concrete paths make the next step straightforward.

What problem does this PR solve?

User pain: repeated IMap metadata updates append WAL history indefinitely. Approach: opt-in per-writer segment rotation and periodic regional snapshots that retain the latest raw mutation for every key. In one sentence: this reduces repeated history in the current region; it does not reclaim every old region or historical key. Example: 10,000 updates of one job key can become one snapshot mutation, while its deletion marker remains to suppress an older region.

1. Code changes

1.1 Core logic

Complete runtime path:

FileMapStore.store/delete -> IMapFileStorage -> WALDisruptor APPEND -> WALWorkHandler
 -> WALWriter -> SegmentedHdfsWriter -> write+hflush -> size threshold -> close/seal -> RegionCompactionPlanner
Shared scheduled thread -> Task.run -> prior snapshot + sealed prefix
 -> WALCompactor -> LatestMutationAccumulator (raw key/value bytes, tombstones, expired puts)
 -> HdfsCompactionStorage.publish -> hsync temp -> unique snapshot rename -> atomic equality-token replacement
 -> planner.committed -> delete replaced inputs
Replay -> DefaultReader captures tokens BEFORE fresh inventory -> scans WAL -> rechecks tokens
 -> WALReader discards a changed/partial accumulator and retries up to 5 times
Destroy -> WALDisruptor.close -> stopCompaction -> task.close waits on run monitor -> CLOSED event -> writer.close

Key findings and correctness:

I inspected all 29 changed files and the MapStore adapter. Default false retains the legacy writer. Enabled compaction touches HDFS/file only; no object-store rename is assumed. Region ownership and raw mutation preservation are sound design choices: active tails, other writers and old regions are excluded, expired puts and tombstones stay. However, the enabled runtime has real persistence, shutdown and capacity blockers. The token-before-inventory protocol and deterministic filesystem-interleaving tests address concurrent replay; they do not address writer close failure or bound the live compactor. There is only one shared thread, so a slow region delays every other registration in this JVM.

Before:

import org.apache.seatunnel.engine.imap.storage.file.common.FileConstants;
import org.apache.seatunnel.engine.imap.storage.file.common.WALReader;
import org.apache.seatunnel.engine.imap.storage.file.config.AbstractConfiguration;
import org.apache.seatunnel.engine.imap.storage.file.config.FileConfiguration;
import org.apache.seatunnel.engine.imap.storage.file.disruptor.WALDisruptor;
import org.apache.seatunnel.engine.imap.storage.file.disruptor.WALEventType;

After:

import org.apache.seatunnel.engine.imap.storage.file.common.FileConstants;
import org.apache.seatunnel.engine.imap.storage.file.common.WALReader;
import org.apache.seatunnel.engine.imap.storage.file.config.AbstractConfiguration;
import org.apache.seatunnel.engine.imap.storage.file.config.CompactionConfig;
import org.apache.seatunnel.engine.imap.storage.file.config.FileConfiguration;
import org.apache.seatunnel.engine.imap.storage.file.disruptor.WALDisruptor;
import org.apache.seatunnel.engine.imap.storage.file.disruptor.WALEventType;

1.2 Compatibility

Partially compatible when enabled: record framing is unchanged and older code can read stable files, but older replay is unsafe during concurrent compaction. All persistence-owning members must be upgraded before enablement, and compaction must be disabled/drained before rollback. Default-disabled legacy writers remain intact. This mixed-version restriction belongs in the incompatible-change/migration guidance and beside both deployment examples; it is not made harmless by the unchanged WAL record bytes.

1.3 Performance and side effects

This adds a shared background scheduler, full-snapshot reads/writes and an unbounded raw-mutation heap set when enabled. A single large/HDFS-stalled plan delays all maps and, through close, member shutdown. Retry retains all inputs and a pending-deletion set; repeated ambiguity rereads the plan every interval and logs a stack trace. Size rotation adds stream close/open on the mutation path. These costs require bounded working memory and shutdown; no local throughput/heap experiment was run.

1.4 Errors, logging, and findings

Issue 1: Bound the live compaction working set before allocating it

  • Location: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/common/WALCompactor.java:34.
  • Description and risk: This is related to @SEZ9's Issue 6 about a silently stopped periodic task, but the immediate production consequence is wider: each interval retains the previous snapshot plus every distinct key/value in all selected segments in one HashMap, alongside the live Hazelcast IMap. Tombstones and expired historical keys intentionally never disappear from this set. A long-lived high-churn region can therefore exhaust the master JVM even when the live IMap is small; segment-size bounds one file, not the accumulated snapshot. Catching Throwable after an OOM does not provide a capacity bound or preserve cluster availability.
  • Best improvement: The minimal safe implementation needs an explicit byte/key work budget checked during accumulation, aborting before publication and retaining authoritative inputs with a visible capacity state. The stronger long-term implementation is bounded partitioned/external merge. Add a deterministic budget-exhaustion test and document the resulting capacity behavior; do not merely catch OOM and repeatedly retry the same full allocation.
  • Responsibility and trade-off: The regional planner/storage/codec split is an appropriate engine IMap persistence boundary, rather than connector code. The smallest safe deliverable preserves current-region ownership and raw replay order while making seal failure, bounded compaction and bounded stop safe. Cross-region reclamation is a different, larger ownership protocol and should stay out of this PR.
  • Severity: P0; blocking: true.
  • Previously raised by another reviewer: Issue 1 partially overlaps @SEZ9 Issue 6 and adds the bounded-working-set requirement; Issue 2 was not raised there.

Issue 2: Retry a snapshot-retirement race inside the asynchronous test predicate

  • Location: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/test/java/org/apache/seatunnel/engine/imap/storage/file/IMapFileStorageTest.java:179.
  • Description and risk: The periodic test resolves a snapshot path and then opens it while another compaction can replace and delete it. Unlike FileMapStoreTest.hasCompactedEntries, this predicate does not catch FileNotFoundException. Awaitility retries assertions, but an uncaught filesystem exception can terminate the wait rather than test the replacement snapshot. The HDFS variant repeats the same pattern.
  • Best improvement: Read through a stable token-aware WAL view, or treat only the expected retirement exception as a retry inside the predicate. Retain exact mutation/count assertions and keep other I/O failures visible.
  • Responsibility and trade-off: The regional planner/storage/codec split is an appropriate engine IMap persistence boundary, rather than connector code. The smallest safe deliverable preserves current-region ownership and raw replay order while making seal failure, bounded compaction and bounded stop safe. Cross-region reclamation is a different, larger ownership protocol and should stay out of this PR.
  • Severity: Medium; blocking: false.
  • Previously raised by another reviewer: Issue 1 partially overlaps @SEZ9 Issue 6 and adds the bounded-working-set requirement; Issue 2 was not raised there.

+1 to @SEZ9's review, especially Issue 1: seal rethrows before clearing current, later writes use the failed/closed stream, WALWorkHandler returns false, and FileMapStore ignores that result (FileMapStore.java:94-111). This remains a persistence blocker and is not duplicated in my numbering. Recovery must preserve/propagate the failed mutation too, not only reopen for the following one. +1 to their Issues 4/5 (one underlying shutdown problem): Task.run and Task.close share a monitor across all I/O, so cancel(false) does not bound destroy; this also blocks merge. Their Issue 6 scheduling failure is real, but I would respectfully avoid treating catch-Throwable-and-continue as the complete OOM repair; Issue 1 above addresses capacity before exhaustion. Their Issues 2/7 describe the size-only trigger and unadopted final tail accurately, and Issue 3 correctly identifies repeated whole-region deferral. Keep TTL replay semantics safe while making deferral observable/backed off; do not choose a different TTL arbitrarily. Their Issue 8 rollout warning should be placed beside the enabling YAML in both languages. No author correction has arrived on this head; I agree with the existing change request.

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: At risk. WALReaderAndWriterTest covers raw mutation identity, active tails, failed token publication, truncated inputs, TTL ties and explicit listing/open interleavings without sleeps. FileMapStoreTest checks actual recovered entries and remaining TTL; ClusterFaultToleranceIT enables compaction and waits for a snapshot. IMapFileStorageTest covers periodic scheduling and shared-thread shutdown with Awaitility. The actual HDFS test is conditional on imap.test.hdfs-uri, so its presence is not proof CI executed HDFS. Stability rating: At risk for Issue 2 below; no fixed sleep was newly added as the compaction readiness mechanism.

2.3 Documentation

EN/ZH state-storage docs describe region scope, tombstones, TTL ambiguity and the heap cost consistently. The deployment snippets omit the operational mixed-version warning and the size-only threshold consequence already flagged by @SEZ9. Please add the concise notices at the copyable enablement points and the incompatible-change guidance.

3. Architecture

3.1 Change location

The regional planner/storage/codec split is an appropriate engine IMap persistence boundary, rather than connector code. The smallest safe deliverable preserves current-region ownership and raw replay order while making seal failure, bounded compaction and bounded stop safe. Cross-region reclamation is a different, larger ownership protocol and should stay out of this PR.

3.2 Maintainability

Keep the behavior, lifecycle ownership, and failure contract together. The regional planner/storage/codec split is an appropriate engine IMap persistence boundary, rather than connector code. The smallest safe deliverable preserves current-region ownership and raw replay order while making seal failure, bounded compaction and bounded stop safe. Cross-region reclamation is a different, larger ownership protocol and should stay out of this PR.

3.3 Extensibility

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

3.4 Upgrade impact

Partially compatible when enabled: record framing is unchanged and older code can read stable files, but older replay is unsafe during concurrent compaction. All persistence-owning members must be upgraded before enablement, and compaction must be disabled/drained before rollback. Default-disabled legacy writers remain intact. This mixed-version restriction belongs in the incompatible-change/migration guidance and beside both deployment examples; it is not made harmless by the unchanged WAL record bytes.

4. Findings summary

# Finding Location Severity
1 Bound the live compaction working set before allocating it seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/common/WALCompactor.java:34 P0
2 Retry a snapshot-retirement race inside the asynchronous test predicate seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/test/java/org/apache/seatunnel/engine/imap/storage/file/IMapFileStorageTest.java:179 Medium

5. Merge recommendation

Merge after fixes

Blocking items: Issue 1; existing @SEZ9 Issue 1 (failed seal loses persistence) and Issues 4/5 (unbounded shutdown), plus the rollout warning. Current-head CI and write-capable maintainer review remain independent requirements.

Non-blocking suggestions: Issue 2: Retry a snapshot-retirement race inside the asynchronous test predicate

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: Label PRs when reviewed: SUCCESS; Signal pull request update: SUCCESS; Build: FAILURE; Build: failure. GitHub reports BLOCKED / REVIEW_REQUIRED.

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

Review time: 2026-11-20T06:42:01.883202-05:00

Local evidence: git fetch obtained head 34da0bb1b05a39fb2296364eff763228fc03050c; git merge-base returned f1ab36f0423c8aa17766959dfd6c6b3f5bc1426a; git diff --stat reports 29 files changed, 2106 insertions(+), 27 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.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Sorry for missing the core-helper documentation in the earlier round; that is a carryover omission. Thanks for the substantial safety fixes. I re-read all 34 changed files and the full write/compact/replay/shutdown chain. The earlier production blockers have concrete corrections, and the remaining requests below are focused on test outcomes and documenting lifecycle ownership.

What problem does this PR solve?

Repeated IMap updates grow append-only WAL files and restart replay time. This PR optionally rotates a writer's current region and replaces sealed history with a latest-mutation snapshot. Example: 100 updates of one job key can become one raw latest record, while tombstones and expired puts still suppress older values in other regions.

1. Code changes

1.1 Core logic

Complete runtime path:

Hazelcast EntryStore -> FileMapStore -> IMapFileStorage -> WALDisruptor -> WALWorkHandler
 -> WALWriter: disabled -> legacy HdfsWriter; enabled -> SegmentedHdfsWriter + per-region planner
 -> successful size seal -> shared CompactionCoordinator task
 -> WALCompactor streams completed frames -> bounded LatestMutationAccumulator (raw bytes, TTL preserved)
 -> HdfsCompactionStorage snapshot hsync/rename -> atomic replay-token update
 -> planner commit -> retryable input retirement
Replay -> DefaultReader captures tokens before data inventory -> reads all regions -> rechecks tokens
 -> WALReader discards the entire accumulator and retries on changed view/missing input
Shutdown -> cancellation flag + interrupt + bounded wait -> drain CLOSED -> check stream-close result
 -> failed stop retains directory; confirmed retry may delete it

Key findings and correctness:

  1. Previous Daniel Issue 1 is addressed by estimated retained-byte and distinct-key budgets, plus serialized-frame rejection before buffer allocation. This is a guard alongside the live IMap, not an exact JVM reservation. Tombstones/expired records remain counted.
  2. +1 to @SEZ9's failed-seal and shutdown concerns: failed append/seal now clears the stream, pauses compaction across the uncertain prefix and surfaces rejected persistence to Hazelcast; the next write opens a new segment. Compactor lifecycle locks no longer cover I/O. Timed-out close fails without deleting files and a later confirmed close can finish destruction.
  3. Unchanged TTL-ambiguous or over-budget plans are deferred without repeated scans; a changed plan can retry. Fatal Error is logged and disables that task, rather than pretending OOM recovery is safe. Size-only rotation and unadopted historical tails remain explicit limitations.
  4. Snapshot publication precedes token replacement and input deletion. Token changes and missing inputs discard the whole replay accumulator; retained raw latest records preserve delete/TTL ordering. Native object stores are rejected when compaction is enabled.
  5. Existing Issue 2's snapshot-open race is fixed with a narrow FileNotFoundException retry, but recursive traversal can still fail before that catch. The new scheduler fixture also needs outcome assertions below.

Before:

import org.apache.seatunnel.engine.imap.storage.api.ExpirableValue;
import org.apache.seatunnel.engine.imap.storage.api.IMapStorage;
import org.apache.seatunnel.engine.imap.storage.api.IMapStorageFactory;
import org.apache.seatunnel.engine.server.common.statestore.EngineStateStoreNames;

import com.hazelcast.core.HazelcastInstance;

After:

import org.apache.seatunnel.engine.imap.storage.api.ExpirableValue;
import org.apache.seatunnel.engine.imap.storage.api.IMapStorage;
import org.apache.seatunnel.engine.imap.storage.api.IMapStorageFactory;
import org.apache.seatunnel.engine.imap.storage.api.exception.IMapStorageException;
import org.apache.seatunnel.engine.server.common.statestore.EngineStateStoreNames;

import com.hazelcast.core.HazelcastInstance;

Collected exact-head Build: https://github.com/dybyte/seatunnel/actions/runs/44889520706 (in progress). CI and the existing maintainer change request remain separate gates; divergence alone is not a reason to add a sync comment.

1.2 Compatibility

Partially incompatible failure behavior, documented in both migration notes: rejected single/batch writes/deletes now fail Hazelcast persistence rather than being acknowledged, and failed/timed-out close prevents directory deletion. Compaction defaults false and retains WAL record format. Enable only after every persistent member has compaction-aware replay; disable/drain before rollback. No config is renamed; new budgets are opt-in compaction settings.

1.3 Performance and side effects

One shared daemon compactor per class loader serializes I/O, so blocked HDFS can delay other regions even though close has a bounded wait. Estimated retained budgets plus one input frame are additional heap alongside Hazelcast; they are not an exact heap cap. Deferral preserves correctness and WAL growth must still be monitored. Token inventories add replay I/O, and retries are limited to five. Failed deletion remains pending rather than being forgotten.

1.4 Errors, logging, and findings

Issue 2: Retain the traversal part of the snapshot-retirement test risk

  • Location: seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/persistence/FileMapStoreTest.java:342.
  • Description and risk: This is related to the previous Issue 2. Catching FileNotFoundException around reader.loadAllData fixes listing-to-open retirement, but Files.walk advances lazily while compaction deletes old snapshots; a NoSuchFileException can surface as UncheckedIOException before the inner catch. The engine IT contains the same recursive walk in containsCompactionSnapshotOutside. An Awaitility condition then aborts instead of retrying a benign retirement.
  • Best improvement: Handle only a verified missing-file traversal cause as retryable, or enumerate stable region directories and tolerate missing snapshot entries. Keep corruption and other I/O failures visible, and retain exact content assertions.
  • Responsibility and trade-off: The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
  • Severity: Medium; blocking: false.
  • Previously raised by another reviewer: No, unless explicitly attributed above.

Issue 3: Give the new scheduler tests a persistence outcome oracle

  • Location: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/test/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinatorTest.java:260.
  • Description and risk: The new Storage.publish ignores the mutation collection and returns a constant path; delete only increments a counter. Several scheduler tests accept published/deleted/committed counts without verifying which inputs remain or what snapshot was committed. They would pass if the coordinator published or retired the wrong data while making the same number of calls. These new tests hit the prohibited count-only interaction pattern. The separate real WAL tests are useful, but do not turn this fixture into an outcome assertion.
  • Best improvement: Make the fixture retain actual input identities and published mutation contents, then assert the correct snapshot/input ledger for recoverable failure, cancellation and deferral. Avoid merely adding more verify/count checks.
  • Responsibility and trade-off: The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
  • Severity: Medium; blocking: true.
  • Previously raised by another reviewer: No, unless explicitly attributed above.

Issue 4: Document the new lifecycle state and core write helpers

  • Location: seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinator.java:142.
  • Description and risk: The new lifecycle/running/failed/deferredPlan state and several new core helpers (including SegmentedHdfsWriter.seal/openNextSegment and the registration overload owning shutdown) lack their required contract comments. This is a prior-round documentation omission for the pre-existing helpers, not a new runtime defect. These fields now decide whether destruction is safe and whether a failed region may compact.
  • Best improvement: Add concise ownership/transition comments at the state and core helper declarations. Keep the correction local; no broader refactor is needed.
  • Responsibility and trade-off: The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.
  • Severity: Medium; blocking: true.
  • Previously raised by another reviewer: No, unless explicitly attributed above.

I read @SEZ9's full CHANGES_REQUESTED review. Their failed-stream persistence and unbounded-shutdown blockers have source and failure-injection corrections here. Their size-only trigger and rollout warnings are now documented at the enabling examples; ambiguous TTL deferral is backed off for unchanged plans, and fatal task loss is logged/disabled. I agree with those safety requirements but would not recommend catch-Throwable-and-blindly-continue after OOM. Their historical change request requires their own recheck. Daniel's earlier capacity blocker is closed; the outcome-test/documentation items below remain.

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: Stable. At risk. Read all changed storage, coordinator, FileMapStore and engine IT tests. Real file tests assert exact raw serialized records, cross-region tombstones/TTL, create/append/seal failure recovery, retained inputs/token on failed publication, partial-frame rejection, budgets and explicit paginated-listing races. Engine restart IT waits for a real snapshot and separately requires one in a new region after restart. FileMapStore restart checks exact entries and expiration drift. No new Thread.sleep was used as the compaction readiness signal; existing sleeps remain unchanged. Native HDFS test is conditional on imap.test.hdfs-uri, so it is not evidence CI ran HDFS. New scheduler cancellation tests have bounded latches/finally release, but their fake storage primarily exposes invocation counters; strengthen the outcome oracle. The recursive traversal race is non-blocking stability risk, not a demonstrated high-probability timing failure.

2.3 Documentation

Read all eight bilingual pages. Enabling YAML now carries the all-members upgrade/rollback warning, size-only rotation and low-volume guidance, budgets and backend restrictions. The state page correctly distinguishes Master-role partition owners from the elected active master. Historical regions, expired keys and shutdown/fatal-error limitations are explicit; no global disk bound or capacity benchmark is claimed.

3. Architecture

3.1 Change location

The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.

3.2 Maintainability

Keep the behavior, lifecycle ownership, and failure contract together. The affected component owns this behavior. Keep the smallest complete correction there; a wider engine or connector redesign is not justified by this diff.

3.3 Extensibility

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

3.4 Upgrade impact

Partially incompatible failure behavior, documented in both migration notes: rejected single/batch writes/deletes now fail Hazelcast persistence rather than being acknowledged, and failed/timed-out close prevents directory deletion. Compaction defaults false and retains WAL record format. Enable only after every persistent member has compaction-aware replay; disable/drain before rollback. No config is renamed; new budgets are opt-in compaction settings.

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
2 Retain the traversal part of the snapshot-retirement test risk seatunnel-engine/seatunnel-engine-server/src/test/java/org/apache/seatunnel/engine/server/persistence/FileMapStoreTest.java:342 Medium
3 Give the new scheduler tests a persistence outcome oracle seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/test/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinatorTest.java:260 Medium
4 Document the new lifecycle state and core write helpers seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file/src/main/java/org/apache/seatunnel/engine/imap/storage/file/compaction/CompactionCoordinator.java:142 Medium

5. Merge recommendation

Merge after fixes

Blocking items: Issues 3, 4. Current-head CI and write-capable maintainer review remain independent requirements.

Non-blocking suggestions: Issue 2: Retain the traversal part of the snapshot-retirement test risk

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 BLOCKED / REVIEW_REQUIRED.

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

Review time: 2026-11-21T07:58:15.156365-05:00

Local evidence: git fetch obtained head f5dae603d2d2cd21ca7e2ac3482a0f3e1bbb001d; git merge-base returned f1ab36f0423c8aa17766959dfd6c6b3f5bc1426a; git diff --stat reports 34 files changed, 3371 insertions(+), 37 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.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the continued work. The CI fact quoted in my full review has changed: Build 44889520706 has completed with failures, rather than remaining in progress. I inspected the failed job logs and separated the signals:

  • engine-v2-it, JDK 11: ClusterFaultToleranceIT.testStreamJobRestoreInAllNodeDown timed out waiting for RUNNING and observed FAILING (212 tests, one error, eight skipped). In that same job/test, PhysicalPlan.startJob -> updateStateTimestamps -> IMap.set -> FileMapStore.store rejected persistence for engine_stateTimestamps, and the job changed PENDING to FAILING. Compaction was active in this fixture. This reaches the persistence behavior changed here, so I cannot dismiss it as an unrelated flaky timeout. Please retain the reports/logs and isolate why that post-restart store was rejected, then rerun this exact recovery case with the full correctness assertions intact. The log establishes the rejection path, not its underlying storage cause.
  • Dependency licenses: the generated dependency inventory contains an extra netty-common-4.1.60.Final.jar. This PR has no POM/dependency edit. Compare the resolved artifact provenance with the canonical inventory before changing either; do not add a random dependency to chase this signal.
  • RocketMQ JDK 17 and MySQL CDC JDK 11 failed downloading the Maven wrapper with HTTP 404 before Maven tests ran. LocalFile JDK 11 hit HTTP 429 at the same wrapper bootstrap. Retrying those failed jobs after repository availability/rate limiting clears is more informative than a connector patch.

I checked the latest dev (7029c0969a9f6ea9add7a11f9262f42fe2ce9da9), its relevant history, and dependency inventory: the missing 4.1.60 jar is not in that inventory, and I did not find a verified upstream fix for these exact failures. I therefore cannot promise that synchronizing dev resolves them, particularly the persistence rejection. Branch divergence is recorded separately.

Conclusion: Merge after fixes. Blocking items: the already reported test/documentation Issues 3 and 4 remain, and the failed engine recovery validation needs resolution. Non-blocking: Issue 2 remains the snapshot-traversal test stability suggestion. This is an update to completed CI evidence, not an additional numbered source finding or a claim that the underlying runtime cause has been proven. Please keep the changes focused on the established failure path.

Checked unchanged head f5dae603d2d2cd21ca7e2ac3482a0f3e1bbb001d against dev: compare diverged, ahead 2 / behind 9. 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-21T13:59:26.155752+00:00.

@DanielLeens

Copy link
Copy Markdown
Contributor

The merge-gate fact cited previously has changed: GitHub now reports actual content conflicts with dev on this unchanged head. Please resolve those conflicts against current dev while retaining the reviewed feature, fixes and regression coverage, then obtain checks for the resulting head. This request is based on a content conflict, not merely on being behind; it does not claim that synchronization cures the existing CI failure.

The existing regression-test/documentation findings and the recorded engine persistence-validation failure remain open.

Unchanged head f5dae603d2d2cd21ca7e2ac3482a0f3e1bbb001d; base dev; compare diverged, ahead 2 / behind 77. This is a CI/merge-state correction, not another full source review. No local build/test/runtime execution was performed. Daniel has READ permission; effective maintainer approval and historical-review dismissal remain separate actions.

Current snapshot (2026-11-27T02:58:48.854495+00:00): Signal pull request update: SUCCESS; Build: FAILURE; merge state DIRTY; review decision REVIEW_REQUIRED.

# Conflicts:
#	docs/en/introduction/concepts/incompatible-changes.md
#	docs/zh/introduction/concepts/incompatible-changes.md
@SEZ9

SEZ9 commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

Thanks for the work on this. The head is still f5dae603d2d2cd21ca7e2ac3482a0f3e1bbb001d, so the previously raised points are all still open, and the PR now has content conflicts with dev (merge state DIRTY, Build: FAILURE).

Remaining asks

  1. Resolve the conflicts against current dev, keeping the feature, the fixes and the regression coverage, and get a fresh check run on the resulting head. Rebasing alone is not expected to fix the Build failure, so please look into that separately.

  2. Address the open code findings:

    • PR13364-F1: a single failed segment close in SegmentedHdfsWriter.seal() leaves the writer permanently broken. Every later IMap mutation fails to persist, with only an ERROR log per write.
    • PR13364-F2: rotation is size-only and the final segment is sealed only after compaction has stopped. With the default 64 MiB segment, a region that writes less than one full segment per process lifetime is never compacted.
    • PR13364-F3: one pair of same-millisecond, same-value mutations with different expiration times makes every compaction attempt for that region fail, with a full re-read and a WARN stack trace on each interval.
    • PR13364-F4: WALDisruptor.close() waits without any bound for an in-flight compaction, so member shutdown can be held up by a full snapshot rewrite or a hung HDFS call.
    • PR13364-F7: Task.close() shares a monitor with the whole compaction run, so IMapFileStorage.destroy() and node shutdown can hang behind a long or stuck compaction.
    • PR13364-F9: an OutOfMemoryError (or any other Error) in the compaction task stops compaction for that IMap without a log line, while the writer keeps rotating segments.
  3. Address the open docs findings:

    • PR13364-F6: the wal.segment-size docs should say that this option decides whether compaction runs at all, and that with the 64 MiB default a low-volume IMap region is never compacted.
    • PR13364-F8: the "upgrade all members before enabling" and rollback constraints appear only in state-storage-and-recovery.md. Please add the warning to the two deployment pages where users copy the YAML.

When you push the update, a short note per finding saying how it was handled (fixed, with the covering test, or why you chose not to change it) would make the follow-up pass much quicker.

@DanielLeens DanielLeens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for contributing to Apache SeaTunnel. I re-reviewed the HDFS and local IMap WAL compaction patch at fa2700a912fa15fe5b309f48956700ade40ccd74, including the single-writer boundary, region rollover, replay, compaction publication, input retirement, shutdown, and the tests and rollout notes.

What the PR changes

New writes can rotate into sealed WAL segments. The coordinator merges sealed inputs, preserves the latest raw value or tombstone, publishes a snapshot and advances the replay token before deleting replaced inputs. Until publication is confirmed, the old WAL remains authoritative. The new collision fixture exercises the distinction between the mutation used for live replay and the complete history needed when expiration ties are ambiguous.

Findings

  1. Medium, blocking — The coordinator failure tests still cannot identify the data that survived. The storage fake in CompactionCoordinatorTest.java:260–279 reads the same mutation for every input, ignores the collection passed to publish, and counts calls to delete without recording paths. The coordinator could publish a wrong set or delete the wrong input and still satisfy those assertions. The new timestamp-collision fixture adds useful coverage at the mutation/replay layer. The preceding scheduler finding remains open at the coordinator layer. Give this fixture distinct input identities and record the snapshot contents and live input paths. After deferral, interrupted publish, and a successful retry, assert exactly which contents and paths are durable.
  2. Medium, blocking — Specify the scheduler lifecycle ownership and the writer transitions. The compaction scheduler owns running, failed and deferredPlan around CompactionCoordinator.Task.run. Please document which state prevents subsequent work, which state is observed during bounded shutdown, and when a changed plan retries. The same prior finding remains for the storage registration overload and the seal/open transition in SegmentedHdfsWriter, where the order determines whether an input can be reclaimed. Keep these descriptions next to the declarations and helpers.
  3. Medium, optional — Keep snapshot-retirement test traversal inside the retry boundary. The current test retries disappearance between listing and replay. Its recursive Files.walk can still report a concurrently removed snapshot while the stream itself is being consumed. If keeping the recursive assertion, retry that specific transient disappearance around iteration as well, while allowing unrelated I/O failures to surface.

The earlier retained-memory and capacity findings remain addressed by byte/key budgets and the serialized-frame limit. The bilingual rollout notes explain default-off behavior, rotation thresholds, the enable-after-upgrade rule and rollback precautions. The HDFS-specific test requires its explicit test URI. Please keep the real-backend verification separate from local-fixture coverage when deciding rollout.

Verification and merge recommendation

The exact-head JDK 11 Linux unit log shows the timestamp-collision class (2 cases), coordinator class (5) and FileMapStore class (8) passing. The JDK 11 engine lane passed; the JDK 17 engine lane and aggregate Apache Build are red. I checked the complete diff and its call sites against the current merge base with a clean diff check. The two prior coordinator findings and green aggregate CI are still required. JDK 11 unit log · JDK 17 engine · Apache Build

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.

3 participants