A local-first multi-agent app development platform, built on PenguinHarness
fix(hmr): ensure transactional upgrade (#408)
Myriad-Dreamin8fad011ca26c
diff --git a/changelog/unreleased/2026-08-23-hmr-teardown-transaction.md b/changelog/unreleased/2026-08-23-hmr-teardown-transaction.mdnew file mode 100644index 00000000..45031cc5--- /dev/null+++ b/changelog/unreleased/2026-08-23-hmr-teardown-transaction.md@@ -0,0 +1,15 @@+# A failed hot update no longer takes the running App down with it++- **Date:** 2026-08-23+- **Type:** fix+- **Scope:** `core`, `server`++[中文版](2026-08-23-hmr-teardown-transaction.zh.md)++Three paths through a hot update could leave the process half-dead: serving HTTP out of closures while its session manager, scheduler and terminals were stopped, with nothing able to bring them back short of a restart. All three shared one shape — an irreversible step taken before the thing that justifies it had succeeded — and all three now treat a swap's teardown as a single transaction.++## Details++- `upgrade()` disposed the running tree and awaited its drain outside the block that converts failure into a recoverable result. A throwing disposer or a rejected drain escaped as a rejection instead, after the old tree was already down, so the caller held no parked document and the host's recovery never ran. Both steps moved inside: once the old tree starts coming down, every failure hands back the document recovery needs.+- `bootNode` booted children and collected `ctx.effect` disposers, then ran the implementation's `create()` and the method-set check, with no unwind on failure. A node that failed half-built left children booted and effects registered with nothing able to reach them — a watcher, an exit listener or a child process leaked for the life of the process, and each retry stacked another. It now unwinds in the same children-first order a successful dispose uses.+- The platform disposed the resource groups a new build could not speak for as its first act, before plugin delivery, the business assembly and the scheduler — any of which can throw. A bundle that changed its resource declaration and then failed took the previous App's terminals down with it, and the host's re-boot of the previous bundle could not bring them back, because recovery re-adopts by handle. Reconciliation now computes the fates and touches nothing; adoption skips a doomed group explicitly; disposal and the declaration overwrite happen once the App is built and nothing left can throw.diff --git a/changelog/unreleased/2026-08-23-hmr-teardown-transaction.zh.md b/changelog/unreleased/2026-08-23-hmr-teardown-transaction.zh.mdnew file mode 100644index 00000000..deba3c66--- /dev/null+++ b/changelog/unreleased/2026-08-23-hmr-teardown-transaction.zh.md@@ -0,0 +1,15 @@+# 热更新失败不再把正在运行的 App 一起带走++- **Date:** 2026-08-23+- **Type:** fix+- **Scope:** `core`, `server`++[English](2026-08-23-hmr-teardown-transaction.md)++热更新有三条路径会让进程处于半死状态:还能靠闭包应答 HTTP,但 session manager、scheduler 与终端都已停止,除重启外无法恢复。三者形态相同——在能证明它成立的那一步成功之前,就先做了不可逆的动作——现在都把 swap 的 teardown 当作一次事务处理。++## 细节++- `upgrade()` 在「把失败转成可恢复结果」的块**之外**执行 dispose 与等待 drain。因此 disposer 抛错或 drain reject 会以 rejection 形式逃逸,而此时旧树已经倒下,调用方手里没有寄存文档,宿主的恢复路径也就从未执行。两步都移进块内:从旧树开始倒下的那一刻起,任何失败都会把恢复所需的文档交还。+- `bootNode` 先启动子节点、收集 `ctx.effect` 的 disposer,再执行实现的 `create()` 与方法集校验,任何失败路径上都没有 unwind。半途失败的节点会留下已启动的子节点与已登记的 effect,而没有任何东西能够触及它们——一个 watcher、一个退出监听器或一个子进程会泄漏至进程结束,且每次重试再叠加一份。现在它按成功 dispose 所用的同一「子节点优先」顺序 unwind。+- 平台把「本次构建无法承接的资源组」的销毁作为**第一个**动作,排在插件投递、业务面组装与 scheduler 启动之前——而这些都可能抛错。一个改变了资源声明、随后失败的 bundle 会把上一个 App 的终端一并带走,且宿主对旧 bundle 的重新启动也救不回来,因为恢复是按句柄重新认领的。现在的调和只**计算**各组的去向而不动手;认领时显式跳过将被销毁的组;销毁与声明覆盖推迟到 App 已经建好、再无可抛错之处时才执行。diff --git a/packages/core/src/kernel/boot.ts b/packages/core/src/kernel/boot.tsindex 97526280..4708e913 100644--- a/packages/core/src/kernel/boot.ts+++ b/packages/core/src/kernel/boot.ts@@ -142,12 +142,47 @@ function parseParkedNode(doc: Json, path: string): ParkedNode {};}+/**+ * Accumulators a node fills as it builds — held by {@link bootNode} so that a failure+ * partway through still has something to unwind.+ */+interface PartialNode {+ children: Map<string, NodeInst | KeyedInst>;+ disposers: Array<() => void>;+}+async function bootNode(impl: AnyImpl,iface: AnyIface,doc: Json,resources: Resources,path: string,+): Promise<NodeInst> {+ const partial: PartialNode = { children: new Map(), disposers: [] };+ try {+ return await buildNode(impl, iface, doc, resources, path, partial);+ } catch (err) {+ // A node that fails half-built still HAS a half: children already booted, effects+ // already registered. Nothing else can reach them — the caller gets an exception,+ // not an instance — so unwinding here is the only chance to run them. Same+ // children-first convention as disposeNode; a throwing disposer must not mask the+ // failure actually being reported.+ try {+ disposeNode({ iface, api: {} as NodeInst["api"], ...partial });+ } catch {+ // Best-effort: the original failure is what the caller needs to see.+ }+ throw err;+ }+}++async function buildNode(+ impl: AnyImpl,+ iface: AnyIface,+ doc: Json,+ resources: Resources,+ path: string,+ partial: PartialNode,): Promise<NodeInst> {const parked = parseParkedNode(doc, path);const parsed = iface.context.strictParse(parked.self, `${path}.self`);@@ -158,7 +193,7 @@ async function bootNode();}- const childInsts = new Map<string, NodeInst | KeyedInst>();+ const childInsts = partial.children;const childHandles: Record<string, unknown> = {};for (const [name, decl] of Object.entries(iface.children)) {const childImpl = impl.children?.[name];@@ -199,7 +234,7 @@ async function bootNode(}}- const disposers: Array<() => void> = [];+ const disposers = partial.disposers;const ctx: NodeCtx = {resources,effect: (dispose) => disposers.push(dispose),diff --git a/packages/core/src/kernel/upgrade.ts b/packages/core/src/kernel/upgrade.tsindex b8f368f3..45fd7915 100644--- a/packages/core/src/kernel/upgrade.ts+++ b/packages/core/src/kernel/upgrade.ts@@ -150,15 +150,19 @@ export async function upgrade<A extends Park, C extends Json>(opts: {doc: parked,};}- opts.current.dispose();- // A disposed tree may have an asynchronous tail — work its dispose effects aborted but- // could not await (effects are synchronous). An implementation exposes it as an optional- // in-process `drained` member; awaiting it HERE, between dispose and boot, is what makes- // a successor never race its predecessor — and a failed boot below cannot lose it,- // because it has already been awaited.- await (opts.current.api as { drained?: () => Promise<void> | undefined }).drained?.();+ // ONE transition, one failure channel: from here the old tree is coming down, so every+ // way this can fail — a throwing disposer, a rejected drain, a successor that will not+ // boot — has to hand the caller the parked document. A rejection escaping instead would+ // leave a disposed tree with nothing booted in its place and no state to recover from,+ // which is the one outcome this function exists to prevent.let instance: Instance<A>;try {+ opts.current.dispose();+ // A disposed tree may have an asynchronous tail — work its dispose effects aborted+ // but could not await (effects are synchronous). An implementation exposes it as an+ // optional in-process `drained` member; awaiting it HERE, between dispose and boot,+ // is what makes a successor never race its predecessor.+ await (opts.current.api as { drained?: () => Promise<void> | undefined }).drained?.();instance = await boot(opts.impl, opts.iface, doc, opts.resources);} catch (error) {return { status: "failed", error, doc: parked };diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.tsindex d360bc3e..b98417e3 100644--- a/packages/server/src/hmr/platform.ts+++ b/packages/server/src/hmr/platform.ts@@ -158,26 +158,34 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {// nothing provable, nothing disposed on its behalf (pre-declaration behavior).const inherited = ctx.resources.claim<Interfaces>(RESOURCE_IFACES_RESOURCE_ID);const inheritable = inherited !== undefined && inherited.family === DECLARED_RESOURCES.family;- for (const [group, offered] of Object.entries(inherited ?? {})) {- if (group === "family") continue;- // Wrong family, wrong version, or a group this build no longer declares: this- // create() cannot speak the contract behind those handles.- const need = DECLARED_RESOURCES[group];- const offers =- Array.isArray(need) && Array.isArray(offered) && need.every((m) => offered.includes(m));- if (!inheritable || !offers) ctx.resources.disposeGroup?.(group);- }- // Overwritten (never released — see the ID's doc) so the NEXT App reads this build's- // declaration, whatever generation it is.- ctx.resources.register(RESOURCE_IFACES_RESOURCE_ID, DECLARED_RESOURCES);+ // DECIDE ONLY. Disposing a group kills live ptys and child processes, and nothing+ // brings them back — so the decision is computed here and ACTED ON at the bottom,+ // once this App is fully built. Everything between can still throw (plugin handlers,+ // workflow factories, the scheduler), and a boot that fails there is recovered by+ // re-booting the previous bundle; that recovery is only honest if the resources it+ // re-adopts are still alive.+ const doomedGroups = Object.entries(inherited ?? {})+ .filter(([group]) => group !== "family")+ .filter(([group, offered]) => {+ // Wrong family, wrong version, or a group this build no longer declares: this+ // create() cannot speak the contract behind those handles.+ const need = DECLARED_RESOURCES[group];+ const offers =+ Array.isArray(need) && Array.isArray(offered) && need.every((m) => offered.includes(m));+ return !inheritable || !offers;+ })+ .map(([group]) => group);const terminals = new TerminalManager(ctx.resources, {// A pushed bundle's node-pty binaries live where the host materialized them.assets: () => caps?.hmr.assetsDir() ?? null,});// Shells started before this instance existed are still running in the registry: claim- // them back so a push is invisible to whoever was typing in one.- terminals.adopt(context.terminals ?? []);+ // them back so a push is invisible to whoever was typing in one — unless their group+ // is doomed, in which case this build cannot speak the contract behind those handles+ // and must not adopt them. It does not dispose them either: that happens at the+ // commit below, so a failed boot leaves them for the recovered predecessor.+ terminals.adopt(doomedGroups.includes("terminal") ? [] : (context.terminals ?? []));// Ordinary code over the claimed capability (see terminal/identity.ts): the resolver// wraps caps.authService, the same object the business routes authenticate with. A// bare kernel has no auth — terminals stay fail-closed there.@@ -260,6 +268,13 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {drained = Promise.allSettled(drains).then(() => undefined);});+ // COMMIT: from here the App is built and nothing below throws, so the irreversible+ // half of the resource reconciliation runs — the groups this build cannot speak for+ // are disposed, and the declaration is overwritten (never released — see the ID's+ // doc) so the NEXT App reads this build's.+ for (const group of doomedGroups) ctx.resources.disposeGroup?.(group);+ ctx.resources.register(RESOURCE_IFACES_RESOURCE_ID, DECLARED_RESOURCES);+const http = seamHttp(app);return {diff --git a/packages/server/test/hmr-resources.test.ts b/packages/server/test/hmr-resources.test.tsindex 4ba01f92..fb05638a 100644--- a/packages/server/test/hmr-resources.test.ts+++ b/packages/server/test/hmr-resources.test.ts@@ -6,7 +6,15 @@* ordering contract and the runtime-capability version handshake (hmr/capabilities.ts).*/import { describe, expect, it, vi } from "vitest";-import { boot, initialDoc, upgrade } from "@prismshadow/penguin-core/kernel";+import {+ boot,+ defineIface,+ initialDoc,+ schema,+ type,+ upgrade,+} from "@prismshadow/penguin-core/kernel";+import type { Json } from "@prismshadow/penguin-core/kernel";import { HotResources } from "../src/hmr/resources.js";import { TerminalManager } from "../src/terminal/manager.js";import type { TerminalSession } from "../src/terminal/session.js";@@ -31,14 +39,17 @@ import {* declaration that no business runtime stands behind it. Without any descriptor the boot* is refused, which is the rule the last describe in this file drives.*/-async function bootPlatform(r: HotResources) {+async function bootPlatform(r: HotResources, context?: { terminals?: string[] }) {r.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });const warn = vi.spyOn(console, "warn").mockImplementation(() => {});try {return await boot(packagedPlatform.impl,packagedPlatform.iface,- initialDoc(packagedPlatform.iface, packagedPlatform.context),+ initialDoc(packagedPlatform.iface, {+ ...(packagedPlatform.context as Record<string, Json>),+ ...context,+ }),r,);} finally {@@ -136,6 +147,41 @@ describe("resource-interface reconciliation at create()", () => {}});+ it("a boot that fails leaves the doomed group ALIVE for the recovered predecessor", async () => {+ // A registry that fails the FIRST pty adoption — standing in for every step between+ // the reconciliation decision and the commit that can throw (adoption itself, and on+ // a capability-carrying host the business assembly and the scheduler).+ class FailsLate extends HotResources {+ private adoptions = 0;+ override register(id: string, resource: unknown, dispose?: () => void): () => void {+ // The re-registration adoption performs, not the test's own seeding.+ if (id.startsWith("terminal:") && this.adoptions++ > 0) {+ throw new Error("adoption blew up");+ }+ return super.register(id, resource, dispose);+ }+ }+ const r = new FailsLate();+ const disposeDoomed = vi.fn();+ // `terminal` is offered in full and rides across; `sandbox` is a group this build no+ // longer declares, so it is DOOMED — and must still be alive after the failure.+ r.register(RESOURCE_IFACES_RESOURCE_ID, { ...PARKED, sandbox: ["x"] });+ r.register("sandbox:thing", "live", disposeDoomed);+ r.register(+ "terminal:pty1",+ { id: "pty1", onExit: () => () => {}, alive: () => true },+ () => {},+ );+ await expect(bootPlatform(r, { terminals: ["pty1"] })).rejects.toThrow(/adoption blew up/);+ // Disposing is irreversible — a killed pty does not come back — so it must not happen+ // until the App that decided it is actually standing. Recovery re-boots the previous+ // bundle, which can only be honest if what it re-adopts is still alive.+ expect(disposeDoomed).not.toHaveBeenCalled();+ expect(r.claim("sandbox:thing")).toBe("live");+ // The declaration is untouched too: the predecessor's is still the live one.+ expect(r.claim(RESOURCE_IFACES_RESOURCE_ID)).toMatchObject({ sandbox: ["x"] });+ });+it("a group this build stops declaring is disposed — unused resources must not leak", async () => {const r = new HotResources();const dispose = vi.fn();@@ -367,3 +413,78 @@ describe("a runtime too old to publish capabilities", () => {}});});++describe("teardown is a transaction, not a sequence of hopeful steps", () => {+ interface Api {+ park(): { v: string };+ drained?(): Promise<void>;+ }+ const Iface = defineIface<Api, { v: string }>({+ name: "t",+ version: 1,+ context: schema<{ v: string }>(type({ v: "string" })),+ methods: ["park"],+ });+ const doc = (): Json => initialDoc(Iface, { v: "a" });++ it("a partly-built boot unwinds the effects it already registered", async () => {+ const ran: string[] = [];+ await expect(+ boot(+ {+ create(ctx) {+ ctx.effect(() => ran.push("first"));+ ctx.effect(() => ran.push("second"));+ throw new Error("half-built");+ },+ },+ Iface,+ doc(),+ new HotResources(),+ ),+ ).rejects.toThrow(/half-built/);+ // Nothing else can reach them — the caller got an exception, not an instance — so a+ // leak here is permanent: a watcher, a listener or a child process for the process's+ // lifetime. Reverse order, the same convention a successful dispose follows.+ expect(ran).toEqual(["second", "first"]);+ });++ it("a rejected drain fails the upgrade instead of escaping over a disposed tree", async () => {+ const resources = new HotResources();+ let oldDisposed = false;+ const current = await boot(+ {+ create(ctx) {+ ctx.effect(() => {+ oldDisposed = true;+ });+ return {+ park: () => ({ v: "a" }),+ drained: () => Promise.reject(new Error("drain blew up")),+ };+ },+ },+ Iface,+ doc(),+ resources,+ );+ const result = await upgrade({+ current,+ impl: { create: () => ({ park: () => ({ v: "a" }) }) },+ iface: Iface,+ resources,+ });+ // The old tree IS down by then, so the caller must get the parked document back —+ // an escaping rejection would leave nothing booted and no state to recover from.+ expect(oldDisposed).toBe(true);+ expect(result.status).toBe("failed");+ if (result.status === "failed") {+ expect(errText(result.error)).toMatch(/drain blew up/);+ expect(result.doc).toMatchObject({ self: { v: "a" } });+ }+ });+});++function errText(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}