Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

RATIS-2846. Preserve read ordering across leader and follower queries - #1722

Open
ivandika3 wants to merge 7 commits into
apache:masterfrom
ivandika3:RATIS-2846
Open

ivandika3 wants to merge 7 commits into
apache:masterfrom
ivandika3:RATIS-2846

Conversation

@ivandika3

@ivandika3 ivandika3 commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

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

State Leader Follower
Applied log index 11 10
Counter value 1 0

This means that the transaction for log entry 11 increments the counter from 0 to 1

A possible sequence

  1. Leader read: getReadIndex return 10, derived from repliedIndex
  2. The leader waits for applied index >= 10, but it already has 11, so it immediately queries its state machine and returns counter value 1 (new counter)
  3. Subsequent follower read will request for leader's repliedIndex and the leader returns the repliedIndex 10, so getReadIndex returns 10
  4. The follower has applied 10 >= repliedIndex 10 and return 0 (Stale read)

The solution is to have a separate monotonically increasing readIndex attributes which is incremented after every read (i.e. queryStateMachine). The leader will take the max(RepliedIndex, lastReadIndex) and use that as the effective ReadIndex.

Some thoughts

  • The assumption might be correct if we use MVCC where we can get the snapshot of the state when the StateMachine is at index RepliedIndex. However, since we don't use this mechanism, the bug exists.
  • This means that the performance improvements of both RATIS-2403 and RATIS-2379 would be reduced depending on how fresh the last successful leader reads. The freshest the last leader reads are, the higher the required ReadIndex and the longer the follower need to wait. This also implies that workloads that only reads from followers should still be able to gain the performance benefits, whereas the workload with frequent leader reads would almost revert back to default ReadIndex performance.
  • The lastReadIndex is quite conservative since it will keep updating the last commitIndex, a better bound is to have the highest log index whose effects the query actually observed, but this requires StateMachine#query to 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.

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.
@ivandika3 ivandika3 self-assigned this Dec 3, 2026

@szetszwo szetszwo 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.

@ivandika3 , this bug is tricky. Still digesting it.

Have two comments inlined so far.

Comment on lines +103 to +114
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)));
}

@szetszwo szetszwo Dec 3, 2026 •

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.

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).

@ivandika3 ivandika3 Dec 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

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.

... 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?

@ivandika3 ivandika3 Dec 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@szetszwo szetszwo Dec 4, 2026 •

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.

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();

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.
@szetszwo

szetszwo commented Dec 5, 2026

Copy link
Copy Markdown
Contributor
  1. The leader waits for applied index >= 10, but it already has 11, so it immediately queries its state machine and returns counter value 1 (new counter)
  2. Subsequent follower read will request for leader's repliedIndex and the leader returns the repliedIndex 10, so getReadIndex returns 10

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

@szetszwo

szetszwo commented Dec 6, 2026 •

Copy link
Copy Markdown
Contributor

@ivandika3 ,

The bug in APPLIED_INDEX and REPLIED_INDEX

State Leader Follower
commitIndex 20 20
appliedIndex 11 12 (transaction 12: Counter++)
Counter value 1 2

APPLIED_INDEX actually also has a bug:

  1. Client reads from Follower and got Counter==2
  2. Later, the same Client reads from Leader and got Counter==1

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

  • Invariant: Leader's commitIndex >= Follower's commitIndex
  • Non-invariant: Leader's (applied|replied) index >= Follower's (applied|replied) index

HDFS Visible Length

The 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

image
  • HDFS-265 (page 5 in appendDesign3.pdf)
  • BR - byte received
  • BA - byte acked, which is the visible length. Since BA_i < BR_k for any i and k, client can switch to any other datanode and it must already has enough bytes.

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).

  • Dn0: BA=10, BR=20
  • Dn1: BA=12, BR=18
  • Dn2: BA=15, BR=16

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

  • Same client case:
    How about the client has to provide the minIndex when switching servers? i.e. Client reads from server 1, it will receive the reply with the appliedIndex. If the client switches to server 2, it will provide the appliedIndex as the minIndex. Server 2 will wait until the max(readIndex,minIndex) to applied before replying.

  • Multi-client case:
    Even the solution here (Leader updating readIndex = max(commitIndex, readIndex)) cannot fix it since reading from a Follower cannot update the readIndex in the Leader. The following example still breaks linearizability.

    1. Client A reads from Follower and got counter==2.
    2. Client A tells Client B to read.
    3. Client B reads from Leader and got counter==1. (NOT LINEARIZABLE)

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?

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants