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

main.ts imports each background service when it starts it, after ready, not at boot #17164

opened this

Check · Review · Land · Live — Its check is queued. Next: reviewer, pushed since the last review.

Ready to land

scout/forge:scout/17021-main-ts-imports-each-background-service → main 7 commits fork 2 threads · 2 unresolved

Review

Sign in to review this change.
6 files changed +301 −159
scripts/gate.ts +1
@@ -54,6 +54,7 @@ export const SLOW: readonly Exclusion[] = [
5454 { file: "test/shared-density.test.ts", reason: "spawns a fresh bun child that loads the whole app and makes forges to read its own RSS; 2 s alone, 2.3 s a test under full-suite load", issue: 16857 },
5555 { file: "test/bundle-boot.test.ts", reason: "bundles src/main.ts with bun build --minify and boots the one file with no source beside it; 2.6 s a test under full-suite load", issue: 16853 },
5656 { file: "test/boot-idle-memory.test.ts", reason: "boots the real src/main.ts and waits real seconds for its RSS to settle; 8.6 s a test", issue: 16851 },
57 { file: "test/boot-lazy.test.ts", reason: "imports the whole MCP module and its tools to compare their routes with the lazy list; 2.2 s alone, 2.5 s under full-suite load", issue: 17021 },
5758 { file: "test/landsim.test.ts", reason: "runs seeded landing simulations over real repositories and queues; 16 s a file alone, 28.8 s and 2.8 s a test under full-suite load", issue: 13765 },
5859 { file: "test/propose-via-fork.test.ts", reason: "runs two real forges and a fake origin, each test pushing real git branches through a fork; 11 s a file alone, 23.9 s and 4.4 s a test under full-suite load", issue: 15193 },
5960 { file: "test/red-on-main.test.ts", reason: "runs test-shards.ts end to end in a scratch git repository, twice over main and the pull; 6.4 s a test under full-suite load", issue: 15319 },
src/kernel/start_service.ts added +33
@@ -0,0 +1,33 @@
1 /**
2 * A background service main.ts imports after the listener answers (#17021): its import and its
3 * start are caught here, so a module that cannot load or a start that throws leaves that one
4 * service off, said once, and the forge stays up. A static import failed before the listener
5 * opened; a lazy one must not take a serving forge dark.
6 */
7 import type { Log } from "./log.ts";
8
9 /**
10 * Load what `load` imports; on a throw, say which and give `undefined`.
11 */
12 export async function loadOrNone<T>(log: Pick<Log, "error">, name: string, load: () => Promise<T>): Promise<T | undefined> {
13 try {
14 return await load();
15 } catch (error) {
16 log.error("background service did not start", { service: name, error: String(error) });
17 return undefined;
18 }
19 }
20
21 /**
22 * Import and start one service: its handle, or `undefined` when it is off or failed. A service
23 * that started says so in its own line, `background service started service=<name>`.
24 */
25 export async function startService<H>(
26 log: Pick<Log, "info" | "error">,
27 name: string,
28 start: () => Promise<H | undefined>,
29 ): Promise<H | undefined> {
30 const handle = await loadOrNone(log, name, start);
31 if (handle !== undefined) log.info("background service started", { service: name });
32 return handle;
33 }
src/main.ts +173 −157
@@ -19,9 +19,7 @@ import { meterOf, sampleCompute } from "./core/run_compute.ts";
1919 import { BATCH_EVERY_MS, ledgerGitTick } from "./core/ledger_git.ts";
2020 import { getRepoById } from "./core/repos.ts";
2121 import { BOOT_ACTOR, setSignup, signupFromEnv } from "./settings/signup.ts";
22 import { startMemorySampler } from "./boards/memory.ts";
2322 import { startHeapCapture } from "./perf/heap_capture.ts";
24 import { startSampler } from "./boards/sampler.ts";
2523 import { sweepStanding } from "./crew/standing.ts";
2624 import { drainOnHandover, handover } from "./release/swap.ts";
2725 import { parentUrlProblem } from "./core/parent_releases.ts";
@@ -64,60 +62,35 @@ import { runGuardSweep } from "./origins/credential.ts";
6462 import { warmHome } from "./web/pages/home_flow.ts";
6563 import { warmPlans } from "./web/pages/milestones.ts";
6664 import { warmBoards } from "./web/pages/boards-view.ts";
67 import { AppsRuntime, IDLE_PULL_DAYS } from "./apps/runtime.ts";
6865 import { previewIdleMs } from "./apps/sleep_window.ts";
6966 import { UPSTREAM_WAIT_MS } from "./apps/upstream_wait.ts";
7067 import { listApps } from "./core/apps.ts";
7168 import { holdAppHosts, releaseAppHosts } from "./apps/holding.ts";
7269 import { resolveAppDomain } from "./apps/host.ts";
73 import { LAND_SETTLE_MS, requeueAbandonedChecks, startChecks } from "./checks/service.ts";
74 import { rearmRelease } from "./checks/landing.ts";
7570 import { VERIFY_EVERY_MS } from "./checks/verify.ts";
7671 import { RED_HOLD_MS } from "./checks/red_main.ts";
77 import { stopQueue } from "./checks/queue.ts";
7872 import { placementFromEnv } from "./checks/placement.ts";
79 import { localPoolSize, startLocalPool } from "./checks/runner_pool.ts";
8073 import { memoryLimitBytes } from "./system/memory_limit.ts";
8174 import { cpuLimit } from "./core/capacity.ts";
82 import { startLooks } from "./looks/service.ts";
83 import { watchTalkLive } from "./actions/talk_live.ts";
84 import { startMaintain } from "./maintain/runner.ts";
85 import { startMirrorOut } from "./origins/mirror-out.ts";
86 import { startMirrorPulls } from "./origins/mirror-pulls.ts";
87 import { startProbes } from "./contract/probes.ts";
88 import { startDatasetNightly } from "./actions/dataset.ts";
89 import { startRoutines } from "./crew/routines.ts";
90 import { startNightly } from "./nightly/service.ts";
91 import { startSnapshots } from "./snapshot/service.ts";
92 import { resolveSnapshots } from "./snapshot/destination.ts";
93 import { resolveMirror } from "./snapshot/mirror.ts";
9475 import { releaseOrphans } from "./core/run_secret.ts";
9576 import { failAbandonedRuns } from "./core/runs.ts";
9677 import { settleLandings } from "./core/landing.ts";
9778 import { DRAIN_LINGER_MAX_S, drainLingerMs, startDraining } from "./http/health.ts";
9879 import { takePresence, warmBehind } from "./apps/presence.ts";
9980 import { STALE_AFTER_MS } from "./runs/lease.ts";
100 import { runnerSettings, startCrew, sweepAssigned } from "./crew/dispatch.ts";
101 import { configureConversation, expectConversation, forgetConversation, resumeInterrupted, turnLive } from "./crew/conversation.ts";
10281 import { sandboxMode } from "./crew/sandbox_policy.ts";
10382 import { CREW_OFF_IN_PREVIEW, crewOffInPreview } from "./crew/preview.ts";
10483 import { typeSafeDecider } from "./crew/decide.ts";
10584 import { graphInstagram } from "./crew/instagram.ts";
10685 import { peopleOnCrews } from "./core/agents.ts";
107 import { startNotifier } from "./crew/notify.ts";
10886 import { tailEvents } from "./core/event_tail.ts";
10987 import { engineChoice, readMachine, shapeWords } from "./engine/mode.ts";
11088 import { runSplit, tuneForSplit } from "./engine/run.ts";
111 import { startDuties } from "./engine/duties.ts";
112 import { startRetention } from "./system/retention.ts";
11389 import { compactOnBoot } from "./system/compact.ts";
114 import { startClogTick } from "./flow/clog_tick.ts";
11590 import { resumeAtBoot } from "./maintenance/service.ts";
116 import { startKeeper } from "./flow/keeper.ts";
11791 import { failStaleSnapshots } from "./core/snapshots.ts";
11892 import { sweepStaleAsks } from "./crew/stale_asks.ts";
11993 import { recordAskLedger } from "./web/studio/asks.ts";
120 import { startPromptRoutine } from "./crew/prompts.ts";
12194 import { configProblem, dataDirOf, preflight } from "./kernel/preflight.ts";
12295 import { running } from "./kernel/version.ts";
12396 import { record as recordDegraded } from "./kernel/degraded_history.ts";
@@ -136,9 +109,6 @@ import { readLandings } from "./release/landings.ts";
136109 import { ownTagsReader } from "./release/own_tags.ts";
137110 import { recordByHand } from "./keeper/by_hand.ts";
138111 import { settleLiveNow } from "./actions/estimates_settle.ts";
139 import { rollProbe, tickStep as keeperTick } from "./keeper/keeper.ts";
140 import { startHostedTick, stepWithBeat } from "./keeper/beat.ts";
141 import { keeperEnv, keeperPorts } from "./keeper/wire.ts";
142112 import { noteKeeperAtBoot } from "./keeper/at_boot.ts";
143113 import { snapshotPlace } from "./actions/health.ts";
144114 import { dropServed, useSleepers } from "./spawn/clients.ts";
@@ -155,6 +125,7 @@ import { census, censusWords, processRows } from "./kernel/census.ts";
155125 import { reapLeftoverBridges } from "./crew/leftovers.ts";
156126 import { crewRoot } from "./crew/workdir.ts";
157127 import { createLog } from "./kernel/log.ts";
128 import { loadOrNone, startService } from "./kernel/start_service.ts";
158129 import { METER_EVERY_MS, newMeterWatch } from "./crew/meter_watch.ts";
159130 import { watchStalls } from "./kernel/loop_lag.ts";
160131 import { createStallRelay } from "./kernel/stall_relay.ts";
@@ -618,9 +589,14 @@ keepFloor(limitValue(app.db, "forge.memory_floor_mb"), (line) => app.log.info(li
618589 // One crew run's length: what a run takes, and how long past its idle
619590 // window an app busy with one is left awake.
620591 const crewRunMs = positive(process.env.FORGE_CREW_TIMEOUT_MIN, 45) * 60_000;
621 const apps = appDomain?.ok
622 ? new AppsRuntime(app, {
623 domain: appDomain.domain,
592 // Each background service is imported here, after the listener answers, not at the top of the boot
593 // (#17021), and through `startService`: one that cannot load or start is off, said once, and the
outdated

The fallback IDLE_PULL_DAYS: 0 is a fake value that would be wrong if it were ever used. Import it where it is needed, and keep one path.

594 // forge stays up.
595 const appsDomain = appDomain?.ok ? appDomain.domain : undefined;
596 const apps = appsDomain === undefined ? undefined : await startService(app.log, "apps", async () => {
597 const { AppsRuntime, IDLE_PULL_DAYS } = await import("./apps/runtime.ts");
598 return new AppsRuntime(app, {
599 domain: appsDomain,
624600 scheme: publicUrl.protocol === "https:" ? "https" : "http",
625601 publicPort:
626602 publicUrl.port === ""
@@ -638,8 +614,8 @@ const apps = appDomain?.ok
638614 // Days a pull may sit untouched before its preview sleeps; 0 keeps
639615 // every preview warm. Unset follows the profit slider, live.
640616 idlePullMs: previewIdleMs(process.env.FORGE_PREVIEW_IDLE_DAYS, IDLE_PULL_DAYS),
641 })
642 : undefined;
617 });
618 });
643619 // Which other forge serves this data's apps, read before this one starts its own.
644620 const presence = apps ? takePresence(app.config.dataDir) : undefined;
645621 // The runtime is registered by its constructor: app hosts stop waiting now,
@@ -675,7 +651,8 @@ const earlySignals = ["SIGINT", "SIGTERM", "SIGHUP"] as const;
675651 for (const signal of earlySignals) process.once(signal, leaveEarly);
676652 // Talk answers while this forge waits for the one it replaces and probes its runner: a message is
677653 // kept, and the person is told the forge is starting (crew/conversation.ts, `startingIn`).
678 if (appsOn && !crewOffInPreview()) expectConversation(app);
654 const conversationModule = await loadOrNone(app.log, "conversation", () => import("./crew/conversation.ts"));
655 if (appsOn && !crewOffInPreview()) conversationModule?.expectConversation(app);
679656 const peerWaitStarted = performance.now();
680657 await waitForPeer(app.db, app.log);
681658 // How long this forge held its queue work for the old one (#7836): the keeper keeps it on the
@@ -687,15 +664,17 @@ for (const signal of earlySignals) process.off(signal, leaveEarly);
687664 // at boot would wait on its lock with the event loop held (#9472).
688665 closeStaleSessions(app.db);
689666 // A repository's own check, on every push a pull or the default branch takes.
690 const checks =
691 process.env.FORGE_CHECKS === "0"
692 ? undefined
693 : startChecks(app, {
667 const [checksModule, queueModule] = await Promise.all([
668 process.env.FORGE_CHECKS === "0" ? undefined : loadOrNone(app.log, "checks", () => import("./checks/service.ts")),
669 loadOrNone(app.log, "merge queue", () => import("./checks/queue.ts")),
670 ]);
671 const checks = await startService(app.log, "checks", async () =>
672 checksModule?.startChecks(app, {
694673 forgeUrl,
695674 // Sized to the pod's CPUs unless the environment says (#2549).
696675 concurrency: positive(process.env.FORGE_CHECKS_CONCURRENCY, Number(capacityDefault("checks.concurrency"))),
697676 redHoldMs: RED_HOLD_MS,
698 landSettleMs: LAND_SETTLE_MS,
677 landSettleMs: checksModule.LAND_SETTLE_MS,
699678 // A roll lets running checks and merge-queue gates finish this long
700679 // before cutting them off, and no longer: the new forge holds its
701680 // own queue work until this one stops writing, so the write pause
@@ -704,13 +683,17 @@ const checks =
704683 drainMs: drainBudgets(process.env).checksMs,
705684 // Main is verified after landing at most this often (#7786).
706685 verifyEveryMs: VERIFY_EVERY_MS,
707 });
686 }),
687 );
708688 // A release that was waiting for its check when this process started waits again (#16228).
709 if (checks !== undefined) void rearmRelease(app).catch((error) => app.log.warn("release re-arm failed", { error: String(error) }));
689 if (checks !== undefined)
690 void import("./checks/landing.ts")
691 .then((m) => m.rearmRelease(app))
692 .catch((error) => app.log.warn("release re-arm failed", { error: String(error) }));
710693 // Under the runner placement the forge is its own first runner pool: N runner processes sized
711694 // to this machine beside serving, children of this process so a release replaces them (#14201).
712 const localRunners = (() => {
713 if (checks === undefined || placementFromEnv().mode !== "runner") return undefined;
695 const localRunners = checks === undefined || placementFromEnv().mode !== "runner" ? undefined : await startService(app.log, "localRunners", async () => {
696 const { localPoolSize, startLocalPool } = await import("./checks/runner_pool.ts");
714697 const size = localPoolSize(
715698 process.env,
716699 { cpus: cpuLimit(), memoryMiB: Math.floor(memoryLimitBytes() / 1_048_576) },
@@ -725,76 +708,82 @@ const localRunners = (() => {
725708 snapshots: join(app.config.dataDir, "check-snapshot"),
726709 entry: join(import.meta.dir, "runner", "main.ts"),
727710 });
728 })();
729 // Migrated repositories kept as a read-only mirror push to their source.
730 const mirrorOut = startMirrorOut(app);
731 // …and take the pulls opened on that mirror as pulls here (#9011).
732 const mirrorPulls = startMirrorPulls(app);
733 // The look: a picture of every environment that comes up green, taken
734 // through this forge's own listener.
735 const looks = appsOn ? startLooks(app, { localUrl: servers.url }) : undefined;
736 // A conversation's preview that starts serving says so in its thread, with the time it took.
737 const talkLive = appsOn ? watchTalkLive(app, turnLive) : undefined;
738 // Maintenance duties (src/maintain): each runs on its interval and leaves a row.
739 const maintain = startMaintain(app);
740 // Is it so: the forge knocks on every door of an app with a contract after
741 // each production deploy and once a night, and compares with the table.
742 const probes = apps === undefined ? undefined : startProbes(app, apps);
743 // The nightly jobs that were Forgejo workflows: the flake hunt and the run
744 // of what the gate excludes, filing the same `Flaky:` and `Red:` issues and
745 // the quarantine pull (docs/DEVELOP.md).
746 const nightly = appsOn ? startNightly(app, { forgeUrl, token: process.env["FORGE_TOKEN"] }) : undefined;
747 // The snapshot: everything that cannot be rebuilt, nightly, to what an
748 // operator sealed on the Backups page, else the platform's (`S3_*`) or a
749 // directory (`FORGE_SNAPSHOT_DIR`). A forge given none says so on that page.
750 const snapshots = startSnapshots(
751 app,
752 () =>
753 resolveSnapshots({
754 db: app.db,
755 dataDir: app.config.dataDir,
756 bus: app.bus,
757 passphrase: process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined,
758 })?.store,
759 {
760 version: running().version,
761 // The off-site lane (#11805): sealed under the passphrase before it leaves.
762 mirror: () =>
763 resolveMirror({
764 db: app.db,
765 dataDir: app.config.dataDir,
766 bus: app.bus,
767 passphrase: process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined,
768 })?.store,
769 passphrase: process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined,
770 },
771 );
772 // The dataset: nightly, to the private repository FORGE_DATASET_REPO names
773 // (`owner/data`); off without it.
774 const dataset = startDatasetNightly(app, process.env["FORGE_DATASET_REPO"]);
775 // What the machine uses (boards/sampler.ts): the pod, each cell and the
776 // node, every 15 s into a ring the `machine` board source reads.
777 const sampler = startSampler(app, {});
778 // What has left its window goes a bounded slice at a time on a pace (`system/retention.ts`). The
779 // drains no page reads (machine samples, wake-up events, the old deploy ledger) are this thread's
780 // always, kept out of the write clock; the age rule and the deploy backfill are the engine's when
781 // it has a thread of its own.
782 const stopRetention = startRetention(app, { local: true, engine: !engineOn });
783 const memorySampler = startMemorySampler(app, workerMemoryEvery());
711 });
712 // These start independently of each other: their imports run together, not one after another.
713 const snapshotPassphrase = process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined;
714 const [mirrorOut, mirrorPulls, looks, talkLive, maintain, probes, nightly, snapshots, dataset, sampler, stopRetention, memorySampler] =
715 await Promise.all([
716 // Migrated repositories kept as a read-only mirror push to their source.
717 startService(app.log, "mirrorOut", async () => (await import("./origins/mirror-out.ts")).startMirrorOut(app)),
718 // …and take the pulls opened on that mirror as pulls here (#9011).
719 startService(app.log, "mirrorPulls", async () => (await import("./origins/mirror-pulls.ts")).startMirrorPulls(app)),
720 // The look: a picture of every environment that comes up green, taken
721 // through this forge's own listener.
722 appsOn ? startService(app.log, "looks", async () => (await import("./looks/service.ts")).startLooks(app, { localUrl: servers.url })) : undefined,
723 // A conversation's preview that starts serving says so in its thread, with the time it took.
724 appsOn && conversationModule !== undefined
725 ? startService(app.log, "talkLive", async () => (await import("./actions/talk_live.ts")).watchTalkLive(app, conversationModule.turnLive))
726 : undefined,
727 // Maintenance duties (src/maintain): each runs on its interval and leaves a row.
728 startService(app.log, "maintain", async () => (await import("./maintain/runner.ts")).startMaintain(app)),
729 // Is it so: the forge knocks on every door of an app with a contract after
730 // each production deploy and once a night, and compares with the table.
731 apps === undefined ? undefined : startService(app.log, "probes", async () => (await import("./contract/probes.ts")).startProbes(app, apps)),
732 // The nightly jobs that were Forgejo workflows: the flake hunt and the run
733 // of what the gate excludes, filing the same `Flaky:` and `Red:` issues and
734 // the quarantine pull (docs/DEVELOP.md).
735 appsOn
736 ? startService(app.log, "nightly", async () =>
737 (await import("./nightly/service.ts")).startNightly(app, { forgeUrl, token: process.env["FORGE_TOKEN"] }))
738 : undefined,
739 // The snapshot: everything that cannot be rebuilt, nightly, to what an
740 // operator sealed on the Backups page, else the platform's (`S3_*`) or a
741 // directory (`FORGE_SNAPSHOT_DIR`). A forge given none says so on that page.
742 startService(app.log, "snapshots", async () => {
743 const [{ startSnapshots }, { resolveSnapshots }, { resolveMirror }] = await Promise.all([
744 import("./snapshot/service.ts"),
745 import("./snapshot/destination.ts"),
746 import("./snapshot/mirror.ts"),
747 ]);
748 const place = { db: app.db, dataDir: app.config.dataDir, bus: app.bus, passphrase: snapshotPassphrase };
749 return startSnapshots(app, () => resolveSnapshots(place)?.store, {
750 version: running().version,
751 // The off-site lane (#11805): sealed under the passphrase before it leaves.
752 mirror: () => resolveMirror(place)?.store,
753 passphrase: snapshotPassphrase,
754 });
755 }),
756 // The dataset: nightly, to the private repository FORGE_DATASET_REPO names
757 // (`owner/data`); off without it.
758 startService(app.log, "dataset", async () =>
759 (await import("./actions/dataset.ts")).startDatasetNightly(app, process.env["FORGE_DATASET_REPO"])),
760 // What the machine uses (boards/sampler.ts): the pod, each cell and the
761 // node, every 15 s into a ring the `machine` board source reads.
762 startService(app.log, "sampler", async () => (await import("./boards/sampler.ts")).startSampler(app, {})),
763 // What has left its window goes a bounded slice at a time on a pace (`system/retention.ts`).
764 // The drains no page reads (machine samples, wake-up events, the old deploy ledger) are this
765 // thread's always, kept out of the write clock; the age rule and the deploy backfill are the
766 // engine's when it has a thread of its own.
767 startService(app.log, "retention", async () =>
768 (await import("./system/retention.ts")).startRetention(app, { local: true, engine: !engineOn })),
769 startService(app.log, "memorySampler", async () =>
770 (await import("./boards/memory.ts")).startMemorySampler(app, workerMemoryEvery())),
771 ]);
784772 // Off unless FORGE_HEAP_CAPTURE_DIR is set, for a copy of production (perf/heap_capture.ts).
785773 const stopHeapCapture = startHeapCapture(process.env, (m) => app.log.info(m));
786774 // The starting boards, once each (actions/boards.ts).
787775 void offerStartingBoards(app)
788776 .then((slugs) => slugs.length > 0 && app.log.info("starting boards offered", { slugs: slugs.join(", ") }))
789777 .catch((error) => app.log.warn("starting boards not offered", { error: String(error) }));
790 const runner = runnerSettings(process.env);
778 const dispatchModule = await loadOrNone(app.log, "crew", () => import("./crew/dispatch.ts"));
779 const runner = dispatchModule?.runnerSettings(process.env);
791780 const crewHeldOff = crewOffInPreview();
792781 if (appsOn && crewHeldOff)
793782 app.log.info(CREW_OFF_IN_PREVIEW, {
794783 why: "FORGE_APP_ENV=preview; set FORGE_CREW_IN_PREVIEW=1 to run it",
795784 });
796 const crew = appsOn && !crewHeldOff
797 ? await startCrew(app, {
785 const crew = appsOn && !crewHeldOff && dispatchModule !== undefined && runner !== undefined
786 ? await startService(app.log, "crew", () => dispatchModule.startCrew(app, {
798787 forgeUrl,
799788 localUrl: servers.url,
800789 binary: runner.binary,
@@ -807,12 +796,12 @@ const crew = appsOn && !crewHeldOff
807796 .map((h) => h.trim())
808797 .filter((h) => h !== ""),
809798 ...(runner.configDir === undefined ? {} : { configDir: runner.configDir }),
810 })
799 }))
811800 : undefined;
812801 // A conversation turn the last process was in the middle of is resumed once
813802 // from its session (crew/conversation.ts); a shutdown leaves it running again.
814803 const conversationsStop = new AbortController();
815 if (crew !== undefined) {
804 if (crew !== undefined && runner !== undefined && conversationModule !== undefined) {
816805 const conversation = {
817806 binary: runner.binary,
818807 localUrl: servers.url,
@@ -821,11 +810,12 @@ if (crew !== undefined) {
821810 ...(runner.configDir === undefined ? {} : { configDir: runner.configDir }),
822811 signal: conversationsStop.signal,
823812 };
824 configureConversation(app, conversation);
825 startRoutines(app, conversationsStop.signal);
826 for (const turn of resumeInterrupted(app, conversation))
813 conversationModule.configureConversation(app, conversation);
814 await startService(app.log, "routines", async () =>
815 (await import("./crew/routines.ts")).startRoutines(app, conversationsStop.signal));
816 for (const turn of conversationModule.resumeInterrupted(app, conversation))
827817 turn.catch((error: unknown) => app.log.error("resumed conversation turn crashed", { error: String(error) }));
828 } else forgetConversation(app);
818 } else conversationModule?.forgetConversation(app);
829819 // Hosted children come back with their apps, awake before the first visit.
830820 // The listener is up; the children open behind it, not in front of /healthz.
831821 // A forge still inside this process is moved into a cell of its own first, where this host holds
@@ -867,9 +857,16 @@ useSleepers(app, (name) => !childAwake(app, name));
867857 // Prompts from Instagram (docs/APPS.md): once a day, for each repository
868858 // that connected an account, the top comment on its latest Reel is told to
869859 // the crew. A minute's clock; nothing leaves the box until a source exists.
870 const prompts = inert ? inertHandle() : startPromptRoutine(app, { client: graphInstagram() });
871860 // What newly asks a person reaches the phone they chose (docs/APPS.md).
872 const notifier = inert ? inertHandle() : startNotifier(app, { forgeUrl });
861 const [prompts, notifier] = inert
862 ? [inertHandle(), inertHandle()]
863 : await Promise.all([
864 startService(app.log, "prompts", async () =>
865 (await import("./crew/prompts.ts")).startPromptRoutine(app, { client: graphInstagram() })).then((h) => h ?? inertHandle()),
866 startService(app.log, "notifier", async () => (await import("./crew/notify.ts")).startNotifier(app, { forgeUrl })).then(
867 (h) => h ?? inertHandle(),
868 ),
869 ]);
873870
874871 // The engine's duties (`engine/duties.ts`): webhook delivery, the estimates, the
875872 // starts sweep, holds, the model review, the week, retention. On this thread
@@ -880,7 +877,11 @@ const notifier = inert ? inertHandle() : startNotifier(app, { forgeUrl });
880877 // (`engine/run.ts`): one that cannot be started or kept hands its duties back to this thread, and
881878 // the forge stays up.
882879 const split = engineOn && tail !== undefined ? runSplit(app, engineShape, tail, loneWriter) : undefined;
883 const stopDuties = engineOn || inert ? () => {} : startDuties(app, { onWorker: false });
880 const stopDuties =
881 (engineOn || inert
882 ? undefined
883 : await startService(app.log, "duties", async () => (await import("./engine/duties.ts")).startDuties(app, { onWorker: false }))) ??
884 (() => {});
884885 // Which shape runs and why, once, as `/system` says it.
885886 app.log.info(`engine shape: ${shapeWords({ ...engineShape, mode: split !== undefined && split.fellBack() === undefined ? "worker" : "inline" })}`, {
886887 why: app.config.engine?.why ?? engineShape.why,
@@ -1071,10 +1072,18 @@ const processTick = (): void => {
10711072 // The clog watch (#6524, #6757) reads the flow every minute; its state is the database's.
10721073 // With an engine thread both are its duties (`engine/duties.ts`), reading what this thread observed
10731074 // from rows.
1074 const stopClogTick = engineOn ? () => {} : startClogTick(app.db, app.bus, (error) => app.log.warn("clog tick failed", { error: String(error) }), 60_000);
10751075 // The throughput keeper (#7645) names what binds landings each minute and lifts what is its to
10761076 // lift.
1077 const stopKeeper = engineOn ? () => {} : startKeeper(app, () => sweepAssigned(app));
1077 const [stopClogTick, stopKeeper] = engineOn
1078 ? [() => {}, () => {}]
1079 : await Promise.all([
1080 startService(app.log, "clogTick", async () =>
1081 (await import("./flow/clog_tick.ts")).startClogTick(app.db, app.bus, (error) => app.log.warn("clog tick failed", { error: String(error) }), 60_000),
1082 ).then((stop) => stop ?? (() => {})),
1083 startService(app.log, "flowKeeper", async () =>
1084 (await import("./flow/keeper.ts")).startKeeper(app, () => dispatchModule?.sweepAssigned(app)),
1085 ).then((stop) => stop ?? (() => {})),
1086 ]);
10781087 // A forge that went down prepared for maintenance comes back by itself. The
10791088 // listener is up (`serve` above) and the checks service started; the tunnel
10801089 // is outside this process and may come up later, so its probe asks again.
@@ -1149,41 +1158,48 @@ if (app.config.forgeRepo) {
11491158 // The release keeper (#7557): cut on cadence, promote, verify under page load, roll back to the
11501159 // named known-good image and hold. Off unless FORGE_RELEASE_KEEPER=on in a cluster
11511160 // (keeper/wire.ts).
1152 const keeperOn = keeperEnv(process.env);
1161 const keeperModules = await loadOrNone(app.log, "keeper", () => Promise.all([import("./keeper/wire.ts"), import("./keeper/beat.ts")]));
11531162 let stopHostedTick: (() => void) | undefined;
1154 if (keeperOn.on) {
1155 const ports = keeperPorts(
1156 app,
1157 keeperOn.mode === "swap"
1158 ? { forgeUrl, deployment: "", container: "", swap: true }
1159 : { forgeUrl, deployment: keeperOn.deployment, container: keeperOn.container },
1160 );
1161 noteKeeperAtBoot(typeof ports === "string" ? { on: false, why: ports } : { on: true });
1162 if (typeof ports === "string") app.log.warn("the release keeper is off", { why: ports });
1163 else {
1164 let said = "";
1165 const step = () =>
1166 void stepWithBeat(app.db, () => keeperTick(ports))
1167 .then((line) => {
1168 if (line !== said) app.log.info("release keeper", { line });
1169 said = line;
1170 })
1171 .catch((error) => app.log.warn("release keeper step failed", { error: String(error) }));
1172 during("release-keeper", step, undefined, app);
1173 setInterval(() => during("release-keeper", step, undefined, app), 60_000);
1174 setInterval(
1175 () => void during("roll-probe", () => rollProbe(ports), undefined, app).catch(() => {}),
1176 1000,
1163 if (keeperModules !== undefined) {
1164 const [{ keeperEnv, keeperPorts }, { startHostedTick, stepWithBeat }] = keeperModules;
1165 const keeperOn = keeperEnv(process.env);
1166 if (keeperOn.on) {
1167 const ports = keeperPorts(
1168 app,
1169 keeperOn.mode === "swap"
1170 ? { forgeUrl, deployment: "", container: "", swap: true }
1171 : { forgeUrl, deployment: keeperOn.deployment, container: keeperOn.container },
11771172 );
1173 noteKeeperAtBoot(typeof ports === "string" ? { on: false, why: ports } : { on: true });
1174 if (typeof ports === "string") app.log.warn("the release keeper is off", { why: ports });
1175 else
1176 await startService(app.log, "keeper", async () => {
1177 const { rollProbe, tickStep: keeperTick } = await import("./keeper/keeper.ts");
1178 let said = "";
1179 const step = () =>
1180 void stepWithBeat(app.db, () => keeperTick(ports))
1181 .then((line) => {
1182 if (line !== said) app.log.info("release keeper", { line });
1183 said = line;
1184 })
1185 .catch((error) => app.log.warn("release keeper step failed", { error: String(error) }));
1186 during("release-keeper", step, undefined, app);
1187 setInterval(() => during("release-keeper", step, undefined, app), 60_000);
1188 setInterval(
1189 () => void during("roll-probe", () => rollProbe(ports), undefined, app).catch(() => {}),
1190 1000,
1191 );
1192 return true;
1193 });
1194 } else {
1195 noteKeeperAtBoot(keeperOn);
1196 app.log.info("the release keeper is off", { why: keeperOn.why });
1197 // Hosted, the release is the host's deploy; the tick says so at boot and hourly (#15530).
1198 stopHostedTick = startHostedTick(app.db, process.env, (tick, ms) => {
1199 const timer = setInterval(() => during("release-hosted", tick, undefined, app), ms);
1200 return () => clearInterval(timer);
1201 });
11781202 }
1179 } else {
1180 noteKeeperAtBoot(keeperOn);
1181 app.log.info("the release keeper is off", { why: keeperOn.why });
1182 // Hosted, the release is the host's deploy; the tick says so at boot and hourly (#15530).
1183 stopHostedTick = startHostedTick(app.db, process.env, (tick, ms) => {
1184 const timer = setInterval(() => during("release-hosted", tick, undefined, app), ms);
1185 return () => clearInterval(timer);
1186 });
11871203 }
11881204 // Only an agent is on a crew (the `repo_crew_agents_only` trigger refuses anyone else). A person
11891205 // put on one before that is reported here for the owner to take off — the
@@ -1219,7 +1235,7 @@ const leaseTimer = setInterval(() => during("lease", () => {
12191235 STALE_AFTER_MS,
12201236 crew === undefined ? ["deploy", "agent"] : ["deploy"],
12211237 );
1222 requeueAbandonedChecks(app, STALE_AFTER_MS);
1238 checksModule?.requeueAbandonedChecks(app, STALE_AFTER_MS);
12231239 // A draft whose run is over or gone (a crash, a restart) is ready: a first app never stays
12241240 // locked.
12251241 readyStranded(app);
@@ -1296,7 +1312,7 @@ function drain(signal: NodeJS.Signals): Promise<unknown> {
12961312 const linger = signal === "SIGTERM" ? Bun.sleep(lingerMs ?? 0) : undefined;
12971313 // The merge queue acts on nothing more: its gates run on through the
12981314 // checks' drain, and a verdict is kept for the forge that carries on (#6611).
1299 stopQueue();
1315 queueModule?.stopQueue();
13001316 conversationsStop.abort();
13011317 return Promise.all([
13021318 linger,
@@ -1315,18 +1331,18 @@ function drain(signal: NodeJS.Signals): Promise<unknown> {
13151331 Promise.resolve(checks?.stop({ drain: signal === "SIGTERM" })).then(() =>
13161332 localRunners?.stop(),
13171333 ),
1318 mirrorOut(),
1319 mirrorPulls(),
1334 mirrorOut?.(),
1335 mirrorPulls?.(),
13201336 looks?.stop(),
13211337 talkLive?.(),
1322 maintain.stop(),
1338 maintain?.stop(),
13231339 probes?.stop(),
13241340 nightly?.stop(),
1325 snapshots.stop(),
1326 dataset.stop(),
1327 sampler.stop(),
1328 stopRetention(),
1329 memorySampler.stop(),
1341 snapshots?.stop(),
1342 dataset?.stop(),
1343 sampler?.stop(),
1344 stopRetention?.(),
1345 memorySampler?.stop(),
13301346 stopHeapCapture(),
13311347 engineStopped,
13321348 ])
test/boot-lazy.test.ts +11
@@ -21,6 +21,17 @@ test("the terminal's server is imported dynamically by the boot", () => {
2121 expect(readFileSync(resolve("src/main.ts"), "utf8")).toContain('import("./tui/ssh.ts")');
2222 });
2323
24 // #17021: the services only the boot starts are not in its static closure; that each still starts
25 // is proved on a real boot (boot-production.test.ts, "background service started service=<name>").
outdated

This greps the source text, so it passes when the import is present but never called. It also checks the closure only for five modules that were never in doubt, not the heavy ones (apps/runtime, checks/service, crew/dispatch, looks/service, snapshot/service). Assert the heavy ones once they are out, and prove the starts on a real boot.

26 // The heavier ones are still reached by pages and actions, each its own follow-up: #17179,
27 // #17180, #17181, #17182, #17183 (apps/runtime, checks/service, crew/dispatch, looks/service,
28 // snapshot/service).
29 test("the boot's static imports do not reach the services only it starts", () => {
30 const closure = [...staticClosure(resolve("src/main.ts"))];
31 const only = ["maintain/runner.ts", "nightly/service.ts", "keeper/keeper.ts", "keeper/wire.ts", "crew/routines.ts"];
32 for (const file of only) expect(closure.some((f) => f.endsWith(`/src/${file}`)), file).toBe(false);
33 });
34
2435 // #12521: the MCP server and its tool index (some two hundred modules) load on first use.
2536 test("the boot's static imports do not reach the MCP server or its tools", () => {
2637 const closure = [...staticClosure(resolve("src/main.ts"))];
test/boot-production.test.ts +38 −2
@@ -54,7 +54,7 @@ afterAll(() => rmSync(root, { recursive: true, force: true }));
5454 * Start `main.ts` with production's variables and `engine` for FORGE_ENGINE (undefined: not
5555 * set), hold it, and report.
5656 */
57 async function boot(name: string, engine: string | undefined): Promise<Boot> {
57 async function boot(name: string, engine: string | undefined, preload?: string): Promise<Boot> {
5858 const dir = join(root, name);
5959 mkdirSync(join(dir, "data"), { recursive: true });
6060 const caFile = join(dir, "ca.crt");
@@ -76,7 +76,7 @@ async function boot(name: string, engine: string | undefined): Promise<Boot> {
7676 const value = process.env[key];
7777 if (value !== undefined && value !== "") env[key] = value;
7878 }
79 const child = Bun.spawn([process.execPath, MAIN], {
79 const child = Bun.spawn([process.execPath, ...(preload === undefined ? [] : ["--preload", preload]), MAIN], {
8080 cwd: dir,
8181 env,
8282 stdin: "ignore",
@@ -147,10 +147,18 @@ describe("main.ts with the variables production sets", () => {
147147 beforeAll(async () => {
148148 // The three ways the engine can be asked for, at once: as production says it (inline), with
149149 // nothing said (what 0.7.599 ran with), and asked for by name.
150 // A fourth boot whose maintenance duties cannot load (#17021): a plugin, loaded first, makes
151 // that module throw at its top level, as a bad roll would.
152 const broken = join(root, "broken-maintain.ts");
153 writeFileSync(
154 broken,
155 `Bun.plugin({ name: "broken-maintain", setup(b) { b.onLoad({ filter: /\\/src\\/maintain\\/runner\\.ts$/ }, () => ({ contents: 'throw new Error("maintain broken on purpose");', loader: "ts" })); } });\n`,
156 );
150157 boots = await Promise.all([
151158 boot("inline", "inline"),
152159 boot("unset", undefined),
153160 boot("worker", "worker"),
161 boot("broken", "inline", broken),
154162 ]);
155163 }, HOLD_MS + 90_000);
156164 const of = (name: string): Boot => boots.find((b) => b.name === name)!;
@@ -175,6 +183,34 @@ describe("main.ts with the variables production sets", () => {
175183 expect(b.output).toContain("engine shape: ");
176184 });
177185
186 // #17021: main.ts imports each background service when it starts it; a real boot still starts
187 // each, and each says so from where it started (kernel/start_service.ts).
188 test("the services main.ts imports after it is ready still start on a real boot", () => {
189 const b = of("inline");
190 expect(b.output, tail(b)).toContain("apps are up");
191 for (const name of ["apps", "checks", "looks", "maintain", "snapshots", "sampler", "crew", "routines"])
192 expect(b.output, `${name}: ${tail(b)}`).toMatch(new RegExp(`background service started service=${name}\\b`));
193 // Off in this boot, so not said to have started.
194 expect(b.output).not.toContain("background service started service=keeper");
195 expect(b.output).not.toContain("did not start");
196 // The nightly jobs are off without a token, and say so from their own start.
197 expect(b.output, tail(b)).toContain("nightly jobs are off");
198 expect(b.output, tail(b)).toMatch(/crew is (not )?ready/);
199 expect(b.output, tail(b)).toContain("the release keeper is off");
200 });
201
202 // #17021: a service module that cannot load is off, said once, and the forge stays up.
203 test("a background service that cannot load leaves the forge answering /healthz", () => {
204 const b = of("broken");
205 expect(b.alive, `exited with ${b.exitCode}:\n${tail(b)}`).toBe(true);
206 expect(b.health, tail(b)).toBe(200);
207 expect(b.output, tail(b)).toMatch(/background service did not start service=maintain .*maintain broken on purpose/);
208 expect(b.output).not.toContain("background service started service=maintain");
209 // The rest of the boot ran past it.
210 expect(b.output, tail(b)).toMatch(/background service started service=sampler\b/);
211 expect(b.output, tail(b)).toContain("forge is up");
212 });
213
178214 test("with nothing said, and as production says it, one thread serves and works", () => {
179215 expect(of("unset").output).toContain(
180216 "engine shape: one thread serves and works",
test/start-service.test.ts added +45
@@ -0,0 +1,45 @@
1 /**
2 * A background service that cannot load or start is off, said once, and the boot carries on
3 * (#17021, kernel/start_service.ts).
4 */
5 import { expect, test } from "bun:test";
6 import { loadOrNone, startService } from "../src/kernel/start_service.ts";
7
8 function recorder() {
9 const lines: string[] = [];
10 return {
11 lines,
12 log: {
13 info: (m: string, f?: Record<string, unknown>) => lines.push(`info ${m} ${JSON.stringify(f)}`),
14 error: (m: string, f?: Record<string, unknown>) => lines.push(`error ${m} ${JSON.stringify(f)}`),
15 },
16 };
17 }
18
19 test("a service that starts gives its handle and says it started", async () => {
20 const r = recorder();
21 const stop = (): void => {};
22 expect(await startService(r.log, "sampler", async () => stop)).toBe(stop);
23 expect(r.lines).toEqual(['info background service started {"service":"sampler"}']);
24 });
25
26 test("a module that throws as it loads leaves the service off and says why", async () => {
27 const r = recorder();
28 const handle = await startService(r.log, "looks", async () => {
29 throw new Error("cannot find module");
30 });
31 expect(handle).toBeUndefined();
32 expect(r.lines).toEqual(['error background service did not start {"service":"looks","error":"Error: cannot find module"}']);
33 });
34
35 test("a service that is off is not said to have started", async () => {
36 const r = recorder();
37 expect(await startService(r.log, "localRunners", async () => undefined)).toBeUndefined();
38 expect(r.lines).toEqual([]);
39 });
40
41 test("a module that loads is given back without a start line", async () => {
42 const r = recorder();
43 expect(await loadOrNone(r.log, "crew", async () => ({ ok: 1 }))).toEqual({ ok: 1 });
44 expect(r.lines).toEqual([]);
45 });

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

Keyboard shortcuts

Docs