diff --git a/scripts/loadtest/README.md b/scripts/loadtest/README.md index 266c641b..99331f49 100644 --- a/scripts/loadtest/README.md +++ b/scripts/loadtest/README.md @@ -6,8 +6,8 @@ Runs user-local helpers against a scratch dashboard with injected faults and loa ```sh node scripts/loadtest/run.mjs smoke # 2 helpers, 20 calls, faults on; about 1 minute -node scripts/loadtest/run.mjs 1 # one scenario: 1 to 6 -node scripts/loadtest/run.mjs all # 1-5 side by side, then 6 alone in its own process; about 2 minutes +node scripts/loadtest/run.mjs 1 # one scenario: 1 to 7 +node scripts/loadtest/run.mjs all # 1-5 side by side, then 6 and 7 each alone in its own process ``` Options: `--dir ` (default a new directory under the system temp dir; mode 0700), `--db ` (copy of a production-like database, taken with `VACUUM INTO`; the source is opened read-only), `--time-scale S` (0.01 to 1, default 0.1, see below), `--time-factor F` (multiplies the fake harness delays, on top of the scale), `--users N`, `--parallel K`, `--calls M`, `--max-minutes N`, `--sequential` (with `all`). Exit code 1 when a line fails. @@ -44,10 +44,11 @@ Requirements: Node 24, `bwrap` (the helper's own sandbox check), and the reposit | 4 | One helper killed with SIGKILL mid-call, restarted 20 s later | no reply lost | | 5 | One helper whose harness always fails (5 slots and the fast lane, so it fails 5 calls in a row before the queue drains) | only that helper cooled off; the others finish every call | | 6 | 50 helpers x 4 slots against 300 mixed calls queued over 25 s, at time scale 0.5 (claim, heartbeat and status intervals about twice production's rate) with harness delays cut to 10% | dashboard p99 under 200 ms, no request over 5 s, no SQLite busy lines, gating p95 wait under 60 s | +| 7 | 20 long-polling runners (protocol 4 claimers in the run process with `wait: 25`; a lease is submitted at once, no harness), 60 calls arriving at random over 120 s, the dashboard restarted at 60 s; time scale 0.25 | pickup p95 under 2 s (scaled); empty claims per minute below polling's (every slot every 15 s); claims held when the dashboard stopped are all answered with an empty reply, none reset | Every scenario also checks that no helper sat idle for over 90 seconds with calls queued without a reason visible to the user (a cool-off, a readiness other than `ready`, a last error, or a helper that is not running). -Definitions: a lost reply is a call the fake harness answered (ledger) whose call row did not end `done`. Duplicate runs are calls with more than one harness start. A reply accepted from a requeued lease is a call two of whose leases ended `submitted` in the helpers' logs. Latency is the dashboard's time per request as the proxy sees it, excluding injected delay and faults. SQLite busy errors are lines in the dashboard log matching `SQLITE_BUSY` or `database is locked`. Queue wait is the call's `queued_ms`. +Definitions: a lost reply is a call the fake harness answered (ledger) whose call row did not end `done`. Duplicate runs are calls with more than one harness start. A reply accepted from a requeued lease is a call two of whose leases ended `submitted` in the helpers' logs. Latency is the dashboard's time per request as the proxy sees it, excluding injected delay, faults and a held claim's wait (`X-Held-Ms`). SQLite busy errors are lines in the dashboard log matching `SQLITE_BUSY` or `database is locked`. Queue wait is the call's `queued_ms`. ## Output diff --git a/scripts/loadtest/proxy.mjs b/scripts/loadtest/proxy.mjs index 2601e569..ca0ce479 100644 --- a/scripts/loadtest/proxy.mjs +++ b/scripts/loadtest/proxy.mjs @@ -7,8 +7,9 @@ // reset and 502 faults that are "after". // Control port (JSON): GET /state; POST /set {rate502, rateReset, rate429, retryAfter, latMin, latMax, afterShare}; // POST /down?s=N (refuse connections for N seconds; the listener closes and reopens); POST /up. -// Every finished request is one line in the log: { t, route, method, status, upMs, totalMs, fault }. `upMs` is the -// dashboard's own time from the forwarded request to the end of its answer; `fault` is empty for an untouched request. +// Every finished request is one line in the log: { t, route, method, status, upMs, heldMs, totalMs, fault }. `upMs` is the +// dashboard's own time from the forwarded request to the end of its answer, less the time a long-polling claim waited for a +// call (`heldMs`, the reply's X-Held-Ms); `fault` is empty for an untouched request. import { createServer, request } from "node:http"; import { appendFileSync } from "node:fs"; @@ -27,10 +28,10 @@ export function startProxy(o) { const proxy = createServer(async (req, res) => { const t0 = Date.now(); const route = routeOf(req.url ?? "/"); - const done = (status, fault, upMs) => { + const done = (status, fault, upMs, heldMs = 0) => { stats.requests++; if (fault) stats.faults[fault] = (stats.faults[fault] ?? 0) + 1; - log({ t: t0, route, method: req.method, status, upMs, totalMs: Date.now() - t0, fault: fault ?? "" }); + log({ t: t0, route, method: req.method, status, upMs, heldMs, totalMs: Date.now() - t0, fault: fault ?? "" }); }; const reset = (fault, upMs) => { done(0, fault, upMs); req.socket.destroy(); }; const after = roll(cfg.afterShare); @@ -49,21 +50,26 @@ export function startProxy(o) { const parts = []; ur.on("data", (c) => parts.push(c)); ur.on("end", () => { - const upMs = Date.now() - up0; + // A long-polling claim waits on purpose; its wait (X-Held-Ms) is not the dashboard's latency. + const heldMs = Number(ur.headers["x-held-ms"] ?? 0) || 0; + const upMs = Math.max(0, Date.now() - up0 - heldMs); const dropAfter = after && roll(cfg.rateReset), failAfter = after && roll(cfg.rate502); if (dropAfter) return reset("reset-after", upMs); if (failAfter) { res.writeHead(502, { "content-type": "text/plain" }).end("Bad Gateway"); return done(502, "502-after", upMs); } const h = { ...ur.headers }; delete h.connection; delete h["transfer-encoding"]; res.writeHead(ur.statusCode ?? 502, h).end(Buffer.concat(parts)); - done(ur.statusCode ?? 502, lat ? "latency" : "", upMs); + done(ur.statusCode ?? 502, lat ? "latency" : "", upMs, heldMs); }); ur.on("error", () => { res.destroy(); done(0, "upstream-error", Date.now() - up0); }); }); fwd.on("error", () => { + if (res.destroyed) return done(0, "client-gone", Date.now() - up0); if (!res.headersSent) res.writeHead(502, { "content-type": "text/plain" }).end("upstream unreachable"); done(502, "upstream-down", Date.now() - up0); }); + // The helper gave up (its own timeout): the dashboard sees the connection close, as it would without the proxy. + res.on("close", () => { if (!res.writableEnded) fwd.destroy(); }); fwd.end(body); }); proxy.on("connection", (s) => { sockets.add(s); s.on("close", () => sockets.delete(s)); }); diff --git a/scripts/loadtest/report.mjs b/scripts/loadtest/report.mjs index ccde5251..2602dd6f 100644 --- a/scripts/loadtest/report.mjs +++ b/scripts/loadtest/report.mjs @@ -115,3 +115,33 @@ export function evaluate(rig, spec, m) { for (const c of checks) lines.push(`${c.ok ? "PASS" : "FAIL"} ${c.name}: ${c.detail}`); return { lines, checks }; } + +/** + * Scenario 7's lines: how fast a held claim picks up a queued call, how often idle runners claim compared with polling every + * 15 s, and how the claims held when the dashboard stopped were answered. `lp` is what the runners recorded (run.mjs). + */ +export function evaluateLongPoll(rig, spec, lp) { + const checks = [], lines = []; + const add = (name, ok, detail) => checks.push({ ok, name, detail }); + // Calls queued while the dashboard was down, or before the runners' first retry after it came back, wait for the restart. + const settle = rig.sc(5000); + const pickups = [], restartPickups = []; + for (const c of rig.calls.values()) { + const at = lp.leases.get(c.id); + if (at === undefined) continue; + (c.enqueuedAt >= lp.stopAt && c.enqueuedAt <= lp.backAt + settle ? restartPickups : pickups).push(at - c.enqueuedAt); + } + const lim = rig.sc(2000), p95 = pct(pickups, 95); + add(`pickup p95 under ${s(lim)}`, p95 !== null && p95 < lim, `p50 ${ms(pct(pickups, 50))}, p95 ${ms(p95)}, max ${ms(pickups.length ? Math.max(...pickups) : null)} over ${pickups.length} calls; ${restartPickups.length} queued around the restart, max ${ms(restartPickups.length ? Math.max(...restartPickups) : null)}`); + // Empty replies per production minute against polling's: every runner slot claims every 15 s when nothing is queued. + const empties = lp.claims.filter((c) => c.status === 200 && c.lease === null && c.reason === null).length; + const prodMin = (lp.end - lp.t0) / rig.ts / 60_000; + const rate = empties / prodMin, baseline = spec.users * 4; + add("idle claims below the polling rate", rate < baseline, `${rate.toFixed(1)} empty claims per production minute (${empties} in ${prodMin.toFixed(1)} min); polling every 15 s: ${baseline}`); + const held = lp.claims.filter((c) => lp.stopAt && c.start < lp.stopAt && c.end >= lp.stopAt); + const bad = held.filter((c) => c.status !== 200 || c.lease !== null); + add("held claims answered at the restart, none reset", held.length > 0 && bad.length === 0, `${held.length} claims held when the dashboard stopped; ${bad.length} not answered with an empty reply${bad.length ? ` (statuses ${[...new Set(bad.map((c) => c.status))].join(", ")})` : ""}`); + lines.push(`long polling: ${lp.claims.length} claims, ${lp.leases.size} leases, ${empties} empty`); + for (const c of checks) lines.push(`${c.ok ? "PASS" : "FAIL"} ${c.name}: ${c.detail}`); + return { lines, checks, metrics: { pickups, restartPickups, empties, prodMin, held: held.length, bad: bad.length } }; +} diff --git a/scripts/loadtest/rig.mjs b/scripts/loadtest/rig.mjs index 6eeca04f..d0e455ab 100644 --- a/scripts/loadtest/rig.mjs +++ b/scripts/loadtest/rig.mjs @@ -108,9 +108,12 @@ export class Rig { } async stopDashboard(signal = "SIGTERM") { if (!this.dash || this.dash.exitCode !== null) return; - this.dash.kill(signal); - await Promise.race([this.dashExit, sleep(15_000).then(() => this.dash.kill("SIGKILL"))]); - await this.dashExit; + // This process only: by the time the fallback fires, `this.dash` may be the restarted dashboard. + const dash = this.dash, exit = this.dashExit; + dash.kill(signal); + const kill = setTimeout(() => dash.kill("SIGKILL"), 15_000); + await exit; + clearTimeout(kill); } async restartDashboard() { this.note("dashboard restart"); await this.stopDashboard(); await this.startDashboard(); this.note("dashboard back"); } /** The dashboard is gone for `seconds` (the proxy keeps answering 502). */ diff --git a/scripts/loadtest/run.mjs b/scripts/loadtest/run.mjs index eb84cb7d..ed31d761 100644 --- a/scripts/loadtest/run.mjs +++ b/scripts/loadtest/run.mjs @@ -1,14 +1,14 @@ #!/usr/bin/env node // Runs the robustness scenarios (section 4 of the plan) against a scratch instance and prints the acceptance report. -// node scripts/loadtest/run.mjs [--dir ] [--db ] [--time-factor F] [--time-scale S] +// node scripts/loadtest/run.mjs [--dir ] [--db ] [--time-factor F] [--time-scale S] // [--users N] [--parallel K] [--calls M] [--max-minutes N] [--sequential] -// `all` runs 1 to 5 side by side, then 6 alone (its latency numbers need the machine to itself). See README.md. +// `all` runs 1 to 5 side by side, then 6 and 7 each alone at their own scale. See README.md. import { spawn } from "node:child_process"; import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { collect, evaluate } from "./report.mjs"; -import { Rig, sleep } from "./rig.mjs"; +import { collect, evaluate, evaluateLongPoll } from "./report.mjs"; +import { MIX, Rig, sleep } from "./rig.mjs"; const argv = process.argv.slice(2); const opt = (n, d) => { const i = argv.indexOf(`--${n}`); return i >= 0 ? argv[i + 1] : d; }; @@ -42,6 +42,9 @@ const SCENARIOS = { // about twice production's. The harness delays are cut instead (time factor) to keep the run short, and the calls arrive // over 25 s, as jobs queue them, rather than in one burst. 6: { title: "50 helpers x 4 slots against 300 mixed calls", users: 50, parallel: 4, calls: 300, rampS: 25, timeFactor: 0.1, timeScale: 0.5, accept: ["noLoss", "latency", "idle"], maxMin: 25 }, + // Long-polling claims with protocol 4 claimers in this process (no harness: a lease is submitted at once), so the runners + // sit in held claims nearly all the time. Production-scale times: calls over 120 s, the restart at 60 s. + 7: { title: "20 idle runners long-polling, random enqueues, a dashboard restart", users: 20, parallel: 1, calls: 60, spreadS: 120, restartAtS: 60, timeFactor: 1, timeScale: 0.25, longPoll: true, maxMin: 8 }, }; /** The time scale scenario `key` runs at: --time-scale when given, else the scenario's own, else the default. */ @@ -49,6 +52,7 @@ const scaleOf = (key) => (SCALE_GIVEN ? TIME_SCALE : SCENARIOS[key].timeScale ?? async function run(key) { const sp = SCENARIOS[key]; + if (sp.longPoll) return runLongPoll(key); const scale = scaleOf(key); const spec = { ...sp, name: `scenario-${key}`, users: Number(opt("users", sp.users)), parallel: Number(opt("parallel", sp.parallel)), calls: Number(opt("calls", sp.calls)), timeFactor: Number(opt("time-factor", sp.timeFactor)) * scale, maxMin: Number(opt("max-minutes", sp.maxMin * Math.max(scale, 0.3))) }; const dir = opt("dir", join(tmpdir(), `autocraft-loadtest-${Date.now()}`)); @@ -80,6 +84,87 @@ async function run(key) { } } +/** + * One long-polling runner slot: claims with `wait: 25` until `lp.stop`, submits each lease at once, and records every claim + * (start, end, HTTP status, lease, reason) in `lp.claims` and each lease's time in `lp.leases`. + */ +async function longPollRunner(rig, u, lp) { + const base = `http://127.0.0.1:${rig.proxyPort}`; + const tiers = { top: "claude-opus-4-5", mid: "claude-sonnet-4-5", small: "claude-haiku-4-5" }; + const post = (path, bearer, body) => fetch(`${base}${path}`, { method: "POST", headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" }, body: JSON.stringify(body), signal: lp.abort.signal }); + for (let n = 1; !lp.stop; n++) { + const start = Date.now(); + let status = 0, reply = null; + try { + const r = await post("/api/remote/claim", u.token, { requestId: `${u.login}-${n}-${Math.random().toString(36).slice(2, 8)}`, protocol: 4, wait: 25, helperVersion: "1.2.0", harness: "claude", harnessVersion: "2.1.0", tiers }); + status = r.status; + reply = status === 200 ? await r.json() : (await r.arrayBuffer(), null); + } catch { /* reset or aborted */ } + if (lp.stop) break; + const end = Date.now(); + lp.claims.push({ start, end, status, lease: reply?.lease?.id ?? null, reason: reply?.reason ?? null }); + if (reply?.lease) { + lp.leases.set(reply.lease.id, end); + const tier = rig.db.prepare("SELECT tier FROM main.remote_calls WHERE id = ?").get(reply.lease.id)?.tier ?? "small"; + try { await (await post("/api/remote/submit", reply.lease.secret, { ok: true, text: "ok", model: tiers[tier], usage: { inputTokens: 1, outputTokens: 1 }, durationMs: 1 })).arrayBuffer(); } catch { /* the job emulator requeues a lost lease */ } + continue; + } + await sleep(status === 200 ? reply.retryAfter * 1000 : rig.sc(1000)); + } +} + +async function runLongPoll(key) { + const sp = SCENARIOS[key]; + const scale = scaleOf(key); + const Sc = (ms) => Math.max(1, Math.round(ms * scale)); + const spec = { ...sp, name: `scenario-${key}`, users: Number(opt("users", sp.users)), calls: Number(opt("calls", sp.calls)) }; + const dir = opt("dir", join(tmpdir(), `autocraft-loadtest-${Date.now()}`)); + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const rig = new Rig({ name: spec.name, dir, users: spec.users, parallel: 1, timeFactor: 1, timeScale: scale, dbFrom: opt("db") }); + const lp = { claims: [], leases: new Map(), stop: false, abort: new AbortController(), t0: 0, end: 0, stopAt: 0, backAt: 0 }; + try { + await rig.init(); + lp.t0 = Date.now(); + const runners = rig.users.map((u) => longPollRunner(rig, u, lp)); + rig.note(`${spec.users} long-polling runners started`); + await sleep(Sc(5000)); + const during = (async () => { + await sleep(Sc(sp.restartAtS * 1000)); + lp.stopAt = Date.now(); + await rig.restartDashboard(); + lp.backAt = Date.now(); + })().catch((e) => rig.note(`scenario step failed: ${e.message}`)); + // Random arrivals: exponential gaps around the mean, small and gating calls as jobs queue them between larger ones. + const mean = Sc(sp.spreadS * 1000) / spec.calls; + for (let i = 0; i < spec.calls; i++) { + await sleep(-Math.log(1 - Math.random()) * mean); + await rig.enqueue(MIX[i % MIX.length]); + if (i === 0) rig.startJobEmulator(); + } + rig.note(`${spec.calls} calls queued over about ${sp.spreadS} production seconds (time scale ${scale})`); + await during; + const drained = await rig.waitDrained(Number(opt("max-minutes", sp.maxMin)) * 60_000); + rig.note(drained ? "queue drained" : `not drained: ${rig.openCalls()} calls still open`); + // One more hold, so the runners' empty replies at their deadlines are counted. + await sleep(Sc(30_000)); + lp.end = Date.now(); + lp.stop = true; + lp.abort.abort(); + await Promise.all(runners); + const m = collect(rig); + const { lines, checks } = evaluate(rig, spec, m); + const lpOut = evaluateLongPoll(rig, spec, lp); + lines.push(...lpOut.lines); + checks.push(...lpOut.checks); + writeFileSync(join(rig.dir, "report.json"), JSON.stringify({ spec: { name: spec.name, title: spec.title }, metrics: { ...m, longPoll: lpOut.metrics }, checks, timeline: rig.events }, null, 1)); + return { key, lines, checks, dir: rig.dir }; + } finally { + lp.stop = true; + lp.abort.abort(); + await rig.stop(); + } +} + /** Runs scenario `key` in a child process (its own time scale) and returns its result. */ async function runApart(key) { const out = join(opt("dir", tmpdir()), `result-${key}-${process.pid}.json`); @@ -89,13 +174,13 @@ async function runApart(key) { } const started = Date.now(); -const keys = which === "all" ? ["1", "2", "3", "4", "5", "6"] : [which]; -if (!keys.every((k) => SCENARIOS[k])) { console.error(`unknown scenario ${which}; use smoke, 1-6 or all`); process.exit(64); } +const keys = which === "all" ? ["1", "2", "3", "4", "5", "6", "7"] : [which]; +if (!keys.every((k) => SCENARIOS[k])) { console.error(`unknown scenario ${which}; use smoke, 1-7 or all`); process.exit(64); } const results = []; // Scenarios at another scale than the rest run apart; the rest share this process. const apart = which === "all" ? keys.filter((k) => scaleOf(k) !== TIME_SCALE) : []; const here = keys.filter((k) => !apart.includes(k)); -if (which === "all" && !flag("sequential")) results.push(...await Promise.all(here.filter((k) => k !== "6").map((k) => run(k))), ...(here.includes("6") ? [await run("6")] : [])); +if (which === "all" && !flag("sequential")) results.push(...await Promise.all(here.filter((k) => k !== "6" && k !== "7").map((k) => run(k))), ...(here.includes("6") ? [await run("6")] : []), ...(here.includes("7") ? [await run("7")] : [])); else for (const k of here) results.push(await run(k)); for (const k of apart) results.push(await runApart(k)); results.sort((a, b) => a.key.localeCompare(b.key)); diff --git a/src/dash/server/index.ts b/src/dash/server/index.ts index 49a80964..861de9a7 100644 --- a/src/dash/server/index.ts +++ b/src/dash/server/index.ts @@ -36,6 +36,7 @@ import { cachedWrite, createSession, deleteSession, loadSession, makeUser, PERM_ import { answering, handleMcp, mcpReply, writes as mcpWrites, type Msg as McpMsg, type Reply as McpReply } from "../mcp/index.ts"; import { loadToken, pruneTokens } from "../mcp/tokens.ts"; import * as remote from "../../remote/calls.ts"; +import { ClaimWaits, heldMsOf } from "../../remote/claim-wait.ts"; import { scaled, TIME_SCALE } from "../../remote/time-scale.ts"; import { isBusy } from "../../db.ts"; import { inferenceMode } from "../../remote/mode.ts"; @@ -220,6 +221,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { // Per helper token, sized for a helper with 16 slots and its fast-lane slot: each idle slot claims every CLAIM_RETRY_S // and again at once after a call ends, with retries on errors; status reports come on every change. const remoteClaimLimit = new RateLimiter(600, 60_000); + const claimWaits = new ClaimWaits(rdb); const remoteStatusLimit = new RateLimiter(120, 60_000); // Bundle, heartbeat, release and submit of one lease: a heartbeat every 30 seconds and retries. const remoteLeaseLimit = new RateLimiter(120, 60_000); @@ -723,10 +725,14 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { // In the server mode no call is queued for helpers: nothing to take for a while. if (inferenceMode(db) !== "user-local") return reply(200, { lease: null, retryAfter: 300, reserve: userReserve(db, caller.login) } satisfies ClaimReply); const perm = claimPermission(caller.login, caller.role); - const out = await remote.claimCall(db, caller, claim, perm.canWrite); + // A held claim whose client leaves stops waiting; a reply already written does not count as leaving. + const gone = new AbortController(); + res.once("close", () => { if (!res.writableEnded) gone.abort(); }); + const out = await remote.claimCall(db, caller, claim, perm.canWrite, Date.now(), { waits: claimWaits, signal: gone.signal, blocked: () => perm.errors.size > 0 }); // Calls passed over because GitHub could not confirm the permission: the helper logs why it gets nothing. if (!out.lease && out.reason === undefined && perm.errors.size) out.reason = [...perm.errors.values()][0]; - return reply(200, out); + // How long the claim waited for a call, so a latency measurement can leave it out. + return reply(200, out, { "x-held-ms": String(heldMsOf(out)) }); } if (path === ROUTES.status) { const caller = loadToken(db, bearer); @@ -937,7 +943,8 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { return sendFile(res, "text/html; charset=utf-8", "no-store", APP_CSP, index); } - return { handle, routes: opts.routes, provider, live, close: () => { clearInterval(maintenance); live.close(); } }; + // Shutting down answers the held claims at once, each with its own short retry, and holds no new ones. + return { handle, routes: opts.routes, provider, live, close: () => { clearInterval(maintenance); claimWaits.close(); live.close(); } }; } export async function startServer(opts: AppOptions): Promise<{ server: Server; url: string; app: ReturnType; close(): Promise }> { @@ -957,11 +964,14 @@ export async function startServer(opts: AppOptions): Promise<{ server: Server; u return { server, app, url: `http://${host}:${addr.port}`, + // The held claims' replies are written first; connections still open after a short flush wait (SSE streams) are cut. close: () => new Promise((resolve) => { stopLiveness(); app.close(); - server.closeAllConnections(); - server.close(() => resolve()); + // A keep-alive connection turns idle only once its reply is out, after close() looked at it. + const idle = setInterval(() => server.closeIdleConnections(), 25); + const cut = setTimeout(() => server.closeAllConnections(), 500); + server.close(() => { clearInterval(idle); clearTimeout(cut); resolve(); }); }), }; } diff --git a/src/remote/calls.ts b/src/remote/calls.ts index be2dfab1..6cba3968 100644 --- a/src/remote/calls.ts +++ b/src/remote/calls.ts @@ -23,6 +23,7 @@ import { ACCEPTED_PROTOCOLS, CLAIM_ID_TTL_S, HEARTBEAT_S, PREPARE_MAX_S, ROUTES, import { claimRepos } from "./my-repos.ts"; import { userMaxCalls } from "./max-calls.ts"; import { claimClass, gating } from "./claim-class.ts"; +import { holdMs, Ticket, type ClaimTry, type ClaimWaits, type EmptyReply } from "./claim-wait.ts"; import { userReserve } from "./reserve.ts"; import { scaled, scaledS } from "./time-scale.ts"; import { CALLER_STALE_MS, IDLE_FRESH_MS, SEEN_EVERY_MS } from "./room.ts"; @@ -513,65 +514,109 @@ export function callStatus(db: DatabaseSync, id: number, login: string): { id: n * claims, so the secret is never stored; the promise is kept from the start, so a repeat that arrives while the first is * still being answered waits for it. */ -const claimReplies = new Map }>(); +const claimReplies = new Map; ticket?: Ticket }>(); /** * Gives the caller the first queued call it may take (claimOrder), filtered by eligibility. `canWrite` reads the caller's live * write permission on a repo. The reply carries the user's reserve either way. A claim repeated with the same request id * gets the first one's reply. While the login's leases are at the user's "Max calls at once" (max-calls.ts), only a follow-up * of its own sessions is leased, one past the limit at most, so a session can finish; otherwise the reply says why. + * With `hold`, a protocol 4 claim that finds nothing and has no reason to give waits for a call up to its `wait` (claim-wait.ts). */ -export function claimCall(db: DatabaseSync, caller: Caller, claim: Claim, canWrite: (repo: string) => Promise, nowMs: number = Date.now()): Promise { +export function claimCall(db: DatabaseSync, caller: Caller, claim: Claim, canWrite: (repo: string) => Promise, nowMs: number = Date.now(), hold?: Hold): Promise { // Entries are in claim order, so the expired ones come first. for (const [k, v] of claimReplies) { if (v.at >= nowMs - scaled(CLAIM_ID_TTL_S * 1000)) break; claimReplies.delete(k); } const key = `${caller.tokenId}:${claim.requestId}`; const seen = claimReplies.get(key); - if (seen) return seen.reply; - const reply = claimNew(db, caller, claim, canWrite, nowMs); - claimReplies.set(key, { at: nowMs, reply }); + if (seen) { + if (hold) seen.ticket?.attach(hold.signal); + return seen.reply; + } + // Protocol 3 helpers send no wait (parseClaim); their claims are answered at once. + const ms = hold && claim.protocol >= 4 ? holdMs(claim.wait) : 0; + const ticket = hold && ms > 0 ? new Ticket(hold.signal) : undefined; + const reply = claimNew(db, caller, claim, canWrite, nowMs, hold && ticket ? { ...hold, ms, ticket } : undefined); + claimReplies.set(key, { at: nowMs, reply, ticket }); reply.catch(() => { if (claimReplies.get(key)?.reply === reply) claimReplies.delete(key); }); + // Every request for a held claim left before its reply: a retry with the same id claims afresh. A lease already given stays + // remembered, so the retry gets it. + if (ticket) ticket.onGone = () => void reply.then((r) => { if (!r.lease && claimReplies.get(key)?.reply === reply) claimReplies.delete(key); }, () => {}); return reply; } -async function claimNew(db: DatabaseSync, caller: Caller, claim: Claim, canWrite: (repo: string) => Promise, nowMs: number): Promise { +/** + * How a claim may wait (claim-wait.ts): `signal` aborts when the request's connection closes before its reply; `blocked` says + * the claim has a reason to give outside its tries (a write permission GitHub could not confirm), so it is answered at once. + * `waits.closed` (shutting down) answers at once too. + */ +export type Hold = { waits: ClaimWaits; signal: AbortSignal; blocked: () => boolean }; + +async function claimNew(db: DatabaseSync, caller: Caller, claim: Claim, canWrite: (repo: string) => Promise, nowMs: number, hold?: Hold & { ms: number; ticket: Ticket }): Promise { + const c = prepareClaim(db, caller, claim, canWrite, nowMs); + if ("reply" in c) return c.reply; + const live = hold?.ticket.live ?? (() => true); + const first = await c.attempt(nowMs, { quick: false, live }); + if (first) return first; + c.idle(nowMs); + if (!hold || hold.waits.closed || hold.ticket.gone || hold.blocked()) return c.empty(nowMs, false); + return hold.waits.hold(hold.ticket, nowMs + hold.ms, { ...c, blocked: hold.blocked }); +} + +/** + * The once-per-claim part of a claim: the helper's version, and a lease of a repeated claim the dashboard no longer remembers. + * Returns a reply when the claim is answered here, else its tries: `attempt` re-reads the cool-off, the accepted models, the + * repos and the user's max calls at once each time, and gives null when there is nothing to take and no reason to give. + */ +function prepareClaim(db: DatabaseSync, caller: Caller, claim: Claim, canWrite: (repo: string) => Promise, nowMs: number): + { reply: ClaimReply } | { attempt: ClaimTry; idle: (nowMs: number) => void; empty: (nowMs: number, held: boolean) => EmptyReply } { if (olderVersion(claim.helperVersion, REQUIRED_HELPER)) throw new HttpError(409, `helper ${claim.helperVersion} is older than ${REQUIRED_HELPER}, the oldest this server accepts; download the current helper from ${ROUTES.helper}`); // A repeat the dashboard no longer remembers (it restarted in between): the lease the first claim took cannot be given // out again, as only its secret's hash is stored, so it goes back to the queue unused and this claim is answered afresh. const orphan = db.prepare("SELECT id, run_id, lease_secret_hash FROM main.remote_calls WHERE token_id = ? AND claim_id = ? AND state = 'leased'").get(caller.tokenId, claim.requestId) as { id: number; run_id: number | null; lease_secret_hash: string | null } | undefined; if (orphan) unlease(db, { id: Number(orphan.id), runId: orphan.run_id, hash: orphan.lease_secret_hash }, "returned to the queue: the claim that leased it was repeated after a server restart", nowMs); expireLeases(db, nowMs); - const cooled = cooloffOf(db, caller.login, nowMs); - if (cooled) return { lease: null, retryAfter: Math.ceil((cooled.until - nowMs) / 1000), reason: cooled.reason, until: cooled.until, reserve: userReserve(db, caller.login) }; - const accepted = acceptedModels(db), floors = minEfforts(db); - const tiers = new Set((Object.keys(claim.tiers) as Tier[]).filter((t) => familyOf(claim.tiers[t]!, accepted[t]) !== null && meetsEffort(claim.efforts?.[t], floors[t], claim.harness))); - if (!tiers.size) throw new HttpError(400, `no tier of the claim has an accepted model at the minimum effort; accepted: ${(Object.keys(accepted) as Tier[]).map((t) => `${t} ${accepted[t].join("/")}${floors[t] ? ` at effort ${floors[t]} or higher` : ""}`).join(", ")}`); - const can = memoWrite(canWrite), others = idleOthers(db, caller.login, nowMs); - const repos = claimRepos(db, caller.login, claim.repos); const fast = claim.fastLane === true; - const max = userMaxCalls(db, caller.login); - const atLimit = (): ClaimReply => ({ lease: null, retryAfter: CLAIM_RETRY_S, reason: `your helpers run ${max} calls, your limit of calls at once (Connect page, My settings)`, reserve: userReserve(db, caller.login) }); - const full = max !== null && leasedBy(db, caller.login) >= max; - let limited = full; - for (const r of claimOrder(db, caller, tiers, repos, claim.sessions ?? [], nowMs, fast)) { - // Only follow-ups of the helper's own sessions carry a parent here (claimOrder). - if (full && r.parent_id === null) continue; - if (!(await eligible(caller, r, can, others))) continue; - const lease = leaseCall(db, Number(r.id), caller, claim, claim.tiers[r.tier]!, Date.now(), max === null ? null : r.parent_id !== null ? max + 1 : max); - if (lease === "limit") { - limited = true; - continue; + // What the latest full try took, for a quick try's look at the queue. + let tiers = new Set(), repos: ReadonlySet | null = null; + const attempt: ClaimTry = async (now, { quick, live }) => { + if (quick && !claimOrder(db, caller, tiers, repos, claim.sessions ?? [], now, fast).length) return null; + const cooled = cooloffOf(db, caller.login, now); + if (cooled) return { lease: null, retryAfter: Math.ceil((cooled.until - now) / 1000), reason: cooled.reason, until: cooled.until, reserve: userReserve(db, caller.login) }; + const accepted = acceptedModels(db), floors = minEfforts(db); + tiers = new Set((Object.keys(claim.tiers) as Tier[]).filter((t) => familyOf(claim.tiers[t]!, accepted[t]) !== null && meetsEffort(claim.efforts?.[t], floors[t], claim.harness))); + if (!tiers.size) throw new HttpError(400, `no tier of the claim has an accepted model at the minimum effort; accepted: ${(Object.keys(accepted) as Tier[]).map((t) => `${t} ${accepted[t].join("/")}${floors[t] ? ` at effort ${floors[t]} or higher` : ""}`).join(", ")}`); + const can = memoWrite(canWrite), others = idleOthers(db, caller.login, now); + repos = claimRepos(db, caller.login, claim.repos); + const max = userMaxCalls(db, caller.login); + const full = max !== null && leasedBy(db, caller.login) >= max; + let limited = full; + for (const r of claimOrder(db, caller, tiers, repos, claim.sessions ?? [], now, fast)) { + // Only follow-ups of the helper's own sessions carry a parent here (claimOrder). + if (full && r.parent_id === null) continue; + if (!(await eligible(caller, r, can, others))) continue; + // The client left while eligibility was read: nothing is leased to nobody. + if (!live()) return null; + const lease = leaseCall(db, Number(r.id), caller, claim, claim.tiers[r.tier]!, Date.now(), max === null ? null : r.parent_id !== null ? max + 1 : max); + if (lease === "limit") { + limited = true; + continue; + } + if (!lease) continue; + takeFromQueueCache(db, Number(r.id)); + // The fast lane says nothing about the helper's other slots: only their claims mark it idle or busy. + if (!fast) db.prepare("UPDATE main.mcp_tokens SET idle_claim_at = NULL WHERE id = ?").run(caller.tokenId); + return { lease, reserve: userReserve(db, caller.login) }; } - if (!lease) continue; - takeFromQueueCache(db, Number(r.id)); - // The fast lane says nothing about the helper's other slots: only their claims mark it idle or busy. - if (!fast) db.prepare("UPDATE main.mcp_tokens SET idle_claim_at = NULL WHERE id = ?").run(caller.tokenId); - return { lease, reserve: userReserve(db, caller.login) }; - } - if (limited) return atLimit(); - if (fast) return { lease: null, retryAfter: CLAIM_RETRY_S, reserve: userReserve(db, caller.login) }; - // An idle helper, with what it takes (the user's picks narrowed by the helper's list): an author's claim gives way to it (idleOthers). - db.prepare("UPDATE main.mcp_tokens SET idle_claim_at = ?, idle_tiers = ?, idle_repos = ? WHERE id = ?").run(nowMs, JSON.stringify([...tiers]), repos ? JSON.stringify([...repos]) : null, caller.tokenId); - return { lease: null, retryAfter: CLAIM_RETRY_S, reserve: userReserve(db, caller.login) }; + if (limited) return { lease: null, retryAfter: CLAIM_RETRY_S, reason: `your helpers run ${max} calls, your limit of calls at once (Connect page, My settings)`, reserve: userReserve(db, caller.login) }; + return null; + }; + return { + attempt, + // An idle helper, with what it takes (the user's picks narrowed by the helper's list): an author's claim gives way to it + // (idleOthers). The fast lane says nothing about the helper's other slots. + idle: (now) => { if (!fast) db.prepare("UPDATE main.mcp_tokens SET idle_claim_at = ?, idle_tiers = ?, idle_repos = ? WHERE id = ?").run(now, JSON.stringify([...tiers]), repos ? JSON.stringify([...repos]) : null, caller.tokenId); }, + empty: (_now, held) => ({ lease: null, retryAfter: held ? scaledS(1) : CLAIM_RETRY_S, reserve: userReserve(db, caller.login) }), + }; } // ---- lease routes ------------------------------------------------------------------ diff --git a/src/remote/claim-wait.ts b/src/remote/claim-wait.ts new file mode 100644 index 00000000..8e288ed9 --- /dev/null +++ b/src/remote/claim-wait.ts @@ -0,0 +1,173 @@ +// Long-polling claims (protocol 4): a claim that finds nothing to take and has no reason to give waits up to its hold time +// for a call. Calls are queued by job processes, not by the dashboard, so a waiting claim cannot be woken in-process: while +// any claim waits, one timer reads the `remote-queue` topic's change counter (src/live.ts) and, when it moved, tries the +// waiting claims one at a time, oldest first. Each claim is also tried in full every RETRY_MS and once at its deadline. +import type { DatabaseSync } from "node:sqlite"; +import { isBusy } from "../db.ts"; +import type { ClaimReply } from "./protocol.ts"; + +export type EmptyReply = Extract; +import { scaled, scaledS } from "./time-scale.ts"; + +/** The longest a claim is held, in seconds, whatever its `wait` asks. */ +export const HOLD_MAX_S = 25; +/** How often the timer reads the topic counter while claims wait. */ +export const TICK_MS = scaled(500); +/** How often a waiting claim is tried in full (cool-off, max calls at once, tiers, repos) even when the queue did not change. */ +export const RETRY_MS = scaled(5_000); + +/** How long a claim asking for `wait` seconds is held, in ms; 0 when it asks for none. */ +export const holdMs = (wait: number | undefined): number => (wait && wait > 0 ? scaled(Math.min(wait, HOLD_MAX_S) * 1000) : 0); + +/** + * One try of a claim: a reply to send now, or null when there is nothing to take and no reason to give. `quick`: the queue + * changed, so try only if the claim's list of candidates is not empty. `live`: whether a client still waits for the reply, + * checked just before a call is leased. + */ +export type ClaimTry = (nowMs: number, opts: { quick: boolean; live: () => boolean }) => Promise; + +/** The claim of one request id, held for every request that waits for it: gone once all of them closed their connection. */ +export class Ticket { + #open = new Set(); + #gone = false; + /** Called once when the last request leaves before the claim is answered. */ + onGone: (() => void) | null = null; + constructor(signal: AbortSignal) { this.attach(signal); } + get gone(): boolean { return this.#gone; } + readonly live = (): boolean => !this.#gone; + /** Another request with the same request id waits for this claim's reply. */ + attach(signal: AbortSignal): void { + if (this.#gone || signal.aborted) return; + this.#open.add(signal); + signal.addEventListener("abort", () => { + this.#open.delete(signal); + if (this.#open.size || this.#gone) return; + this.#gone = true; + this.onGone?.(); + }, { once: true }); + } +} + +type Waiter = { + ticket: Ticket; + deadline: number; + nextTry: number; + /** The topic counter at this claim's last try; null before its first try in the wait. */ + seq: number | null; + from: number; + attempt: ClaimTry; + /** Records the claim as an idle helper's (idle_claim_at). */ + idle: (nowMs: number) => void; + /** The empty reply; `held` when it ends a wait that ran to its deadline. */ + empty: (nowMs: number, held: boolean) => EmptyReply; + /** A reason outside the try to answer at once (a write permission GitHub could not confirm). */ + blocked: () => boolean; + resolve: (r: ClaimReply) => void; + reject: (e: unknown) => void; + done: boolean; +}; + +/** How long each held reply waited, for the `X-Held-Ms` header. */ +const held = new WeakMap(); +export const heldMsOf = (r: ClaimReply): number => held.get(r) ?? 0; + +/** The waiting claims of one dashboard process. */ +export class ClaimWaits { + #db: DatabaseSync; + #tickMs: number; + #retryMs: number; + #waiters: Waiter[] = []; + #timer: NodeJS.Timeout | null = null; + #running = false; + #closed = false; + + /** `db`: the helper routes' connection (short busy timeout); a busy database skips a tick. */ + constructor(db: DatabaseSync, opts: { tickMs?: number; retryMs?: number } = {}) { + this.#db = db; + this.#tickMs = opts.tickMs ?? TICK_MS; + this.#retryMs = opts.retryMs ?? RETRY_MS; + } + + /** Shutting down: new claims are answered at once. */ + get closed(): boolean { return this.#closed; } + get size(): number { return this.#waiters.length; } + + /** Holds a claim whose first try found nothing until a try finds something, its client leaves, or `deadline`. */ + hold(ticket: Ticket, deadline: number, w: Pick): Promise { + return new Promise((resolve, reject) => { + const now = Date.now(); + const waiter: Waiter = { ...w, ticket, deadline, nextTry: now + this.#retryMs, seq: null, from: now, resolve, reject, done: false }; + const prev = ticket.onGone; + ticket.onGone = () => { + if (!waiter.done) { + try { this.#settle(waiter, waiter.empty(Date.now(), false)); } catch (e) { this.#settle(waiter, null, e); } + } + prev?.(); + }; + this.#waiters.push(waiter); + this.#timer ??= setInterval(() => void this.#tick(), this.#tickMs); + this.#timer.unref(); + }); + } + + /** Answers every held claim with an empty reply that asks for a retry in 1 to 5 s (spread, so a restart is not hit at once), and stops holding. */ + close(): void { + this.#closed = true; + const now = Date.now(); + for (const w of [...this.#waiters]) { + if (w.done) continue; + let r: EmptyReply; + try { r = w.empty(now, false); } catch (e) { this.#settle(w, null, e); continue; } + this.#settle(w, { ...r, retryAfter: scaledS(1 + Math.floor(Math.random() * 5)) }); + } + } + + #settle(w: Waiter, r: ClaimReply | null, err?: unknown): void { + if (w.done) return; + w.done = true; + const i = this.#waiters.indexOf(w); + if (i >= 0) this.#waiters.splice(i, 1); + if (!this.#waiters.length && this.#timer) { clearInterval(this.#timer); this.#timer = null; } + if (r) { held.set(r, Date.now() - w.from); w.resolve(r); } else w.reject(err); + } + + /** One pass: tries, one at a time, the claims whose queue changed, whose full retry is due, or whose deadline passed. */ + async #tick(): Promise { + if (this.#running) return; + this.#running = true; + try { + let seq: number; + try { + seq = Number((this.#db.prepare("SELECT seq FROM main.change_seq WHERE topic = 'remote-queue'").get() as { seq: number } | undefined)?.seq ?? 0); + } catch (e) { + if (isBusy(e)) return; + throw e; + } + for (const w of [...this.#waiters]) { + if (w.done) continue; + const now = Date.now(); + const final = now >= w.deadline, full = final || now >= w.nextTry; + if (!full && w.seq === seq) continue; + w.seq = seq; + if (full) w.nextTry = now + this.#retryMs; + try { + const r = await w.attempt(now, { quick: !full, live: w.ticket.live }); + if (w.done) continue; + if (r) this.#settle(w, r); + else if (w.blocked()) this.#settle(w, w.empty(now, false)); + else if (final) { + w.idle(now); + this.#settle(w, w.empty(now, true)); + } + } catch (e) { + // A busy database: the claim keeps waiting and is tried again, unless this was its last try. + if (!isBusy(e) || final) this.#settle(w, null, e); + } + } + } catch (e) { + console.error(`claim waits: ${(e as Error).stack ?? e}`); + } finally { + this.#running = false; + } + } +} diff --git a/test/remote-longpoll.test.ts b/test/remote-longpoll.test.ts new file mode 100644 index 00000000..74a4dea1 --- /dev/null +++ b/test/remote-longpoll.test.ts @@ -0,0 +1,143 @@ +// Long-polling claims (protocol 4): a claim with nothing to take waits for a call queued by another process, answers empty at +// its deadline (still counting its helper idle), never holds for protocol 3, stops at a cool-off or the user's max calls at +// once, stops when its client leaves, and is answered cleanly when the dashboard shuts down. +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { after, describe, test } from "node:test"; +import { SCRATCH } from "./scratch.ts"; + +// Every user-local window, the hold included, at a fifth: a 25 s hold is 5 s, the full retry every second. Read on import. +process.env.AUTOCRAFT_REMOTE_TIME_SCALE = "0.2"; +const { addLogin } = await import("../src/access.ts"); +const { apiRoutes } = await import("../src/dash/api/index.ts"); +const { createToken } = await import("../src/dash/mcp/tokens.ts"); +const { loadConfig } = await import("../src/dash/server/config.ts"); +const { startServer } = await import("../src/dash/server/index.ts"); +const { FakeProvider } = await import("../src/dash/server/provider.ts"); +const { RateLimiter } = await import("../src/dash/server/util.ts"); +const { connect } = await import("../src/db.ts"); +const { CLAIM_RETRY_S, enqueueCall } = await import("../src/remote/calls.ts"); +const { setUserMaxCalls } = await import("../src/remote/max-calls.ts"); +const { setInferenceMode } = await import("../src/remote/mode.ts"); +const { ROUTES } = await import("../src/remote/protocol.ts"); + +mkdirSync(SCRATCH, { recursive: true }); +const dir = mkdtempSync(join(SCRATCH, "remote-longpoll-")); +after(() => rmSync(dir, { recursive: true, force: true })); + +describe("long-polling claims", async () => { + const file = join(dir, "t.db"), perms = join(dir, "perms.json"); + writeFileSync(perms, "{}"); + const db = connect(file), remoteDb = connect(file, { busyTimeoutMs: 100 }), other = connect(file); + setInferenceMode(db, "user-local", "test"); + const tokens: Record = {}; + for (const login of ["bob", "carol", "dave", "erin"]) { + addLogin(db, "cli", login, "maintainer", null); + const t = createToken(db, login, "runner", false, true); + tokens[login] = { token: t.token, id: t.row.id }; + db.prepare("INSERT OR REPLACE INTO repo_permissions (login, repo, permission, checked_at) VALUES (?, 'photocraft', 'write', ?)").run(login, new Date().toISOString()); + } + const config = loadConfig({ AUTOCRAFT_DEV_AUTH: "1", AUTOCRAFT_LISTEN: "127.0.0.1:0", AUTOCRAFT_DB: file, AUTOCRAFT_DEV_PERMS: perms }); + const limiter = new RateLimiter(60, 3600_000); + const s = await startServer({ config, db, remoteDb, provider: new FakeProvider(perms), feedbackLimiter: limiter, routes: apiRoutes({ limiter }) }); + let closed = false; + after(async () => { if (!closed) await s.close(); for (const c of [other, remoteDb, db]) c.close(); }); + + let n = 0; + const claim = async (login: string, extra: Record = {}, signal?: AbortSignal) => { + const body = { requestId: `longpoll-${String(++n).padStart(4, "0")}`, protocol: 4, wait: 25, helperVersion: "1.2.0", harness: "claude", harnessVersion: "2.1", tiers: { top: "opus" }, ...extra }; + const t = Date.now(); + const r = await fetch(`${s.url}${ROUTES.claim}`, { method: "POST", headers: { authorization: `Bearer ${tokens[login]!.token}`, "content-type": "application/json" }, body: JSON.stringify(body), ...(signal && { signal }) }); + assert.equal(r.status, 200); + return { reply: await r.json() as { lease: { id: number; secret: string } | null; retryAfter?: number; reason?: string }, ms: Date.now() - t, held: Number(r.headers.get("x-held-ms")) }; + }; + /** Queues a call through another connection, as a job process does. */ + const enqueue = (): number => enqueueCall(other, { + promptId: "review.opus", promptVersion: "t", tier: "top", effort: "high", askedModel: "opus", items: [{ repo: "photocraft", number: 1 }], level: 2, maxAttempts: 2, + bundle: { promptId: "review.opus", promptVersion: "t", tier: "top", effort: "high", timeoutSeconds: 600, maxTurns: null, stdin: "x", system: null, mounts: [], mcpServers: [], keepSession: false, hints: {} }, + }); + const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + const state = (id: number) => (db.prepare("SELECT state FROM remote_calls WHERE id = ?").get(id) as { state: string }).state; + + test("a held claim takes a call queued by another process within a second; a repeat of its request id gets the same lease", async () => { + const first = claim("bob", { requestId: "longpoll-same-0001" }); + await sleep(100); + const again = claim("bob", { requestId: "longpoll-same-0001" }); + await sleep(200); + const at = Date.now(); + const id = enqueue(); + const [a, b] = await Promise.all([first, again]); + assert.equal(a.reply.lease?.id, id); + assert.equal(b.reply.lease?.secret, a.reply.lease?.secret); + assert.ok(Date.now() - at < 1000, `answered ${Date.now() - at} ms after the call was queued`); + assert.ok(a.held >= 250, "the reply says how long it waited"); + }); + + test("a held claim with nothing to take answers empty at its deadline and records its helper as idle", async () => { + const r = claim("bob", { wait: 2 }); + await sleep(100); + db.prepare("UPDATE mcp_tokens SET idle_claim_at = NULL WHERE id = ?").run(tokens.bob!.id); + const { reply, held } = await r; + assert.equal(reply.lease, null); + assert.equal(reply.retryAfter, 0.2); + assert.ok(held >= 350 && held < 1500, `held ${held} ms of a 400 ms hold`); + assert.ok((db.prepare("SELECT idle_claim_at FROM mcp_tokens WHERE id = ?").get(tokens.bob!.id) as { idle_claim_at: number | null }).idle_claim_at !== null); + }); + + test("a protocol 3 claim is answered at once, whatever it sends as wait", async () => { + const { reply, ms, held } = await claim("bob", { protocol: 3 }); + assert.equal(reply.lease, null); + assert.equal(reply.retryAfter, CLAIM_RETRY_S); + assert.equal(held, 0); + assert.ok(ms < 500, `answered in ${ms} ms`); + }); + + test("a held claim whose client left takes nothing; the next claim with the same request id gets the call", async () => { + const ac = new AbortController(); + const gone = claim("bob", { requestId: "longpoll-gone-0001" }, ac.signal).catch(() => null); + await sleep(200); + ac.abort(); + await gone; + await sleep(100); + const id = enqueue(); + await sleep(400); + assert.equal(state(id), "queued"); + const { reply } = await claim("bob", { requestId: "longpoll-gone-0001" }); + assert.equal(reply.lease?.id, id); + }); + + test("the user's max calls at once and a cool-off end a held claim with their reason", async () => { + setUserMaxCalls(db, "carol", 1); + const full = claim("carol"); + await sleep(200); + // Another of carol's helpers leases a call meanwhile: queued and leased in one transaction, so the held claim never sees it queued. + other.exec("BEGIN IMMEDIATE"); + const id = enqueue(); + other.prepare("UPDATE remote_calls SET state = 'leased', user_login = 'carol', leased_at = ?, heartbeat_at = ? WHERE id = ?").run(Date.now(), Date.now(), id); + other.exec("COMMIT"); + const a = await full; + assert.equal(a.reply.lease, null); + assert.match(a.reply.reason ?? "", /limit of calls at once/); + assert.ok(a.ms < 2500, `answered after ${a.ms} ms of a 5 s hold`); + + const cooled = claim("dave"); + await sleep(200); + other.prepare("INSERT INTO remote_cooloffs (login, until, reason) VALUES ('dave', ?, 'testing cool-off')").run(Date.now() + 60_000); + const b = await cooled; + assert.equal(b.reply.reason, "testing cool-off"); + assert.ok(b.ms < 2500, `answered after ${b.ms} ms of a 5 s hold`); + }); + + test("shutting down answers held claims with a short retry, not a reset", async () => { + const r = claim("erin"); + await sleep(200); + const t = Date.now(); + closed = true; + await s.close(); + const { reply } = await r; + assert.equal(reply.lease, null); + assert.ok(reply.retryAfter! >= 0.2 && reply.retryAfter! <= 1, `retryAfter ${reply.retryAfter}`); + assert.ok(Date.now() - t < 1000); + }); +});