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



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