From 0f6cb0f712cb4dcfcccb45f0ec58b3962519dc92 Mon Sep 17 00:00:00 2001 From: Yaacov Date: Mon, 23 Nov 2026 12:25:47 +0200 Subject: [PATCH] fix(daemon): drop a lease whose connection closed while its open waited UnitTable.open() takes the connection's lease after awaiting the unit's creation, or another client's creation of the same unit. When the connection closed in that window, disconnected() had already run without the lease, so nothing dropped it and the unit stayed pinned. open() now drops such a lease as disconnected() would, reconnect grace and module released() hook included, and removes the closed connection's lease set. New contract SA-DAEMON-OPEN-LEASE, offered to Oh My Pi; realign at the next alignment. Co-Authored-By: Claude Opus 5.5 --- SCIENT.md | 1 + packages/coding-agent/src/daemon/units.ts | 10 ++ .../test/scient/daemon-open-lease.test.ts | 124 ++++++++++++++++++ scripts/scient/divergences.json | 13 ++ 4 files changed, 148 insertions(+) create mode 100644 packages/coding-agent/test/scient/daemon-open-lease.test.ts diff --git a/SCIENT.md b/SCIENT.md index d7e311f1eb..b9049f071a 100644 --- a/SCIENT.md +++ b/SCIENT.md @@ -20,6 +20,7 @@ Everything else is upstream's code and behavior. | Native addon cache | A compiled binary extracts its addons into a directory named for their content, so two builds on one upstream version never load each other's, and it loads only from that directory. A modern addon that fails to load falls back to the same build's baseline addon; an addon found beside the executable is not a fallback. | | Symbol | The sign-in page every browser sign-in ends on and the `stats` dashboard show Scient Agent's symbol (`packages/utils/src/scient/scient-agent-symbol.svg.txt`, the file Scient Desktop shows for the agent; copy it over when the symbol changes) in Scient's colors. | | Shared workers | The tiny model worker, the embedding server and word prediction run in Oh My Pi's per-user daemon. The daemon's build carries Scient Agent's release, not the upstream package version, so a new Scient Agent release has an older release's daemon re-exec into it, which replaces its workers. | +| Daemon leases | A client that disconnects while Oh My Pi's per-user daemon is still starting a unit for it (a language server, a worker, a background process) no longer leaves that unit running for good: its lease is dropped as on any lost connection, after the usual reconnect grace. Offered to Oh My Pi as [#20263](https://github.com/can1357/oh-my-pi/pull/20263); to be realigned at the next alignment, retired if Oh My Pi merges it or replaced by Oh My Pi's own fix. | | Updates | `scient-agent update` only updates plugins. The startup update check and the startup marketplace refresh are off, and Oh My Pi's background auto-update is never offered or started. A host or installer replaces the executable. | | Reporting | Automatic tool-issue reports to OMP's service are off by default. | | Shell traces | The bash tool records no execution trace unless the user turns `display.shellVisualization` on. Scient Agent's host draws no shell visualization, and every live frame of a running command would carry the whole trace, up to megabytes. | diff --git a/packages/coding-agent/src/daemon/units.ts b/packages/coding-agent/src/daemon/units.ts index eaa184ebfb..761428a34a 100644 --- a/packages/coding-agent/src/daemon/units.ts +++ b/packages/coding-agent/src/daemon/units.ts @@ -588,6 +588,16 @@ export class UnitTable { entry.lastUsed = Date.now(); let lease: string | undefined; if (request.lease !== false) lease = this.#addLease(entry, connection); + // scient(SA-DAEMON-OPEN-LEASE): begin - A connection that closed while this open awaited the unit was already disconnected without this lease: drop it as `disconnected` would. + if (lease !== undefined && connection.closed) { + entry.idleNotBefore = Math.max(entry.idleNotBefore ?? 0, Date.now() + DAEMON_RESUME_LEASE_GRACE_MS); + this.#dropLease(lease); + lease = undefined; + // `#addLease` recreated the closed connection's lease set; `disconnected` will not run again to remove it. + const connectionId = connection.client.connectionId; + if (this.#connectionLeases.get(connectionId)?.size === 0) this.#connectionLeases.delete(connectionId); + } + // scient(SA-DAEMON-OPEN-LEASE): end if (request.awaitReady !== false) { try { if (entry.procRuntime && entry.proc?.ready) { diff --git a/packages/coding-agent/test/scient/daemon-open-lease.test.ts b/packages/coding-agent/test/scient/daemon-open-lease.test.ts new file mode 100644 index 0000000000..7745cb09cb --- /dev/null +++ b/packages/coding-agent/test/scient/daemon-open-lease.test.ts @@ -0,0 +1,124 @@ +/** + * A lease taken by a connection that closed while its `open` was still waiting for the unit to be created + * is dropped as a lost connection's, instead of pinning the unit forever. + */ +import { afterEach, describe, expect, it } from "bun:test"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import type { DaemonModule, ModuleClient, ModuleUnit } from "../../src/daemon/module"; +import { + DAEMON_RESUME_LEASE_GRACE_MS as LEASE_GRACE_MS, + type DaemonEvent, + GLOBAL_SCOPE, + type UnitPolicy, +} from "../../src/daemon/protocol"; +import { DaemonStore } from "../../src/daemon/store"; +import { type UnitConnection, UnitTable } from "../../src/daemon/units"; + +const KIND = "gated"; +// No idle delay of its own, so an idle timer that waits longer shows the reconnect grace. +const POLICY: UnitPolicy = { hold: "leases", idleMs: 0, onIdle: "stop", restart: "no", survive: "none" }; + +interface Harness { + table: UnitTable; + /** Let the pending module open finish. */ + finishOpen(): void; + /** Clients the unit's `released` hook was called for. */ + released: string[]; +} + +const cleanups: (() => Promise | void)[] = []; + +afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); +}); + +async function startTable(): Promise { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "daemon-open-lease-")); + const store = DaemonStore.open(path.join(dir, "daemon.db")); + const gate = Promise.withResolvers(); + const released: string[] = []; + const module: DaemonModule = { + kind: KIND, + version: 1, + policy: () => POLICY, + async open(): Promise { + await gate.promise; + const exited = Promise.withResolvers<{ reason?: string }>(); + return { + label: "gated", + pids: () => [], + ready: Promise.resolve(), + busy: () => false, + attach() {}, + released: (client: ModuleClient) => void released.push(client.connectionId), + async stop(reason: string) { + exited.resolve({ reason }); + }, + exited: exited.promise, + }; + }, + }; + const table = new UnitTable({ store, modules: [module], resumed: false, onLivenessChange() {} }); + await table.start(); + cleanups.push(() => fs.rmSync(dir, { recursive: true, force: true })); + cleanups.push(() => store.close()); + cleanups.push(() => table.shutdown()); + return { table, finishOpen: () => gate.resolve(), released }; +} + +function connection(): UnitConnection & { closed: boolean } { + return { + client: { connectionId: crypto.randomUUID(), pid: 0, build: "" }, + closed: false, + send(_event: DaemonEvent) {}, + }; +} + +function unit(table: UnitTable) { + const found = table.list({ op: "list", kind: KIND }).units[0]; + if (!found) throw new Error("the gated unit is missing"); + return found; +} + +describe("daemon open after its connection closed", () => { + it("drops the lease of a connection that closed while its open created the unit", async () => { + const { table, finishOpen, released } = await startTable(); + const client = connection(); + + const opening = table.open(client, { kind: KIND, scope: GLOBAL_SCOPE, key: "k" }); + const closedAt = Date.now(); + client.closed = true; + table.disconnected(client); + finishOpen(); + await opening; + + const snapshot = unit(table); + expect(snapshot.leases).toBe(0); + // The idle timer is armed again, after the reconnect grace: the unit is no longer pinned. + expect(snapshot.idleAt).toBeGreaterThanOrEqual(closedAt + LEASE_GRACE_MS); + expect(released).toEqual([client.client.connectionId]); + }); + + it("drops the lease of a connection that closed while its open waited for another client's creation", async () => { + const { table, finishOpen, released } = await startTable(); + const creator = connection(); + const waiter = connection(); + + const creating = table.open(creator, { kind: KIND, scope: GLOBAL_SCOPE, key: "k" }); + const waiting = table.open(waiter, { kind: KIND, scope: GLOBAL_SCOPE, key: "k" }); + const closedAt = Date.now(); + waiter.closed = true; + table.disconnected(waiter); + finishOpen(); + const created = await creating; + await waiting; + + expect(unit(table).leases).toBe(1); + expect(released).toEqual([waiter.client.connectionId]); + table.release(creator, created.lease!); + expect(unit(table).leases).toBe(0); + expect(unit(table).idleAt).toBeGreaterThanOrEqual(closedAt + LEASE_GRACE_MS); + }); +}); diff --git a/scripts/scient/divergences.json b/scripts/scient/divergences.json index 4192275795..e0671a96fe 100644 --- a/scripts/scient/divergences.json +++ b/scripts/scient/divergences.json @@ -557,6 +557,19 @@ "bun --cwd=packages/coding-agent test test/scient/codex-plugins.test.ts test/scient/codex-plugins-oauth.test.ts test/scient/mcp-host-command.test.ts" ] }, + "SA-DAEMON-OPEN-LEASE": { + "status": "active", + "contract": "A daemon client whose connection closes while its open is still waiting for the unit to be created (its own creation or another client's) does not leave the unit pinned: the lease taken after disconnected() already ran is dropped as disconnected() would drop it, with the reconnect grace and the module's released() hook, and the closed connection keeps no lease record. Offered to Oh My Pi as can1357/oh-my-pi#20263. At the next alignment, retire this contract as upstreamed if Oh My Pi merged that fix, or replace it with Oh My Pi's own fix if it fixed this differently.", + "owned": [ + "packages/coding-agent/test/scient/daemon-open-lease.test.ts" + ], + "upstream": [ + "packages/coding-agent/src/daemon/units.ts" + ], + "verification": [ + "bun --cwd=packages/coding-agent test test/scient/daemon-open-lease.test.ts" + ] + }, "SA-DAEMON-REJOIN": { "status": "active", "contract": "Oh My Pi's daemon test \"a client reconnecting within the grace adopts the same process\" reopens the unit only after describe shows the daemon dropped the closed connection's lease, as the grace test above it waits. The harness's close() settles when the client socket closes, before the daemon handles the close, so the open could be counted beside the stale lease (leases 2), which failed Scient's main on 2026-11-22. Test-only; the daemon's connection-bound lease accounting is unchanged. This inherited flake needs an upstream fix.",