project: fast-forward tracking ref from prefetch

Since 624361, _CheckForImmutableRevision requires a pinned revision to
be an ancestor of refs/remotes/<remote>/<upstream>. That check was added
because skipping the fetch left the tracking ref stale, and repo upload
then tried to upload every commit between the stale ref and HEAD.

When a background prefetch (git maintenance prefetch, or tools using the
same refs/prefetch/remotes/<remote>/<branch> layout) already has the
pin, sync still runs a network fetch for every project whose tracking
ref is behind. On one Android checkout synced after 19 days, 1268 of
1301 such fetches received no objects (median 0.86s each, about 2.5 min
of wall time at --jobs-network=8).

If the prefetched tip contains the revision and is a fast-forward of the
existing tracking ref, fast-forward the tracking ref to it locally and
skip the fetch. The tracking ref ends where a fetch at prefetch time
would have left it, so the repo upload problem 624361 fixed does not
come back. The ref is never created, rewound, or moved sideways, and the
update is a compare-and-swap. When the prefetched tip does not contain
the revision, sync fetches as before.

Verified E2E with file:// remotes, a SHA-pinned manifest, and a
blob:limit partial clone: upstream main fetched to move refs/remotes,
while this change fast-forwarded from refs/prefetch with no fetch.
HEAD, refs/remotes, and repo status matched; a prefetch ref behind the
pin still fetched.

Bug: 588401628
Test: PYTHONPATH=. pytest tests (1444 passed; black/isort/flake8 clean)
Change-Id: Iea3c44b18c8fda6cbf2e05f771d43c84b68acf07
Reviewed-on: https://gerrit-review.googlesource.com/c/git-repo/+/637283
Tested-by: Ram Peri <ramperi@google.com>
Reviewed-by: Gavin Mak <gavinmak@google.com>
Commit-Queue: Ram Peri <ramperi@google.com>
diff --git a/project.py b/project.py
index 8f4f324..11a7da3 100644
--- a/project.py
+++ b/project.py
@@ -2081,6 +2081,7 @@
                 and self._CheckForImmutableRevision(
                     use_superproject=use_superproject,
                     depth=depth,
+                    allow_prefetch=True,
                 )
                 and (has_shallow or not self._IsShallow(depth))
             )
@@ -3340,6 +3341,7 @@
         self,
         use_superproject: Optional[bool] = None,
         depth: Optional[int] = None,
+        allow_prefetch: bool = False,
     ) -> bool:
         try:
             # if revision (sha or tag) is not present then following function
@@ -3366,12 +3368,21 @@
 
             # Verify revision is an ancestor of the upstream tracking ref.
             if verify_upstream:
-                self.bare_git.merge_base(
-                    "--is-ancestor",
-                    self.revisionExpr,
-                    upstream_rev,
-                    log_as_error=False,
-                )
+                try:
+                    self.bare_git.merge_base(
+                        "--is-ancestor",
+                        self.revisionExpr,
+                        upstream_rev,
+                        log_as_error=False,
+                    )
+                except error.GitError:
+                    if (
+                        not allow_prefetch
+                        or not self._FastForwardUpstreamFromPrefetch(
+                            upstream_rev
+                        )
+                    ):
+                        raise
             return True
         except error.GitError:
             # There is no such persistent revision. We have to fetch it.
@@ -3414,6 +3425,68 @@
         except OSError:
             return set()
 
+    def _FastForwardUpstreamFromPrefetch(self, upstream_rev: str) -> bool:
+        """Fast-forwards the upstream tracking ref to its prefetched value.
+
+        `git maintenance run --task=prefetch` and similar background tools
+        fetch refs/remotes/<remote>/<branch> into
+        refs/prefetch/remotes/<remote>/<branch> without touching the tracking
+        ref. When that prefetched tip contains the revision being synced and
+        is a fast-forward of the existing tracking ref, moving the tracking
+        ref to it gives the same result as a fetch done when the prefetch ran,
+        without another network round trip.
+
+        Args:
+            upstream_rev: The tracking ref, e.g. refs/remotes/goog/main.
+
+        Returns:
+            True if the tracking ref now contains self.revisionExpr.
+        """
+        if not upstream_rev.startswith("refs/remotes/"):
+            return False
+        prefetch_ref = "refs/prefetch/" + upstream_rev[len("refs/") :]
+        try:
+            prefetch_rev = self.bare_git.rev_parse(
+                "--verify",
+                "--quiet",
+                f"{prefetch_ref}^{{commit}}",
+                log_as_error=False,
+            )
+            self.bare_git.merge_base(
+                "--is-ancestor",
+                self.revisionExpr,
+                prefetch_rev,
+                log_as_error=False,
+            )
+        except error.GitError:
+            return False
+
+        try:
+            old_rev = self.bare_git.rev_parse(
+                "--verify",
+                "--quiet",
+                f"{upstream_rev}^{{commit}}",
+                log_as_error=False,
+            )
+            self.bare_git.merge_base(
+                "--is-ancestor",
+                old_rev,
+                prefetch_rev,
+                log_as_error=False,
+            )
+            # Compare-and-swap so a concurrent fetch is never overwritten.
+            self.bare_git.update_ref(
+                "-m",
+                f"repo: fast-forward from {prefetch_ref}",
+                upstream_rev,
+                prefetch_rev,
+                old_rev,
+                log_as_error=False,
+            )
+        except error.GitError:
+            return False
+        return True
+
     def _HasShallow(self) -> bool:
         """Check if this project has a shallow file in its gitdir."""
         return bool(
@@ -3758,6 +3831,7 @@
                 if self._CheckForImmutableRevision(
                     use_superproject=use_superproject,
                     depth=depth,
+                    allow_prefetch=True,
                 ) and (has_shallow or not self._IsShallow(depth)):
                     if verbose:
                         print(
diff --git a/tests/test_project.py b/tests/test_project.py
index bab4c8d..a7b240e 100644
--- a/tests/test_project.py
+++ b/tests/test_project.py
@@ -3099,6 +3099,166 @@
                 proj._CheckForImmutableRevision(use_superproject=False)
             )
 
+    def _make_linear_history(
+        self, proj: project.Project, tempdir: str, count: int
+    ) -> List[str]:
+        """Creates `count` commits on HEAD and returns their ids in order."""
+        test_file = os.path.join(tempdir, "file.txt")
+        commits = []
+        for i in range(count):
+            with open(test_file, "w") as f:
+                f.write(f"commit{i}")
+            proj.work_git.add("file.txt")
+            proj.work_git.commit("-m", f"commit {i}")
+            commits.append(proj.work_git.rev_parse("HEAD"))
+        return commits
+
+    def _get_upstream_project(self, tempdir: str) -> project.Project:
+        proj = _create_mock_project(tempdir)
+        proj.bare_git = project.Project._GitGetByExec(
+            proj, bare=True, gitdir=proj.gitdir
+        )
+        proj.upstream = "refs/heads/main"
+        proj.work_git.config("remote.origin.url", "http://example.com/repo")
+        proj.work_git.config(
+            "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"
+        )
+        return proj
+
+    def test_check_immutable_revision_read_only_by_default(
+        self,
+    ) -> None:
+        """Default allow_prefetch=False does not mutate the tracking ref."""
+        with utils_for_test.TempGitTree() as tempdir:
+            proj = self._get_upstream_project(tempdir)
+            c1, c2, c3 = self._make_linear_history(proj, tempdir, 3)
+            proj.work_git.update_ref("refs/remotes/origin/main", c1)
+            proj.work_git.update_ref("refs/prefetch/remotes/origin/main", c3)
+            proj.revisionExpr = c2
+
+            self.assertFalse(
+                proj._CheckForImmutableRevision(use_superproject=False)
+            )
+            self.assertEqual(
+                proj.work_git.rev_parse("refs/remotes/origin/main"), c1
+            )
+
+    def test_check_immutable_revision_fast_forwards_from_prefetch(
+        self,
+    ) -> None:
+        """A prefetched tip containing the revision replaces a fetch."""
+        with utils_for_test.TempGitTree() as tempdir:
+            proj = self._get_upstream_project(tempdir)
+            c1, c2, c3 = self._make_linear_history(proj, tempdir, 3)
+            proj.work_git.update_ref("refs/remotes/origin/main", c1)
+            proj.work_git.update_ref("refs/prefetch/remotes/origin/main", c3)
+            proj.revisionExpr = c2
+
+            self.assertTrue(
+                proj._CheckForImmutableRevision(
+                    use_superproject=False, allow_prefetch=True
+                )
+            )
+            self.assertEqual(
+                proj.work_git.rev_parse("refs/remotes/origin/main"), c3
+            )
+
+    def test_check_immutable_revision_prefetch_needs_upstream_ref(
+        self,
+    ) -> None:
+        """Without a tracking ref, the prefetched tip is not used."""
+        with utils_for_test.TempGitTree() as tempdir:
+            proj = self._get_upstream_project(tempdir)
+            _, c2 = self._make_linear_history(proj, tempdir, 2)
+            proj.work_git.update_ref("refs/prefetch/remotes/origin/main", c2)
+            proj.revisionExpr = c2
+
+            self.assertFalse(
+                proj._CheckForImmutableRevision(
+                    use_superproject=False, allow_prefetch=True
+                )
+            )
+            self.assertNotIn(
+                "refs/remotes/origin/main",
+                proj.work_git.for_each_ref("--format=%(refname)"),
+            )
+
+    def test_check_immutable_revision_prefetch_without_revision_fetches(
+        self,
+    ) -> None:
+        """A prefetched tip that does not contain the revision is ignored."""
+        with utils_for_test.TempGitTree() as tempdir:
+            proj = self._get_upstream_project(tempdir)
+            c1, c2, c3 = self._make_linear_history(proj, tempdir, 3)
+            proj.work_git.update_ref("refs/remotes/origin/main", c1)
+            proj.work_git.update_ref("refs/prefetch/remotes/origin/main", c2)
+            proj.revisionExpr = c3
+
+            self.assertFalse(
+                proj._CheckForImmutableRevision(
+                    use_superproject=False, allow_prefetch=True
+                )
+            )
+            self.assertEqual(
+                proj.work_git.rev_parse("refs/remotes/origin/main"), c1
+            )
+
+    def test_check_immutable_revision_prefetch_never_rewinds_upstream(
+        self,
+    ) -> None:
+        """The tracking ref is not moved unless it is a fast-forward."""
+        with utils_for_test.TempGitTree() as tempdir:
+            proj = self._get_upstream_project(tempdir)
+            c1, c2 = self._make_linear_history(proj, tempdir, 2)
+            # A side commit not on the tracking ref's history.
+            proj.work_git.checkout("-q", "--detach", c1)
+            with open(os.path.join(tempdir, "side.txt"), "w") as f:
+                f.write("side")
+            proj.work_git.add("side.txt")
+            proj.work_git.commit("-m", "side")
+            side = proj.work_git.rev_parse("HEAD")
+            proj.work_git.update_ref("refs/remotes/origin/main", side)
+            proj.work_git.update_ref("refs/prefetch/remotes/origin/main", c2)
+            proj.revisionExpr = c2
+
+            self.assertFalse(
+                proj._CheckForImmutableRevision(
+                    use_superproject=False, allow_prefetch=True
+                )
+            )
+            self.assertEqual(
+                proj.work_git.rev_parse("refs/remotes/origin/main"), side
+            )
+
+    def test_remote_fetch_skips_network_when_prefetch_contains_pin(
+        self,
+    ) -> None:
+        """_RemoteFetch skips `git fetch` when the prefetch has the pin."""
+        with utils_for_test.TempGitTree() as tempdir:
+            proj = self._get_upstream_project(tempdir)
+            c1, c2, c3 = self._make_linear_history(proj, tempdir, 3)
+            proj.work_git.update_ref("refs/remotes/origin/main", c1)
+            proj.work_git.update_ref("refs/prefetch/remotes/origin/main", c3)
+            proj.revisionExpr = c2
+
+            with mock.patch.object(
+                project.git_command,
+                "GitCommand",
+                wraps=project.git_command.GitCommand,
+            ) as git_cmd:
+                self.assertTrue(
+                    proj._RemoteFetch(
+                        current_branch_only=True, use_superproject=False
+                    )
+                )
+            fetches = [
+                c for c in git_cmd.call_args_list if "fetch" in c.args[1]
+            ]
+            self.assertEqual(fetches, [])
+            self.assertEqual(
+                proj.work_git.rev_parse("refs/remotes/origin/main"), c3
+            )
+
     def test_sync_network_half_stale_upstream_fetches(self) -> None:
         """Sync_NetworkHalf does not skip fetch when upstream ref is behind."""
         with utils_for_test.TempGitTree() as tempdir: