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

Every environment is dark for a minute after a restart: a boot deploy spends 59s before the app is even started #514

Closed opened this
Closed without merging

mason/forge:mason/296-every-environment-is-dark-for-a-minute-a → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +315 −16
docs/APPS.md +7
@@ -91,6 +91,13 @@ around it. None is advisory.
9191 line stays measured from `startedAt` and says `after the deploy
9292 started`; a deploy no push asked for — a redeploy someone pressed, a
9393 boot reconcile — is worded the same way and never claims a push.
94 Where that time went is in the log too, step by step
95 (`apps/timing.ts`): a `timing:` line before the process starts splits
96 the wait for a permit (`turn`), reading the manifest, the checkout, the
97 data and the setup, and one after it answers says how long the process
98 took and when it first said anything. A restart brings every app's
99 production back before any preview, and a production deploy waiting
100 for a permit goes ahead of the previews waiting for one.
94101 5. **A private app answers only to someone the forge vouches for.** An app's
95102 `access` is `public` or `private` (defaulting to the repository's
96103 visibility), and it is set apart from the repository's own: the code can
forge.json +1 −1
@@ -6,7 +6,7 @@
66 "ready": 90
77 },
88 "check": {
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts test/web-apps.test.ts",
9 "run": "bun x tsc --noEmit && bun scripts/test-shards.ts --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/apps-busy.test.ts test/apps-boot.test.ts test/apps-token.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts test/shards.test.ts test/migrate.test.ts test/vitals.test.ts test/asks.test.ts test/feed.test.ts test/feed-page.test.ts test/offline.test.ts test/share.test.ts test/cloud.test.ts test/run-secrets.test.ts test/forge-cloudflare.test.ts test/usage.test.ts test/standing.test.ts test/board-windows.test.ts test/spawn-plan.test.ts test/spawn.test.ts test/web-apps.test.ts",
1010 "timeout": 1800
1111 }
1212 }
src/apps/process.ts +10
@@ -17,6 +17,7 @@ import { forgeApiUrl } from "./token.ts";
1717 import { isReservedAppEnvName } from "../core/app_env.ts";
1818 import { err, ok, type Result } from "../kernel/result.ts";
1919 import { stripForgeDirs } from "../runs/paths.ts";
20 import { seconds } from "./timing.ts";
2021
2122 export interface ProcessHandle {
2223 readonly pid: number;
@@ -314,6 +315,8 @@ export async function startProcess(
314315
315316 const port = freePort();
316317 log(`$ ${manifest.run} (PORT=${port})`);
318 const spawnedAt = Date.now();
319 let firstOutputAt: number | undefined;
317320 const proc = Bun.spawn(["/bin/sh", "-c", `exec ${manifest.run}`], {
318321 cwd: input.dir,
319322 env: appEnv({
@@ -335,6 +338,7 @@ export async function startProcess(
335338 // Output is pumped for the life of the process, not just the start.
336339 const recent: string[] = [];
337340 const remember = (raw: string): void => {
341 firstOutputAt ??= Date.now();
338342 const line = stripForgeDirs([input.dir, input.dataDir], raw);
339343 recent.push(line);
340344 if (recent.length > 20) recent.shift();
@@ -381,6 +385,12 @@ export async function startProcess(
381385 });
382386 }
383387 log(`ready: ${input.url}`);
388 // How the process's own share of the start divides: the time until it
389 // first said anything (the runtime loading the app, the app's own boot
390 // work) and the time until its health path answered.
391 log(
392 `timing: answered ${seconds(Date.now() - spawnedAt)} after the process was started${firstOutputAt === undefined ? "" : ` — its first output after ${seconds(firstOutputAt - spawnedAt)}`}`,
393 );
384394 return ok({ handle, tested });
385395 }
386396
src/apps/runtime.ts +31 −6
@@ -47,6 +47,7 @@ import { appendRunLog } from "../runs/log.ts";
4747 import { primaryDomain } from "../core/domains.ts";
4848 import { BUSY_WORDS, busyReason, type BusyReason } from "./busy.ts";
4949 import { exportTree, readFileAt } from "./checkout.ts";
50 import { seconds, Stopwatch } from "./timing.ts";
5051 import type { DomainResolver } from "./domains.ts";
5152 import {
5253 appsRoot,
@@ -224,8 +225,7 @@ const PUSH_REASONS: readonly string[] = ["push", "opened", "merge"];
224225
225226 /** How long between two instants, in seconds to one decimal place: `3.4s`. */
226227 function elapsedSeconds(fromIso: string, toIso: string): string {
227 const ms = Math.max(0, Date.parse(toIso) - Date.parse(fromIso));
228 return `${(ms / 1000).toFixed(1)}s`;
228 return seconds(Date.parse(toIso) - Date.parse(fromIso));
229229 }
230230
231231 /**
@@ -531,13 +531,20 @@ export class AppsRuntime {
531531 }),
532532 );
533533 });
534 // Every app's production first, then every app's previews: deploys
535 // take the gate in the order they are asked for, and the environment a
536 // person actually visits must never come back behind someone's preview.
534537 const known = new Set<string>();
538 const present: { record: AppRecord; repo: Repo }[] = [];
535539 for (const record of listApps(this.app.db)) {
536540 known.add(record.id);
537541 const repo = getRepoById(this.app.db, record.repoId);
538 if (!repo) continue;
539 await this.reconcileApp(record, repo, "boot");
542 if (repo) present.push({ record, repo });
540543 }
544 for (const { record, repo } of present)
545 await this.reconcileApp(record, repo, "boot", "production");
546 for (const { record, repo } of present)
547 await this.reconcileApp(record, repo, "boot", "preview");
541548 this.pruneDirs(known);
542549 this.sweeper = setInterval(
543550 () => void this.sweep(),
@@ -591,8 +598,9 @@ export class AppsRuntime {
591598 })) {
592599 const env = previewEnv(pull.number);
593600 open.add(env);
601 if (only === "production") continue;
594602 const head = await this.pullHead(dir, pull);
595 if (head === undefined || only === "production") continue;
603 if (head === undefined) continue;
596604 // A preview the forge built in an earlier life comes back asleep, not
597605 // deployed: nobody is looking at it this second, and the first who
598606 // does wakes it warm. Thirty previews starting at once is what a
@@ -859,10 +867,21 @@ export class AppsRuntime {
859867 `deploy ${state.env} of ${repo.ownerName}/${repo.name} at ${run.commitOid.slice(0, 7)} (${run.reason})`,
860868 );
861869
870 // The clock starts at the claim, the instant the log calls "the deploy
871 // started"; the first lap is the wait for a permit. Production goes
872 // ahead of previews waiting for one: it is the environment a person
873 // actually visits.
874 const clock = new Stopwatch();
862875 // A deploy that throws is a failed run, never a fallen forge: the chain
863876 // this runs on would otherwise reject unhandled and take the process.
864877 const outcome = await this.gate
865 .run(() => this.bringUp(state, repo, run, write, abort.signal))
878 .run(
879 () => {
880 clock.lap("turn");
881 return this.bringUp(state, repo, run, write, abort.signal, clock);
882 },
883 { first: state.env === "production" },
884 )
866885 .catch((error: unknown) => ({
867886 ok: false as const,
868887 error: `deploy failed: ${error instanceof Error ? error.message : String(error)}`,
@@ -994,6 +1013,7 @@ export class AppsRuntime {
9941013 run: Run,
9951014 write: (line: string) => void,
9961015 signal: AbortSignal,
1016 clock: Stopwatch,
9971017 ): Promise<
9981018 | { ok: true; value: Live; tested: Promise<Result<void, string>> }
9991019 | { ok: false; error: string }
@@ -1004,6 +1024,7 @@ export class AppsRuntime {
10041024 readFileAt(bare, run.commitOid, "package.json"),
10051025 ]);
10061026 const manifest = parseManifest(forgeJson, packageJson);
1027 clock.lap("manifest");
10071028 if (!manifest.ok) {
10081029 return {
10091030 ok: false,
@@ -1027,6 +1048,7 @@ export class AppsRuntime {
10271048 const exported = await exportTree(bare, run.commitOid, dir);
10281049 if (!exported.ok) return { ok: false, error: exported.error };
10291050 }
1051 clock.lap(warm ? "checkout (warm)" : "checkout");
10301052
10311053 const seeded = ensureEnvData(
10321054 this.app.config.dataDir,
@@ -1043,6 +1065,7 @@ export class AppsRuntime {
10431065 write(`data: ${seeded} from production`);
10441066 else if (seeded === "empty" && state.env !== "production")
10451067 write("data: starting empty");
1068 clock.lap("data");
10461069
10471070 // The process's own credential; every way out of here without a
10481071 // process to hold it revokes it.
@@ -1074,6 +1097,8 @@ export class AppsRuntime {
10741097 log: write,
10751098 warm,
10761099 };
1100 clock.lap("setup");
1101 write(clock.line("starting the process"));
10771102 const start = async (): ReturnType<typeof startProcess> => {
10781103 try {
10791104 return await startProcess({ ...startInput, signal });
src/apps/timing.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * Where a deploy's time went, step by step, in the words its log uses.
3 *
4 * A deploy is a short line of steps — a turn at the gate, reading the
5 * manifest, the checkout, the data, then the process — and the one number
6 * the log used to print ("serving … 21.8s after the deploy started") cannot
7 * say which of them held it. A stopwatch takes a lap at the end of each
8 * step and prints them all on one `timing:` line, so a slow start is
9 * attributed rather than guessed.
10 */
11
12 /** Seconds to one decimal place: `3.4s`. */
13 export const seconds = (ms: number): string =>
14 `${(Math.max(0, ms) / 1000).toFixed(1)}s`;
15
16 export class Stopwatch {
17 private readonly from: number;
18 private last: number;
19 private readonly laps: { name: string; ms: number }[] = [];
20
21 constructor(private readonly now: () => number = Date.now) {
22 this.from = now();
23 this.last = this.from;
24 }
25
26 /** End the step called `name`: it took the time since the previous lap. */
27 lap(name: string): void {
28 const at = this.now();
29 this.laps.push({ name, ms: at - this.last });
30 this.last = at;
31 }
32
33 /** Milliseconds since the stopwatch started. */
34 elapsed(): number {
35 return this.now() - this.from;
36 }
37
38 /**
39 * `timing: <what> 0.4s after the deploy started — turn 0.0s · checkout
40 * 0.3s · …`, every lap so far in the order it was taken.
41 */
42 line(what: string): string {
43 const steps = this.laps.map((l) => `${l.name} ${seconds(l.ms)}`).join(" · ");
44 return `timing: ${what} ${seconds(this.elapsed())} after the deploy started${steps === "" ? "" : ` — ${steps}`}`;
45 }
46 }
src/git/env.ts +22 −7
@@ -87,16 +87,23 @@ export function trustedCaBundle(
8787 * FIFO on purpose: LIFO would be marginally better for cache locality and
8888 * catastrophically worse for fairness, which is the entire point — the
8989 * request that has waited longest goes next, so a burst degrades everyone's
90 * latency a little rather than starving somebody forever.
90 * latency a little rather than starving somebody forever. The one
91 * exception is asked for by name (`first`), and is FIFO among itself.
9192 */
9293 export class Gate {
9394 private active = 0;
94 private readonly waiting: (() => void)[] = [];
95 private readonly waiting: { wake: () => void; first: boolean }[] = [];
9596 private peak = 0;
9697
9798 constructor(readonly limit: number) {}
9899
99 async acquire(): Promise<() => void> {
100 /**
101 * Take a permit, waiting for one if none is free. `first` waits ahead of
102 * everyone who is not — still FIFO among its own kind, so it can jump a
103 * queue but never starve another `first` — which is how a production
104 * deploy gets the next permit while previews are waiting.
105 */
106 async acquire(options: { first?: boolean } = {}): Promise<() => void> {
100107 if (this.active < this.limit) {
101108 this.active++;
102109 } else {
@@ -105,7 +112,12 @@ export class Gate {
105112 // changes owner. Decrementing first would open a window in which a
106113 // caller arriving synchronously slips in ahead of the queue and the
107114 // limit is briefly exceeded — a semaphore that is only usually one.
108 await new Promise<void>((resolve) => this.waiting.push(resolve));
115 const first = options.first === true;
116 await new Promise<void>((wake) => {
117 const behind = first ? this.waiting.findIndex((w) => !w.first) : -1;
118 if (behind === -1) this.waiting.push({ wake, first });
119 else this.waiting.splice(behind, 0, { wake, first });
120 });
109121 }
110122 if (this.active > this.peak) this.peak = this.active;
111123 let released = false;
@@ -115,14 +127,17 @@ export class Gate {
115127 if (released) return;
116128 released = true;
117129 const next = this.waiting.shift();
118 if (next !== undefined) next();
130 if (next !== undefined) next.wake();
119131 else this.active--;
120132 };
121133 }
122134
123135 /** Run `work` holding one permit, released however it ends. */
124 async run<T>(work: () => Promise<T>): Promise<T> {
125 const release = await this.acquire();
136 async run<T>(
137 work: () => Promise<T>,
138 options: { first?: boolean } = {},
139 ): Promise<T> {
140 const release = await this.acquire(options);
126141 try {
127142 return await work();
128143 } finally {
src/web/client.ts +1 −1
@@ -187,7 +187,7 @@ const elapsedTickJs = /* js */ `
187187 `;
188188
189189 const logLineJs = /* js */ `
190 var FORGE = /^(claude:|done:|failed:|paused|declined:|cloning |branch |forked |pushing |push refused|clone kept|nothing to propose|opened pull|updated pull|committed the|could not|checking out|deploy |data: |\\$ |session |the session|interrupted|passed in|install |test |start |ready |process )/;
190 var FORGE = /^(claude:|done:|failed:|paused|declined:|cloning |branch |forked |pushing |push refused|clone kept|nothing to propose|opened pull|updated pull|committed the|could not|checking out|deploy |data: |\\$ |session |the session|interrupted|passed in|install |test |start |ready |process |timing: )/;
191191 function line(kind, speaker, fill) {
192192 var el = document.createElement('div');
193193 el.className = 'ln ln-' + kind;
src/web/pages/runs.ts +1 −1
@@ -114,7 +114,7 @@ export const costText = (usd: number): string => `$${usd.toFixed(2)}`;
114114 export type LineKind = "tool" | "forge" | "say" | "you";
115115
116116 const FORGE_LINE =
117 /^(claude:|done:|failed:|paused|declined:|cloning |branch |forked |pushing |push refused|clone kept|nothing to propose|opened pull|updated pull|committed the|could not|checking out|deploy |data: |\$ |session |the session|interrupted|passed in|install |test |start |ready |process )/;
117 /^(claude:|done:|failed:|paused|declined:|cloning |branch |forked |pushing |push refused|clone kept|nothing to propose|opened pull|updated pull|committed the|could not|checking out|deploy |data: |\$ |session |the session|interrupted|passed in|install |test |start |ready |process |timing: )/;
118118
119119 export function lineKind(line: string): LineKind {
120120 if (line.startsWith("→ ")) return "tool";
test/agents.test.ts +27
@@ -837,6 +837,33 @@ describe("git process limits and timeouts", () => {
837837 expect(order).toEqual([1, 2, 3]);
838838 });
839839
840 test("a `first` waiter goes ahead of the others, and FIFO among its own kind", async () => {
841 const gate = new Gate(1);
842 const order: string[] = [];
843 const held = await gate.acquire();
844 const waiters = (
845 [
846 ["preview-1", false],
847 ["production-a", true],
848 ["preview-2", false],
849 ["production-b", true],
850 ] as const
851 ).map(async ([name, first]) => {
852 const release = await gate.acquire({ first });
853 order.push(name);
854 release();
855 });
856 held();
857 await Promise.all(waiters);
858 expect(order).toEqual([
859 "production-a",
860 "production-b",
861 "preview-1",
862 "preview-2",
863 ]);
864 expect(gate.stats().active).toBe(0);
865 });
866
840867 test("concurrent git reads never exceed the process cap", async () => {
841868 const dataDir = await mkdtemp(join(tmpdir(), "forge-gate-"));
842869 try {
test/apps-boot.test.ts added +169
@@ -0,0 +1,169 @@
1 /**
2 * A restart brings production back first, and says where each deploy's
3 * time went (issue #296): every app's production is reconciled before any
4 * preview, and the log names the wait for a turn, the manifest, the
5 * checkout, the data and the process's own start, each with its seconds.
6 */
7 import { afterAll, beforeAll, describe, expect, 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 { enableApp } from "../src/actions/apps.ts";
13 import { openPull } from "../src/actions/pulls.ts";
14 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
15 import { AppsRuntime } from "../src/apps/runtime.ts";
16 import { seconds, Stopwatch } from "../src/apps/timing.ts";
17 import type { Repo } from "../src/core/repos.ts";
18 import { listRuns, type Run } from "../src/core/runs.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { readRunLog } from "../src/runs/log.ts";
22
23 describe("the stopwatch a deploy's log reads from", () => {
24 test("each lap is the time since the one before, in order, on one line", () => {
25 let now = 1_000;
26 const clock = new Stopwatch(() => now);
27 now += 0; // no wait for a turn
28 clock.lap("turn");
29 now += 340;
30 clock.lap("checkout");
31 now += 20_060;
32 clock.lap("data");
33 expect(clock.elapsed()).toBe(20_400);
34 expect(clock.line("starting the process")).toBe(
35 "timing: starting the process 20.4s after the deploy started — turn 0.0s · checkout 0.3s · data 20.1s",
36 );
37 });
38
39 test("seconds never go negative, and round to a tenth", () => {
40 expect(seconds(-5)).toBe("0.0s");
41 expect(seconds(1_250)).toBe("1.3s");
42 });
43 });
44
45 describe("a restart brings every app's production up before any preview", () => {
46 let dataDir: string;
47 let app: App;
48 let servers: Servers;
49 let runtime: AppsRuntime;
50 let alice: User;
51 const DOMAIN = "boot.test";
52 const repos: Repo[] = [];
53 const previews: string[] = [];
54
55 // No package.json, so a checkout is never warm and a preview is never
56 // put back to sleep at boot: every environment deploys again.
57 const FORGE_JSON = JSON.stringify({
58 app: { run: "sh run.sh", install: "", health: "/", ready: 10 },
59 });
60 const RUN_SH = `exec bun -e "Bun.serve({port:Number(process.env.PORT),hostname:'127.0.0.1',fetch:()=>new Response('ok')})"\n`;
61
62 const runtimeFor = (): AppsRuntime =>
63 new AppsRuntime(app, {
64 domain: DOMAIN,
65 scheme: "http",
66 publicPort: servers.port,
67 forgeUrl: servers.url,
68 // One permit: the order the gate hands them out is the order the
69 // environments come up, and that order is the assertion.
70 concurrency: 1,
71 });
72
73 async function settledAll(
74 where: (run: Run) => boolean,
75 count: number,
76 ): Promise<Run[]> {
77 const deadline = Date.now() + 60_000;
78 while (Date.now() < deadline) {
79 const runs = repos
80 .flatMap((r) => listRuns(app.db, r.id, { kind: "deploy", limit: 50 }))
81 .filter(where);
82 if (
83 runs.length >= count &&
84 runs.every((r) => r.state === "ok" || r.state === "failed")
85 )
86 return runs;
87 await Bun.sleep(50);
88 }
89 throw new Error("runs did not settle in time");
90 }
91
92 beforeAll(async () => {
93 dataDir = await mkdtemp(join(tmpdir(), "forge-boot-"));
94 app = createApp({ dataDir, port: 0 });
95 servers = await serve(app);
96 runtime = runtimeFor();
97 await runtime.start();
98 const created = await createUser(app.db, {
99 username: "alice",
100 email: "[email protected]",
101 password: "a-good-passphrase",
102 adminIfFirst: true,
103 });
104 if (!created.ok) throw new Error(created.error);
105 alice = created.value;
106 for (const name of ["first", "second"]) {
107 const made = await createRepo(app, alice, {
108 name,
109 visibility: "public",
110 });
111 if (!made.ok) throw new Error(String(made.error));
112 const repo = made.value;
113 repos.push(repo);
114 const committed = await commitToBranch(app, alice, repo, {
115 message: "An app",
116 files: [
117 { path: "forge.json", content: FORGE_JSON },
118 { path: "run.sh", content: RUN_SH },
119 ],
120 });
121 if (!committed.ok) throw new Error(JSON.stringify(committed.error));
122 const enabled = enableApp(app, alice, repo, {});
123 if (!enabled.ok) throw new Error(String(enabled.error));
124 const branch = await commitToBranch(app, alice, repo, {
125 branch: "note",
126 base: repo.defaultBranch,
127 message: "A note",
128 files: [{ path: "NOTE.md", content: "hi\n" }],
129 });
130 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
131 const opened = await openPull(app, alice, repo, {
132 title: "A note",
133 baseBranch: repo.defaultBranch,
134 headBranch: "note",
135 });
136 if (!opened.ok) throw new Error(String(opened.error));
137 previews.push(`pull-${opened.value.number}`);
138 }
139 await settledAll(() => true, 4);
140 }, 90_000);
141
142 afterAll(async () => {
143 await runtime.stop();
144 servers.stop();
145 app.close();
146 await rm(dataDir, { recursive: true, force: true });
147 });
148
149 test("both productions answer before either preview, and the log says where the time went", async () => {
150 await runtime.stop();
151 runtime = runtimeFor();
152 await runtime.start();
153 const boot = await settledAll((r) => r.reason === "boot", 4);
154 expect(boot.every((r) => r.state === "ok")).toBe(true);
155 const order = [...boot]
156 .sort((a, b) => Date.parse(a.servingAt!) - Date.parse(b.servingAt!))
157 .map((r) => (r.env === "production" ? "production" : "preview"));
158 expect(order).toEqual(["production", "production", "preview", "preview"]);
159
160 const production = boot.find((r) => r.env === "production")!;
161 const text = readRunLog(dataDir, production.id).lines.join("\n");
162 expect(text).toMatch(
163 /timing: starting the process \d+\.\ds after the deploy started — turn \d+\.\ds · manifest \d+\.\ds · checkout \d+\.\ds · data \d+\.\ds · setup \d+\.\ds/,
164 );
165 expect(text).toMatch(
166 /timing: answered \d+\.\ds after the process was started/,
167 );
168 }, 90_000);
169 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs