Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ agents (SQL, CLI, later MCP). Nothing leaves the machine.
`/quantext view`:

1. `$.http.fetch('http://127.0.0.1:<port>/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 </dev/null &', runtime, '<plugin root>/engine/engine.js', log, dataDir])`,
paths as arguments (ADR 27). Poll `/health` up to 10 s. Every command, the version probes too, runs in
Expand All @@ -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.

Expand Down
15 changes: 15 additions & 0 deletions packages/engine/src/cli/deadline.ts
Original file line number Diff line number Diff line change
@@ -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<T>(work: () => Promise<T>, ms: number, onLate: () => void): Promise<T> {
const timer = setTimeout(onLate, ms);
timer.unref();
try {
return await work();
} finally {
clearTimeout(timer);
}
}
29 changes: 22 additions & 7 deletions packages/engine/src/cli/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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;
Expand Down Expand Up @@ -197,13 +200,25 @@ export async function serve(options: ServeOptions, hooks: ServeHooks): Promise<n
} finally {
clearInterval(idle);
stopping.abort();
await catchUp.catch(() => 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");
},
);
}
}

Expand Down
3 changes: 2 additions & 1 deletion packages/engine/src/ingest/discover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
34 changes: 34 additions & 0 deletions packages/engine/test/cli/deadline.test.ts
Original file line number Diff line number Diff line change
@@ -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<string>((resolve) => {
void withDeadline(
() => new Promise<never>(() => 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);
});
27 changes: 27 additions & 0 deletions packages/engine/test/ingest/ingest.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { execFileSync } from "node:child_process";
import {
appendFileSync,
chmodSync,
closeSync,
constants,
mkdirSync,
openSync,
readdirSync,
readFileSync,
renameSync,
Expand Down Expand Up @@ -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");
Expand Down
65 changes: 60 additions & 5 deletions packages/mod/src/viewer.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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`
Expand All @@ -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
Expand All @@ -52,17 +59,53 @@ async function readEngineFile($: EngineInterface, dataDir: string): Promise<Engi
return parseEngineFile(text);
}

/** `answer`, or undefined when it has not come within `ms`. */
function within<T>($: EngineInterface, ms: number, answer: Promise<T>): Promise<T | undefined> {
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) => {
$.ui.log(`quantext: /health on port ${port}: ${String(error)}`, { to: "debug" });
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<boolean> {
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. */
Expand All @@ -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. */
Expand Down Expand Up @@ -109,6 +152,18 @@ export async function openViewer($: EngineInterface): Promise<void> {
}

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) {
Expand Down
7 changes: 7 additions & 0 deletions packages/mod/test/viewer-world.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, Answer>;
afterStart?: Record<string, Answer>;
/** What each URL answers once `kill` has run with this signal (`TERM` for a plain `kill`); unset: no change. */
afterKill?: Partial<Record<"TERM" | "KILL", Record<string, Answer>>>;
/** Each command's `--version` output; a command not listed is not on PATH. */
versions?: Record<string, string>;
/** What `uname -s` prints. */
Expand Down Expand Up @@ -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`) };
Expand Down
Loading
Loading