iceberg icon indicating copy to clipboard operation
iceberg copied to clipboard

Per-commitId group separation for stale DataWritten recovery

Open t3hw opened this issue 8 months ago • 10 comments

Per-commitId group separation for stale DataWritten recovery

Problem

When Coordinator.doCommit() fails or times out, stale DataWritten events from the previous commit cycle persist in the buffer. On the next successful commit, tableCommitMap() merges stale and current events into a single RowDelta. All files receive the same Iceberg sequence number, which breaks equality delete semantics (data_sequence_number < delete_sequence_number required, strictly less-than). This causes duplicate rows in append workloads. (The same sequence-number collision would also affect CDC/equality-delete workloads, though those are out of scope for this PR.)

Clearing the buffer on new commits is not safe either: workers that finished after a partial-commit timeout have already committed source offsets via sendOffsetsToTransaction(), so their DataWritten events cannot be re-produced. Discarding them causes data loss.

Solution

Stale events are retained in the buffer and committed separately — each commitId group in its own RowDelta with a distinct Iceberg sequence number.

CommitState

  • tableCommitGroups() groups buffered envelopes by table, then by commitId within each table. Uses LinkedHashMap to preserve control-topic consumption order — stale groups sort before current groups and receive lower sequence numbers.
  • removeEnvelopes() selectively removes only successfully committed envelopes from the buffer. Failed groups are retained for retry in subsequent cycles.
  • Adaptive retry tracking via recordGroupFailure() / recordGroupSuccess() / isGroupBlocking() — per-commitId retry counter using ConcurrentHashMap.
  • CommitStateMXBean JMX interface exposing StaleGroupCount and BufferSize for operational monitoring.

Coordinator

  • doCommit() iterates commitId groups per table sequentially (oldest first). Tables are committed in parallel via Tasks.foreach().
  • Per-group offset isolation: stale groups write only their own envelope offsets to the Iceberg snapshot, not the global consumer position. This prevents an offset poisoning scenario where subsequent groups' envelopes would be incorrectly filtered out by Iceberg's offset-based deduplication.
  • Sequence number ordering: if a stale group fails, remaining groups for that table are skipped to preserve strictly increasing sequence numbers.
  • Retry exhaustion: when a stale group exceeds stale-max-blocking-retries, a ConnectException is thrown and propagated to move the connector to FAILED state, forcing operator intervention.
  • Partial offset advancement: when the buffer is not fully drained, consumer offsets advance to the minimum uncommitted envelope offset per partition, bounding re-consumption on restart.

Channel

  • commitConsumerOffsetsTo(Map) commits specific partition offsets to Kafka, used for partial offset advancement when groups remain in the buffer.

Configuration

Property Default Description
iceberg.control.commit.stale-max-blocking-retries 3 Number of times a stale group blocks subsequent groups before failing the connector. 0 = fail immediately.

Test coverage

CommitState unit tests (TestCommitState.java):

  • testTableCommitGroupsSingleCommitId — single group, correct envelope count
  • testTableCommitGroupsMultipleCommitIds — stale + current groups, ordered correctly
  • testTableCommitGroupsPreservesInsertionOrder — interleaved commitIds, first-seen order
  • testStartNewCommitDoesNotClearBuffer — stale events survive across cycles
  • testRemoveEnvelopesSelectiveRemoval — only specified envelopes removed
  • testIsBufferEmpty — empty after clear, not empty after add

Coordinator integration tests (TestCoordinator.java):

  • testMultiGroupCommitProducesSequentialSnapshots — stale + current groups produce 2 snapshots with strictly increasing sequence numbers and distinct commitIds
  • testStaleGroupBlocksForNRetriesThenStopsBlocking — parameterized (0, 3): isGroupBlocking blocks for N retries, stops on N+1
  • testStaleGroupBlocksThenThrowsConnectException — parameterized (0, 3): ConnectException propagates after N+1 failures
  • testStaleGroupFailureStopsConnector — exception contains "Connector stopping", no CommitComplete sent
  • testZeroRetriesMultiTableCommitsGoodTableBeforeFailing — 2 tables, retries=0: good table snapshot saved before connector dies
  • testMultiTablePartialCommitWithStaleExhaustion — 2 tables, retries=3: good table accumulates 4 snapshots, bad table gets 0, then ConnectException

Recovery scenario test (TestRecoveryScenario.java):

  • testSequentialCommitsProduceSeparateSnapshots — sequential commits produce 2 snapshots with increasing sequence numbers

Acknowledgements

The core per-commitId group separation approach was originally contributed by @koodin9, who identified that clearing the buffer causes data loss in partial-commit scenarios and implemented the fix of committing each commitId group in its own RowDelta. This PR rebases that original implementation onto @koodin9's branch and extends it with production hardening: selective buffer draining, per-group offset isolation, configurable retry escalation, partial offset advancement, ConnectException propagation, and JMX monitoring. The final design was shaped through collaborative review with @koodin9.

t3hw avatar Mar 16 '26 11:03 t3hw

@bryanck hey, i was researching a duplication issue and it led me to this proposed solution. can you assist in reviewing this change?

t3hw avatar Mar 16 '26 12:03 t3hw

Hi, thanks for looking into this issue. I've been working on the same problem in our fork (based on https://github.com/databricks/iceberg-kafka-connect) and wanted to share some observations about the partial commit (timeout) scenario that this fix may not fully address.

When commitTimeoutMs is exceeded, the Coordinator performs a partial commit — it commits only the DataWritten events received so far and moves on. Workers that were still processing at the time will send their DataWritten(A) + DataComplete(A) later to the control topic.

Here's the timeline:

  • Cycle A:

    • startNewCommit(A)→ commitBuffer.clear() + new UUID
    • consumeAvailable() → Worker 0 still processing, nothing consumed
    • isCommitTimedOut() → true
    • doCommit(true) → partial commit succeeds (without Worker 0's data)
    • clearResponses()
    • endCurrentCommit()
  • Worker 0 finishes and sends DataWritten(A) + DataComplete(A) to control topic

  • process() call N:

    • consumeAvailable() → DataWritten(A) consumed → added to commitBuffer
  • process() call N+1:

    • startNewCommit(B)→ commitBuffer.clear() ← DataWritten(A) DISCARDED
    • consumeAvailable() → ...

With this PR's fix, commitBuffer.clear() in startNewCommit() discards Worker 0's DataWritten(A). Since the partial commit already advanced the control topic consumer offsets (via commitConsumerOffsets()), this event won't be re-consumed. The data files exist on storage but are never committed to the Iceberg table — resulting in data loss.

The root cause is broader

The underlying issue isn't just stale events lingering in the buffer — it's that tableCommitMap() doesn't distinguish events by commitId. Even if stale events survive in the buffer (which they should, since they represent legitimate data), they get merged into the same RowDelta as current-cycle events, receiving the same sequence number. This breaks equality delete semantics (data_sequence_number < delete_sequence_number is required for equality deletes to apply).

Alternative approach: commit-id-based separation

Instead of discarding stale events, a safer fix would be to separate them by commitId and commit each group in its own RowDelta. This ensures:

  • Stale data files get a lower sequence number (committed first)
  • Current data files get a higher sequence number (committed last)
  • Equality deletes from the current cycle correctly apply to stale data (stale_seq < current_seq)
  • No data loss — all legitimate DataWritten events are committed

This approach also covers the failed-commit and recovery scenarios your PR addresses, since stale events from any prior cycle are naturally separated by their commitId.

We've already implemented this approach in our fork and will be deploying it to production soon. We'll also be opening a PR here shortly.

koodin9 avatar Mar 20 '26 08:03 koodin9

@jerryzhujing @t3hw I just opened a PR, could you please take a look?

koodin9 avatar Mar 21 '26 00:03 koodin9

@koodin9 @t3hw I merged below changes and it works for me and no duplicates in my testing for one week. https://github.com/apache/iceberg/pull/15651/changes/9afa6831e051234b1f30bff56f649694327e0375

I didn't test the latest changes of this pr. So what is the difference between latest changes in this pr and above link changes? Is there any issues if I on use changes in https://github.com/apache/iceberg/pull/15651/changes/9afa6831e051234b1f30bff56f649694327e0375 in production? Any bugs in https://github.com/apache/iceberg/pull/15651/changes/9afa6831e051234b1f30bff56f649694327e0375

jerryzhujing avatar Mar 26 '26 15:03 jerryzhujing

Not necessarily a bug, but the final changes should handle temporary failures, such as momentary catalog unavailability or network failures, gracefully through a retry loop that is missing from the earlier commit.

t3hw avatar Mar 26 '26 16:03 t3hw

@t3hw In https://github.com/apache/iceberg/commit/9afa6831e051234b1f30bff56f649694327e0375 if any temporary failures the task will error out?

jerryzhujing avatar Mar 27 '26 00:03 jerryzhujing

@t3hw In 9afa683 if any temporary failures the task will error out?

yeah, i think it might never error out on permanent failures, but continue to buffer commit envelopes.

t3hw avatar Mar 29 '26 11:03 t3hw

Fixed conflicts and aligned with main

t3hw avatar Apr 28 '26 09:04 t3hw

Hi @t3hw and @koodin9,

Thank you both for your awesome work on this! We actually hit the exact same bug (duplicate records during partial commits/timeouts) in our own environment, so we are really looking forward to this fix.

Since we are currently blocked by this issue, I was wondering if you could share a rough estimate of the merge timeline? Are there any major blockers or specific areas needing review right now?

Also, please let us know if there is anything we can do to help push this forward.

Thanks again for the great collaboration on this!

tongwai-wong-appier avatar Apr 29 '26 07:04 tongwai-wong-appier

hey @tongwai-wong-appier No clue regarding the merge timeline, I am planning to bring it up in the dev mailing list and ask for a committer to review this PR.

t3hw avatar May 27 '26 09:05 t3hw