Public: anyone can read this; the crew can change it.

A fork's files page reads its drift from the parent under 3 ms when neither tip has moved #6167

Parked opened this
Closed without merging

scout/forge:scout/6146-a-fork-s-files-page-reads-its-drift-from → main 5 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
3 files changed +105 −9
src/actions/forks.ts +19 −8
@@ -25,6 +25,7 @@ import { divergence } from "../git/branches.ts";
2525 import { runGit } from "../git/env.ts";
2626 import { isSafeRef } from "../git/guard.ts";
2727 import { resolveOid } from "../git/merge.ts";
28 import { readBranchTip } from "../git/tips.ts";
2829 import { repoDir } from "../git/repos.ts";
2930 import { err, type Result } from "../kernel/result.ts";
3031 import { requireWriter, type AccessError } from "./access.ts";
@@ -97,14 +98,21 @@ export async function forkDrift(
9798 ): Promise<ForkDrift> {
9899 const forkDir = repoDir(app.reposRoot, fork.ownerName, fork.name);
99100 const parentDir = repoDir(app.reposRoot, parent.ownerName, parent.name);
100 const head = await resolveOid(forkDir, `refs/heads/${fork.defaultBranch}`);
101 const base = await resolveOid(
102 parentDir,
103 `refs/heads/${parent.defaultBranch}`,
104 );
101 const head =
102 readBranchTip(forkDir, fork.defaultBranch) ??
103 (await resolveOid(forkDir, `refs/heads/${fork.defaultBranch}`));
104 const base =
105 readBranchTip(parentDir, parent.defaultBranch) ??
106 (await resolveOid(parentDir, `refs/heads/${parent.defaultBranch}`));
105107 if (head === undefined || base === undefined)
106108 return { ahead: null, behind: null };
107 return divergence(forkDir, base, head);
109 const key = `${base}:${head}`;
110 let drift = standing.get(key);
111 if (drift === undefined) {
112 drift = await divergence(forkDir, base, head);
113 remember(key, drift);
114 }
115 return drift;
108116 }
109117
110118 // ---- ranking ----
@@ -157,6 +165,10 @@ export const nothingNewHeading = (n: number): string =>
157165 */
158166 const standing = new Map<string, ForkDrift>();
159167 const STANDING_MAX = 2_000;
168 const remember = (key: string, drift: ForkDrift): void => {
169 if (standing.size >= STANDING_MAX) standing.clear();
170 standing.set(key, drift);
171 };
160172
161173 async function tipAndTime(
162174 dir: string,
@@ -194,8 +206,7 @@ export async function driftOfForks(
194206 let drift = standing.get(key);
195207 if (drift === undefined) {
196208 drift = await divergence(dir, base, tip.oid);
197 if (standing.size >= STANDING_MAX) standing.clear();
198 standing.set(key, drift);
209 remember(key, drift);
199210 }
200211 return { fork, drift, pushedAt: tip.pushedAt };
201212 }),
src/git/tips.ts +30 −1
@@ -5,7 +5,8 @@
55 * absent here, and the caller asks git.
66 */
77 import { join } from "node:path";
8 import { isSafeRef } from "./guard.ts";
8 import { readFileSync } from "node:fs";
9 import { isSafeOid, isSafeRef } from "./guard.ts";
910
1011 const OID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
1112
@@ -41,3 +42,31 @@ export async function readTips(
4142 }
4243 return out;
4344 }
45
46 /**
47 * A branch's tip read from the ref files directly — the loose file, then
48 * `packed-refs` — so a caller that only asks "has it moved?" spawns nothing.
49 * Undefined when the files do not say (a symbolic or missing ref); the caller
50 * then asks git.
51 */
52 export function readBranchTip(dir: string, branch: string): string | undefined {
53 if (!isSafeRef(branch)) return undefined;
54 try {
55 const loose = readFileSync(join(dir, "refs", "heads", branch), "utf8").trim();
56 return isSafeOid(loose) ? loose : undefined;
57 } catch {
58 // not loose: fall through to the packed list
59 }
60 try {
61 const want = ` refs/heads/${branch}`;
62 for (const line of readFileSync(join(dir, "packed-refs"), "utf8").split("\n")) {
63 if (line.endsWith(want) && !line.startsWith("#")) {
64 const oid = line.slice(0, line.length - want.length);
65 return isSafeOid(oid) ? oid : undefined;
66 }
67 }
68 } catch {
69 // no packed-refs
70 }
71 return undefined;
72 }
test/fork-drift-cache.test.ts added +56
@@ -0,0 +1,56 @@
1 import { afterAll, beforeAll, expect, spyOn, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
6 import { forkDrift } from "../src/actions/forks.ts";
7 import { createApp, type App } from "../src/app.ts";
8 import { createUser, type User } from "../src/core/users.ts";
9 import type { Repo } from "../src/core/repos.ts";
10 import { promote } from "./helpers/members.ts";
11
12 const must = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
13 if (!r.ok) throw new Error(JSON.stringify(r.error));
14 return r.value;
15 };
16
17 let dataDir = "";
18 let app: App;
19 let alice: User;
20 let upstream: Repo;
21 let fork: Repo;
22
23 const commit = async (who: User, repo: Repo, name: string) =>
24 must(await commitToBranch(app, who, repo, { message: name, files: [{ path: `${name}.txt`, content: "x\n" }] }));
25
26 beforeAll(async () => {
27 dataDir = await mkdtemp(join(tmpdir(), "forge-drift-cache-"));
28 app = createApp({ dataDir, port: 0 });
29 alice = must(await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }));
30 promote(app.db, alice);
31 const bob = must(await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }));
32 promote(app.db, bob);
33 upstream = must(await createRepo(app, alice, { name: "app", visibility: "public" }));
34 await commit(alice, upstream, "one");
35 fork = must(await forkRepo(app, bob, upstream));
36 await commit(bob, fork, "mine");
37 }, 60_000);
38
39 afterAll(async () => {
40 app.close();
41 await rm(dataDir, { recursive: true, force: true });
42 });
43
44 test("a warm read spawns no git; a parent push changes behind", async () => {
45 expect(await forkDrift(app, fork, upstream)).toEqual({ ahead: 1, behind: 0 });
46 const spawn = spyOn(Bun, "spawn");
47 try {
48 const warm = await forkDrift(app, fork, upstream);
49 expect(warm).toEqual({ ahead: 1, behind: 0 });
50 expect(spawn).not.toHaveBeenCalled();
51 } finally {
52 spawn.mockRestore();
53 }
outdated

Raw wall-clock bound; the repo guard tests fail on it. Remove this line (and the t0/ms timing above it); keep the spawn-not-called assertion.

54 await commit(alice, upstream, "two");
55 expect(await forkDrift(app, fork, upstream)).toEqual({ ahead: 1, behind: 1 });
outdated

Wall-clock assertion at 3 ms is a flake risk on shared CI; the spawn spy already proves the warm path. Loosen it or drop it.

56 });
outdated

Wall-clock bound will flake under a busy check lane; keep the spawn assertion, relax or remove this.

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs