ApprovalInference: Ignore approvals given on a non-current patchset

Ignore approvals granted on a patch-set after it is no longer the
current patch-set. For example, consider a CR -2 given on patchset#2
when patchset#3 is the current-patchset. Such approvals will no longer
be inferenced.

Release-Notes: Approvals given on a non-current patchset will not be inferenced
Bug: Issue 346574013
Change-Id: I36d4a79919e75de4acb331a4ea5f8ea1467a34ec
diff --git a/java/com/google/gerrit/server/approval/ApprovalInference.java b/java/com/google/gerrit/server/approval/ApprovalInference.java
index 695997a..ab3ea86 100644
--- a/java/com/google/gerrit/server/approval/ApprovalInference.java
+++ b/java/com/google/gerrit/server/approval/ApprovalInference.java
@@ -345,6 +345,12 @@
     }
   }
 
+  private boolean isPatchSetApprovalStale(ChangeNotes notes, PatchSetApproval psa) {
+    Map.Entry<PatchSet.Id, PatchSet> nextPatchSet =
+        notes.load().getPatchSets().higherEntry(psa.patchSetId());
+    return nextPatchSet != null && psa.granted().after(nextPatchSet.getValue().createdOn());
+  }
+
   private Collection<PatchSetApproval> getForPatchSetWithoutNormalization(
       ChangeNotes notes,
       ProjectState project,
@@ -410,7 +416,8 @@
     Map<String, FileDiffOutput> priorVsCurrent = null;
     LabelTypes labelTypes = project.getLabelTypes();
     for (PatchSetApproval psa : priorApprovals) {
-      if (resultByUser.contains(psa.label(), psa.accountId())) {
+      if (resultByUser.contains(psa.label(), psa.accountId())
+          || isPatchSetApprovalStale(notes, psa)) {
         continue;
       }
       Optional<LabelType> type = labelTypes.byLabel(psa.labelId());