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

A woken cell starts in seconds and on the release that is serving #16481

Merged opened this

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

Merged

sold/wake-fix → main 0 commits 2 threads · 2 unresolved

  • Merged. sold/wake-fix was merged into main as 0bc75f9.

Review

Sign in to review this change.
5 files changed +113 −15
src/runs/peer.ts +17 −2
@@ -17,6 +17,7 @@
1717
1818 import type { Database } from "bun:sqlite";
1919 import type { Log } from "../kernel/log.ts";
20 import { SIZE_ENV } from "../spawn/usage.ts";
2021 import { HEARTBEAT_MS, heldRuns } from "./lease.ts";
2122
2223 /** Two renewals missed: the lease is not being kept. */
outdated

Duplicate of SIZE_ENV in src/spawn/usage.ts. Import it, or share it from a leaf module.

@@ -29,6 +30,19 @@ export const PEER_WAIT_MAX_MS = 720_000;
2930 */
3031 const POLL_MS = 1_000;
3132
33 /**
34 * A cell is a child forge its parent stops and starts on its own data; a predecessor that is gone
35 * stops renewing within one fresh window, so a cell waits that long for it, not for the pod's
36 * grace (a woken cell took four minutes to ready its crew on 2026-11-25).
37 */
38 export const CELL_PEER_WAIT_MAX_MS = PEER_FRESH_MS;
39
40 /** How long this process holds its boot for a peer: the pod's grace, or a cell's one window. */
41 export function peerWaitCeiling(env: Readonly<Record<string, string | undefined>> = process.env): number {
42 const cell = env[SIZE_ENV];
43 return cell !== undefined && cell !== "" ? CELL_PEER_WAIT_MAX_MS : PEER_WAIT_MAX_MS;
44 }
45
3246 /** Running runs whose lease another process renewed within `PEER_FRESH_MS` of `now`. */
3347 export function peerRuns(db: Database, now = Date.now()): number {
3448 const here = heldRuns(db);
@@ -52,17 +66,18 @@ export type PeerOutcome = "alone" | "gone" | "waited out";
5266 export async function waitForPeer(db: Database, log: Log, opts: PeerWait = {}): Promise<PeerOutcome> {
5367 const now = opts.now ?? Date.now;
5468 const sleep = opts.sleep ?? Bun.sleep;
55 const maxMs = opts.maxMs ?? PEER_WAIT_MAX_MS;
69 const maxMs = opts.maxMs ?? peerWaitCeiling();
5670 const started = now();
5771 let live = peerRuns(db, started);
5872 if (live === 0) return "alone";
5973 log.warn("another forge still works this database: this one serves, and starts its own work once it lets go", {
6074 runs: live,
75 cell: maxMs < PEER_WAIT_MAX_MS,
6176 maxSeconds: Math.round(maxMs / 1000),
6277 });
6378 while (live > 0) {
6479 if (now() - started >= maxMs) {
65 log.warn("another forge still works this database; starting beside it", { runs: live });
80 log.warn("another forge still works this database; starting beside it", { runs: live, waitedSeconds: Math.round((now() - started) / 1000) });
6681 return "waited out";
6782 }
6883 await sleep(opts.pollMs ?? POLL_MS);
src/spawn/cell.ts +21 −11
@@ -9,6 +9,7 @@
99 */
1010
1111 import { namedRunner } from "../crew/runner_env.ts";
12 import { existsSync } from "node:fs";
1213 import { tmpdir } from "node:os";
1314 import { dirname, join } from "node:path";
1415 import { clientAddress, namesClient, nameClient } from "../http/peer.ts";
@@ -18,6 +19,8 @@ import { cellsAvailable, commandPid, killTree, openCell, type Cell, type CellSpe
1819 import { childEnv, freePort, lineCutter } from "../apps/process.ts";
1920 import { childCommand } from "../settings/child_heap.ts";
2021 import { childDirOf } from "../actions/spawn.ts";
22 import { releaseDir } from "../release/checkout.ts";
23 import { alive, readServing } from "../release/serving.ts";
2124 import { openBeatDoor, parentLocal, type BeatDoor } from "./beat-door.ts";
2225 import { hostedPlacement, parentOrigin, childPublicUrl, type BodyStore, type Placement } from "./placement.ts";
2326 import { SIZE_IO, SIZES, type Size } from "./sizes.ts";
@@ -100,15 +103,6 @@ export async function stopGently(child: { readonly pid: number; readonly exited:
100103 await child.exited;
101104 }
102105
103 function alive(pid: number): boolean {
104 try {
105 process.kill(pid, 0);
106 return true;
107 } catch {
108 return false;
109 }
110 }
111
112106 /** A forge started within this long is not put to sleep by the idle sweep (#11155). */
113107 export const NEW_FORGE_MS = 10 * 60_000;
114108
@@ -118,6 +112,20 @@ export const START_BACKOFF_MS = 30_000;
118112 const MAIN = join(import.meta.dir, "..", "main.ts");
119113 const CODE = join(import.meta.dir, "..", "..");
120114
115 /**
116 * The tree the parent serves from now. A release swap starts the new tree from `releases/<sha>/`
117 * and names it in `release/serving.json`; a cell woken after that runs that tree, not the paths
118 * this process was loaded from (the old release's, while it drains). Today's paths when no swap
119 * has named one, its process is gone, or its tree is not there.
120 */
121 export function servingTree(dataDir: string, own: { main: string; root: string } = { main: MAIN, root: CODE }): { main: string; root: string; sha?: string } {
122 const s = readServing(dataDir);
123 if (s === undefined || !alive(s.pid)) return own;
124 const root = releaseDir(dataDir, s.sha);
125 const main = join(root, "src", "main.ts");
126 return existsSync(main) ? { main, root, sha: s.sha } : own;
127 }
128
121129 /** A size's limits as a cell holds them. */
122130 export function cellLimits(size: Size): Limits {
123131 const s = SIZES[size];
@@ -259,6 +267,8 @@ export interface Stamp {
259267 }
260268
261269 export function stampFor(source: Pick<CodeSource, "kind" | "commit">, parent: Running = running()): Stamp {
270 // The parent's tree from a swapped release: that commit, and no version this process does not run.
271 if (source.kind === "parent" && source.commit !== undefined && source.commit !== parent.commit) return { commit: source.commit };
262272 if (source.kind === "parent") return { ...(parent.version === UNSTAMPED ? {} : { version: parent.version }), ...(parent.commit === null ? {} : { commit: parent.commit }) };
263273 return source.commit === undefined || source.commit === "" ? {} : { commit: source.commit };
264274 }
@@ -542,7 +552,7 @@ export function makeRegistry(parent: App, launcher?: Launcher): CellChildren {
542552 const url = childPublicUrl(input.name, parentOrigin(parent.config));
543553 const door = openBeatDoor(parent);
544554 const parentPort = door.port;
545 const spec = launchSpecFor(parent, input, { port, parentPort }, undefined, source.kind === "parent" ? undefined : source.root);
555 const spec = launchSpecFor(parent, input, { port, parentPort }, undefined, source.kind === "parent" && source.root === CODE ? undefined : source.root);
546556 const heard = childLog((line) => parent.log.info("child forge", { name: input.name, line }));
547557 const log = (raw: string): void => {
548558 const line = plainLine(raw);
@@ -615,7 +625,7 @@ export function makeRegistry(parent: App, launcher?: Launcher): CellChildren {
615625 // The parent decides what the cell runs: its own code, the last that came up, or the parent's
616626 // (`own_code.ts`).
617627 const started = await oneAtATime(parent, input.name, async () => {
618 const sources = await sourcesFor(parent, { name: input.name, childDir: childDirOf(parent, input.bodyId) }, { main: MAIN, root: CODE });
628 const sources = await sourcesFor(parent, { name: input.name, childDir: childDirOf(parent, input.bodyId) }, servingTree(parent.config.dataDir));
619629 return startFirstThatWorks(parent, input.name, sources, (source) => startOn(input, source));
620630 });
621631 if ("why" in started) {
src/spawn/own_code.ts +2 −2
@@ -407,9 +407,9 @@ export function recordGood(app: App, name: string, commit: string): void {
407407 export async function sourcesFor(
408408 app: App,
409409 input: { readonly name: string; readonly childDir: string },
410 parent: { readonly main: string; readonly root: string },
410 parent: { readonly main: string; readonly root: string; readonly sha?: string },
411411 ): Promise<CodeSource[]> {
412 const fallback: CodeSource = { kind: "parent", ...parent };
412 const fallback: CodeSource = { kind: "parent", main: parent.main, root: parent.root, ...(parent.sha === undefined ? {} : { commit: parent.sha }) };
413413 const state = readOwnCode(app, input.name);
414414 const repo = ownRepoOf(input.childDir);
415415 if (!state.on || repo === undefined) return [fallback];
test/wake-peer-cap.test.ts added +33
@@ -0,0 +1,33 @@
1 import { Database } from "bun:sqlite";
2 import { expect, test } from "bun:test";
3 import { createLog } from "../src/kernel/log.ts";
4 import { CELL_PEER_WAIT_MAX_MS, PEER_FRESH_MS, PEER_WAIT_MAX_MS, peerWaitCeiling, waitForPeer } from "../src/runs/peer.ts";
5
6 test("a cell waits one heartbeat window for a predecessor; the parent keeps the pod's grace", () => {
7 expect(peerWaitCeiling({})).toBe(PEER_WAIT_MAX_MS);
8 expect(peerWaitCeiling({ FORGE_CELL_SIZE: "small" })).toBe(CELL_PEER_WAIT_MAX_MS);
9 expect(CELL_PEER_WAIT_MAX_MS).toBe(PEER_FRESH_MS);
10 });
11
12 test("a cell's wait ends at its ceiling while a peer keeps its run fresh", async () => {
13 const prior = process.env["FORGE_CELL_SIZE"];
14 process.env["FORGE_CELL_SIZE"] = "small";
15 try {
16 const db = new Database(":memory:");
17 db.run("CREATE TABLE run (id TEXT PRIMARY KEY, state TEXT, heartbeat_at TEXT)");
18 let clock = 1_000_000;
19 db.run("INSERT INTO run VALUES ('r1','running',?1)", [new Date(clock).toISOString()]);
20 const out = await waitForPeer(db, createLog("peer-test"), {
21 now: () => clock,
22 sleep: async (ms) => {
23 clock += ms;
24 db.run("UPDATE run SET heartbeat_at = ?1", [new Date(clock).toISOString()]);
25 },
26 });
27 expect(out).toBe("waited out");
28 expect(clock - 1_000_000).toBeLessThanOrEqual(CELL_PEER_WAIT_MAX_MS + 1_000);
29 } finally {
30 if (prior === undefined) delete process.env["FORGE_CELL_SIZE"];
31 else process.env["FORGE_CELL_SIZE"] = prior;
32 }
33 });
test/wake-serving-tree.test.ts added +40
@@ -0,0 +1,40 @@
1 import { expect, test } from "bun:test";
2 import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { servingTree, stampFor } from "../src/spawn/cell.ts";
6
7 const own = { main: "/old/src/main.ts", root: "/old" };
8 const sha = "a".repeat(40);
9
10 function data(serving?: { pid: number; sha: string }, tree = true): string {
11 const dir = mkdtempSync(join(tmpdir(), "wake-"));
12 if (serving) {
13 mkdirSync(join(dir, "release"), { recursive: true });
14 writeFileSync(join(dir, "release", "serving.json"), JSON.stringify(serving));
15 }
16 if (tree) {
17 mkdirSync(join(dir, "releases", sha, "src"), { recursive: true });
18 writeFileSync(join(dir, "releases", sha, "src", "main.ts"), "");
19 }
20 return dir;
21 }
22
23 test("a waking cell reads the tree the swapped release serves from", () => {
24 const dir = data({ pid: process.pid, sha });
25 const t = servingTree(dir, own);
26 expect(t.root).toBe(join(dir, "releases", sha));
27 expect(t.main).toBe(join(dir, "releases", sha, "src", "main.ts"));
28 expect(t.sha).toBe(sha);
29 });
30
31 test("with no swap named, a dead server, or no tree, today's paths stand", () => {
32 expect(servingTree(data(), own)).toEqual(own);
33 expect(servingTree(data({ pid: 2 ** 22 + 12345, sha }), own)).toEqual(own);
34 expect(servingTree(data({ pid: process.pid, sha }, false), own)).toEqual(own);
35 });
36
37 test("a cell on a swapped release's tree is stamped with that commit, not the old version", () => {
38 expect(stampFor({ kind: "parent", commit: sha }, { version: "0.7.1", commit: "b".repeat(40) })).toEqual({ commit: sha });
39 expect(stampFor({ kind: "parent", commit: sha }, { version: "0.7.1", commit: sha })).toEqual({ version: "0.7.1", commit: sha });
40 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs