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

Two pulls opened in the same instant can be recorded with one head #17273

opened this

Merged 41h 30m ago, live in production

mason/forge:mason/17255-two-pulls-opened-in-the-same-instant-can → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/17255-two-pulls-opened-in-the-same-instant-can was merged into main as 3bb7949.

Review

Sign in to review this change.
5 files changed +163 −38
src/core/following.ts −7
@@ -534,13 +534,6 @@ export async function refreshPullHead(
534534 if (tip === undefined) return undefined;
535535 await writeRef(snapshotDir, `refs/pull/${pull.number}/head`, tip);
536536 // The row says where the head is too, so a reader of the pull — the API,
537 // a page — sees the same tip the ref holds. Written with the ref, before
538 // any await: a refresh that reads the ref as current between the two
539 // would otherwise answer from a row still naming the old head.
540 forge.db
541 .query("UPDATE pull SET head_oid = ?2 WHERE issue_id = ?1")
542 .run(pull.id, tip);
543 // The row says where the head is too, so a reader of the pull — the API,
544537 // a page — sees the same tip the ref holds. Written with no await after
545538 // the ref moves: a concurrent refresh sees the ref current and returns
546539 // nothing, and its caller reads this row (#12870).
src/git/merge.ts +25 −7
@@ -489,13 +489,31 @@ export async function fetchInto(
489489 srcRef: string,
490490 ): Promise<string | undefined> {
491491 if (!isSafeRef(srcRef)) return undefined;
492 const fetched = await runGit(
493 ["fetch", "--no-tags", "--quiet", sourceDir, srcRef],
494 { cwd: baseDir, timeoutMs: 120_000 },
495 );
496 if (!fetched.ok) return undefined;
497 const tip = await runGit(["rev-parse", "FETCH_HEAD"], { cwd: baseDir });
498 return tip.ok ? tip.value.trim() : undefined;
492 // The tip is read from a ref only this fetch writes, never from FETCH_HEAD: that is one
493 // file per repository, so two fetches into one base at once each read whichever tip was
494 // written last (#17255).
495 const dest = `refs/forge/fetch/${crypto.randomUUID()}`;
496 try {
497 const fetched = await runGit(
498 [
499 "fetch",
500 "--no-tags",
501 "--quiet",
502 "--no-write-fetch-head",
outdated

The result of update-ref -d is dropped. If the process dies between the fetch and here, the temp ref stays in the base for good. Delete it in a finally, or sweep old refs/forge/fetch/ refs at boot.

503 sourceDir,
504 `+${srcRef}:${dest}`,
505 ],
506 { cwd: baseDir, timeoutMs: 120_000 },
507 );
508 if (!fetched.ok) return undefined;
509 const tip = await runGit(["rev-parse", "--verify", `${dest}^{commit}`], {
510 cwd: baseDir,
511 });
512 return tip.ok ? tip.value.trim() : undefined;
513 } finally {
514 // Also when the fetch failed or timed out half-way: the ref may exist.
515 await runGit(["update-ref", "-d", dest], { cwd: baseDir });
516 }
499517 }
500518
501519 /** Write a ref to an oid unconditionally (for refs/pull/N/*). */
src/origins/git-mirror.ts +35 −24
@@ -257,31 +257,42 @@ export async function fetchRefFrom(
257257
258258 const pinned = await vettedEnv(url, authEnv);
259259 if (!pinned.ok) return pinned;
260 const run = await runGitCapture(
261 [
262 "fetch",
263 "--no-tags",
264 "--no-recurse-submodules",
265 "--quiet",
266 url,
267 // A bare source ref: the objects arrive and FETCH_HEAD names the tip,
268 // without any local ref moving.
269 srcRef,
270 ],
271 { cwd: dir, env: pinned.value, timeoutMs: FETCH_TIMEOUT_MS },
272 );
273 if (run.code !== 0) {
274 return err({
275 message:
276 redact(run.stderr.trim(), ...secretsIn(authEnv)) ||
277 `could not fetch ${srcRef}`,
278 });
260 const dest = `refs/forge/fetch/${crypto.randomUUID()}`;
261 try {
262 const run = await runGitCapture(
263 [
264 "fetch",
265 "--no-tags",
266 "--no-recurse-submodules",
267 "--quiet",
268 url,
269 "--no-write-fetch-head",
270 // The tip lands in a ref only this fetch writes, deleted below: the
271 // objects arrive and no branch moves. FETCH_HEAD is one file per
272 // repository, so two fetches into one dir at once would read each
273 // other's tip (#17255).
274 `+${srcRef}:${dest}`,
275 ],
276 { cwd: dir, env: pinned.value, timeoutMs: FETCH_TIMEOUT_MS },
277 );
278 if (run.code !== 0) {
279 return err({
280 message:
281 redact(run.stderr.trim(), ...secretsIn(authEnv)) ||
282 `could not fetch ${srcRef}`,
283 });
284 }
285 const tip = await runGitCapture(
286 ["rev-parse", "--verify", `${dest}^{commit}`],
287 { cwd: dir },
288 );
289 const oid = tip.stdout.trim();
290 if (tip.code !== 0 || !isSafeOid(oid))
291 return err({ message: `no such ref upstream: ${srcRef}` });
292 return ok(oid);
293 } finally {
294 await runGitCapture(["update-ref", "-d", dest], { cwd: dir });
279295 }
280 const tip = await runGitCapture(["rev-parse", "FETCH_HEAD"], { cwd: dir });
281 const oid = tip.stdout.trim();
282 if (tip.code !== 0 || !isSafeOid(oid))
283 return err({ message: `no such ref upstream: ${srcRef}` });
284 return ok(oid);
285296 }
286297
287298 export interface PushUpdate {
test/cross-repo-pull.test.ts +42
@@ -315,4 +315,46 @@ describe("cross-repo pull requests (fork → upstream)", () => {
315315 });
316316 expect(refused.status).toBe(404);
317317 });
318
319 test("two cross-repo pulls opened at once each record their own head (#17255)", async () => {
320 const tips: string[] = [];
321 for (const branch of ["race-a", "race-b", "race-c"]) {
322 const edited = await call("/api/v1/repos/bob/app/edits", bobToken, {
323 method: "POST",
324 body: JSON.stringify({
325 newBranch: branch,
326 base: "main",
327 message: branch,
328 files: [{ path: `${branch}.txt`, content: `${branch}\n` }],
329 }),
330 });
331 expect(edited.status).toBe(201);
332 tips.push(
333 (await json<{ commit: { commitOid: string } }>(edited)).commit
334 .commitOid,
335 );
336 }
337 const branches = ["race-a", "race-b", "race-c"];
338 const opened = await Promise.all(
339 branches.map((head) =>
340 call("/api/v1/repos/alice/app/pulls", bobToken, {
341 method: "POST",
342 body: JSON.stringify({
343 title: head,
344 base: "main",
345 head,
346 headRepo: "bob/app",
347 }),
348 }),
349 ),
350 );
351 for (const [i, response] of opened.entries()) {
352 expect(response.status).toBe(201);
353 const { number } = await json<{ number: number }>(response);
354 const detail = await json<{ status: { headOid: string } }>(
355 await call(`/api/v1/repos/alice/app/pulls/${number}`, aliceToken),
356 );
357 expect(detail.status.headOid).toBe(tips[i]!);
358 }
359 });
318360 });
test/fetch-into-race.test.ts added +61
@@ -0,0 +1,61 @@
1 import { afterAll, beforeAll, expect, 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 { fetchInto } from "../src/git/merge.ts";
6
7 const env = {
8 ...process.env,
9 GIT_AUTHOR_NAME: "t",
10 GIT_AUTHOR_EMAIL: "[email protected]",
11 GIT_COMMITTER_NAME: "t",
12 GIT_COMMITTER_EMAIL: "[email protected]",
13 };
14 const git = (cwd: string, ...args: string[]): string => {
15 const p = Bun.spawnSync(["git", ...args], { cwd, env });
16 if (p.exitCode !== 0)
17 throw new Error(`git ${args.join(" ")}: ${p.stderr.toString()}`);
18 return p.stdout.toString().trim();
19 };
20
21 let root: string;
22 let base: string;
23 const forks: { dir: string; ref: string; tip: string }[] = [];
24
25 beforeAll(async () => {
26 root = await mkdtemp(join(tmpdir(), "forge-fetch-into-"));
27 const work = join(root, "work");
28 git(root, "init", "-q", "-b", "main", work);
29 await Bun.write(join(work, "f"), "base\n");
30 git(work, "add", "f");
31 git(work, "commit", "-qm", "base");
32 base = join(root, "base.git");
33 git(root, "clone", "-q", "--bare", work, base);
34 for (const name of ["a", "b", "c", "d"]) {
35 git(work, "checkout", "-q", "-B", name, "main");
36 await Bun.write(join(work, "f"), `${name}\n`);
37 git(work, "commit", "-qam", name);
38 const dir = join(root, `${name}.git`);
39 git(root, "clone", "-q", "--bare", work, dir);
40 const tip = git(work, "rev-parse", "HEAD");
41 forks.push({ dir, ref: `refs/heads/${name}`, tip });
42 }
43 });
44
outdated

Please show this goes red on the old FETCH_HEAD code. Four forks over ten rounds may pass on the old code by luck. Also add the createPull-level test of two simultaneous cross-repo pulls that the issue asks for.

45 afterAll(async () => {
46 await rm(root, { recursive: true, force: true });
47 });
48
49 test("fetches into one repository at once answer each their own tip", async () => {
50 for (let round = 0; round < 10; round++) {
51 const got = await Promise.all(forks.map((f) => fetchInto(base, f.dir, f.ref)));
52 expect(got).toEqual(forks.map((f) => f.tip));
53 }
54 });
55
56 test("a fetch leaves no ref of its own behind, and what it brought stays readable", async () => {
57 const f = forks[0]!;
58 expect(await fetchInto(base, f.dir, f.ref)).toBe(f.tip);
59 expect(git(base, "for-each-ref", "refs/forge/")).toBe("");
60 expect(git(base, "cat-file", "-t", f.tip)).toBe("commit");
61 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs