Skip to content

Commit 885121b

Browse files
authored
perf(gateway): cache session PR git facts (#114311)
1 parent 71a472b commit 885121b

3 files changed

Lines changed: 288 additions & 79 deletions

File tree

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import { runGit } from "../agents/worktrees/git.js";
2+
import {
3+
gitOutput,
4+
resolveBranchLanding,
5+
type MergedPullHead,
6+
} from "./control-ui-session-prs-landing.js";
7+
import { parseGitHubRemoteUrl } from "./github-remote.js";
8+
9+
const LOCAL_GIT_CACHE_MS = 10_000;
10+
const LOCAL_GIT_CACHE_LIMIT = 100;
11+
12+
/** GitHub repo + branch resolved from a session's git checkout. */
13+
export type SessionPullRequestGitContext = {
14+
owner: string;
15+
repo: string;
16+
branch: string;
17+
/** Checkout root for local diff stats; absent for stubbed test contexts. */
18+
root?: string;
19+
/** Remote default branch when origin/HEAD is resolvable. */
20+
defaultBranch?: string;
21+
};
22+
23+
export type SessionPullRequestLocalGitDeps = {
24+
gitOutput?: typeof gitOutput;
25+
runGit?: typeof runGit;
26+
resolveBranchLanding?: typeof resolveBranchLanding;
27+
};
28+
29+
type SessionPullRequestBranchFacts = {
30+
creatable: boolean;
31+
stats: { additions: number; deletions: number; changedFiles: number } | null;
32+
};
33+
34+
type LocalGitCacheEntry<T> = { expiresAt: number; promise: Promise<T> };
35+
36+
function createLocalGitCache<T>() {
37+
const entries = new Map<string, LocalGitCacheEntry<T>>();
38+
return (key: string, load: () => Promise<T>): Promise<T> => {
39+
const cached = entries.get(key);
40+
if (cached && cached.expiresAt > Date.now()) {
41+
entries.delete(key);
42+
entries.set(key, cached);
43+
return cached.promise;
44+
}
45+
const entry = { expiresAt: Date.now() + LOCAL_GIT_CACHE_MS, promise: load() };
46+
entries.delete(key);
47+
entries.set(key, entry);
48+
while (entries.size > LOCAL_GIT_CACHE_LIMIT) {
49+
const oldestKey = entries.keys().next().value;
50+
if (oldestKey === undefined) {
51+
break;
52+
}
53+
entries.delete(oldestKey);
54+
}
55+
return entry.promise;
56+
};
57+
}
58+
59+
// Process-local and bounded: ten seconds keeps sidebar checkout/tree facts
60+
// responsive; removing this freshness window respawns Git for every row.
61+
const cachedGitContext = createLocalGitCache<SessionPullRequestGitContext | null>();
62+
const cachedBranchFacts = createLocalGitCache<SessionPullRequestBranchFacts | undefined>();
63+
64+
export function resolveCachedGitContext(
65+
root: string,
66+
deps: SessionPullRequestLocalGitDeps,
67+
): Promise<SessionPullRequestGitContext | null> {
68+
return cachedGitContext(root, async () => {
69+
const output = deps.gitOutput ?? gitOutput;
70+
const branch = await output(root, ["rev-parse", "--abbrev-ref", "HEAD"]);
71+
if (!branch || branch === "HEAD") {
72+
return null;
73+
}
74+
const remoteUrl = await output(root, ["remote", "get-url", "origin"]);
75+
const remote = remoteUrl ? parseGitHubRemoteUrl(remoteUrl) : null;
76+
if (!remote) {
77+
return null;
78+
}
79+
const defaultRef = await output(root, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"]);
80+
const defaultBranch = defaultRef?.replace(/^origin\//, "");
81+
if (defaultBranch === branch) {
82+
return null;
83+
}
84+
return { ...remote, branch, root, ...(defaultBranch ? { defaultBranch } : {}) };
85+
});
86+
}
87+
88+
export function resolveCachedSessionBranchFacts(
89+
context: SessionPullRequestGitContext & { root: string },
90+
mergedHeads: readonly MergedPullHead[],
91+
load: () => Promise<SessionPullRequestBranchFacts | undefined>,
92+
): Promise<SessionPullRequestBranchFacts | undefined> {
93+
const landingKey = JSON.stringify([context.defaultBranch ?? null, mergedHeads]);
94+
return cachedBranchFacts(`${context.root}\0${context.branch}\0${landingKey}`, load);
95+
}

‎src/gateway/control-ui-session-prs.test.ts‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,114 @@ describe("loadControlUiSessionPullRequests", () => {
331331
expect(fetchImpl.mock.calls).toHaveLength(0);
332332
});
333333

334+
it("caches git context through repeated GitHub failures, then expires it", async () => {
335+
const fetchImpl = routedFetch([
336+
{
337+
match: "/pulls?head=",
338+
response: () => githubJson({ message: "unavailable" }, 503),
339+
},
340+
]);
341+
const gitOutputImpl = vi.fn(async (_root: string, args: string[]) => {
342+
if (args[0] === "rev-parse") {
343+
return "feature";
344+
}
345+
if (args[0] === "remote") {
346+
return "[email protected]:openclaw/openclaw.git";
347+
}
348+
return "origin/main";
349+
});
350+
const load = (root = "/repo/context-cache") =>
351+
loadControlUiSessionPullRequests(
352+
{ sessionKey: "agent:main:main" },
353+
{
354+
fetchImpl,
355+
resolveGitRoot: async () => root,
356+
gitOutput: gitOutputImpl,
357+
},
358+
);
359+
360+
await expect(load()).rejects.toBeInstanceOf(Error);
361+
await expect(load()).rejects.toBeInstanceOf(Error);
362+
expect(gitOutputImpl).toHaveBeenCalledTimes(3);
363+
expect(fetchImpl.mock.calls).toHaveLength(1);
364+
365+
await expect(load("/repo/other-context")).rejects.toBeInstanceOf(Error);
366+
expect(gitOutputImpl).toHaveBeenCalledTimes(6);
367+
368+
vi.advanceTimersByTime(10_001);
369+
await expect(load()).rejects.toBeInstanceOf(Error);
370+
expect(gitOutputImpl).toHaveBeenCalledTimes(9);
371+
// The longer GitHub failure cache remains independent of local Git expiry.
372+
expect(fetchImpl.mock.calls).toHaveLength(1);
373+
});
374+
375+
it("caches branch facts by root while refresh only bypasses the GitHub cache", async () => {
376+
let pulls: Record<string, unknown>[] = [];
377+
const fetchImpl = routedFetch([
378+
{ match: "/pulls?head=", response: () => githubJson(pulls) },
379+
{ match: "/repos/openclaw/openclaw", response: () => githubJson({ fork: false }) },
380+
]);
381+
const resolveBranchLanding = vi.fn(async () => ({
382+
pushedSha: "a".repeat(40),
383+
statsBase: "base",
384+
hasLandedPullRequest: false,
385+
provenNewPushedWork: false,
386+
}));
387+
const gitOutputImpl = vi.fn(async (_root: string, args: string[]) =>
388+
args[0] === "rev-list" ? "1" : null,
389+
);
390+
const runGitImpl = vi.fn(async (root: string) => ({
391+
stdout:
392+
root === "/repo/b" ? " 1 file changed, 2 insertions(+)" : " 1 file changed, 1 insertion(+)",
393+
stderr: "",
394+
code: 0,
395+
}));
396+
const load = (sessionKey: string, refresh = false) =>
397+
loadControlUiSessionPullRequests(
398+
{ sessionKey, ...(refresh ? { refresh: true } : {}) },
399+
{
400+
fetchImpl,
401+
resolveGitContext: async () => ({
402+
...context,
403+
branch: "cache/test",
404+
root: sessionKey.endsWith(":b") ? "/repo/b" : "/repo/a",
405+
defaultBranch: "main",
406+
}),
407+
gitOutput: gitOutputImpl,
408+
runGit: runGitImpl,
409+
resolveBranchLanding,
410+
},
411+
);
412+
413+
expect((await load("agent:main:a")).branch?.additions).toBe(1);
414+
expect((await load("agent:main:a", true)).branch?.additions).toBe(1);
415+
expect(resolveBranchLanding).toHaveBeenCalledTimes(1);
416+
expect(runGitImpl).toHaveBeenCalledTimes(1);
417+
expect(gitOutputImpl).toHaveBeenCalledTimes(2);
418+
expect(
419+
fetchImpl.mock.calls.filter((call) =>
420+
requestUrl(call[0] as RequestInfo | URL).includes("/pulls?head="),
421+
),
422+
).toHaveLength(2);
423+
424+
pulls = [pullListItem({ merged_at: "2026-07-09T10:00:00Z" })];
425+
expect((await load("agent:main:a", true)).branch?.additions).toBe(1);
426+
expect(resolveBranchLanding).toHaveBeenCalledTimes(2);
427+
expect(runGitImpl).toHaveBeenCalledTimes(2);
428+
expect(gitOutputImpl).toHaveBeenCalledTimes(4);
429+
430+
vi.advanceTimersByTime(10_001);
431+
expect((await load("agent:main:a")).branch?.additions).toBe(1);
432+
expect(resolveBranchLanding).toHaveBeenCalledTimes(3);
433+
expect(runGitImpl).toHaveBeenCalledTimes(3);
434+
expect(gitOutputImpl).toHaveBeenCalledTimes(6);
435+
436+
expect((await load("agent:main:b")).branch?.additions).toBe(2);
437+
expect(resolveBranchLanding).toHaveBeenCalledTimes(4);
438+
expect(runGitImpl).toHaveBeenCalledTimes(4);
439+
expect(gitOutputImpl).toHaveBeenCalledTimes(8);
440+
});
441+
334442
it("refreshes a cached empty result after the assistant creates a PR", async () => {
335443
let pulls: Record<string, unknown>[] = [];
336444
const fetchImpl = routedFetch([

0 commit comments

Comments
 (0)