layerfs 0.10.1: recover the page service after a host handover (#961)

When plugins change, magpie retires the old plugin host and starts a new one. The old host can keep port 43717 for up to 10 minutes while it finishes calls. In 0.10.0, the new host stored its failed bind as the service, and `if (service) return` blocked every later try. Once the old host exited, the page stayed refused until the host restarted.

Now a service is kept only once it is listening. A failed bind retries with backoff (1s, doubling, capped at 30s, the timer unref'd) while a store exists, and a listener that closes starts again. A failed backend start is retried too, and the first mutation's race with the empty-store check gets one more check. layerfs 0.10.1.

Run at the reviewed head 6f2d484e8f3367d1d614d4be5d9a44a701165fb4, on mote (temp HOME, Bun 1.4.2):
- bun test packages/layerfs: 68 pass (main: 64). page-lifecycle.test.mjs: 3 of 3 green. bun scripts/check.mjs: exit 0.
- The new tests against main's index.mjs: the handover and backend-retry tests go red.
- Broken by hand: dropping the backendPromise reset, the retry schedule, or storing the service before it listens each turns a test red.
- Probes: a closed listener comes back; with the port held for good, the retries cap at one every 30s and leak no servers; a pending retry doesn't hold the process open. page-service.mjs is unchanged, so its Host and Origin checks cover every retry.

Not covered by a test (follow-up): restarting a closed listener, sharing one startup between concurrent calls, and the store-version recheck. recheck and storeVersion overlap: either alone handles the race.
This commit is contained in:
Calmhayl
2026-11-11 10:25:25 +08:00
committed by GitHub
parent f8a52a2477
commit 2ee2ee84f9
5 changed files with 323 additions and 15 deletions
+20
View File
@@ -192,6 +192,15 @@ serves its chat page:
refused-to-connect page until the first project is provisioned;
a store with no recorded checkpoints yet shows the page's honest
empty state.
- **The service recovers after a host handover.** A retired plugin
host may still hold the page port while finishing a request. The
replacement retries a failed bind automatically, starting after
one second and backing off to at most 30 seconds. A closed listener
is retried too; concurrent tool calls share one startup attempt.
Retries begin only after a project store exists, write no extra
checkpoints, and do not keep an otherwise finished host alive.
An already refused frame may need a reload after the listener
recovers; neither the gateway nor an agent task needs restarting.
- **The service is closed to other sites.** It emits no CORS
headers and refuses any request carrying an Origin (a sandboxed
iframe's fetch sends `Origin: null`); it serves no `.js` data
@@ -228,6 +237,17 @@ node tools/gen-trajectory.mjs # regenerate the page's bundled sample trajector
Zero runtime dependencies; the arguments are JSON Schema, like the other
tools packages. MIT.
## Changes in 0.10.1
The page service now survives Magpie replacing its plugin host. A
retired host can keep port 43717 until its in-flight request finishes;
the replacement now retries a failed bind with bounded backoff instead
of remembering a server that never listened. Once the port is free,
the page recovers without another tool call or a gateway restart. A
closed listener is restarted too, and concurrent calls share one
startup check. Retries only begin after a project exists, so an empty
store still writes nothing and starts no polling.
## Changes in 0.10.0
The page's live channel comes back, out of the plugin's own folder. The
@@ -0,0 +1,49 @@
import { pathToFileURL } from "node:url"
let releaseTrajectory
if (process.env.LAYERFS_TEST_HOLD_TRAJECTORY === "1") {
const { SimBackend } = await import(new URL("../layerfs.mjs", import.meta.url))
const trajectory = SimBackend.prototype.trajectory
const gate = new Promise((resolve) => { releaseTrajectory = resolve })
SimBackend.prototype.trajectory = async function () {
await gate
return trajectory.call(this)
}
}
const { LayerfsTools } = await import(pathToFileURL(process.env.LAYERFS_TEST_INDEX).href)
const plugin = await LayerfsTools({}, { pagePort: Number(process.env.LAYERFS_TEST_PORT) })
process.on("message", async ({ id, method }) => {
try {
let result
if (method === "provision" || method === "concurrent") {
const provision = () => plugin.tool.provision.execute({
project: "fixture",
source: process.env.LAYERFS_TEST_SOURCE,
}, {})
result = method === "concurrent"
? await Promise.all(Array.from({ length: 20 }, provision))
: await provision()
} else if (method === "releaseTrajectory") {
releaseTrajectory()
} else if (method === "backendFailure") {
process.env.MAGPIE_LAYERFS_NATIVE = "1"
try {
await plugin.tool.status.execute()
throw new Error("native backend should be refused")
} catch (error) {
if (!String(error.message).includes("sim-only")) throw error
result = { rejected: true }
} finally {
process.env.MAGPIE_LAYERFS_NATIVE = ""
}
} else if (method === "status") {
result = await plugin.tool.status.execute()
} else {
throw new Error(`unknown test method ${method}`)
}
process.send({ id, result })
} catch (error) {
process.send({ id, error: String(error?.stack || error) })
}
})
process.send({ ready: true })
+82 -14
View File
@@ -51,7 +51,10 @@ const callingAgent = (ctx) => {
export const LayerfsTools = async (ctx = {}, options = {}) => {
let backendPromise
const backend = () => (backendPromise ??= createBackend(process.env, options))
const backend = () => (backendPromise ??= createBackend(process.env, options).catch((error) => {
backendPromise = undefined
throw error
}))
const execEnabled = () => options?.exec === true || process.env.MAGPIE_LAYERFS_EXEC === "1"
// A call touches only the state its own operation needs. Reads (history,
// resolve, status) change nothing and start nothing.
@@ -59,20 +62,82 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
const b = await backend()
return fn(b)
}
// The page's service, started once: the gates above, then a listen on
// the configured port (options.pagePort, MAGPIE_LAYERFS_PAGE_PORT,
// else the default). A second call while the first service lives is
// a no-op; a failed start stays failed for this instance, quietly.
// A new host may start before the retired host releases this port.
// Keep one start in flight, and remember a service only after it
// actually listens. Retry while a real store exists, without keeping
// an otherwise finished host alive or polling before the first project.
let service = null
const ensureService = async () => {
if (service) return
let hasEntries = false
try { hasEntries = readdirSync(join(storeHome(), "projects")).length > 0 } catch { /* no store yet */ }
if (!hasEntries) return
let data
try { data = await (await backend()).trajectory() } catch { return }
if (!data.projects.length) return
service = startPageService({ backend: await backend(), port: resolvePagePort(options) })
let starting = null
let retryTimer = null
let retryDelay = 1000
let storeVersion = 0
let recheck = false
let hasStore = false
const retry = () => {
if (!hasStore || retryTimer || service?.server.listening) return
retryTimer = setTimeout(() => {
retryTimer = null
ensureService().catch(() => { /* the page never blocks a tool */ })
}, retryDelay)
retryTimer.unref?.()
retryDelay = Math.min(retryDelay * 2, 30000)
}
const ensureService = () => {
if (service?.server.listening) return Promise.resolve()
if (starting) {
recheck = true
return starting
}
if (retryTimer) {
clearTimeout(retryTimer)
retryTimer = null
}
const version = storeVersion
recheck = false
starting = (async () => {
let hasEntries
try {
hasEntries = readdirSync(join(storeHome(), "projects")).length > 0
} catch (error) {
hasStore = false
return
}
if (!hasEntries) {
hasStore = false
return
}
const b = await backend()
const data = await b.trajectory()
if (!data.projects.length) {
hasStore = false
return
}
hasStore = true
const candidate = startPageService({ backend: b, port: resolvePagePort(options) })
const stopped = () => {
if (service !== candidate || candidate.server.listening) return
service = null
retry()
}
candidate.server.once("close", stopped)
candidate.server.on("error", stopped)
if (!await candidate.listening || !candidate.server.listening) {
retry()
return
}
service = candidate
retryDelay = 1000
})().catch(() => {
retry()
}).finally(() => {
starting = null
if ((recheck || storeVersion !== version) &&
!service?.server.listening && !retryTimer) {
recheck = false
queueMicrotask(() => ensureService().catch(() => { /* the tools stay usable */ }))
}
})
return starting
}
ensureService().catch(() => { /* no service: the tools are untouched */ })
// A mutating call may have created the store's first project: offer
@@ -80,6 +145,9 @@ export const LayerfsTools = async (ctx = {}, options = {}) => {
const mutate = async (fn) => {
const b = await backend()
const out = await fn(b)
// The first mutation may race the factory's empty-store check. Let the
// in-flight check finish, then run one more against the new store.
storeVersion++
ensureService().catch(() => { /* never on the tool call's path */ })
return out
}
+1 -1
View File
@@ -49,5 +49,5 @@
"directory": "packages/layerfs"
},
"type": "module",
"version": "0.10.0"
"version": "0.10.1"
}
+171
View File
@@ -0,0 +1,171 @@
import { afterAll, expect, test } from "bun:test"
import assert from "node:assert/strict"
import { fork } from "node:child_process"
import { access, mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"
import http from "node:http"
import { tmpdir } from "node:os"
import { join, resolve, sep } from "node:path"
import { fileURLToPath } from "node:url"
import { setTimeout as delay } from "node:timers/promises"
const ownTestRoot = await mkdtemp(join(tmpdir(), "layerfs-page-lifecycle-"))
const target = process.env.LAYERFS_TEST_INDEX || join(import.meta.dir, "index.mjs")
afterAll(async () => {
const absolute = resolve(ownTestRoot)
assert.ok(absolute.startsWith(resolve(tmpdir()) + sep), "cleanup stays inside the test root")
await rm(absolute, { recursive: true, force: true })
}, 120_000)
async function until(action, message, timeout = 9000) {
const end = Date.now() + timeout
let last
do {
try {
last = await action()
if (last) return last
} catch {}
await delay(50)
} while (Date.now() < end)
assert.fail(`${message}; last=${JSON.stringify(last)}`)
}
async function request(port) {
return new Promise((resolve) => {
const req = http.get({ hostname: "127.0.0.1", port, path: "/" }, (response) => {
let body = ""
response.setEncoding("utf8").on("data", (chunk) => { body += chunk })
response.on("end", () => resolve(response.statusCode === 200 && body.includes("fixture")))
})
req.setTimeout(250, () => req.destroy())
req.on("error", () => resolve(false))
})
}
async function fixture({ block = false, holdTrajectory = false } = {}) {
const folder = await mkdtemp(join(ownTestRoot, "case-"))
const home = join(folder, "home")
const source = join(folder, "source")
await mkdir(home)
await mkdir(source)
await writeFile(join(source, "hello.txt"), "fixture content\n")
const blocker = http.createServer((_, response) => response.writeHead(503).end())
await new Promise((resolve) => blocker.listen(0, "127.0.0.1", resolve))
const port = blocker.address().port
if (!block) await new Promise((resolve) => blocker.close(resolve))
const store = join(home, "store")
const child = fork(fileURLToPath(new URL("./fixtures/page-lifecycle.mjs", import.meta.url)), [], {
env: {
...process.env,
HOME: home,
USERPROFILE: home,
MAGPIE_LAYERFS_HOME: store,
MAGPIE_LAYERFS_BACKEND: "sim",
MAGPIE_LAYERFS_NATIVE: "",
LAYERFS_TEST_INDEX: target,
LAYERFS_TEST_PORT: String(port),
LAYERFS_TEST_SOURCE: source,
LAYERFS_TEST_HOLD_TRAJECTORY: holdTrajectory ? "1" : "",
},
stdio: ["ignore", "pipe", "pipe", "ipc"],
})
let errorOutput = ""
child.stderr.on("data", (chunk) => { errorOutput += chunk })
const pending = new Map()
let readyResolve
const ready = new Promise((resolve) => { readyResolve = resolve })
child.on("message", (message) => {
if (message.ready) readyResolve(message)
else pending.get(message.id)?.(message)
})
let nextId = 0
const rpc = async (method) => {
const id = ++nextId
const response = await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`test RPC timed out: ${method}; ${errorOutput}`)), 5000)
pending.set(id, (message) => {
clearTimeout(timer)
pending.delete(id)
resolve(message)
})
child.send({ id, method })
})
if (response.error) throw new Error(response.error)
return response
}
const cleanup = async () => {
if (blocker.listening) await new Promise((resolve) => blocker.close(resolve))
if (child.exitCode === null) {
const exited = new Promise((resolve) => child.once("exit", resolve))
child.kill()
await exited
}
const absolute = resolve(folder)
assert.ok(absolute.startsWith(resolve(ownTestRoot) + sep), "cleanup stays inside the fixture")
await rm(absolute, { recursive: true, force: true })
}
try {
await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`child failed to initialize: ${errorOutput}`)), 5000)
ready.then((message) => { clearTimeout(timer); resolve(message) })
})
} catch (error) {
await cleanup()
throw error
}
return {
home, store, port, rpc, cleanup,
release: () => new Promise((resolve) => blocker.close(resolve)),
}
}
test("retries automatically after a retired host releases the page port", async () => {
const f = await fixture({ block: true })
try {
await f.rpc("provision")
expect(await request(f.port)).toBe(false)
// The first retry is due one second after the failed bind.
await delay(1200)
await f.release()
await until(() => request(f.port), "page must recover without another tool call", 3500)
} finally {
await f.cleanup()
}
}, 15_000)
test("concurrent reused provisions wait for the trajectory check", async () => {
const f = await fixture({ holdTrajectory: true })
try {
await f.rpc("provision")
const result = await f.rpc("concurrent")
expect(result.result.every((entry) => entry.reused)).toBe(true)
expect(await request(f.port)).toBe(false)
await f.rpc("releaseTrajectory")
await until(() => request(f.port), "one shared start must listen")
} finally {
await f.cleanup()
}
}, 15_000)
test("an absent project store writes nothing and starts no polling server", async () => {
const f = await fixture()
try {
await delay(1400)
await expect(access(f.store)).rejects.toThrow()
await expect(access(join(f.home, "projects"))).rejects.toThrow()
} finally {
await f.cleanup()
}
}, 15_000)
test("a rejected backend initialization is not cached forever", async () => {
const f = await fixture()
try {
expect((await f.rpc("backendFailure")).result.rejected).toBe(true)
const result = await f.rpc("status")
expect(result.result.backend).toBe("sim")
expect(result.result.projects).toEqual([])
} finally {
await f.cleanup()
}
}, 15_000)