GetRelated: Handle index staleness for change on which the endpoint is invoked

To compute the related changes of a patch set we:

1. Get all the groups from the patch sets of the corresponding change.
2. Query for all changes in the project that have any of these groups.

The matched changes are then sorted by RelatedChangesSorter.

It is expected that the change for which the REST endpoint is invoked is
contained in the set of matched changes. Since we search by the change's
project and groups, it must always match.

However the index can be stale for that change in two ways:

1. The index knows the change but not yet the patch set for which the
   REST endpoint is invoked.
2. The index does not yet know the change for which the REST endpoint is
   invoked.

Case 1. was already handled by forcing a reload of the change when the
wanted patch set was not present in the ChangeData that was returned
from the index.

This change adds handling for case 2. If the change is missing in the
index result we now load its ChangeData from NoteDb and add it to the
result.

If the change is missing in the result then RelatedChangesSorter#sort
fails with a NullPointerException because it doesn't find a commit for
the given start patch set [1] (the commits are gathered from the given
change set which is missing the change for the start patch set).

[1]
java.lang.NullPointerException: commit b0f113907a693dbf911f5721afb5332647ed6990 of patch set 121,1 not found in {936be82cf638c033e1674c19b086bc0af8b07300=122,1, 2e5531ccee8872ddfb6595798416512f0fe6dec0=123,1}
        at java.util.Objects.requireNonNull(Objects.java:290)
        at com.google.gerrit.server.restapi.change.RelatedChangesSorter.sort(RelatedChangesSorter.java:80)
        at com.google.gerrit.server.restapi.change.GetRelated.getRelated(GetRelated.java:103)
        at com.google.gerrit.server.restapi.change.GetRelated.apply(GetRelated.java:76)
        at com.google.gerrit.server.restapi.change.GetRelated.apply(GetRelated.java:52)
        at com.google.gerrit.httpd.restapi.RestApiServlet.lambda$invokeRestReadViewWithRetry$3(RestApiServlet.java:741)
        ....

Signed-off-by: Edwin Kempin <ekempin@google.com>
Change-Id: I9a94d734aed5a84c8d9510f6fcc5baca4c3416e2
diff --git a/java/com/google/gerrit/server/restapi/change/GetRelated.java b/java/com/google/gerrit/server/restapi/change/GetRelated.java
index a846d50..5f075f6 100644
--- a/java/com/google/gerrit/server/restapi/change/GetRelated.java
+++ b/java/com/google/gerrit/server/restapi/change/GetRelated.java
@@ -14,6 +14,7 @@
 
 package com.google.gerrit.server.restapi.change;
 
+import static com.google.common.base.Preconditions.checkArgument;
 import static java.util.stream.Collectors.toSet;
 
 import com.google.common.annotations.VisibleForTesting;
@@ -55,17 +56,20 @@
   private final PatchSetUtil psUtil;
   private final RelatedChangesSorter sorter;
   private final IndexConfig indexConfig;
+  private final ChangeData.Factory changeDataFactory;
 
   @Inject
   GetRelated(
       Provider<InternalChangeQuery> queryProvider,
       PatchSetUtil psUtil,
       RelatedChangesSorter sorter,
-      IndexConfig indexConfig) {
+      IndexConfig indexConfig,
+      ChangeData.Factory changeDataFactory) {
     this.queryProvider = queryProvider;
     this.psUtil = psUtil;
     this.sorter = sorter;
     this.indexConfig = indexConfig;
+    this.changeDataFactory = changeDataFactory;
   }
 
   @Override
@@ -98,7 +102,7 @@
     boolean isEdit = rsrc.getEdit().isPresent();
     PatchSet basePs = isEdit ? rsrc.getEdit().get().getBasePatchSet() : rsrc.getPatchSet();
 
-    reloadChangeIfStale(cds, basePs);
+    cds = reloadChangeIfStale(cds, rsrc.getChange(), basePs);
 
     for (RelatedChangesSorter.PatchSetData d : sorter.sort(cds, basePs)) {
       PatchSet ps = d.patchSet();
@@ -127,14 +131,30 @@
     return psUtil.byChange(notes).stream().flatMap(ps -> ps.groups().stream()).collect(toSet());
   }
 
-  private void reloadChangeIfStale(List<ChangeData> cds, PatchSet wantedPs) {
-    for (ChangeData cd : cds) {
-      if (cd.getId().equals(wantedPs.id().changeId())) {
-        if (cd.patchSet(wantedPs.id()) == null) {
-          cd.reloadChange();
-        }
-      }
+  private List<ChangeData> reloadChangeIfStale(
+      List<ChangeData> changeDatasFromIndex, Change wantedChange, PatchSet wantedPs) {
+    checkArgument(
+        wantedChange.getId().equals(wantedPs.id().changeId()),
+        "change of wantedPs (%s) doesn't match wantedChange (%s)",
+        wantedPs.id().changeId(),
+        wantedChange.getId());
+
+    List<ChangeData> changeDatas = new ArrayList<>(changeDatasFromIndex.size() + 1);
+    changeDatas.addAll(changeDatasFromIndex);
+
+    // Reload the change in case the patch set is absent.
+    changeDatas.stream()
+        .filter(
+            cd -> cd.getId().equals(wantedPs.id().changeId()) && cd.patchSet(wantedPs.id()) == null)
+        .forEach(ChangeData::reloadChange);
+
+    if (changeDatas.stream().noneMatch(cd -> cd.getId().equals(wantedPs.id().changeId()))) {
+      // The change of the wanted patch set is missing in the result from the index.
+      // Load it from NoteDb and add it to the result.
+      changeDatas.add(changeDataFactory.create(wantedChange));
     }
+
+    return changeDatas;
   }
 
   static RelatedChangeAndCommitInfo newChangeAndCommit(