Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(server): a retired machines generation installs no re-hold timer

lmliheng367fb0fdf950
diff --git a/changelog/unreleased/2026-11-10-machines-hold-timer-after-stop.md b/changelog/unreleased/2026-11-10-machines-hold-timer-after-stop.md
new file mode 100644
index 00000000..01380438
--- /dev/null
+++ b/changelog/unreleased/2026-11-10-machines-hold-timer-after-stop.md
@@ -0,0 +1,18 @@
+# A retired machines generation installs no re-hold timer
+
+- **Date:** 2026-11-10
+- **Type:** fix
+- **Scope:** `server`
+- **Breaking:** no
+
+[中文版](2026-11-10-machines-hold-timer-after-stop.zh.md)
+
+When the App is hot-pushed, the outgoing generation's dispose effect calls `MachinesService.stop()`. But `start()` reaches out over the network before it settles — it hands its build to machines that carry a different one, then re-holds the connections the record says were held — so a push can land in the middle of that. The timer that sweeps for dropped connections once a minute was installed **after** those awaits with no regard for the stop that may have arrived in between: it was never cleared, and it went on reading a database the retired generation had already closed, raising an unhandled rejection in the process every minute.
+
+A generation now remembers that it was retired (`#stopped`): `stop()` sets it, and `start()` looks at it before it touches anything, after each await, and again before installing the timer. A successor generation is a new instance, so it starts afresh as before.
+
+The test suite had the same leak from the other end: `createTestApp`'s cleanup disposed the hot host and closed the database, but never called `machines.stop()`, so an App booted inside a test file left that timer behind for the rest of the worker's life. Cleanup now retires the machines generation the way the platform's own dispose effect does.
+
+## Verification
+
+`test/machines-lifecycle.test.ts` pins the three states — a live generation re-holds once a minute, a `stop()` landing mid-start installs no timer, and a retired generation's `start()` reaches nothing — plus an App's cleanup retiring its generation.
diff --git a/changelog/unreleased/2026-11-10-machines-hold-timer-after-stop.zh.md b/changelog/unreleased/2026-11-10-machines-hold-timer-after-stop.zh.md
new file mode 100644
index 00000000..5d985863
--- /dev/null
+++ b/changelog/unreleased/2026-11-10-machines-hold-timer-after-stop.zh.md
@@ -0,0 +1,26 @@
+# 退役的那一代 machines 不再装「保持连接」的定时器
+
+- **日期:** 2026-11-10
+- **类型:** 修复
+- **范围:** `server`
+- **破坏性变更:** 否
+
+[English](2026-11-10-machines-hold-timer-after-stop.md)
+
+App 被热推时,旧一代的 dispose 效果会调用 `MachinesService.stop()`。可 `start()` 在落定之前要先走网络 ——
+先把构建交给那些带着不同版本的机器,再重新保持记录里说「曾被保持」的连接 —— 所以一次热推完全可能落在中间。
+那个每分钟扫一遍「该保持却没保持」的定时器,正是**在这些 await 之后**才装上的,完全不看这中间有没有人来过
+`stop()`:它再也不会被清掉,而且每一分钟都去读一个已退役那一代早就关掉的数据库,于是进程里每分钟多一条
+unhandled rejection。
+
+现在每一代自己记住「已被退役」(`#stopped`):`stop()` 把它置上,`start()` 在动手之前、每个 await 之后、
+以及装定时器之前都看它一眼。后继的那一代是新的实例,照旧从头开始。
+
+测试套件里这处泄漏的另一端也堵上了:`createTestApp` 的拆台会 dispose 热宿主、关掉数据库,却从不调用
+`machines.stop()`,于是在某个用例里启动的 App 会把那个定时器留给这个 worker 的余生。现在拆台会像平台自己的
+dispose 效果那样,把这一代 machines 退役掉。
+
+## 验证
+
+`test/machines-lifecycle.test.ts` 钉住三种状态 —— 活着的一代每分钟照常重试、`start()` 途中落下的 `stop()`
+一个定时器都不装、退役那一代的 `start()` 什么也不碰 —— 外加「App 拆台会把这一代退役」。
diff --git a/packages/server/src/machines/service.ts b/packages/server/src/machines/service.ts
index 3b89c8a0..e6dc7814 100644
--- a/packages/server/src/machines/service.ts
+++ b/packages/server/src/machines/service.ts
@@ -190,6 +190,13 @@ export class MachinesService {
readonly #jobs = new Map<string, MachineJob>();
/** The standing intent: while this App lives, machines recorded as held are re-held when found dropped. */
#keepHeld: ReturnType<typeof setInterval> | null = null;
+ /**
+ * Whether this generation has been retired. start() reaches out over the network before it
+ * settles, so a hot push's stop() can land while it is still awaiting: the generation must
+ * then install nothing — a timer on a retired generation would read a database that is
+ * already closed, once a minute, until the process ends.
+ */
+ #stopped = false;
/** Per machine, when the next re-hold may be tried (epoch ms) and how many tries have failed in a row. */
readonly #reholdNotBefore = new Map<string, number>();
readonly #reholdFailures = new Map<string, number>();
@@ -1083,17 +1090,23 @@ export class MachinesService {
* slow to answer must not hold up the App that serves everything else.
*/
async start(): Promise<void> {
+ // A generation that stop() already retired is not started: whatever it opened would be
+ // outside that stop()'s sweep, and its timer would outlive the database underneath it.
+ if (this.#stopped) return;
// The build first, the connections second: a machine behind this build is brought
// forward over a transient session and its server restarted, and only then re-held —
// so the connection that stays is to the server that will keep running, and the Model
// config handed over as it connects lands on the build that will read it.
await this.syncOutOfDate();
+ if (this.#stopped) return;
await this.autoConnect();
// Held is a standing intent, not a boot-time attempt: a machine that could not be
// re-held at boot — the network still settling, its server not yet up — or that drops
// later and whose session did not come back, is tried again on a widening wait until it
// is held or a person stops using it. Unref'd: a timer must not keep a process alive.
- if (this.#keepHeld === null) {
+ // The check above and this one both look at #stopped: either await is long enough for a
+ // hot push's stop() to land, and a timer installed after it would never be cleared.
+ if (!this.#stopped && this.#keepHeld === null) {
this.#keepHeld = setInterval(() => void this.autoConnect(), KEEP_HELD_MS);
this.#keepHeld.unref?.();
}
@@ -1105,6 +1118,7 @@ export class MachinesService {
* Nothing here closes by a remembered pid: the child handles are this generation's own.
*/
stop(): void {
+ this.#stopped = true;
if (this.#keepHeld !== null) clearInterval(this.#keepHeld);
this.#keepHeld = null;
closeAllConnections();
diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.ts
index f6689236..7f4d3615 100644
--- a/packages/server/test/helpers.ts
+++ b/packages/server/test/helpers.ts
@@ -434,6 +434,11 @@ export async function createTestApp(options: TestAppOptions = {}): Promise<TestA
// sweeps its resource registry, which is where every live pty is registered.
deps.hmr.dispose();
deps.channels.dispose();
+ // Machines holds a once-a-minute re-hold timer and live ssh sessions — the same kind of
+ // platform-owned thing, but the hot host's registry does not carry them. Left running,
+ // the timer outlives this root's database and every later test file in the worker pays
+ // for it with "database is not open" (the platform's own dispose effect calls this).
+ deps.machines.stop();
deps.db.close();
// maxRetries: Windows can report ENOTEMPTY/EBUSY while handles from the test's own
// just-closed files (SQLite, trace writers) are still being released — Node's rm
diff --git a/packages/server/test/machines-lifecycle.test.ts b/packages/server/test/machines-lifecycle.test.ts
new file mode 100644
index 00000000..97764775
--- /dev/null
+++ b/packages/server/test/machines-lifecycle.test.ts
@@ -0,0 +1,120 @@
+/**
+ * The machines generation's lifetime: what start() installs while this App lives, and what a
+ * retired generation must not install afterwards.
+ *
+ * The re-hold timer is the reason this file exists. start() reaches out over the network
+ * before it settles, so a hot push's stop() (the platform's dispose effect) can land while it
+ * is still awaiting; a timer installed after that would never be cleared, and would read a
+ * database that is already closed once a minute. The same leak reached the test suite: an
+ * App's cleanup that did not call stop() left the timer reading a closed root.
+ *
+ * Scenarios:
+ * - A generation that was never stopped re-holds on its own, once a minute.
+ * - A stop() landing while start() is still reaching out installs no timer at all.
+ * - A retired generation's start() reaches nothing, so a late caller cannot revive it.
+ * - An App's cleanup retires its machines generation — a start() afterwards touches nothing.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import fs from "node:fs";
+import type { DatabaseSync } from "node:sqlite";
+import { openDatabase } from "../src/db/database.js";
+import { MachinesRepo } from "../src/db/repos/machines.js";
+import { MachinesService } from "../src/machines/service.js";
+import type { MachinesEffects } from "../src/machines/service.js";
+import { remoteLayoutFor } from "../src/machines/layout.js";
+import { createTestApp, makeTempRoot, waitFor } from "./helpers.js";
+
+/** This machine's id; minted from the `machine` table in the real server, fixed here. */
+const LOCAL_ID = "TESTlocalID00000";
+/** KEEP_HELD_MS in machines/service.ts: how long a generation waits between re-hold sweeps. */
+const KEEP_HELD_MS = 60_000;
+
+describe("machines generation lifetime", () => {
+ const open: Array<{ store: DatabaseSync; root: string }> = [];
+ const services: MachinesService[] = [];
+
+ afterEach(() => {
+ vi.useRealTimers();
+ for (const service of services.splice(0)) service.stop();
+ for (const { store, root } of open.splice(0)) {
+ store.close();
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ /**
+ * A service over a fresh root and store, with only the reaching-out faked: one alias in the
+ * ssh config, no build to hand over, and a counter for every read of that config — which is
+ * what a re-hold sweep starts with.
+ */
+ const harness = async () => {
+ const root = await makeTempRoot();
+ const store = openDatabase(":memory:");
+ open.push({ store, root });
+ let reads = 0;
+ const effects: Partial<MachinesEffects> = {
+ listAliases: () => {
+ reads += 1;
+ return ["nas"];
+ },
+ resolvePlan: () => null,
+ now: () => new Date("2026-08-24T12:00:00.000Z"),
+ };
+ const service = new MachinesService(
+ root,
+ LOCAL_ID,
+ new MachinesRepo(store),
+ effects,
+ undefined,
+ remoteLayoutFor("release"),
+ );
+ services.push(service);
+ return { service, reads: () => reads };
+ };
+
+ it("a generation that is not stopped re-holds on its own, once a minute", async () => {
+ vi.useFakeTimers();
+ const built = await harness();
+ await built.service.start();
+ const afterBoot = built.reads();
+ // The boot's own sweep read the config once — the control that makes the assertions below
+ // about NOT reading anything meaningful.
+ expect(afterBoot).toBeGreaterThan(0);
+
+ await vi.advanceTimersByTimeAsync(KEEP_HELD_MS);
+ expect(built.reads()).toBeGreaterThan(afterBoot);
+ });
+
+ it("a stop() landing while start() is still reaching out installs no re-hold timer", async () => {
+ vi.useFakeTimers();
+ const built = await harness();
+ // start() runs synchronously up to its first await, so this stop() is the hot push that
+ // arrives mid-sweep — the case the guard in start() is for.
+ const started = built.service.start();
+ built.service.stop();
+ await started;
+
+ const reads = built.reads();
+ await vi.advanceTimersByTimeAsync(KEEP_HELD_MS * 3);
+ expect(built.reads()).toBe(reads);
+ });
+
+ it("a retired generation's start() reaches nothing", async () => {
+ const built = await harness();
+ built.service.stop();
+ await built.service.start();
+ expect(built.reads()).toBe(0);
+ });
+
+ it("an App's cleanup retires its machines generation, so a late start() touches nothing", async () => {
+ const built = await harness();
+ // The App's boot calls start() itself (Startup.setup), as the real platform does.
+ const app = await createTestApp({ machines: built.service });
+ await waitFor(() => built.reads() > 0);
+ await app.cleanup();
+
+ const afterCleanup = built.reads();
+ await built.service.start();
+ expect(built.reads()).toBe(afterCleanup);
+ });
+});