diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0ddeed3..acd5049 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -39,7 +39,9 @@ agents (SQL, CLI, later MCP). Nothing leaves the machine. `/quantext view`: 1. `$.http.fetch('http://127.0.0.1:/health')`, with the port from `~/.quantext/engine.json` (4747 when free; - ADR 25). If it answers, go to step 4. + ADR 25). If it answers with the pid the file names, fetch `/` too (5 s): `/health` is answered from memory, so + an engine whose file reads hang passes it while the browser waits for ever. If `/` answers, go to step 4; if not, + stop that pid (`kill`, then `kill -KILL`, 3 s each) and go on to step 2. 2. Find a runtime: `node` ≥ 22.18, else `bun`, else show a clear message with install steps. 3. Start it detached: `$.process.run(['sh', '-c', 'umask 077; mkdir -p "$3" && chmod 700 "$3" && cd "$3" && nohup "$0" "$1" serve --live while-viewer >>"$2" 2>&1 /engine/engine.js', log, dataDir])`, paths as arguments (ADR 27). Poll `/health` up to 10 s. Every command, the version probes too, runs in @@ -52,6 +54,7 @@ The engine: - keeps **one instance per machine** (an OS file lock in `~/.quantext/`, plus the port; ADR 22); - **exits after an idle period** with no viewer connected (setting: `live ingest: while viewer open | always`); +- **ends its process when a stop takes more than 10 s**, so a stuck stop cannot keep the port and the lock; - writes its database and log to **`~/.quantext/`**, not to the plugin's data folder, because uninstalling a plugin deletes that folder. diff --git a/packages/engine/src/cli/deadline.ts b/packages/engine/src/cli/deadline.ts new file mode 100644 index 0000000..7ba0bbd --- /dev/null +++ b/packages/engine/src/cli/deadline.ts @@ -0,0 +1,15 @@ +/** A time limit for work that must not hang the process, such as the engine's stop. */ + +/** + * Runs `work` and calls `onLate` once if it has not settled within `ms`; the work goes on. The timer does not keep + * the process alive, so work that ends in time ends the process as before. + */ +export async function withDeadline(work: () => Promise, ms: number, onLate: () => void): Promise { + const timer = setTimeout(onLate, ms); + timer.unref(); + try { + return await work(); + } finally { + clearTimeout(timer); + } +} diff --git a/packages/engine/src/cli/serve.ts b/packages/engine/src/cli/serve.ts index 92de61a..bdf857a 100644 --- a/packages/engine/src/cli/serve.ts +++ b/packages/engine/src/cli/serve.ts @@ -15,6 +15,7 @@ import { createIngest, watchTranscripts } from "../ingest/index.ts"; import { createQuery, installViews } from "../query/index.ts"; import type { SqlDriver, Store } from "../store/index.ts"; import { openReader, openStore, StoreLockedError } from "../store/index.ts"; +import { withDeadline } from "./deadline.ts"; import { engineUrl, printable, readEngineFile, removeEngineFile, writeEngineFile } from "./engine-file.ts"; import { openUrl } from "./open-url.ts"; import { probeHealth } from "./probe.ts"; @@ -24,6 +25,8 @@ const API_VERSION = 1; /** The engine's port when it is free (ADR 25); else any free port, named in `engine.json`. */ export const DEFAULT_PORT = 4747; export const DEFAULT_IDLE_MINUTES = 10; +/** How long a stop may take before the process ends anyway: a stuck stop must not hold the port and the lock. */ +export const STOP_TIMEOUT_MS = 10_000; export interface ServeOptions { dataDir: string; @@ -197,13 +200,25 @@ export async function serve(options: ServeOptions, hooks: ServeHooks): Promise undefined); // reported above - await watcher?.stop(); - await api?.close(); - await worker?.close(); - reader?.close(); - store.close(); - removeEngineFile(dataDir, process.pid); + await withDeadline( + async () => { + await catchUp.catch(() => undefined); // reported above + await watcher?.stop(); + await api?.close(); + await worker?.close(); + reader?.close(); + store.close(); + removeEngineFile(dataDir, process.pid); + }, + STOP_TIMEOUT_MS, + () => { + // A stuck stop still answers /health from memory while file reads never end: the viewer would load forever. + hooks.err(`qx: the engine did not stop within ${STOP_TIMEOUT_MS / 1000} s; exiting\n`); + removeEngineFile(dataDir, process.pid); + // Not process.exit: it waits for the thread pool, and a thread blocked in a system call never returns. + process.kill(process.pid, "SIGKILL"); + }, + ); } } diff --git a/packages/engine/src/ingest/discover.ts b/packages/engine/src/ingest/discover.ts index 34203c4..ef73e93 100644 --- a/packages/engine/src/ingest/discover.ts +++ b/packages/engine/src/ingest/discover.ts @@ -88,7 +88,8 @@ export async function logFiles(main: string): Promise<{ files: LogFiles; errors: errors.push({ path: dir, error: describe(error) }); return; } - const names = new Set(entries.map((e) => e.name)); + // Regular files only: open() on a FIFO waits for a writer and holds a thread-pool thread for ever. + const names = new Set(entries.filter((e) => e.isFile()).map((e) => e.name)); for (const entry of entries) { const path = join(dir, entry.name); if (entry.isDirectory()) await walk(path); diff --git a/packages/engine/test/cli/deadline.test.ts b/packages/engine/test/cli/deadline.test.ts new file mode 100644 index 0000000..708513b --- /dev/null +++ b/packages/engine/test/cli/deadline.test.ts @@ -0,0 +1,34 @@ +import { expect, test } from "vitest"; +import { withDeadline } from "../../src/cli/deadline.ts"; + +test("work that never ends calls onLate once its time is up", async () => { + const late = new Promise((resolve) => { + void withDeadline( + () => new Promise(() => undefined), + 10, + () => resolve("late"), + ); + }); + expect(await late).toBe("late"); +}); + +test("work that ends in time gives its result, and onLate is never called", async () => { + let lateCalls = 0; + expect( + await withDeadline( + async () => 7, + 10, + () => lateCalls++, + ), + ).toBe(7); + await new Promise((r) => setTimeout(r, 30)); + expect(lateCalls).toBe(0); +}); + +test("work that fails in time passes its error on, and onLate is never called", async () => { + let lateCalls = 0; + const failing = () => Promise.reject(new Error("closing failed")); + await expect(withDeadline(failing, 10, () => lateCalls++)).rejects.toThrow("closing failed"); + await new Promise((r) => setTimeout(r, 30)); + expect(lateCalls).toBe(0); +}); diff --git a/packages/engine/test/ingest/ingest.test.ts b/packages/engine/test/ingest/ingest.test.ts index 36d6d6f..f1e5fb2 100644 --- a/packages/engine/test/ingest/ingest.test.ts +++ b/packages/engine/test/ingest/ingest.test.ts @@ -1,7 +1,11 @@ +import { execFileSync } from "node:child_process"; import { appendFileSync, chmodSync, + closeSync, + constants, mkdirSync, + openSync, readdirSync, readFileSync, renameSync, @@ -427,6 +431,29 @@ describe("subagents", () => { expect(expected.sessions.find((x) => x.parentId !== undefined)).toBeDefined(); }); + test("whose meta file is not a regular file (a FIFO) are read without it, and the read does not block", async () => { + // open() on a FIFO waits for a writer, holding a thread-pool thread: the stop of the engine then never ended. + const s = await setup(); + const files = layout(s.root, "subagent"); + writeText(files.main, readFileSync(files.source)); + const agent = files.subagents[0]; + if (agent === undefined || agent.meta === undefined) throw new Error("the subagent scenario has a meta file"); + writeText(agent.path, readFileSync(agent.source)); + execFileSync("mkfifo", [agent.meta]); + const fifo = agent.meta; + // Lets a blocked open() go on, so a failing run does not keep a pool thread for ever. + onCleanup(() => { + try { + closeSync(openSync(fifo, constants.O_WRONLY | constants.O_NONBLOCK)); + } catch { + // ENXIO: no reader waits on the FIFO, which is the passing case + } + }); + const timeout = new Promise((r) => setTimeout(() => r("blocked"), 2000)); + expect(await Promise.race([s.ingest.ingestAll().then(() => "read"), timeout])).toBe("read"); + expect(graphOf(s.store, files.main).sessions).toHaveLength(2); + }); + test("and the main transcript growing together give the same graph as one read", async () => { const s = await setup(); const files = layout(s.root, "subagent"); diff --git a/packages/mod/src/viewer.ts b/packages/mod/src/viewer.ts index b9bac01..516b836 100644 --- a/packages/mod/src/viewer.ts +++ b/packages/mod/src/viewer.ts @@ -1,6 +1,6 @@ /** * `/quantext view`: find the engine by `~/.quantext/engine.json` and `/health`, start the bundled one when none - * runs, and open the viewer. The engine is started only here, never by itself (ARCHITECTURE "Starting the + * runs (or when the one found does not serve the viewer's page: it is stopped first), and open the viewer. The engine is started only here, never by itself (ARCHITECTURE "Starting the * engine"). Each step's outcome reaches the person as a toast. */ import type { EngineInterface } from "claude-code"; @@ -13,6 +13,10 @@ export const HEALTH_TIMEOUT_MS = 1_000; /** How long a started engine has to answer, and how often it is asked. */ export const START_TIMEOUT_MS = 10_000; export const START_POLL_MS = 250; +/** How long the viewer's page may take: an engine still catching up is slow, a stuck one never answers. */ +export const PAGE_TIMEOUT_MS = 5_000; +/** How long an engine has to go after each signal (`kill`, then `kill -KILL`). */ +export const STOP_WAIT_MS = 3_000; /** * Starts the engine detached, with every path passed as an argument (`$0` the runtime, `$1` the engine, `$2` @@ -25,7 +29,10 @@ export const START_SCRIPT = /** How much of a failed start's stderr a toast shows. */ const STDERR_SHOWN = 200; -type Found = { kind: "same"; url: string } | { kind: "other"; version: string; pid: number } | { kind: "none" }; +type Found = + | { kind: "same"; url: string; port: number; pid: number } + | { kind: "other"; version: string; pid: number } + | { kind: "none" }; /** * What a command run gave, or undefined when it could not start (not on PATH). It runs in `cwd`, never the @@ -52,9 +59,13 @@ async function readEngineFile($: EngineInterface, dataDir: string): Promise($: EngineInterface, ms: number, answer: Promise): Promise { + return Promise.race([answer, $.clock.sleep(ms).then(() => undefined)]); +} + /** `/health` of the address, or undefined when it does not answer within HEALTH_TIMEOUT_MS. */ async function askHealth($: EngineInterface, port: number) { - const timeout = $.clock.sleep(HEALTH_TIMEOUT_MS).then(() => undefined); const answer = $.http.fetch(`${engineUrl(port)}health`).then( (r) => (r.ok ? parseHealth(r.text) : undefined), (error: unknown) => { @@ -62,7 +73,39 @@ async function askHealth($: EngineInterface, port: number) { return undefined; }, ); - return Promise.race([answer, timeout]); + return within($, HEALTH_TIMEOUT_MS, answer); +} + +/** + * Whether the engine serves the viewer's page. `/health` is answered from memory, so an engine whose file reads + * hang (seen in a stop that never ended) passes it, and the browser then waits for ever. + */ +async function servesPage($: EngineInterface, port: number): Promise { + const answer = $.http.fetch(engineUrl(port)).then( + (r) => r.ok, + (error: unknown) => { + $.ui.log(`quantext: the viewer's page: ${String(error)}`, { to: "debug" }); + return false; + }, + ); + return (await within($, PAGE_TIMEOUT_MS, answer)) === true; +} + +/** + * Stops the engine with this pid: `kill`, then `kill -KILL`, each given STOP_WAIT_MS to take effect. The pid is + * the one `/health` answered with, so it is the engine's. True once that engine answers no more. + */ +async function stopEngine($: EngineInterface, dataDir: string, version: string, pid: number, cwd: string) { + const signals = [() => tryRun($, ["kill", String(pid)], cwd), () => tryRun($, ["kill", "-KILL", String(pid)], cwd)]; + for (const send of signals) { + await send(); + const until = (await $.clock.now()) + STOP_WAIT_MS; + while ((await $.clock.now()) < until) { + await $.clock.sleep(START_POLL_MS); + if ((await findEngine($, dataDir, version)).kind === "none") return true; + } + } + return false; } /** The engine `engine.json` names, if it answers as that process; `other` when it is another version. */ @@ -72,7 +115,7 @@ async function findEngine($: EngineInterface, dataDir: string, version: string): const health = await askHealth($, file.port); if (health === undefined || health.pid !== file.pid) return { kind: "none" }; // stale file, or a hung engine if (health.version !== version) return { kind: "other", version: health.version, pid: health.pid }; - return { kind: "same", url: engineUrl(file.port) }; + return { kind: "same", url: engineUrl(file.port), port: file.port, pid: file.pid }; } /** `node` when it is 22.18 or later, else `bun` when it is 1.3.3 or later, else undefined. */ @@ -109,6 +152,18 @@ export async function openViewer($: EngineInterface): Promise { } let found = await findEngine($, dataDir, version); + if (found.kind === "same" && !(await servesPage($, found.port))) { + const { pid } = found; + $.ui.toast(`quantext: the engine (pid ${pid}) does not serve the viewer; starting it again…`); + if (!(await stopEngine($, dataDir, version, pid, engineDir))) { + $.ui.toast( + `quantext: the engine (pid ${pid}) does not serve the viewer and did not stop; ` + + `stop it (kill -9 ${pid}), then run /quantext view again.`, + ); + return; + } + found = { kind: "none" }; + } if (found.kind === "none") { const runtime = await findRuntime($, engineDir); if (runtime === undefined) { diff --git a/packages/mod/test/viewer-world.ts b/packages/mod/test/viewer-world.ts index a346b68..0f58672 100644 --- a/packages/mod/test/viewer-world.ts +++ b/packages/mod/test/viewer-world.ts @@ -34,6 +34,8 @@ export interface WorldOptions { /** What each URL answers; one not listed is refused. Once the engine starts: `afterStart`, and an engine.json. */ http?: Record; afterStart?: Record; + /** What each URL answers once `kill` has run with this signal (`TERM` for a plain `kill`); unset: no change. */ + afterKill?: Partial>>; /** Each command's `--version` output; a command not listed is not on PATH. */ versions?: Record; /** What `uname -s` prints. */ @@ -91,6 +93,11 @@ export function world(on: On, options: WorldOptions = {}) { return { value: ran("") }; } if (cmd === "open" || cmd === "xdg-open") return { value: ran("") }; + if (cmd === "kill") { + const after = options.afterKill?.[arg === "-KILL" ? "KILL" : "TERM"]; + if (after !== undefined) http = after; + return { value: ran("") }; + } const version = options.versions?.[cmd]; if (version === undefined || arg !== "--version") throw new Error(`spawn ${cmd} ENOENT`); return { value: ran(`${version}\n`) }; diff --git a/packages/mod/test/viewer.test.ts b/packages/mod/test/viewer.test.ts index 792ca44..9697028 100644 --- a/packages/mod/test/viewer.test.ts +++ b/packages/mod/test/viewer.test.ts @@ -1,3 +1,4 @@ +import type { HttpResponse } from "claude-code"; import { expect, test } from "claude-code/testing"; import { parseEngineFile } from "../src/engine-file.ts"; import { command } from "./kit.ts"; @@ -6,12 +7,15 @@ import { DATA, engineFile, health, world } from "./viewer-world.ts"; const HEALTH = "http://127.0.0.1:4747/health"; const URL = "http://127.0.0.1:4747/"; +const PAGE: HttpResponse = { status: 200, ok: true, headers: { "content-type": "text/html" }, text: "" }; +const SERVES = { [HEALTH]: health(), [URL]: PAGE }; + test("/quantext view opens a running engine of the same version and starts nothing", async ($, on) => { - const w = world(on, { files: { [`${DATA}/engine.json`]: engineFile() }, http: { [HEALTH]: health() } }); + const w = world(on, { files: { [`${DATA}/engine.json`]: engineFile() }, http: SERVES }); const r = await $.command.run(command("quantext", "view")); expect(r.text).toBe("quantext: opening the viewer…"); await w.settle(); - expect(w.fetched).toEqual([HEALTH]); + expect(w.fetched).toEqual([HEALTH, URL]); expect(w.argvs).toEqual([ ["uname", "-s"], ["open", URL], @@ -24,15 +28,71 @@ test("the address is built from the port alone: a url in engine.json reaches no const file = engineFile({ port: 5001, url: evil }); const w = world(on, { files: { [`${DATA}/engine.json`]: file }, - http: { "http://127.0.0.1:5001/health": health() }, + http: { "http://127.0.0.1:5001/health": health(), "http://127.0.0.1:5001/": PAGE }, }); await $.command.run(command("quantext", "view")); await w.settle(); - expect(w.fetched).toEqual(["http://127.0.0.1:5001/health"]); + expect(w.fetched).toEqual(["http://127.0.0.1:5001/health", "http://127.0.0.1:5001/"]); expect(w.argvs.at(-1)).toEqual(["open", "http://127.0.0.1:5001/"]); expect(JSON.stringify([w.fetched, w.argvs, w.toasts])).not.toContain("evil"); }); +test("an engine that answers /health but not the viewer's page is stopped and started again", async ($, on) => { + const w = world(on, { + files: { [`${DATA}/engine.json`]: engineFile() }, + http: { [HEALTH]: health(), [URL]: "hang" }, + afterKill: { TERM: {} }, + versions: { node: "v24.14.0" }, + afterStart: SERVES, + }); + await $.command.run(command("quantext", "view")); + await w.settle(); + expect(w.argvs.map((a) => a.slice(0, 2))).toEqual([ + ["kill", "4242"], + ["node", "--version"], + ["sh", "-c"], + ["uname", "-s"], + ["open", URL], + ]); + expect(w.toasts).toEqual([ + "quantext: the engine (pid 4242) does not serve the viewer; starting it again…", + "quantext: starting the engine…", + `quantext: the viewer is at ${URL}`, + ]); +}); + +test("a stuck engine that outlasts kill gets kill -KILL", async ($, on) => { + const w = world(on, { + files: { [`${DATA}/engine.json`]: engineFile() }, + http: { [HEALTH]: health(), [URL]: { ...PAGE, status: 500, ok: false } }, + afterKill: { KILL: {} }, + versions: { node: "v24.14.0" }, + afterStart: SERVES, + }); + await $.command.run(command("quantext", "view")); + await w.settle(); + expect(w.argvs.slice(0, 3).map((a) => a.slice(0, 2))).toEqual([ + ["kill", "4242"], + ["kill", "-KILL"], + ["node", "--version"], + ]); + expect(w.toasts.at(-1)).toBe(`quantext: the viewer is at ${URL}`); +}); + +test("an engine that cannot be stopped is named with its pid, and nothing is started", async ($, on) => { + const w = world(on, { + files: { [`${DATA}/engine.json`]: engineFile() }, + http: { [HEALTH]: health(), [URL]: "hang" }, + versions: { node: "v24.14.0" }, + }); + await $.command.run(command("quantext", "view")); + await w.settle(); + expect(w.argvs.map((a) => a[0])).toEqual(["kill", "kill"]); + expect(w.toasts.at(-1)).toBe( + "quantext: the engine (pid 4242) does not serve the viewer and did not stop; stop it (kill -9 4242), then run /quantext view again.", + ); +}); + test("engine.json is checked field by field", () => { const ok = { apiVersion: 1, version: "0.4.0", pid: 7, port: 4747 }; const text = (fields: Record) => JSON.stringify({ ...ok, ...fields }); @@ -162,7 +222,7 @@ test("an engine of another version is named with its pid to stop, and nothing is }); test("on Linux it opens the viewer with xdg-open; elsewhere it only shows the address", async ($, on) => { - const w = world(on, { files: { [`${DATA}/engine.json`]: engineFile() }, http: { [HEALTH]: health() }, os: "Linux" }); + const w = world(on, { files: { [`${DATA}/engine.json`]: engineFile() }, http: SERVES, os: "Linux" }); await $.command.run(command("quantext", "view")); await w.settle(); expect(w.argvs.at(-1)).toEqual(["xdg-open", URL]); @@ -171,7 +231,7 @@ test("on Linux it opens the viewer with xdg-open; elsewhere it only shows the ad test("on another OS it shows the address and opens nothing", async ($, on) => { const w = world(on, { files: { [`${DATA}/engine.json`]: engineFile() }, - http: { [HEALTH]: health() }, + http: SERVES, os: "FreeBSD", }); await $.command.run(command("quantext", "view")); diff --git a/scripts/lib/egress-policy.ts b/scripts/lib/egress-policy.ts index b878f4d..04eeda1 100644 --- a/scripts/lib/egress-policy.ts +++ b/scripts/lib/egress-policy.ts @@ -25,6 +25,11 @@ export const POLICY: EgressPolicy = { { argv: ["rundll32", "url.dll,FileProtocolHandler", null], reason: "opens the viewer's URL on Windows" }, { argv: [["node", "bun"], "--version"], reason: "the mod finds a runtime for the engine" }, { argv: ["uname", "-s"], reason: "the mod picks open or xdg-open" }, + { + argv: ["kill", null], + reason: "the mod stops its own engine (pid from /health) when it does not serve the viewer", + }, + { argv: ["kill", "-KILL", null], reason: "the mod ends its own engine when kill did not stop it" }, { argv: ["sh", "-c", START_SCRIPT, ["node", "bun"], null, null, null], reason: "the mod starts the bundled engine detached (ARCHITECTURE, Starting the engine)",