Repository navigation
Conversation
Use the committed index directly without allocating or updating lastReadIndex. Retain monotonic read bounds for applied and replied index modes. Add local and RPC regressions for state exposed before applied-index publication. Validated 70 linearizable-read tests, Checkstyle, and SpotBugs.
There was a problem hiding this comment.
@ivandika3 , this bug is tricky. Still digesting it.
Have two comments inlined so far.
| public CompletableFuture<Message> applyTransaction(TransactionContext trx) { | ||
| final TermIndex termIndex = TermIndex.valueOf(trx.getLogEntry()); | ||
| final int count = counter.incrementAndGet(); | ||
| final CompletableFuture<Void> gate = applyGate; | ||
| if (gate != null) { | ||
| // Queries may observe the updated value while application has not yet published its index. | ||
| valueUpdated.complete(termIndex); | ||
| gate.join(); | ||
| } | ||
| updateLastAppliedTermIndex(termIndex); | ||
| return CompletableFuture.completedFuture(Message.valueOf(Integer.toString(count))); | ||
| } |
There was a problem hiding this comment.
This applyTransaction implementation seems incorrect:
When implementing StateMachine.applyTransaction, should it updateLastAppliedTermIndex first or change the state first?
Claude: Call updateLastAppliedTermIndex first, or do both inside one critical section that query also respects. Never change the state first and update lastApplied afterwards with no shared lock. That ordering is the hazard in BlockingAppliedIndexStateMachine.
Why updating last is unsafe. If the state changes first, there is a window where a query can see entry i while getLastAppliedTermIndex() < i. With APPLIED_INDEX, the leader's readIndex comes from getLastAppliedTermIndex(). So a leader read can return i, and a later follower read can get a readIndex below i and return the older value. That breaks linearizability.
Why updating first is safe, even though lastApplied briefly runs ahead of the state:
- Reads: a read with readIndex i doesn't query right away. ReadRequests.waitToAdvance waits until the updater reports index i applied, and the updater only reports it once the applyTransaction future completes (StateMachineUpdater.java:285). So the read can't see the state before i is in it.
- Snapshots: StateMachineUpdater.takeSnapshot waits for all pending apply futures before calling stateMachine.takeSnapshot() (StateMachineUpdater.java:308). So a snapshot can't record index i while i is only half-applied. This holds for both triggers: the automatic snapshot and the snapshot-management request (which goes through takeSnapshotAsync).
There was a problem hiding this comment.
Thanks for the review. I checked with Codex and both ordering has its consistency drawbacks so both are not safe.
updateLastAppliedTermIndex first then update the state is unsafe for queryStale since a stale read can satisfy minIndex while still returning the old counter
For example,
Publish lastApplied = i
Pause before incrementing
queryStale(GET, minIndex=i) returns the previous counter value
On the other hand, update the state first and then updateLastAppliedTermIndex is unsafe for linearizable follower read as you demonstrated. A leader query can expose the new value before its applied index advances, allowing a subsequent follower read to return an older value under the original APPLIED_INDEX behavior.
Increment counter for entry i
Pause before publishing lastApplied = i
Leader query returns the incremented value
Subsequent follower read obtains readIndex < i
Follower returns the previous value
So to ensure the correctness we should synchronize both applyTransaction and query to make updateLastAppliedTermIndex and state change atomic. In this case, the ordering of updateLastAppliedTermIndex and the state change should not matter, but I'll update so that the updateLastAppliedTermIndex is updated before similar to other StateMachine implementation.
There was a problem hiding this comment.
... stale read can satisfy minIndex ...
@ivandika3 , That's a good point! However, stale read seems not a popular feature. We may document it (or make it configurable). By default, we should recommend updateLastAppliedTermIndex first then update the state. What do you think?
There was a problem hiding this comment.
Thanks @szetszwo , let's document this. I updated some documentation.
So if we doesn't use queryStale, we might not need need to synchronize the applyTransaction and the query. Otherwise, we need to synchronize them.
There was a problem hiding this comment.
For stale read, we could fix it by waiting also the future returned by applyTransaction. Then updateLastAppliedTermIndex first works for all cases. Filed RATIS-2854.
| break; | ||
| case APPLIED_INDEX: | ||
| readIndexSupplier = () -> server.getState().getLastAppliedIndex(); | ||
| supplier = () -> server.getState().getLastAppliedIndex(); |
There was a problem hiding this comment.
The APPLIED_INDEX case seems okay.
With APPLIED_INDEX, the bug seems not applying. Please check
Claude: You're right: with APPLIED_INDEX the bug doesn't happen. I was also wrong earlier to say the commit index is the right bound to publish.
Why APPLIED_INDEX is safe:
- With APPLIED_INDEX, the readIndex is stateMachine.getLastAppliedTermIndex() (ServerState.java:525-527).
- A state machine moves its lastApplied forward before, or together with, exposing the new state. For example, CounterStateMachine.applyTransaction calls updateLastAppliedTermIndex(ti) before increment() (ReadOnlyRequestTests.java:383-385).
- So anything a leader query can see is at an index no higher than lastApplied at that moment. lastApplied only goes up, so every later readIndex, on the leader or a follower, covers it.
- BlockingAppliedIndexStateMachine breaks that ordering on purpose: it changes the counter, blocks, and only then updates lastApplied. The new APPLIED_INDEX test checks a state machine that violates the assumption, not a real bug.
REPLIED_INDEX does have the bug. The leader has applied entry i, so queries can see it, but the write reply is still held, so repliedIndex < i. A follower read then gets a readIndex below i and can return stale data.
There was a problem hiding this comment.
Thanks @szetszwo for catching this. I think the issue is because of the wrong ordering in the test state machine implementation, not that it's a Ratis bug. The APPLIED_INDEX should not need to fallback to commitIndex. This is good since it means the impact is not as large as I thought.
I updated the fix so that it only handles the REPLIED_INDEX, I make lastReadIndex to use the last appliedIndex instead of commitIndex.
Publish the applied index before updating the counter under the same monitor used by queries. Remove gate scaffolding and verify leader and follower reads after the completed write. Validated all 12 APPLIED_INDEX tests.
Publish the applied index after successful queries instead of the committed index. Keep APPLIED_INDEX and COMMIT_INDEX on their direct suppliers. Validated 70 linearizable-read tests, Checkstyle, and SpotBugs.
Document index update ordering, query synchronization, stale-read minIndex requirements, and application future completion. Explain how successful linearizable leader queries advance the REPLIED_INDEX read bound. Validated Javadocs, Checkstyle, and site rendering with Maven Site Plugin 3.12.1.
Remove the duplicate state machine and its configuration setup. Keep the existing CounterStateMachine unchanged. Validated all 12 APPLIED_INDEX tests.
Metadata entries may advance the state machine applied index before the assertion runs. Require the applied index to include the completed write instead of requiring equality. Validated all 12 APPLIED_INDEX tests.
@ivandika3 , The bug is that the leader replied 11 but still keeps repliedIndex == 10. So, the current fix updating with readIndex with appliedIndex seems correct. Will think about this again tomorrow. |
The bug in APPLIED_INDEX and REPLIED_INDEX
APPLIED_INDEX actually also has a bug:
The problem with APPLIED_INDEX and REPLIED_INDEX is that Leader's (applied|replied) index can be smaller than Follower's. For commitIndex, it is always true that
HDFS Visible LengthThe problem is similar to the visible length problem (HDFS-265) in HDFS -- when a block is being written, datanodes may have different visible lengths. After a client read from a datanode and saw length n bytes, if it switches to another datanode, it must see at least n bytes. HDFS uses acked length
When a client first reads from a Dn, the Dn will serves up to its BA. But when the client switches to another Dn, it will provide the length L it already saw. Then, the new Dn will serve up to max(BA, L).
Client read from Dn0, it will get 10 bytes. When it switches to Dn2, it can read max(15, 10) = 15 byte. When it switches again to Dn1, it still can read max(12, 15) = 15 bytes. Fix in Ratis
Fortunately, the multi-client cases may not be required for many of the applications. How about we fix the same client case and document it that multi-client case won't work for APPLIED_INDEX and REPLIED_INDEX? |
What changes were proposed in this pull request?
Generated-by: GPT 6.1 Sol
Please refer to https://issues.apache.org/jira/browse/RATIS-2846
The leader batch write implementation in RATIS-2403 and the appliedIndex as ReadIndex in RATIS-2379 can both return stale reads. The main wrong assumption is that either RepliedIndex will ensure that all clients can only see the replies up to RepliedIndex, the actual read itself can read the StateMachine state up to AppliedIndex and the subsequent follower read might not see the transactions between the leader's RepliedIndex and the AppliedIndex which triggers the stale reads.
For example, we have a counter implementation with REPLIED_INDEX enabled and with the following state
This means that the transaction for log entry 11 increments the counter from 0 to 1
A possible sequence
getReadIndexreturn 10, derived from repliedIndexThe solution is to have a separate monotonically increasing readIndex attributes which is incremented after every read (i.e.
queryStateMachine). The leader will take themax(RepliedIndex, lastReadIndex)and use that as the effective ReadIndex.Some thoughts
StateMachine#queryto return the index that the read is based on which is not trivial. We can address this in future tickets. One way is we store the Raft log index with the data that are queried, but this is very invasive.What is the link to the Apache JIRA
https://issues.apache.org/jira/browse/RATIS-2846
How was this patch tested?
IT.