szetszwo commented on code in PR #1722:
URL: https://github.com/apache/ratis/pull/1722#discussion_r4790173002


##########
ratis-test/src/test/java/org/apache/ratis/grpc/TestLinearizableReadAppliedIndexWithGrpc.java:
##########
@@ -26,4 +51,71 @@ public class TestLinearizableReadAppliedIndexWithGrpc
   public Type readIndexType() {
     return Type.APPLIED_INDEX;
   }
+
+  @ParameterizedTest
+  @ValueSource(booleans = {false, true})
+  public void testLeaderReadBeforeAppliedIndexUpdate(boolean local) throws 
Exception {
+    getProperties().setClass(MiniRaftCluster.STATEMACHINE_CLASS_KEY,
+        BlockingAppliedIndexStateMachine.class, StateMachine.class);
+    try {
+      runWithNewCluster(cluster -> {
+        final RaftServer.Division leader = RaftTestUtil.waitForLeader(cluster);
+        final BlockingAppliedIndexStateMachine stateMachine =
+            (BlockingAppliedIndexStateMachine)leader.getStateMachine();
+        final RaftPeerId follower = cluster.getFollowers().get(0).getId();
+        final CompletableFuture<Void> applyGate = new CompletableFuture<>();
+        try (RaftClient writer = cluster.createClient(leader.getId());
+             RaftClient leaderReader = cluster.createClient(leader.getId());
+             RaftClient followerReader = cluster.createClient(follower)) {
+          assertReplyExact(0, leaderReader.async().sendReadOnly(QUERY, 
leader.getId()).get(10, TimeUnit.SECONDS));
+          assertReplyExact(0, followerReader.async().sendReadOnly(QUERY, 
follower).get(10, TimeUnit.SECONDS));
+          stateMachine.applyGate = applyGate;
+          try {
+            final CompletableFuture<RaftClientReply> write = 
writer.async().send(INCREMENT);
+            final TermIndex writeIndex = stateMachine.valueUpdated.get(10, 
TimeUnit.SECONDS);
+            assertTrue(stateMachine.getLastAppliedTermIndex().getIndex() < 
writeIndex.getIndex());
+            assertFalse(write.isDone(), "Application must remain pending 
before publishing its applied index");
+
+            if (local) {
+              assertEquals("1", leader.readOnlyAsync(QUERY).get(10, 
TimeUnit.SECONDS).getContent().toStringUtf8());
+            } else {
+              assertReplyExact(1, leaderReader.async().sendReadOnly(QUERY, 
leader.getId()).get(10, TimeUnit.SECONDS));
+            }
+            assertReplyExact(1, followerReader.async().sendReadOnly(QUERY, 
follower).get(10, TimeUnit.SECONDS));
+            assertTrue(stateMachine.getLastAppliedTermIndex().getIndex() < 
writeIndex.getIndex());
+            assertFalse(write.isDone(), "Read ordering must not require 
finishing the leader's application");
+          } finally {
+            applyGate.complete(null);
+          }
+        }
+      });
+    } finally {
+      getProperties().setClass(MiniRaftCluster.STATEMACHINE_CLASS_KEY, 
CounterStateMachine.class, StateMachine.class);
+    }
+  }
+
+  public static class BlockingAppliedIndexStateMachine extends 
BaseStateMachine {
+    private final AtomicInteger counter = new AtomicInteger();
+    private final CompletableFuture<TermIndex> valueUpdated = new 
CompletableFuture<>();
+    private volatile CompletableFuture<Void> applyGate;
+
+    @Override
+    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)));
+    }

Review Comment:
   This applyTransaction implementation seems incorrect:
   
    When implementing StateMachine.applyTransaction, should it 
updateLastAppliedTermIndex first or change the start 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).



##########
ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderStateImpl.java:
##########
@@ -416,19 +405,23 @@ boolean isApplied() {
     }
 
     this.readIndexType = RaftServerConfigKeys.Read.ReadIndex.type(properties);
+    this.lastReadIndex = readIndexType == Type.COMMIT_INDEX ? null
+        : new RaftLogIndex("lastReadIndex", RaftLog.INVALID_LOG_INDEX);
+    final Supplier<Long> supplier;
     switch (readIndexType) {
     case REPLIED_INDEX:
       this.replyFlusher = new ReplyFlusher(server.getId(), 
state.getLastAppliedIndex(),
           
RaftServerConfigKeys.Read.ReadIndex.repliedIndexBatchInterval(properties));
-      readIndexSupplier = replyFlusher::getRepliedIndex;
+      supplier = replyFlusher::getRepliedIndex;
       break;
     case APPLIED_INDEX:
-      readIndexSupplier = () -> server.getState().getLastAppliedIndex();
+      supplier = () -> server.getState().getLastAppliedIndex();

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



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to