Repository navigation
fix(inkless:switch): stamp the diskless leader epoch on consumer fetches of a switched partition [KC-852] - #896
Conversation
…hes of a switched partition [KC-852] Diskless produce writes every batch with leader epoch 0, and a switched partition served those batches to consumers as stored. A consumer that read past the seal validated its position with epoch 0, the local classic log answered with the end of classic epoch 0, and the consumer reset to the seal and re-read every record from there. Epoch 0 is also a real classic epoch, and an OffsetsForLeaderEpoch request carries no offset, so the broker can't tell that consumer from one whose classic records the partition lost before it sealed. A switched partition now serves diskless batches with the diskless leader epoch, as the consolidated local log does. The classic log answers a requested epoch up to the last classic leader epoch, and a greater epoch gets the diskless end offset, which is at least the committed seal. Assisted-by: Claude Fable 5.2
There was a problem hiding this comment.
🟡 Changes recommended
Critical epoch-boundary errors in ReplicaManager can route consumers to the wrong log during the diskless transition, causing replacement records to be skipped or suffix records to be replayed.
2 open issues
What changed in this PR
This PR addresses consumer replay after a classic-to-diskless switch by distinguishing diskless batch epochs from classic epochs during position validation. It replaces #888’s blanket handling of epoch 0.
Changes:
- Stamp diskless fetch responses with the partition’s diskless leader epoch.
- Route epoch lookups using the last classic epoch and floor diskless end offsets at the committed seal.
- Add unit and cluster regression tests and document consumer epoch handling.
| File | Description |
|---|---|
docs/inkless/DISKLESS_CONSOLIDATION.md |
Document consumer batch epochs and epoch-lookup routing. |
core/src/test/scala/unit/kafka/server/ReplicaManagerInklessTest.scala |
Test epoch stamping, routing, and the seal floor. |
core/src/test/java/kafka/server/InklessTopicTypeSwitcherClusterTest.java |
Test consumer resume from a committed offset past the seal. |
core/src/main/scala/kafka/server/ReplicaManager.scala |
Stamp response batches and update epoch-lookup routing. |
Review effort: Balanced
…ess leader epoch [KC-852] Comparing the requested epoch with the last classic leader epoch gave two wrong answers. A classic epoch whose records the partition lost entirely is above the last surviving classic epoch, so it got the diskless end offset and the consumer skipped the records that replaced the lost ones. An abort marker that the sealed leader writes is in the leader epoch of the seal commit, which is also the diskless leader epoch of phase 1, so a consumer past the seal got the classic answer and reset to the seal. The diskless leader epoch of the seal commit separates the two kinds of epoch, but the controller sets disklessLeaderEpoch again when phase 2 starts. The partition registration now keeps the first value in initialDisklessLeaderEpoch (tag 105). The classic log answers a requested epoch below it, and that epoch and later ones get the diskless end offset. A partition that switched before the registration kept the value compares with disklessLeaderEpoch. Assisted-by: Claude Fable 5.2
There was a problem hiding this comment.
🔵 Needs a closer look
The new persisted epoch boundary ties consumer truncation to seal commits, phase changes, and metadata snapshots, requiring human review of mixed-version and failover invariants that static inspection cannot establish.
No open issues 🎉
2 resolved since last review
Review effort: Balanced
There was a problem hiding this comment.
I've been chasing it this morning but I think I managed to find it. It's very convoluted and requires many stars to align, so I was a bit hesitant on calling this out on the PR as one has to be very unlucky for this and I don't think a human review could have possibly caught it. Since however we're working with agents, it might be easier to fix it. Whether it's a follow up or this one, I let you to decide that.
There is a bug in the ReplicaManager.lastOffsetForLeaderEpoch routing when a consumer validates a lost classic epoch against a follower whose LeaderEpochFileCache has no entry above that epoch.
Because the follower returns UNDEFINED_EPOCH_OFFSET from LeaderEpochFileCache.endOffsetFor, the !isDisklessEpoch && localResult.endOffset != UNDEFINED_EPOCH_OFFSET && localResult.endOffset <= classicToDisklessStartOffset check evaluates to false even though the queried epoch is below initialDisklessLeaderEpoch. Execution falls through to disklessOffsetForLeaderEpoch and answers with the diskless end offset instead of the seal, so the consumer treats its stale position as valid and silently skips replacement diskless records.
Conditions required
- A consumer has a committed position with a classic epoch that the partition lost.
- A follower's
LeaderEpochFileCachehas no entry above that epoch. - The consumer validates its position against that follower after the seal commits.
- The diskless end offset is above the seal (at or above the consumer's position to skip all replacement records, or between the seal and the consumer's position to truncate too high and skip part of them).
Setup
- Three brokers: A (
broker.rack=az-a), B (broker.rack=az-b), and C (broker.rack=az-c). - Topic
t, one partition, replicas[A, B, C],min.insync.replicas=1, remote storage on, no transactional producers. eligible.leader.replicas.versionis enabled (default in 4.1+).
Reproduction sequence
- Epoch 0, leader A. Produce offsets 0 to 9. All three replicas replicate them, so every replica has
LEO=10,HW=10, and cache[(0, 0)]. - Move leadership to B with only B in the ISR (epoch 1). Stop C cleanly so the ISR shrinks to
{A, B}(leaderEpochstays 0, and C won't replicate the epoch-1 writes). Then stop A cleanly. Controlled shutdown elects B in epoch 1 withISR={B}, and B'smakeLeadercaches(1, 10). - Write the records that the partition loses (epoch 1). Produce offsets 10 to 14 to B in epoch 1. High watermark becomes 15 because B is the only ISR member. Consumer group
greads offsets 0 to 14 and commits offset 15 withleaderEpoch=1. Stop the consumer. - B loses offsets 10 to 14 (epoch 2, leaderless).
- Run
kill -9on B, truncate B's active segment to the byte position of offset 10 (fromkafka-dump-log.sh), and delete that segment's index files. - Wait for B's session to expire (
handleBrokerFenced). The partition becomes leaderless (leader=-1),ISR=[],ELR=[B],lastKnownElr=[B], andleaderEpochbumps from 1 to 2 (PartitionRegistration.mergeincrementsleaderEpochwheneverrecord.leader() != NO_LEADER_CHANGE). - Start B. Log recovery truncates B to offset 10 and drops
(1, 10)from B's epoch cache, leaving[(0, 0)]. Because B registers after an unclean shutdown,handleBrokerUncleanShutdownclears B fromELR ( ELR=[]) while keepinglastKnownElr=[B]andleaderEpoch=2.
- Run
- Last-known-leader election of B (epoch 3,
RECOVERING). Once B unfences (handleBrokerUnfenced),ISRandELRare both empty andlastKnownElr=[B], so the controller elects B in epoch 3 inRECOVERINGstate (ISR=[B],lastKnownElr=[]). B'sLEOis 10, itsHWis 10, andmakeLeadercaches(3, 10). - Bring A and C back into the ISR. Start A and C with producers off. They follow B in epoch 3. Their
LEO(10) already matches B's, so they neither truncate nor append batches. They rejoin the ISR ({B, A, C}), and their caches stay[(0, 0)]. - Switch the topic to diskless (epoch 4, seal at 10). Set
diskless.enable=trueont.- The pending switch record sets
leader=B, bumpingleaderEpochfrom 3 to 4. - B seals at
LEO=10andmakeLeaderreplaces(3, 10)with(4, 10), leaving B's cache at[(0, 0), (4, 10)]. - The controller commits
classicToDisklessStartOffset=10,disklessLeaderEpoch=4, andinitialDisklessLeaderEpoch=4. - With no open transactions, no abort marker is written, so A's and C's caches stay
[(0, 0)].
- The pending switch record sets
- Keep followers without a diskless epoch in their local caches. Block remote log uploads so the partition stays in phase 1 (
classicPrefixInRemoteStorage=false) and consolidation stays off. (The same bug also happens in phase 2 if consolidation is disabled or hasn't appended a batch to the follower yet.) - Produce diskless records. Produce 20 records. They receive diskless offsets 10 to 29, and the diskless end offset is 30.
- Resume consumer group
gon follower C. Start groupgwithclient.id=repro,diskless_az=az-c. In phase 1,InklessTopicMetadataTransformerroutes among alive ISR members and picks C while preservingleaderEpoch=4. The consumer seeks to(offset=15, offsetEpoch=1)and sendsOffsetsForLeaderEpoch(currentLeaderEpoch=4, leaderEpoch=1)to C. - C answers with the diskless end offset (30). In
ReplicaManager.lastOffsetForLeaderEpoch:- The partition has a committed seal (
10 >= 0), so C takes the switched-partition branch. - C's high watermark is 10 (
>= 10), sohasCompleteLocalClassicPrefixistrueand C answers from its local log withfetchOnlyFromLeader=false. endOffsetFor(1, 10)on cache[(0, 0)]returns(UNDEFINED_EPOCH, UNDEFINED_EPOCH_OFFSET)withErrors.NONEbecauselatestEpochis 0 andhigherEntry(1)isnull.firstDisklessLeaderEpochis 4, soisDisklessEpoch(1 >= 4) isfalse.- The classic
else ifbranch still doesn't match becauselocalResult.endOffset == UNDEFINED_EPOCH_OFFSET. - Execution falls into the
elsebranch, queries the control plane for the diskless end offset (30), applies the seal floor (max(30, 10) = 30), and returnsleaderEpoch=1, endOffset=30.
- The partition has a committed seal (
- The consumer skips records 10 to 14.
SubscriptionState.maybeCompleteValidationsees30 >= 15and completes validation. The consumer reads from offset 15 and never sees diskless offsets 10 to 14.
Expected vs. actual
- Expected: C answers with
endOffset=10(andleaderEpoch=0, or the seal offset for the latest classic epoch). The consumer logsTruncation detected ... resetting offset to the first offset known to divergeand reads offsets 10 to 29. - Control run on leader B (
diskless_az=az-b): B's cache is[(0, 0), (4, 10)], soendOffsetFor(1, 10)returns(0, 10)and the consumer truncates to 10. - Repeat on follower A (
diskless_az=az-a): A has cache[(0, 0)]and returns the same wrongendOffset=30as C.
Cause
When firstDisklessLeaderEpoch != NO_DISKLESS_LEADER_EPOCH, leaderEpoch != UNDEFINED_EPOCH, and !isDisklessEpoch, the requested epoch is known to be a classic epoch. If the local classic cache returns UNDEFINED_EPOCH_OFFSET (because this replica is a follower with no cached epoch above the lost classic epoch), ReplicaManager.lastOffsetForLeaderEpoch shouldn't fall through to disklessOffsetForLeaderEpoch; it should answer at classicToDisklessStartOffset (matching what the leader returns from its cache).
…cal log has no end offset at or below it [KC-852] A follower caches the leader epochs of the batches it appends. If the partition lost every record of a classic epoch, a follower that appended no batch afterward has no cached epoch above it, and its local log has no end offset for that epoch. The broker then asked the diskless log, whose end offset told a consumer that had read the lost records to keep its position, and the consumer skipped the records that replaced them. The leader answered the same request with the seal. An epoch below the initial diskless leader epoch is a classic epoch, and a classic epoch ends at the seal at the latest. For such an epoch, the broker now answers with the seal when the local log has no end offset or has one past the seal. Assisted-by: Claude Fable 5.2
|
Thanks for chasing this down. It's valid, and it also happens on |
#896 landed on main after the sync branched. Its test calls getOrCreateLog with Scala named arguments, which the Java LogManager doesn't support, so pass them positionally. Assisted-by: Claude Opus 5.5
#896 landed on main after the sync branched. Its test calls getOrCreateLog with Scala named arguments, which the Java LogManager doesn't support, so pass them positionally. Assisted-by: Claude Opus 5.5
#896 landed on main after the sync branched. Its test calls getOrCreateLog with Scala named arguments, which the Java LogManager doesn't support, so pass them positionally. Assisted-by: Claude Opus 5.5

A consumer that reads past the seal of a switched partition resets to the seal the next time it validates its position. It then re-reads every record from the seal to that position.
Problem
Diskless produce writes every batch with leader epoch 0 (
UnifiedLog.LEADER_EPOCH), andFetchHandlerreturns the batches with that epoch. A consumer that tails a switched partition therefore has a position past the seal withoffsetEpoch=0. Consolidation writes the same batches to the local log with the diskless leader epoch, so a consumer that reads below the local high watermark of a consolidating replica gets that epoch instead.The consumer validates a position with
OffsetsForLeaderEpochin two cases: when it resumes from a committed offset that carries a leader epoch, and when a metadata update shows a different leader or leader epoch for the partition. The request carries the epoch of the position and no offset.For a switched partition,
ReplicaManager.lastOffsetForLeaderEpochasks the local classic log first. If the classic end offset is at or belowclassicToDisklessStartOffset, the broker returns it. In the classic log, epoch 0 is a real epoch that ends at or below the seal, so the broker answers the diskless position with a classic end offset. The consumer treats an end offset below its position as a truncation.The broker can't fix this in the answer alone, because two consumers send the same request:
Example on
mainThe setup matches
testLastOffsetForLeaderEpochRoutesByInitialDisklessLeaderEpoch:classicToDisklessStartOffset)[(epoch 0, start 0), (epoch 5, start 10)]offsetEpoch=0The validation runs in this order:
OffsetsForLeaderEpochwithleaderEpoch=0.LeaderEpochFileCache.endOffsetFor(0)returns the start offset of the next cached epoch, which is 10.endOffset=10.Truncation detectedand seeks to offset 10.Fix
This PR replaces #888, which answered every request for epoch 0 from the diskless log. That hid the truncation from the second consumer.
The change has three parts:
ReplicaManager.fetchDisklessMessagessets the diskless leader epoch on the batches that a switched partition serves from diskless storage. Every consumer fetch of diskless storage goes through that method, including a delayed fetch and the diskless supplement of a local read. A position past the seal then has a diskless leader epoch on either fetch path, and epoch 0 means a classic record again.FetchCompletercopies the batches of each fetch into a new buffer, so the stored bytes keep epoch 0. A partition with no diskless leader epoch keeps its batches as they are.initialDisklessLeaderEpoch(tag 105). The controller sets it in the record that commits the seal, to the diskless leader epoch of that commit. The record that starts phase 2 and a lowered seal setdisklessLeaderEpochagain and keep this field. Undoing the switch clears it.disklessLeaderEpoch.The routing needs the epoch of the seal commit because it separates the two kinds of epoch. The switch bumps the leader epoch before the commit and stops classic produce, so every classic record is in an earlier leader epoch, apart from the abort markers that the sealed leader writes. Every batch that a consumer fetches from diskless storage has that epoch or a later one.
disklessLeaderEpochcan't serve as the boundary, because the controller sets it again when phase 2 starts. A consumer that read in phase 1 then has an epoch below it.The diskless answer for a switched partition is at least the committed seal. A control-plane placeholder row reports end offset 0, and without the floor a consumer at or past the seal would truncate to 0.
DisklessLeaderEndPoint.atLeastCommittedSealapplies the same floor for consolidating followers.The local lookup still runs first, so its errors, such as
NOT_LEADER_OR_FOLLOWER, reach the client as before.The same example with the fix
The batches that the consumer fetched in phase 2 carry epoch 5, so its position is offset 200 with
offsetEpoch=5:OffsetsForLeaderEpochwithleaderEpoch=5.endOffset=200.A consumer that read in phase 1 sends epoch 3. The broker gives the same answer, 200. On
mainthe classic log answers that request with 10.A classic position that the partition lost
In the same setup, a consumer at offset 15 read classic records that the partition lost before it sealed at 10:
OffsetsForLeaderEpochwith the epoch of its position. That epoch is 0 if the lost records were in the surviving classic epoch, or 2 if the partition lost every record of a later classic epoch.main.A lost classic epoch on a follower
A follower caches the leader epochs of the batches it appends. If the partition lost every record of a classic epoch, a follower that appended no batch afterward has no cached epoch above it.
LeaderEpochFileCache.endOffsetForthen returns no end offset for that epoch. A consumer reaches a follower when the metadata transformer routes it to a replica in its availability zone.testLastOffsetForLeaderEpochHybridAnswersSealForLostClassicEpochOnFollowerbuilds a follower with offsets 0 to 100 in epoch 0, epoch cache[(epoch 0, start 0)], the seal at 101, 4 as the initial diskless leader epoch, and 200 as the diskless end offset:offsetEpoch=1sendsOffsetsForLeaderEpochwithleaderEpoch=1.endOffset=101.Before this change, on
maintoo, the broker asked the diskless log in step 3 and returned 200, and the consumer kept position 105.An abort marker at the seal
If a transaction is open at the switch, the sealed leader writes the abort marker in the leader epoch of the seal commit.
testLastOffsetForLeaderEpochHybridAsksDisklessForEpochOfSealCommitbuilds a classic prefix whose last record, at offset 101, is in epoch 1, with the seal at 102 and 1 as the initial diskless leader epoch. A request for epoch 1 gets the diskless end offset, 200. A request for epoch 0 gets the classic answer, 101.Limits
ListOffsetsstill reports leader epoch 0 for a diskless offset. A consumer that resets its position doesn't validate it, becauseOffsetFetcherUtils.resetPositionIfNeededdrops the epoch.Test plan
testDisklessFetchOfSwitchedPartitionCarriesDisklessLeaderEpochfetches batches with epoch 0 throughfetchDisklessMessagesand expects epoch 5 on each. With theReplicaManagerofmainit fails withexpected: <List(5, 5)> but was: <List(0, 0)>.testDisklessFetchOfPartitionWithoutDisklessLeaderEpochKeepsBatchEpochcovers a partition with no diskless leader epoch.testLastOffsetForLeaderEpochRoutesByInitialDisklessLeaderEpochbuilds the example. It expects 200 for epochs 3 and 5, and the seal, 10, for epochs 0 and 2. It then removes the initial diskless leader epoch and expects 10 for epoch 3 and 200 for epoch 5. With theReplicaManagerofmainit fails withexpected: <200> but was: <10>.testLastOffsetForLeaderEpochHybridAsksDisklessForEpochOfSealCommitcovers the abort marker case. With theReplicaManagerofmainit fails withexpected: <200> but was: <102>.testLastOffsetForLeaderEpochHybridAnswersSealForLostClassicEpochOnFollowercovers the follower case and expects the seal, 101.testLastOffsetForLeaderEpochHybridAnswersSealForClassicEpochThatEndsPastSealcovers a local log with a classic record at the seal, where classic epoch 0 ends at 101 and the seal is 100. It expects 100. Without the last commit of this branch, the second test fails withexpected: <100> but was: <200>, and the first one gets 200 where it expects 101.testLastOffsetForLeaderEpochHybridFloorsDisklessEndOffsetAtSealhas the control plane report end offset 0 for a partition sealed at 101 and expects 101. With theReplicaManagerofmainit fails withexpected: <101> but was: <0>.PartitionRegistrationTestcovers the new field: the record round trip,mergeacross the seal commit, a lowered seal, the phase 2 record, and an undone switch, andequals,diff, andtoString.ReplicationControlManagerInklessTestchecks thatinitDisklessLogsets the field and that the phase 2 flag keeps it.InklessTopicTypeSwitcherClusterTest.testConsumerResumesFromCommittedOffsetPastSealruns on a 3-broker cluster. A consumer tails a switched partition sealed at offset 20 and commits offset 50. A second consumer in the same group starts at offset 50, and the commit hasleaderEpoch=2. Onmain, the same consumer commitsleaderEpoch=0and the second consumer starts at offset 20.ReplicaManagerInklessTest(314 tests),InklessTopicTypeSwitcherClusterTest(9 tests),ClassicToDisklessSwitchLastKnownLeaderClusterTest(2 tests),InklessDisklessListOffsetsTest(5 tests),DelayedFetchTest(15 tests),InitDisklessLogManagerTest(77 tests),InklessMetadataViewTest(38 tests),DescribeTopicPartitionsRequestHandlerTest(3 tests), the tests inio.aiven.inkless.consolidation(153 tests), andTopicSwitchCommandTest. In themetadatamodule,PartitionRegistrationTest,ReplicationControlManagerInklessTest,PartitionChangeBuilderTest, and theorg.apache.kafka.imagetests pass (620 tests).make valereports no alerts on the added lines.test_fault_between_seal_commit_and_phase_2withfault=object_storage_outagepassed in 1 run. It resumes a consumer group at the seal with the epoch of the last classic record, in phase 1 and again in phase 2.test_switch_succeeds_with_degraded_network, where the failure first showed, passed in 3 runs. In those runs the consumer validates its positions only when the seal commit changes the leader epoch, so they don't cover a validation after phase 2 starts.🤖 Generated with Claude Code