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

Find and fix why open pulls stop merging, starting with #14528 #16116

Merged opened this in answer to

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/16095-find-and-fix-why-open-pulls-stop-merging → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/16095-find-and-fix-why-open-pulls-stop-merging was merged into main as aeaf20b.

Review

Sign in to review this change.
6 files changed +243 −1
src/apps/permit_ceiling.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * The most a deploy may hold one of the runtime's two deploy permits (#16095). A step that waits
3 * on something that never answers used to hold its permit for hours, and every deploy behind it
4 * (production's among them) waited too. At the ceiling the work is aborted, the permit goes to
5 * the next deploy and this run fails saying why.
6 */
7
8 import { during } from "../perf/jobs.ts";
9
10 /** Install is capped at 10 minutes and the start at its `ready` wait; this is well past both. */
11 export const PERMIT_CEILING_MS = 30 * 60_000;
12
13 /** `work`'s result, or `late(...)` when it outlives `ms`, after calling `abort` once. */
14 export async function withinCeiling<T>(work: Promise<T>, ms: number, abort: () => void, late: (seconds: number) => T): Promise<T> {
15 let timer: ReturnType<typeof setTimeout> | undefined;
16 const over = new Promise<T>((resolve) => {
17 timer = setTimeout(
18 () =>
19 during("deploy-permit-ceiling", () => {

If abort() throws, resolve never runs and the permit stays held. Use try/finally so resolve(late(...)) always runs.

20 // The permit goes back whatever `abort` does: a throw must not keep it held.
21 try {
22 abort();
23 } catch {
24 // an abort that failed has nothing more to give; the run still fails below
25 } finally {
26 resolve(late(Math.round(ms / 1000)));
27 }
28 }),
29 ms,
30 );
31 });
32 // The work may still settle after it lost the race; its rejection is no one's to read.
33 work.catch(() => undefined);
34 try {
35 return await Promise.race([work, over]);
36 } finally {
37 clearTimeout(timer);
38 }
39 }
src/apps/runtime_deploy.ts +47 −1
@@ -8,6 +8,7 @@ import { recordCarried } from "../core/carried.ts";
88 import { noteRelease, noteReleaseTests, recordsReleases } from "./release_record.ts";
99 import { gateBudgetMs, gatesPush, gateSummary, withinBudget } from "./push_gate.ts";
1010 import { tellGated } from "./gate_notice.ts";
11 import { PERMIT_CEILING_MS, withinCeiling } from "./permit_ceiling.ts";
1112 import { releaseOfCommit } from "../core/release_subject.ts";
1213 import { runDir } from "../core/pulls.ts";
1314 import { checkPreview } from "./preview_spec.ts";
@@ -154,6 +155,26 @@ export function livePreviews(
154155 return n;
155156 }
156157
158 /**
159 * What a bring-up cut off at the permit ceiling leaves when it finally stops: a process that
160 * started after all is stopped, its token revoked and its tree removed (unless serving uses it).
161 * Settles whatever the bring-up does, and clears `state.settling` if it is still this one.
162 */
163 function settleAbandoned(rt: AppsRuntime, state: Environment, bringing: ReturnType<AppsRuntime["bringUp"]>): Promise<void> {
164 const settled: Promise<void> = bringing
165 .then(async (late) => {
166 if (!late.ok) return;
167 await late.value.handle.stop();
168 revokeAppToken(rt.app.db, late.value.tokenId);
169 if (late.value.dir !== state.live?.dir) await rm(late.value.dir, { recursive: true, force: true });
170 })
171 .catch(() => undefined)
172 .finally(() => {
173 if (state.settling === settled) state.settling = undefined;
174 });
175 return settled;
176 }
177
157178 export async function execute(
158179 rt: AppsRuntime,
159180 state: Environment,
@@ -199,6 +220,22 @@ export async function execute(
199220 `deploy ${state.env} of ${repo.ownerName}/${repo.name} at ${run.commitOid.slice(0, 7)} (${run.reason})`,
200221 );
201222
223 // A bring-up of this environment cut off at the permit ceiling may still be running in a step
224 // that does not hear the abort; this deploy would write the same tree beside it. It waits for
225 // that one to stop first, holding no permit, so other apps' deploys go ahead meanwhile.
226 if (state.settling !== undefined) {
227 write("waiting for the previous bring-up, stopped at the permit ceiling, to finish");
228 await state.settling;
229 if (rt.stopped) {
230 state.deploying = undefined;
231 lease();
232 const done = cancelRun(rt.app.db, run.id, STOPPED_SUMMARY);
233 write(`cancelled: ${STOPPED_SUMMARY}`);
234 if (done) announceRun(rt.app, done);
235 return;
236 }
237 }
238
202239 // The clock starts at the claim, the instant the log calls "the deploy
203240 // started"; the first lap is the wait for a permit. Production goes
204241 // ahead of previews waiting for one: it is the environment a person
@@ -212,7 +249,16 @@ export async function execute(
212249 clock.lap("turn");
213250 // Read again after the wait for a permit: a move may land in it.
214251 repo = getRepoById(rt.app.db, repo.id) ?? repo;
215 return rt.bringUp(state, repo, run, write, abort.signal, clock);
252 const bringing = rt.bringUp(state, repo, run, write, abort.signal, clock);
253 return withinCeiling(
254 bringing,
255 rt.options.permitCeilingMs ?? PERMIT_CEILING_MS,
256 () => {
257 state.settling = settleAbandoned(rt, state, bringing);
258 abort.abort();
259 },
260 (seconds) => ({ ok: false as const, error: `deploy failed: bringing it up took longer than ${seconds} s, so the permit went to the next deploy` }),
261 );
216262 },
217263 { first: state.env === "production" },
218264 )
src/apps/runtime_env.ts +7
@@ -24,6 +24,8 @@ export const log = createLog("apps");
2424 export interface RuntimeOptions {
2525 /** Milliseconds an app may take to begin an answer before a 504 (`apps/upstream_wait.ts`). */
2626 readonly upstreamWaitMs?: number | undefined;
27 /** Most a deploy may hold a deploy permit, ms (`apps/permit_ceiling.ts`); tests shorten it. */
28 readonly permitCeilingMs?: number | undefined;
2729 /** The domain app hostnames hang off: `<slug>.<domain>`. */
2830 readonly domain: string;
2931 /** `http` or `https` — what the public URL of an app starts with. */
@@ -344,6 +346,11 @@ export interface Environment {
344346 keptAwake?: BusyReason | undefined;
345347 /** The deploy in flight, if one is. */
346348 deploying?: { run: Run; abort: AbortController } | undefined;
349 /**
350 * A bring-up cut off at the permit ceiling that has not yet stopped (#16095): the next deploy
351 * of this environment waits for it, outside any permit, so the two never share its tree.
352 */
353 settling?: Promise<void> | undefined;
347354 /** The next deploy, waiting its turn; replaced by a newer request. */
348355 queued?: Run | undefined;
349356 chain: Promise<void>;
test/deploy-permit-ceiling.test.ts added +120
@@ -0,0 +1,120 @@
1 /**
2 * A deploy whose bring-up never answers fails at the permit ceiling with its reason and frees
3 * the permit, so the next deploy runs (#16095). Drives `execute`, so removing the wiring fails it.
4 * A bring-up cut off that way may still be running a step that ignores the abort: the next deploy
5 * of the same environment waits for it to stop, while other environments take the permit.
6 */
7 import { afterAll, beforeAll, expect, spyOn, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { AppsRuntime } from "../src/apps/runtime.ts";
13 import { newApp } from "../src/actions/apps.ts";
14 import { getAppById } from "../src/core/apps.ts";
15 import { getRepoById } from "../src/core/repos.ts";
16 import { createRun, getRun } from "../src/core/runs.ts";
17 import { createUser } from "../src/core/users.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 let dataDir = "";
23 let app: App;
24 let runtime: AppsRuntime;
25 let bring: ReturnType<typeof spyOn>;
26 let appId = "";
27 let repoId = "";
28 const signals: AbortSignal[] = [];
29 type Bring = ReturnType<AppsRuntime["bringUp"]>;
30 /** What the next bring-ups do, in order; past the end each fails at once with "second ran". */
31 const script: ((env: string) => Bring)[] = [];
32
33 beforeAll(async () => {
34 dataDir = await mkdtemp(join(tmpdir(), "forge-ceiling-"));
35 app = createApp({ dataDir, port: 0 });
36 runtime = new AppsRuntime(app, {
37 domain: "apps.test", scheme: "http", forgeUrl: "http://forge.test", concurrency: 1, permitCeilingMs: 150,
38 });
39 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice",
40 email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
41 if (!made.ok) throw new Error(made.error);
42 const created = await newApp(app, made.value, { name: "hello", description: "d", visibility: "public" });
43 if (!created.ok) throw new Error(String(created.error));
44 appId = created.value.app.id;
45 repoId = created.value.repo.id;
46 bring = spyOn(AppsRuntime.prototype, "bringUp").mockImplementation(
47 async (...a: Parameters<AppsRuntime["bringUp"]>): ReturnType<AppsRuntime["bringUp"]> => {
48 signals.push(a[4]);
49 const next = script.shift();
50 return next === undefined ? { ok: false, error: "second ran" } : next(a[2].env);
51 },
52 );
53 });
54
55 afterAll(async () => {
56 bring.mockRestore();
57 app.close();
58 await rm(dataDir, { recursive: true, force: true });
59 });
60
61 test("a hung bring-up fails the run with the ceiling message, aborts it, and the next deploy gets the permit", async () => {
62 script.push(() => new Promise<never>(() => {}));
63 const record = getAppById(app.db, appId)!;
64 const repo = getRepoById(app.db, repoId)!;
65 const run = (env: "production" | "pull-1") => createRun(app.db, { repoId, kind: "deploy", env, commitOid: "1".repeat(40), reason: "push" });
66 const a = run("production");
67 const b = run("pull-1");
68 const first = runtime.execute(runtime.envFor(record, "production"), repo, a);
69 const second = runtime.execute(runtime.envFor(record, "pull-1"), repo, b);
70 await Promise.race([Promise.all([first, second]), new Promise((_, no) => setTimeout(() => no(new Error("permit held")), 5_000))]);
71 expect(getRun(app.db, a.id)?.state).toBe("failed");
72 expect(getRun(app.db, a.id)?.summary).toContain("took longer than 0 s");
73 expect(signals[0]?.aborted).toBe(true);
74 expect(getRun(app.db, b.id)?.summary).toContain("second ran");
75 });
76
77 test("a bring-up stalled before it hears the abort keeps the next deploy of its environment waiting, not other environments", async () => {
78 const record = getAppById(app.db, appId)!;
79 const repo = getRepoById(app.db, repoId)!;
80 const run = (env: "pull-3" | "pull-2") => createRun(app.db, { repoId, kind: "deploy", env, commitOid: "2".repeat(40), reason: "push" });
81 // The first bring-up stalls in a step that never reads the signal (the manifest read, say),
82 // and only stops when this test lets it; `inFlight` counts bring-ups of pull-3 running.
83 let inFlight = 0;
84 let overlapped = false;
85 let release = (): void => {};
86 let stopped = 0;
87 script.push(async () => {
88 inFlight++;
89 await new Promise<void>((resolve) => (release = resolve));
90 inFlight--;
91 // It started a process after all: the late success is stopped, not left running.
92 return { ok: true, value: { commitOid: "2".repeat(40), handle: { port: 0, stop: async () => void stopped++ }, dir: join(dataDir, "late"), runId: "x", since: "", manifest: {} }, tested: Promise.resolve({ ok: true, value: undefined }) } as unknown as Awaited<Bring>;
93 });
94 const after = async (env: string): Bring => {
95 if (env !== "pull-3") {
96 script.unshift(after); // pull-3's deploy has yet to come
97 return { ok: false, error: "other environment ran" };
98 }
99 if (inFlight > 0) overlapped = true;
100 return { ok: false, error: "after it settled" };
101 };
102 script.push(after);
103 const prod = runtime.envFor(record, "pull-3");
104 const a = run("pull-3");
105 await runtime.execute(prod, repo, a);
106 expect(getRun(app.db, a.id)?.summary).toContain("took longer than");
107 // The same environment's next deploy waits; another environment's goes ahead meanwhile.
108 const b = run("pull-3");
109 const waiting = runtime.execute(prod, repo, b);
110 const c = run("pull-2");
111 await runtime.execute(runtime.envFor(record, "pull-2"), repo, c);
112 expect(getRun(app.db, c.id)?.summary).toContain("other environment ran");
113 expect(getRun(app.db, b.id)?.state).toBe("running");
114 release();
115 await waiting;
116 expect(overlapped).toBe(false);
117 expect(getRun(app.db, b.id)?.summary).toContain("after it settled");
118 expect(stopped).toBe(1);
119 expect(prod.settling).toBeUndefined();
120 });
test/job-slices.test.ts +1
@@ -261,6 +261,7 @@ function jobs(): Record<string, () => unknown> {
261261 * on.
262262 */
263263 const UNTIMED: Record<string, string> = {
264 "deploy-permit-ceiling": "a one-shot timer armed per deploy that only aborts it and resolves the race when a deploy outlives 30 minutes; permit-ceiling.test.ts and deploy-permit-ceiling.test.ts drive it with a short ceiling",
264265 "upstream-wait": "a one-shot timer that only aborts one proxied request when its app sends no headers in 30 s; no work of its own, cleared when the headers arrive; the upstream-wait tests drive it with a short wait",
265266 "runner-wait": "one-shot timers that only resolve a promise: a runner's claim held open, a check's look at its job each second (checks/runner_jobs.ts, runner_step.ts) and the runner program's own pauses; off unless FORGE_CHECKS_PLACEMENT=runner, and checks-runner-placement.test.ts drives all three",
266267 "git-pace": "a one-shot timer in git/pace.ts that only resolves the promise a paced pack write waits on: no work of its own, armed per pack chunk while a page response is in flight; git-pace.test.ts drives the pacer with a fake clock",
test/permit-ceiling.test.ts added +29
@@ -0,0 +1,29 @@
1 import { expect, test } from "bun:test";
2 import { withinCeiling } from "../src/apps/permit_ceiling.ts";
3
4 test("work that never settles is aborted at the ceiling and the permit's holder gets the late answer", async () => {
5 let aborted = 0;
6 const never = new Promise<string>(() => {});
7 const out = await withinCeiling(never, 50, () => aborted++, (s) => `late after ${s}`);
8 expect(out).toBe("late after 0");
9 expect(aborted).toBe(1);
10 });
11
12 test("work that settles in time is returned and nothing is aborted", async () => {
13 let aborted = 0;
14 const out = await withinCeiling(Promise.resolve("done"), 5_000, () => aborted++, () => "late");
15 expect(out).toBe("done");
16 expect(aborted).toBe(0);
17 });
18
19 test("work that rejects after the ceiling raises nothing", async () => {
20 const slow = new Promise<string>((_, reject) => setTimeout(() => reject(new Error("x")), 100));
21 expect(await withinCeiling(slow, 20, () => {}, () => "late")).toBe("late");
22 await slow.catch(() => undefined);
23 });
24
25 test("an abort that throws still gives the late answer", async () => {
26 const never = new Promise<string>(() => {});
27 const out = await withinCeiling(never, 20, () => { throw new Error("boom"); }, () => "late");
28 expect(out).toBe("late");
29 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs