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


##########
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:
   Thanks for the review. I checked with Codex and both ordering has its 
consistency drawbacks.
   
   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.
   
   



##########
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:
   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.
   
   



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