Skip to content

[Fix][Zeta] Fix IMap file data comparison contract - #11465

Merged
dybyte merged 3 commits into
apache:devfrom
nielifeng:codex/fix-imap-file-data-compare
Jul 22, 2026
Merged

dybyte merged 3 commits into
apache:devfrom
nielifeng:codex/fix-imap-file-data-compare

Conversation

@nielifeng

@nielifeng nielifeng commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Purpose

Fixes #11462.

IMapFileData.compareTo never returned 0 when timestamps were equal, which violated the Comparable contract and could make Collections.sort fail in WAL recovery.

Changes

  • Compare records by key identity first, then timestamp descending within the same key.
  • Use deterministic delete and value tie-breakers for equal-timestamp records so the comparator is antisymmetric and can return 0 for identical records.
  • Apply the same contract-compliant comparator to IMapData and IMapFileData.
  • Remove the ownership-epoch and writer-sequence design because Hadoop FileSystem does not provide a portable atomic CAS primitive across HDFS, S3, and OSS; object-store rename cannot safely allocate a global epoch.

Ordering scope

This fix guarantees a deterministic total order and prevents the TimSort contract failure. For a same-key, same-millisecond collision it deterministically places a tombstone before a value. It does not claim general last-write-wins ordering for independently active writers, because that would require a portable durable global mutation token that the supported Hadoop filesystems do not expose.

Tests

  • Newer timestamps sort first within a key.
  • Same-timestamp deletes sort before puts.
  • Records are grouped by key before timestamp ordering.
  • Equality and antisymmetry are preserved.
  • Sorting thousands of timestamp collisions does not throw.

Verified with:

./mvnw -o -pl seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file test
./mvnw -o -pl seatunnel-engine/seatunnel-engine-storage/imap-storage-plugins/imap-storage-file -DskipTests verify

Result: 13 tests, 0 failures, 0 errors, 1 credential-dependent OSS test skipped; module verify passed.

@github-actions github-actions Bot added the Zeta label Jul 16, 2026

@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 working on this. I rechecked the latest head ca20619343ba against the actual WAL replay path, and I do see one blocker before merge.

  1. The new comparator fixes the compareTo contract, but it also changes same-timestamp replay semantics in a way that can recover the wrong final state for a key.
    • WALReader sorts all records first (WALReader.java:64 and :90) and then keeps the first surviving record for each key (WALReader.java:67-79 and :94-110).
    • IMapFileStorage only stamps records with System.currentTimeMillis() (IMapFileStorage.java:292 and :301), so two updates to the same key in the same millisecond are a real case.
    • With the new tie-break in IMapDataComparator.java:40-65, equal-timestamp records are no longer ordered by append order. They are ordered by deleted, key class / bytes, and value class / bytes instead.

That means a same-millisecond sequence like put(A) -> put(B) or delete -> put for the same key can now replay the wrong winner after sorting, because the winner is whichever record sorts first by the comparator, not whichever record was appended last in the WAL.

So from my side the merge blocker is: please preserve the real append order for equal-timestamp records (for example with an explicit WAL sequence / offset, or another stable last-write tie-break), and then add a regression test for same-key same-millisecond replay. The current tests only prove the comparator contract; they do not cover the restore semantics above.

Current gate facts on Thursday, July 16, 2026:

  • the branch is behind dev (ahead_by=1, behind_by=29, compare status diverged)
  • Build is still in progress

But the replay-semantics issue above is the source-level blocker from my side.

@nielifeng

Copy link
Copy Markdown
Contributor Author

Thanks @DanielLeens, you're right — the content-based tie-break broke same-millisecond replay semantics. Fixed in 6811bc3d8.

What changed

  • Added a monotonic sequenceId to the WAL record, stamped in WALWriter.write (the single disruptor consumer thread), so it reflects true append order into the WAL file.
  • The comparator now uses sequenceId as the primary equal-timestamp tie-break: the later append gets the larger id and sorts first, so WALReader's keep-first dedup keeps the actual last write. This is correct for same-key same-ms put→delete, put→put, and delete→put.
  • Two records sharing a millisecond timestamp were necessarily written by the same WALWriter instance (file rotation and restart both take far longer than 1ms), so the sequence is consistent for exactly the records that need it.
  • Backward compatibility: sequenceId is declared last, and protostuff-runtime 1.8.0 assigns field tags by declaration order, so existing WAL files stay deserializable and read back as 0. Zero-sequence (legacy) records fall through to the original stable content-based tie-breaks, so the Comparable contract still holds for old data.

Tests

  • Added WALReaderAndWriterTest.testReplayKeepsLastWriteForSameKeySameTimestamp — the end-to-end same-key same-ms replay test you asked for. It writes through the real WALWriter/WALReader path and asserts the last write wins for all three orderings. Confirmed it fails without the sequence stamp (recreated-key resurrection is lost) and passes with it.
  • Added comparator-level tests for the sequence tie-break, antisymmetry with sequence ids, and the legacy zero-sequence fallback.

All 11 tests in the module pass; spotless is clean.

@dybyte dybyte left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the update. I think the new sequence ID fixes ordering within a single WALWriter, but I am not sure it is comparable across regions.

Each WALWriter owns an independent counter starting from zero, while WALReader collects records recursively from multiple region directories. Therefore, two records for the same key may have the same timestamp but sequence IDs produced by different writers. In that case, a larger sequence ID does not necessarily represent a later write.

The assumption that equal-timestamp records must come from the same writer appears to cover file rotation and restart, but not concurrently active storage instances or ownership migration between regions.

Also, since replay only needs to select the latest record for each key, would it be clearer to order records by key identity first, and then by timestamp within the same key?

For example:

keyClassName -> key bytes -> timestamp descending -> cross-writer comparable version descending

The version could be something such as an ownership epoch combined with a writer-local sequence. This would avoid comparing timestamps and local sequence IDs across unrelated keys, while still ensuring that the newest record appears first within each key.

valueClassName and value bytes do not appear to represent replay order. They seem useful only as deterministic total-order fallbacks, if such fallbacks are required.

@nielifeng

Copy link
Copy Markdown
Contributor Author

@dybyte you're right, and I traced it through the code to confirm the reachability. Sharing what I found.

The cross-region path is real. IMapFileStorage.initialize sets region = String.valueOf(System.nanoTime()) per instance and writes under businessRootPath + region + "/", but businessRootPath is only namespace/clusterName/businessName — it does not include the region. WALReader.loadAllData/loadAllKeys read from businessRootPath and merge records across all region directories before sorting. Since FileMapStoreFactory uses the stable mapName as businessName while each FileMapStore.init creates a fresh IMapFileStorage (hence a fresh region), the same logical key can end up in different region dirs across restart or ownership migration on shared storage (OSS/HDFS). So a per-writer AtomicLong starting at 0 is not comparable across regions — exactly your point.

Why it corrupts the winner, concretely. In the comparator the equal-timestamp chain is sequenceId desc → deleted → keyClass → keyBytes → valueClass → valueBytes. Two same-key records from different regions in the same millisecond will very likely carry equal small sequence ids, so sequenceCompare == 0 and the tie-break sinks to deleted and then value bytes — i.e. content order, not append order. At that point last-write-wins is lost: a same-ms delete+put can resolve to the wrong survivor regardless of real order. This confirms your observation that valueClassName/value bytes don't represent replay order.

Scope note (being honest about likelihood). Triggering an actual wrong state still needs the narrow window of a same-key write in the same millisecond across two regions. The correctness gap is real; the trigger is a low-probability boundary (restart/migration timing), not a common path.

On the fix. Your key-identity-first ordering with a cross-writer-comparable version (ownership epoch + writer-local sequence) is the correct general solution, but it's a larger change (persisting an epoch, touching IMapFileData layout + serialization compatibility). A smaller alternative is to keep the per-writer sequence for the single-writer case and explicitly document that imap-file storage does not guarantee last-write for same-key same-millisecond writes across regions. Which direction do you and the maintainers prefer — the full epoch-based ordering, or the minimal fix + documented limitation? Happy to implement whichever you'd like to land.

@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 re-reviewed the latest head 6811bc3d828c from scratch.

Findings

Issue 1: Config/option changes without doc updates

  • Why it matters: Consider updating docs/example configs for the new/changed options.
  • Severity: Low

Review conclusion

Conclusion: can merge; the notes below are non-blocking

2. Suggested (non-blocking) follow-ups

  • Issue 1: Config/option changes without doc updates

Nice work — thanks again for the contribution. Happy to discuss any of the above.

@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 update. I re-reviewed the complete current diff and the IMap WAL write/recovery path. One persisted-ordering issue still blocks merge.

Blocking finding

Issue 1: WAL sequence numbers are not globally ordered across storage regions

  • Location: IMapFileStorage.java:147-166,235-238, WALWriter.java:46,59-61, WALReader.java:84-105, and IMapDataComparator.java:42-60
  • Each WALWriter starts its sequence at zero, while each storage initialization can write a new region and recovery merges records from all regions. For equal timestamps, independent regions can therefore contain equal sequence values; the comparator then falls through to content/delete ordering, while the reader globally sorts and keeps the first record per key.
  • Risk: restart or ownership migration can replay an older value, or the wrong side of a value/delete pair. This confirms @dybyte's existing cross-region finding, which remains unresolved.
  • Suggested fix: persist an ordering key that is monotonic across regions, or make region generation part of the ordering and prove last-write-wins recovery with equal-timestamp value/update/delete tests across multiple regions.

Severity: High. Merge gate: blocking. The current Build failure is a separate gate and cannot clear the recovery problem. Happy to re-review an updated head.

@dybyte

dybyte commented Jul 19, 2026

Copy link
Copy Markdown
Member

@dybyte you're right, and I traced it through the code to confirm the reachability. Sharing what I found.

The cross-region path is real. IMapFileStorage.initialize sets region = String.valueOf(System.nanoTime()) per instance and writes under businessRootPath + region + "/", but businessRootPath is only namespace/clusterName/businessName — it does not include the region. WALReader.loadAllData/loadAllKeys read from businessRootPath and merge records across all region directories before sorting. Since FileMapStoreFactory uses the stable mapName as businessName while each FileMapStore.init creates a fresh IMapFileStorage (hence a fresh region), the same logical key can end up in different region dirs across restart or ownership migration on shared storage (OSS/HDFS). So a per-writer AtomicLong starting at 0 is not comparable across regions — exactly your point.

Why it corrupts the winner, concretely. In the comparator the equal-timestamp chain is sequenceId desc → deleted → keyClass → keyBytes → valueClass → valueBytes. Two same-key records from different regions in the same millisecond will very likely carry equal small sequence ids, so sequenceCompare == 0 and the tie-break sinks to deleted and then value bytes — i.e. content order, not append order. At that point last-write-wins is lost: a same-ms delete+put can resolve to the wrong survivor regardless of real order. This confirms your observation that valueClassName/value bytes don't represent replay order.

Scope note (being honest about likelihood). Triggering an actual wrong state still needs the narrow window of a same-key write in the same millisecond across two regions. The correctness gap is real; the trigger is a low-probability boundary (restart/migration timing), not a common path.

On the fix. Your key-identity-first ordering with a cross-writer-comparable version (ownership epoch + writer-local sequence) is the correct general solution, but it's a larger change (persisting an epoch, touching IMapFileData layout + serialization compatibility). A smaller alternative is to keep the per-writer sequence for the single-writer case and explicitly document that imap-file storage does not guarantee last-write for same-key same-millisecond writes across regions. Which direction do you and the maintainers prefer — the full epoch-based ordering, or the minimal fix + documented limitation? Happy to implement whichever you'd like to land.

@nielifeng I think either approach is reasonable.

@nielifeng

nielifeng commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor Author

@dybyte @DanielLeens The cross-region WAL ordering blocker is addressed in the latest head 04a142f5f.

What changed:

  • Allocate a business-scoped ownership epoch in shared storage for each WAL region.
  • Use an epoch-writerUUID region path so independently initialized writers never share a WAL path.
  • Persist writerEpoch + writerId + writer-local sequenceId on every WAL record.
  • Order records by key identity -> timestamp desc -> writer epoch desc -> writer id desc -> sequence desc, followed by deterministic content fallbacks.
  • Append the new serialized fields after the existing fields, so legacy WAL records remain readable with 0/null defaults.

Regression coverage now includes:

  • same-key/same-timestamp put, update, delete, and recreate within one writer;
  • replay across two regions where the older writer has the larger local sequence but the newer ownership epoch must win;
  • sequential and concurrent epoch allocation, including existing numeric region directories;
  • comparator equality, antisymmetry, key grouping, writer identity, epoch, and sequence behavior.

Verification:

  • IMap file module: 23 tests, 0 failures, 0 errors, 1 credential-dependent OSS test skipped.
  • Spotless and repository CI-tool checks pass.
  • A broader reactor/unit-test scan found no PR-related compilation or behavioral failures; Docker/native-architecture-dependent tests were kept separate from code failures.

Could you please re-review the latest head?

@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 working on this! I re-reviewed the complete current-head diff and the relevant runtime path. The direction makes sense, but I found the following blocker that needs to be resolved before merge:

  1. Blocker 1 — +1 to dybyte's ordering concern for the supported object-store path. Epoch reservation relies on temp-file creation plus rename, but S3/OSS rename is copy/delete rather than portable CAS. Concurrent writers can reserve the same epoch, and writer-id ordering is not write ordering. Please use an atomic conditional-create/CAS mechanism or a durable globally comparable mutation token.

The current Build is failing; CI remains a separate gate and does not change the source verdict above. The current failed lanes include Run / unit-test (11, ubuntu-latest), Run / engine-v2-it (11, ubuntu-latest), Run / kafka-connector-it (11, ubuntu-latest). Please retrigger or inspect those exact job logs after the source update.

Please address these together on the next head; I’ll re-review the full updated diff once it is ready.

@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 working on this! I re-reviewed the complete current-head diff and the relevant runtime path. The direction makes sense, but I found the following blocker that needs to be resolved before merge:

  1. Blocker 1 — +1 to dybyte's ordering concern for the supported object-store path. Epoch reservation relies on temp-file creation plus rename, but S3/OSS rename is copy/delete rather than portable CAS. Concurrent writers can reserve the same epoch, and writer-id ordering is not write ordering. Please use an atomic conditional-create/CAS mechanism or a durable globally comparable mutation token.

The current Build is failing; CI remains a separate gate and does not change the source verdict above. The current failed lanes include Run / unit-test (11, ubuntu-latest), Run / engine-v2-it (11, ubuntu-latest), Run / kafka-connector-it (11, ubuntu-latest). Please retrigger or inspect those exact job logs after the source update.

Please address these together on the next head; I’ll re-review the full updated diff once it is ready.

@nielifeng
nielifeng force-pushed the codex/fix-imap-file-data-compare branch from 04a142f to 07496ae Compare July 21, 2026 03:52
@nielifeng

Copy link
Copy Markdown
Contributor Author

Updated head 07496ae8a and addressed the object-store ordering blocker by removing the epoch reservation and writer metadata entirely. The previous temp-file plus rename flow was not a portable CAS on S3/OSS, so it could not safely support the claimed global ordering.

This PR is now scoped to the minimal fix discussed in review: key identity first, timestamp descending within a key, then deterministic tombstone/value fallbacks to satisfy the Comparable contract. The code explicitly documents that independently active writers with the same key and millisecond do not have general last-write-wins semantics.

Verification on current dev: 13 tests, 0 failures/errors, 1 credential-dependent OSS test skipped; module verify passed. Please re-review the simplified head.

@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 re-reviewed the latest head 07496ae8a186 from scratch.

What this PR fixes

  • User pain: IMapFileData.compareTo (and IMapData.compareTo) never returned 0 and wasn't antisymmetric (o.timestamp - this.timestamp > 0 ? 1 : -1), so TimSort in Collections.sort could throw IllegalArgumentException: Comparison method violates its general contract! during WAL recovery, failing IMap restore on Zeta restart.
  • Fix approach: Introduce a shared IMapDataComparator that produces a deterministic total order (keyClassName → key bytes → timestamp desc → deleted flag → valueClassName → value bytes) and wire it into both IMapData.compareTo and IMapFileData.compareTo, with new unit tests for antisymmetry, zero-on-equal, and mass-collision sorting.
  • One-line summary: The comparator fix itself is sound and well-tested, but the PR is internally inconsistent — the description says the writer-epoch/sequence design was removed, yet WALWriter still stamps writerEpoch/writerId/sequenceId onto records (calling setters not shown as added to IMapFileData in this diff), and the new testReplayKeepsLastWriteForSameKeySameTimestamp asserts last-append-wins semantics (e.g. put-after-delete resurrects recreated-key) that the comparator alone cannot deliver, since it deterministically orders tombstones before puts at equal timestamps; this needs to be reconciled before merge, plus the existing doc-gap finding stands.

Runtime chain I rechecked

WAL recovery path (where the broken comparator was hit):
  FileStorage.loadAll()
    -> WALReader.loadAllData(parentPath, searchKeys)  WALReader.java
      -> readAllData(parentPath) collects List<IMapFileData> across WAL region files
      -> Collections.sort(fileDataList) / list.sort(...)  (previously threw TimSort contract violation)
        -> IMapFileData.compareTo(o)  IMapFileData.java:49
          -> IMapDataComparator.compare(...)  IMapDataComparator.java:27
            -> compareNullableString(keyClassName)  IMapDataComparator.java:39
            -> compareBytes(key)  IMapDataComparator.java:44
            -> Long.compare(rightTimestamp, leftTimestamp)  IMapDataComparator.java:49  (descending, newest first)
            -> Boolean.compare(rightDeleted, leftDeleted)  IMapDataComparator.java:58  (tombstone before put)
            -> compareNullableString(valueClassName) / compareBytes(value)  IMapDataComparator.java:63-68
      -> per-key, first record after sort wins in loadAllData's dedup, so same-key same-timestamp collisions now resolve to the tombstone — which contradicts testReplayKeepsLastWriteForSameKeySameTimestamp's 'recreated-key' expectation unless sequenceId is consulted somewhere not in this diff

WAL write path (new epoch/sequence stamping):
  IMapDataOperation via WALDisruptor consumer (single thread)
    -> WALWriter.write(IMapFileData)  WALWriter.java:70
      -> data.setWriterEpoch(writerEpoch) / data.setWriterId(writerId) / data.setSequenceId(sequenceGenerator.incrementAndGet())  WALWriter.java:71-73  (setters/fields not added to IMapFileData in this diff — likely compile break or dead design the description claims was removed)
      -> IFileWriter.write(data)  (OrcWriter/ProtobufWALWriter via DiscoveryWalFileFactory)

Findings

Issue 1: Config/option changes without doc updates

  • Why it matters: Consider updating docs/example configs for the new/changed options.
  • Severity: Low

Review conclusion

Conclusion: can merge; the notes below are non-blocking

2. Suggested (non-blocking) follow-ups

  • Issue 1: Config/option changes without doc updates

Nice work — thanks again for the contribution. Happy to discuss any of the above.

@dybyte dybyte left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Could we add a small WALReader regression test confirming that a tombstone wins for the same key and timestamp? The comparator-level test already covers the ordering, but an end-to-end test would document and protect the intended replay behavior.

@nielifeng

Copy link
Copy Markdown
Contributor Author

@dybyte Added the requested WALReader regression coverage in b44e57b9a and synced the branch with current dev (latest head 63500bb03).

The new testReplayKeepsTombstoneForSameKeyAndTimestamp writes a value followed by a tombstone for the same key and exact timestamp through the real WALWriter, then replays through WALReader. It verifies both recovery APIs:

  • loadAllData does not restore the deleted key;
  • loadAllKeys does not expose the deleted key.

The test uses an isolated WAL directory and cleans it up after the suite.

Verification:

  • focused WALReaderAndWriterTest: 2 tests, 0 failures/errors;
  • full imap-storage-file module: 14 tests, 0 failures/errors, 1 credential-dependent OSS test skipped;
  • Spotless passed as part of Maven verify.

Could you please re-review the latest head?

@dybyte dybyte left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

+1 if CI passes

@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 contribution! I rechecked the complete current-head diff, deletion ledger, existing reviewer findings, and the relevant runtime path. I do not see a source-level blocker in this version.

The previous source concern is resolved on 63500bb037ab: the local writer-epoch approach was removed and the current diff uses a deterministic shared comparator.

The source verdict is clear, but the required Build is still pending. Please let the current checks finish; a write-capable maintainer may still need to complete the approval gate afterward.

@nielifeng

Copy link
Copy Markdown
Contributor Author

CI follow-up: the approved source head remains unchanged at 63500bb. The failed Build spans unrelated connector integration lanes plus the Windows unit lane, while the focused WALReader and full imap-storage-file verification already passed locally. I re-ran failed jobs only; workflow 29817282445 is now queued as attempt 2. No business-code change was made.

@nielifeng

Copy link
Copy Markdown
Contributor Author

CI follow-up for head 63500bb037ab:

Attempt 2 completed with only two unrelated connector E2E failures:

  • all-connectors-it-4 (JDK 8): ElasticsearchTimerFlushIT.testElasticsearchTimerFlush timed out waiting for its condition; the lane otherwise reported 70/71 tests without failures.
  • paimon-connector-it (JDK 11): PaimonWithS3IT failed during Testcontainers startup because the SeaTunnel container did not emit received new worker register within the startup timeout. The earlier Paimon schema mismatch messages were expected negative-test output, not the final failure.

All source/unit/style jobs and the other connector lanes completed successfully. I re-ran failed jobs only; workflow 29817282445 is now queued as attempt 3. No source change was made.

@dybyte
dybyte merged commit d4446df into apache:dev Jul 22, 2026
7 checks passed
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.

[Bug] [Zeta] IMapFileData.compareTo violates Comparable contract (TimSort crash + lost deletes)

4 participants