mirror of
https://github.com/storytold/autocraft.git
synced 2026-11-23 07:51:02 +01:00
Merge branch 'rb-t6-load' into rb-int
Lease tombstones, old lease drops and spent cool-off rows go with the minute maintenance (pruneRemote); requeue and unlease drop the cached queue order; the liveness stamp uses the helper routes' connection.
This commit is contained in:
commit
d77fb3d7ea
17 files changed
+363
-91
No files matched your search
@@ -101,7 +101,7 @@ To sign in through a GitHub App instead, register it from the dashboard's GitHub
|
||||
| `AUTOCRAFT_SECRETS_FILE` | The secrets file above |
|
||||
| `AUTOCRAFT_GITHUB_APP_NAME` | App name suggested on the registration form, default `AutoCraft` |
|
||||
| `AUTOCRAFT_WEB_DIST` | Built frontend, default `web/dist` |
|
||||
| `AUTOCRAFT_TRUST_PROXY` | `1` behind a proxy that sets `X-Forwarded-For` |
|
||||
| `AUTOCRAFT_TRUST_PROXY` | The number of proxies in front that set `X-Forwarded-For` (`1` behind one proxy) |
|
||||
|
||||
The server speaks plain HTTP; put a reverse proxy with HTTPS in front. More variables are in [docs/operations.md](docs/operations.md).
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ The image sets every path (`/data/...`, `/config/...`). A deployment sets only t
|
||||
| Name | Required | Default | Purpose |
|
||||
|---|---|---|---|
|
||||
| `AUTOCRAFT_BASE_URL` | dashboard: yes | none | Public origin, `https://autocraft.example.com`, no path. Used for sign-in callbacks and links. |
|
||||
| `AUTOCRAFT_TRUST_PROXY` | behind a proxy | off | `1` reads the client address from the last `X-Forwarded-For` entry, for rate limits. Set it only when the proxy sets that header. |
|
||||
| `AUTOCRAFT_TRUST_PROXY` | behind a proxy | `0` | The number of proxies that append to `X-Forwarded-For`; the client address for rate limits is that many entries from the end (`1`: the last entry). A proxy that replaces the header with a CDN's client header counts as one. |
|
||||
| `GH_TOKEN` | yes, on dashboard, runner and periodic | none | GitHub token for `gh` (the dashboard's image proxy and repository adds, sync, pipeline calls): a classic token with `repo`, `read:org` and `workflow` scopes. Keep it in a Secret. |
|
||||
| `AUTOCRAFT_STOP_TIMEOUT` | no | `25` | Seconds the runner may take to stop. Keep the pod's `terminationGracePeriodSeconds` above it (30). |
|
||||
| `AUTOCRAFT_HEALTH_LISTEN` | no | off | `host:port` of a runner listener that serves only `/healthz` and `/readyz`. |
|
||||
|
||||
+1
-1
@@ -215,7 +215,7 @@ After a reboot Docker starts the services again; the pipeline state is in the da
|
||||
|
||||
Any TLS reverse proxy on the VPS forwards the public origin to `127.0.0.1:3005`. It must:
|
||||
|
||||
- pass `Host` and set `X-Forwarded-For` (with `AUTOCRAFT_TRUST_PROXY=1` the dashboard reads the last entry);
|
||||
- pass `Host` and set `X-Forwarded-For` (`AUTOCRAFT_TRUST_PROXY` is the number of proxies that append to it; with `1` the dashboard reads the last entry);
|
||||
- not buffer or time out `GET /api/live` early (an event stream that stays open);
|
||||
- accept request bodies of at least 1 MB (`POST /webhooks/github` allows 1 MB);
|
||||
- route nothing to 8981.
|
||||
|
||||
+4
-2
@@ -64,7 +64,7 @@ The frontend is the React app in `web/`. Build it before serving: `pnpm -C web i
|
||||
| `AUTOCRAFT_WEB_DIST` | Directory of the built frontend. Default `web/dist` in the repo. |
|
||||
| `AUTOCRAFT_SECRETS_FILE` | JSON file with `github_client_id`, `github_client_secret` and `session_key` (at least 32 characters, random). Must be mode 0600; the server refuses to start if it is missing, incomplete, or readable by group or others. Registering the GitHub App from the dashboard (GitHub App page, operators only) adds `github_app_id`, `github_app_slug`, `github_app_private_key`, `github_app_client_id`, `github_app_client_secret`, `github_app_webhook_secret` and `github_app_owner` (`{"login", "type"}`, the user or organization that owns the app). The GitHub App page's Remove button deletes every `github_app_*` key through the same atomic write (refused while the GitHub identity is the GitHub App) and links to the app's GitHub settings page, where the operator deletes the app. The dashboard rewrites this file itself for that: it writes a temporary file beside it and renames it over the file (a symlink stays a symlink), so the directory must be writable by the server user. Registration checks this first and refuses to start when it cannot write. The server reads the app's keys again whenever the file changes, so registering or removing the app needs no restart. Whether GitHub reads, writes and dashboard sign-in use the box account or the GitHub App is one instance-wide setting (GitHub App page, or `autocraft identity [box|app]`); switching ends every dashboard session and takes effect in the runner and the dashboard at their next GitHub call, without a restart. Under `box`, every `gh` and `git` call uses the server user's own `gh` login. Under `app`, every read (GraphQL, REST, git fetch over HTTPS, the image proxy, repository checks when tracking) runs with an installation token of the owner it concerns (the first tracked repo's owner when a read names none) and never sees the box account's credentials; the `gh` login of the server user is not needed. A read for which no installation token can be minted fails with an error naming the owner. The GitHub rate figures shown on the Pipeline page and used by the sync's reserve are those of the token in use. Permission checks of a signed-in person use that person's own token in both modes. |
|
||||
| `AUTOCRAFT_GITHUB_APP_NAME` | Name suggested on the registration form. Default `AutoCraft`; at most 34 letters, digits, spaces, dashes or underscores. |
|
||||
| `AUTOCRAFT_TRUST_PROXY` | `1` to take the client address for rate limits from the last `X-Forwarded-For` entry. Set it only behind a proxy that sets that header. |
|
||||
| `AUTOCRAFT_TRUST_PROXY` | The number of trusted proxies in front of the server (0 to 9, default 0), for the client address of the rate limits. Each proxy is assumed to append the address it was reached from to `X-Forwarded-For`, so the client is that many entries from the end; with 0 the socket address counts. A proxy that replaces the header with a CDN's client-address header counts as one, and must then refuse connections that do not come from the CDN. |
|
||||
| `AUTOCRAFT_IMG_CACHE` | Disk cache of the image proxy. Default `$XDG_CACHE_HOME/autocraft/img` (`~/.cache/...`); empty for no disk cache. |
|
||||
|
||||
The GitHub OAuth App needs no scopes, and expiring user tokens are supported: the server refreshes them as needed and ends the session when a refresh fails. Tokens are stored encrypted with a key derived from `session_key`; changing `session_key` makes the stored GitHub tokens unreadable until each user signs in again.
|
||||
@@ -235,7 +235,9 @@ A call goes to a maintainer or operator whose cached GitHub permission is `write
|
||||
| Caller gone | A queued or leased call whose job stopped polling for 5 minutes fails. |
|
||||
| Waiting | The runner leaves at most 12 hours of queue time out of a job's deadline and no-progress stop; a call still queued after that is withdrawn ("no helper took the call in time") and the job stops. |
|
||||
|
||||
Ended calls are kept 24 hours for task status and follow-ups, then deleted.
|
||||
Ended calls are kept 24 hours for task status and follow-ups; the dashboard deletes older ones once a minute.
|
||||
|
||||
**Limits.** Per helper token: 600 claims and 120 status reports a minute. Per lease: 120 bundle, heartbeat, release and submit requests a minute, and 300 tool calls. Failed authentications count against the client address (300 a minute, shared with `/mcp`). Beyond a limit the answer is 429 with `Retry-After`. When the database stays locked for 2 seconds, a helper route answers 503 with `Retry-After: 5`.
|
||||
|
||||
**Cool-off.** Cool-off applies to a login, across all its helpers and tokens:
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// Times claimCall against a large user-local queue: 500 queued calls on 25 repos, 50 helper tokens that asked for work a
|
||||
// moment ago. Two cases: a helper that takes the first call, and an author's claim that gives way on every call and so
|
||||
// walks the whole queue. Run: node --no-warnings scripts/remote-claim-bench.ts
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createToken } from "../src/dash/mcp/tokens.ts";
|
||||
import { connect } from "../src/db.ts";
|
||||
import { claimCall, enqueueCall, type Caller } from "../src/remote/calls.ts";
|
||||
import { setInferenceMode } from "../src/remote/mode.ts";
|
||||
import { PROTOCOL_VERSION, type Claim, type TaskBundle } from "../src/remote/protocol.ts";
|
||||
|
||||
const CALLS = 500, REPOS = 25, IDLE = 50, ROUNDS = 40;
|
||||
const dir = mkdtempSync(join(tmpdir(), "claim-bench-"));
|
||||
try {
|
||||
const db = connect(join(dir, "bench.db"));
|
||||
setInferenceMode(db, "user-local", "bench");
|
||||
const now = Date.now(), iso = new Date(now).toISOString();
|
||||
const bundle: Omit<TaskBundle, "callId"> = { promptId: "review.opus", promptVersion: "1", tier: "top", effort: "medium", timeoutSeconds: 600, maxTurns: 10, stdin: "x".repeat(20_000), system: null, mounts: [], mcpServers: [], keepSession: false, hints: {} };
|
||||
const perm = db.prepare("INSERT OR REPLACE INTO repo_permissions (login, repo, permission, checked_at) VALUES (?, ?, ?, ?)");
|
||||
const caller = (login: string): Caller => {
|
||||
db.prepare("INSERT OR IGNORE INTO access (login, role) VALUES (?, 'maintainer')").run(login);
|
||||
return { tokenId: createToken(db, login, "helper", false, true).row.id, login, role: "maintainer" };
|
||||
};
|
||||
// "author" wrote every PR; the idle helpers asked for top-tier work. Only the last of them may write, so an author's claim
|
||||
// looks through the others for every call before it gives way.
|
||||
const author = caller("author"), taker = caller("taker");
|
||||
for (let i = 0; i < IDLE; i++) {
|
||||
const c = caller(`idle${i}`);
|
||||
db.prepare("UPDATE mcp_tokens SET idle_claim_at = ?, idle_tiers = '[\"top\"]', idle_repos = NULL WHERE id = ?").run(now, c.tokenId);
|
||||
for (let r = 0; r < REPOS; r++) perm.run(c.login, `repo${r}`, i === IDLE - 1 ? "write" : "read", iso);
|
||||
}
|
||||
for (let i = 0; i < CALLS; i++) {
|
||||
const repo = `repo${i % REPOS}`, number = 1000 + i;
|
||||
db.prepare("INSERT INTO items (repo, number, kind, state, title, author, created_at, updated_at) VALUES (?, ?, 'pr', 'OPEN', 't', 'author', ?, ?)").run(repo, number, iso, iso);
|
||||
db.prepare("INSERT INTO pr_commits (repo, number, oid, committed_at, author, co_authors) VALUES (?, ?, ?, ?, 'author', '[\"someone\"]')").run(repo, number, `oid${i}`, iso);
|
||||
enqueueCall(db, { promptId: "review.opus", promptVersion: "1", tier: "top", effort: "medium", askedModel: "opus", bundle, items: [{ repo, number }], level: i % 5, maxAttempts: 2 }, now);
|
||||
}
|
||||
const claim: Claim = { requestId: "bench-claim-0001", protocol: PROTOCOL_VERSION, helperVersion: "9.0.0", harness: "claude", harnessVersion: "2.1", tiers: { top: "opus" } };
|
||||
const canWrite = async () => true;
|
||||
const time = async (label: string, c: Caller, expectLease: boolean): Promise<void> => {
|
||||
const ms: number[] = [];
|
||||
for (let i = 0; i < ROUNDS; i++) {
|
||||
const t = performance.now();
|
||||
const r = await claimCall(db, c, { ...claim, requestId: `bench-${label}-${String(i).padStart(4, "0")}` }, canWrite);
|
||||
ms.push(performance.now() - t);
|
||||
if (Boolean(r.lease) !== expectLease) throw new Error(`${label}: lease ${r.lease ? "given" : "missing"}`);
|
||||
}
|
||||
ms.sort((a, b) => a - b);
|
||||
console.log(`${label.padEnd(10)} median ${ms[Math.floor(ms.length / 2)]!.toFixed(2)} ms, p90 ${ms[Math.floor(ms.length * 0.9)]!.toFixed(2)} ms, first ${ms[0]!.toFixed(2)}..${ms[ms.length - 1]!.toFixed(2)} ms`);
|
||||
};
|
||||
await time("pass-over", author, false);
|
||||
await time("take", taker, true);
|
||||
db.close();
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
+7
-1
@@ -4,6 +4,9 @@ import { scopeToTracked } from "../repos.ts";
|
||||
import { ConfigError, loadConfig } from "./server/config.ts";
|
||||
import { startServer } from "./server/index.ts";
|
||||
|
||||
/** How long a helper route waits for SQLite's write lock before it answers 503. */
|
||||
const REMOTE_BUSY_MS = 2_000;
|
||||
|
||||
async function serve(): Promise<void> {
|
||||
let config;
|
||||
try {
|
||||
@@ -16,9 +19,12 @@ async function serve(): Promise<void> {
|
||||
const db = connect(config.dbPath);
|
||||
scopeToTracked(db);
|
||||
sweepRunningCards(db);
|
||||
const { url, close } = await startServer({ config, db });
|
||||
// The helper routes' own connection: they wait at most REMOTE_BUSY_MS for a write lock and then answer 503.
|
||||
const remoteDb = connect(config.dbPath, { busyTimeoutMs: REMOTE_BUSY_MS });
|
||||
const { url, close } = await startServer({ config, db, remoteDb });
|
||||
console.log(`dashboard listening on ${url}${config.devAuth ? " (development sign-in)" : ""}`);
|
||||
const stop = () => void close().then(() => {
|
||||
remoteDb.close();
|
||||
db.close();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
@@ -52,7 +52,7 @@ export type Config = {
|
||||
devAuth: boolean;
|
||||
devPermsFile: string | null;
|
||||
devTokenTtlMs: number | null; // fake provider's access-token lifetime
|
||||
trustProxy: boolean;
|
||||
trustProxy: number; // proxies in front of the server that append to X-Forwarded-For; 0: use the socket address
|
||||
imageCacheDir: string | null; // the image proxy's disk cache; null: none
|
||||
secrets: Secrets;
|
||||
secretsFile: string | null; // where registration writes the app's secrets
|
||||
@@ -248,13 +248,15 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
|
||||
throw new ConfigError("AUTOCRAFT_BASE_URL is not set");
|
||||
}
|
||||
const webDistEnv = envVar("WEB_DIST", env);
|
||||
const trustRaw = envVar("TRUST_PROXY", env) || "0";
|
||||
if (!/^[0-9]$/.test(trustRaw)) throw new ConfigError("AUTOCRAFT_TRUST_PROXY must be the number of trusted proxies in front of the server, 0 to 9");
|
||||
return {
|
||||
host, port, baseUrl, devAuth, secrets, secretsFile,
|
||||
dbPath: envVar("DB", env) ?? dbPath(),
|
||||
webDist: webDistEnv ? resolve(webDistEnv) : DEFAULT_WEB_DIST,
|
||||
devPermsFile: devAuth ? (envVar("DEV_PERMS", env) ?? null) : null,
|
||||
devTokenTtlMs: devAuth && envVar("DEV_TOKEN_TTL", env) ? Number(envVar("DEV_TOKEN_TTL", env)) * 1000 || null : null,
|
||||
trustProxy: envVar("TRUST_PROXY", env) === "1",
|
||||
trustProxy: Number(trustRaw),
|
||||
imageCacheDir: envVar("IMG_CACHE", env) === "" ? null : defaultImageCacheDir(env),
|
||||
};
|
||||
}
|
||||
+46
-10
@@ -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 { isBusy } from "../../db.ts";
|
||||
import { inferenceMode } from "../../remote/mode.ts";
|
||||
import { HELPERS_PATH, parseStatus, storeStatus } from "../../remote/helpers.ts";
|
||||
import { ROUTES, type ClaimReply, type StatusReply, type ToolReply } from "../../remote/protocol.ts";
|
||||
@@ -77,9 +78,15 @@ export const APP_CSP = [
|
||||
"base-uri 'none'", "frame-ancestors 'none'",
|
||||
].join("; ");
|
||||
|
||||
/** Seconds a helper waits before retrying a request that found the database busy. */
|
||||
const BUSY_RETRY_S = 5;
|
||||
|
||||
export type AppOptions = {
|
||||
config: Config;
|
||||
db: DatabaseSync;
|
||||
// The connection of the helper routes and the remote maintenance: a short busy timeout, so a locked database answers 503 at
|
||||
// once instead of holding the event loop for the 30-second timeout of `db`. Default: `db`.
|
||||
remoteDb?: DatabaseSync;
|
||||
provider?: Provider;
|
||||
routes?: Route[]; // default: the JSON API
|
||||
images?: ImageProxy; // default: fetches with global fetch and the bot's gh token
|
||||
@@ -175,6 +182,7 @@ function cookie(name: string, value: string, maxAgeSec: number): string {
|
||||
|
||||
export function createApp(opts: AppOptions & { routes: Route[] }) {
|
||||
const { config, db } = opts;
|
||||
const rdb = opts.remoteDb ?? db;
|
||||
const provider = opts.provider ?? providerFor(config, () => githubIdentity(db));
|
||||
// The org setup link signs in with the OAuth App even when dashboard sign-in uses the GitHub App.
|
||||
const setupProvider = opts.provider ?? (config.devAuth ? provider : oauthProviderFor(config));
|
||||
@@ -208,8 +216,12 @@ export function createApp(opts: AppOptions & { routes: Route[] }) {
|
||||
// The Inbox MCP server (POST /mcp): calls per login and failed authentications per client address, and feedback posts per login as on the dashboard.
|
||||
const mcpLimitToken = new RateLimiter(120, 60_000);
|
||||
const mcpLimitIp = new RateLimiter(300, 60_000);
|
||||
// Claims of one login: a helper with several slots claims every few seconds at most.
|
||||
const remoteLimitToken = new RateLimiter(240, 60_000);
|
||||
// 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 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);
|
||||
// Tool calls of one remote call (item, reference and check tools together).
|
||||
const remoteToolLimit = new RateLimiter(300, 60_000);
|
||||
const remoteArchiveLimit = new RateLimiter(20, 60_000); // tarball fetches per lease
|
||||
@@ -221,14 +233,27 @@ export function createApp(opts: AppOptions & { routes: Route[] }) {
|
||||
const callbackUrl = `${config.baseUrl ?? ""}/auth/callback`;
|
||||
let lastPrune = 0;
|
||||
|
||||
// The client address for the per-address limits. Each of the `trustProxy` proxies in front of the server appends the
|
||||
// address it was reached from to X-Forwarded-For, so the client is that many entries from the end; entries further left
|
||||
// came from the client and are not trusted. A proxy that replaces the header with a CDN's client header counts as one.
|
||||
function clientIp(req: IncomingMessage): string {
|
||||
if (config.trustProxy) {
|
||||
if (config.trustProxy > 0) {
|
||||
const xff = String(req.headers["x-forwarded-for"] ?? "").split(",").map((s) => s.trim()).filter(Boolean);
|
||||
if (xff.length) return xff[xff.length - 1]!;
|
||||
if (xff.length) return xff[Math.max(0, xff.length - config.trustProxy)]!;
|
||||
}
|
||||
return req.socket.remoteAddress ?? "?";
|
||||
}
|
||||
|
||||
// Ended remote calls, finished check relays and the status of deleted tokens, once a minute; a busy database skips a round.
|
||||
const maintenance = setInterval(() => {
|
||||
try {
|
||||
remote.pruneRemote(rdb);
|
||||
} catch (e) {
|
||||
if (!isBusy(e)) console.log(`remote maintenance failed: ${(e as Error).message}`);
|
||||
}
|
||||
}, 60_000);
|
||||
maintenance.unref();
|
||||
|
||||
function secure(headers: Record<string, string | string[]>, csp: string): Record<string, string | string[]> {
|
||||
headers["content-security-policy"] = csp;
|
||||
headers["x-frame-options"] = "DENY";
|
||||
@@ -575,6 +600,12 @@ export function createApp(opts: AppOptions & { routes: Route[] }) {
|
||||
} catch (e) {
|
||||
const api = (req.url ?? "").startsWith("/api/");
|
||||
if (e instanceof HttpError) return send(res, nonce, api ? apiError(e.status, e.message) : errorPage(nonce, e.status, "Request refused", e.message));
|
||||
// The database stayed locked past the connection's busy timeout (the helper routes wait only briefly): try again shortly.
|
||||
if (isBusy(e)) {
|
||||
if (res.headersSent) return void res.destroy();
|
||||
res.writeHead(503, secure({ "cache-control": "no-store", "content-type": "application/json; charset=utf-8", "retry-after": String(BUSY_RETRY_S) }, "default-src 'none'"));
|
||||
return void res.end(JSON.stringify({ error: "the database is busy; try again shortly" }));
|
||||
}
|
||||
console.error(`${req.method} ${(req.url ?? "").split("?")[0]}: ${(e as Error).stack ?? e}`);
|
||||
if (!res.headersSent) send(res, nonce, api ? apiError(500, "server error; it is logged") : errorPage(nonce, 500, "Something went wrong", "The error is logged on the server."));
|
||||
else res.destroy();
|
||||
@@ -678,13 +709,14 @@ export function createApp(opts: AppOptions & { routes: Route[] }) {
|
||||
const method = path === ROUTES.bundle || path === ROUTES.tarball ? "GET" : "POST";
|
||||
if (req.method !== method) return reply(405, { error: `use ${method}` }, { allow: method });
|
||||
const tooMany = (): void => reply(429, { error: "too many requests; wait a minute" }, { "retry-after": "60" });
|
||||
const db = rdb;
|
||||
try {
|
||||
if (path === ROUTES.claim) {
|
||||
const caller = loadToken(db, bearer);
|
||||
if (!caller && !mcpLimitIp.allow(clientIp(req))) return tooMany();
|
||||
if (!caller) return reply(401, { error: "a valid AutoCraft agent token is required (Authorization: Bearer <token>)" }, { "www-authenticate": 'Bearer realm="autocraft"' });
|
||||
if (!caller.canRun) return reply(403, { error: "this token cannot run tasks; make one with Can run tasks on the Connect page" });
|
||||
if (!remoteLimitToken.allow(caller.login.toLowerCase())) return tooMany();
|
||||
if (!remoteClaimLimit.allow(String(caller.tokenId))) return tooMany();
|
||||
const claim = remote.parseClaim(await readJson(req));
|
||||
// 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);
|
||||
@@ -699,17 +731,19 @@ export function createApp(opts: AppOptions & { routes: Route[] }) {
|
||||
if (!caller && !mcpLimitIp.allow(clientIp(req))) return tooMany();
|
||||
if (!caller) return reply(401, { error: "a valid AutoCraft agent token is required (Authorization: Bearer <token>)" }, { "www-authenticate": 'Bearer realm="autocraft"' });
|
||||
if (!caller.canRun) return reply(403, { error: "this token cannot run tasks; make one with Can run tasks on the Connect page" });
|
||||
if (!remoteLimitToken.allow(caller.login.toLowerCase())) return tooMany();
|
||||
if (!remoteStatusLimit.allow(String(caller.tokenId))) return tooMany();
|
||||
storeStatus(db, caller.tokenId, caller.login, parseStatus(await readJson(req)));
|
||||
return reply(200, { ok: true, reserve: userReserve(db, caller.login) } satisfies StatusReply);
|
||||
}
|
||||
const tool = path.startsWith(`${ROUTES.tool}/`) ? /^([a-z][a-z0-9_-]{0,40})\/([a-z][a-z0-9_]{0,60})$/.exec(path.slice(ROUTES.tool.length + 1)) : null;
|
||||
if (![ROUTES.bundle, ROUTES.heartbeat, ROUTES.submit, ROUTES.release, ROUTES.tarball].includes(path as never) && !tool) return reply(404, { error: "not found" });
|
||||
// An unknown secret counts against the address; a known one whose lease ended or went back to the queue is answered 410.
|
||||
if (!remote.leaseState(db, bearer)) {
|
||||
const state = remote.leaseState(db, bearer);
|
||||
if (!state) {
|
||||
if (!mcpLimitIp.allow(clientIp(req))) return tooMany();
|
||||
return reply(401, { error: "a lease secret is required (Authorization: Bearer <secret>)" }, { "www-authenticate": 'Bearer realm="autocraft"' });
|
||||
}
|
||||
if (path !== ROUTES.tarball && !tool && !remoteLeaseLimit.allow(String(state.id))) return tooMany();
|
||||
const gone = (): void => reply(410, { error: "the lease is gone (expired, withdrawn or already submitted)" });
|
||||
if (path === ROUTES.bundle) {
|
||||
const b = remote.bundleOf(db, bearer);
|
||||
@@ -763,6 +797,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) {
|
||||
res.end(body === null ? "" : JSON.stringify(body));
|
||||
};
|
||||
const rpcError = (code: number, message: string) => ({ jsonrpc: "2.0", id: null, error: { code, message } });
|
||||
const db = rdb;
|
||||
if (req.method !== "POST") return reply(405, rpcError(-32000, "POST one JSON-RPC message; this server has no event stream"), { allow: "POST" });
|
||||
if (!sameOrigin(req)) return reply(403, rpcError(-32000, "cross-origin request refused"));
|
||||
const bearer = /^Bearer\s+(\S+)$/i.exec(String(req.headers.authorization ?? ""))?.[1];
|
||||
@@ -900,15 +935,16 @@ 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: () => live.close() };
|
||||
return { handle, routes: opts.routes, provider, live, close: () => { clearInterval(maintenance); live.close(); } };
|
||||
}
|
||||
|
||||
export async function startServer(opts: AppOptions): Promise<{ server: Server; url: string; app: ReturnType<typeof createApp>; close(): Promise<void> }> {
|
||||
const feedbackLimiter = opts.feedbackLimiter ?? new RateLimiter(60, 3600_000);
|
||||
const app = createApp({ ...opts, feedbackLimiter, routes: opts.routes ?? (await defaultRoutes(feedbackLimiter, opts.githubUserId)) });
|
||||
const server = createServer({ requestTimeout: 30_000, headersTimeout: 15_000 }, (req, res) => void app.handle(req, res));
|
||||
// Job processes expire user-local leases only while this process stamps that it serves (src/remote/liveness.ts).
|
||||
const stopLiveness = startLiveness(opts.db);
|
||||
// Job processes expire user-local leases only while this process stamps that it serves (src/remote/liveness.ts). The
|
||||
// stamp uses the helper routes' short busy timeout: a busy database skips a tick rather than stalling the event loop.
|
||||
const stopLiveness = startLiveness(opts.remoteDb ?? opts.db);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(opts.config.port, opts.config.host, resolve);
|
||||
|
||||
@@ -227,6 +227,7 @@ const ADDED_COLUMNS: [table: string, column: string, type: string][] = [
|
||||
["remote_calls", "started_at", "INTEGER"],
|
||||
["remote_calls", "claim_id", "TEXT"],
|
||||
["remote_lease_drops", "login", "TEXT COLLATE NOCASE"],
|
||||
["remote_calls", "authors", "TEXT"],
|
||||
["dupe_comparisons", "sizes", "TEXT"],
|
||||
["build_envs", "confidential", "INTEGER NOT NULL DEFAULT 0"],
|
||||
["build_envs", "confidential_since", "TEXT"],
|
||||
@@ -238,6 +239,8 @@ const ADDED_COLUMNS: [table: string, column: string, type: string][] = [
|
||||
// Covering indexes on the hash columns let the planner compare stored hashes without reading item rows.
|
||||
// The trigger clears the hashes of an item whose hashed fields were edited without bringing its own (sync does).
|
||||
const ADDED_INDEXES = [
|
||||
// Covers the claims' read of the queued remote calls (src/remote/calls.ts queuedCalls) and the room count, so neither walks the overflow pages of each row's bundle.
|
||||
"CREATE INDEX IF NOT EXISTS main.remote_calls_queued ON remote_calls(class, seen_at, level, since, step, repo, prompt_id, tier, parent_id, sticky_login, released_by, released_at) WHERE state = 'queued'",
|
||||
// One live card per set of choices: a double press cannot run the same choice twice.
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS main.conversation_cards_choice_live ON conversation_cards(choice_id) WHERE choice_id IS NOT NULL AND state IN ('proposed', 'running', 'done')",
|
||||
// Records the answerer's role when an answer is written (any writer); cleared with the answerer by an undo.
|
||||
@@ -619,7 +622,20 @@ function stampOf(db: DatabaseSync): string | null {
|
||||
}
|
||||
}
|
||||
|
||||
export function connect(path: string = dbPath()): DatabaseSync {
|
||||
/**
|
||||
* Opens the database and brings its schema up to date. `busyTimeoutMs` replaces the 30-second busy timeout once the
|
||||
* schema is current: a connection that serves requests waits that long for a write lock, then throws SQLITE_BUSY.
|
||||
*/
|
||||
export function connect(path: string = dbPath(), opts: { busyTimeoutMs?: number } = {}): DatabaseSync {
|
||||
const db = open(path);
|
||||
if (opts.busyTimeoutMs !== undefined) db.exec(`PRAGMA busy_timeout = ${Math.max(0, Math.floor(opts.busyTimeoutMs))}`);
|
||||
return db;
|
||||
}
|
||||
|
||||
/** Whether `e` is SQLite's "database is locked" (SQLITE_BUSY, any extended code): another connection held the write lock past the busy timeout. */
|
||||
export const isBusy = (e: unknown): boolean => typeof (e as { errcode?: unknown } | null)?.errcode === "number" && ((e as { errcode: number }).errcode & 0xff) === 5;
|
||||
|
||||
function open(path: string): DatabaseSync {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const db = new DatabaseSync(path, { timeout: 30_000 });
|
||||
// WAL so the dashboard can read while a sync writes
|
||||
|
||||
+152
-62
@@ -1,7 +1,7 @@
|
||||
// Remote calls of the user-local inference mode. The calling process (askClaude, src/classify/run.ts) inserts a call
|
||||
// and polls its row; a maintainer's helper claims it with an agent token that may run tasks, fetches the bundle and
|
||||
// sends heartbeats and the reply with the lease secret (routes in src/dash/server/index.ts, wire format in protocol.ts).
|
||||
// Nothing here runs on a timer: leases are checked by the calling process on each poll and by every claim.
|
||||
// Leases are checked by the calling process on each poll and by every claim; the dashboard deletes old rows once a minute (pruneRemote).
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import type { ItemRef } from "../../web/src/api/types.ts";
|
||||
import { allocation, callQueue, queueOrder, stepOf, throwIfHalted, WaitLimitError, type Waiter } from "../agents/call.ts";
|
||||
@@ -16,13 +16,13 @@ import { fillHarness, rootArgs, validRoot } from "../prompts/harness.ts";
|
||||
import { rootAgents } from "../sandbox/agents.ts";
|
||||
import { joinParts } from "../prompts/index.ts";
|
||||
import { scrub } from "../runner/scrub.ts";
|
||||
import { cooloffOf, noteDrop, noteFailure, noteSuccess } from "./cooloff.ts";
|
||||
import { cooloffOf, noteDrop, noteFailure, noteSuccess, pruneCooloffs } from "./cooloff.ts";
|
||||
import { dashboardAlive } from "./liveness.ts";
|
||||
import { acceptedModels, familyOf, isEffort, isTier, meetsEffort, minEfforts, TIERS } from "./mode.ts";
|
||||
import { CLAIM_ID_TTL_S, PREPARE_MAX_S, PROTOCOL_VERSION, ROUTES, type Claim, type ClaimReply, type HarnessId, type Heartbeat, type Release, type Submit, type SubmitReply, type TaskBundle, type Tier } from "./protocol.ts";
|
||||
import { claimRepos } from "./my-repos.ts";
|
||||
import { userReserve } from "./reserve.ts";
|
||||
import { CALLER_STALE_MS, IDLE_FRESH_MS } from "./room.ts";
|
||||
import { CALLER_STALE_MS, IDLE_FRESH_MS, SEEN_EVERY_MS } from "./room.ts";
|
||||
import { WRITE_PERMISSIONS } from "../dash/server/provider.ts";
|
||||
import { PERM_READ_TTL } from "../dash/server/sessions.ts";
|
||||
import { endChecks, serveChecks } from "./check-relay.ts";
|
||||
@@ -83,10 +83,13 @@ export type NewCall = {
|
||||
export function enqueueCall(db: DatabaseSync, c: NewCall, nowMs: number = Date.now()): number {
|
||||
const s = stepOf(c.promptId), q = callQueue(c.promptId);
|
||||
const sticky = c.parentId === undefined ? null : (db.prepare("SELECT user_login FROM main.remote_calls WHERE id = ?").get(c.parentId) as { user_login: string | null } | undefined)?.user_login ?? null;
|
||||
return Number(db.prepare(`INSERT INTO main.remote_calls (job_id, step, stage, prompt_id, prompt_version, tier, effort, asked_model, bundle, state, items, repo, class, level, since, seen_at, queued_since, max_attempts, timeout_ms, parent_id, sticky_login, reference_repo)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
||||
const authors = judges(c.promptId) ? JSON.stringify(authorsOf(db, c.items)) : "[]";
|
||||
const id = Number(db.prepare(`INSERT INTO main.remote_calls (job_id, step, stage, prompt_id, prompt_version, tier, effort, asked_model, bundle, state, items, repo, class, level, since, seen_at, queued_since, max_attempts, timeout_ms, parent_id, sticky_login, reference_repo, authors)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
||||
.run(s.jobId, s.step, s.stage, c.promptId, c.promptVersion, c.tier, c.effort, c.askedModel, JSON.stringify(c.bundle), JSON.stringify(c.items), q.repo, q.cls, c.level, nowMs, nowMs, nowMs,
|
||||
Math.max(1, c.maxAttempts), c.bundle.timeoutSeconds * 1000, c.parentId ?? null, sticky, c.referenceRepo ?? null).lastInsertRowid);
|
||||
Math.max(1, c.maxAttempts), c.bundle.timeoutSeconds * 1000, c.parentId ?? null, sticky, c.referenceRepo ?? null, authors).lastInsertRowid);
|
||||
dropQueueCache(db);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** Ends a call that is in one of `states` as failed; true when it did. A leased call's agent run fails with it. */
|
||||
@@ -106,10 +109,9 @@ export function withdrawJobCalls(db: DatabaseSync, reason: string, jobId?: numbe
|
||||
return ids.filter((r) => withdrawCall(db, Number(r.id), reason)).length;
|
||||
}
|
||||
|
||||
/** Keeps the secret hash of a lease that just ended or went back to the queue, so its routes answer 410 (leaseState); kept as long as ended calls. */
|
||||
/** Keeps the secret hash of a lease that just ended or went back to the queue, so its routes answer 410 (leaseState); kept as long as ended calls (pruneRemote). */
|
||||
function bury(db: DatabaseSync, id: number, hash: string | null, nowMs: number): void {
|
||||
if (hash === null) return;
|
||||
db.prepare("DELETE FROM main.remote_lease_tombstones WHERE at < ?").run(nowMs - KEEP_MS);
|
||||
db.prepare("INSERT OR IGNORE INTO main.remote_lease_tombstones (secret_hash, call_id, at) VALUES (?, ?, ?)").run(hash, id, nowMs);
|
||||
}
|
||||
|
||||
@@ -125,6 +127,7 @@ function requeue(db: DatabaseSync, r: Pick<Row, "id" | "run_id" | "attempt" | "m
|
||||
released_by = COALESCE(?, released_by), released_at = CASE WHEN ? IS NULL THEN released_at ELSE ? END
|
||||
WHERE id = ? AND state = 'leased' AND attempt = ? AND leased_at IS ?`).run(fail ? "failed" : "queued", fail ? 0 : 1, fail ? null : nowMs, fail ? nowMs : null, reason, skip, skip, nowMs, r.id, r.attempt, r.leased_at);
|
||||
if (Number(up.changes) !== 1) return false;
|
||||
dropQueueCache(db);
|
||||
bury(db, r.id, r.lease_secret_hash, nowMs);
|
||||
if (r.run_id !== null) finishRun(db, r.run_id, { state: "failed", error: reason, summary: opts.summary ?? "lease ended" });
|
||||
return true;
|
||||
@@ -135,6 +138,7 @@ function unlease(db: DatabaseSync, r: { id: number; runId: number | null; hash:
|
||||
const up = db.prepare(`UPDATE main.remote_calls SET state = 'queued', lease_secret_hash = NULL, token_id = NULL, claim_id = NULL, started_at = NULL, queued_since = ?, error = ?, progress = NULL, released_by = COALESCE(?, released_by), released_at = CASE WHEN ? IS NULL THEN released_at ELSE ? END
|
||||
WHERE id = ? AND state = 'leased' AND lease_secret_hash IS ?`).run(nowMs, why, releasedBy, releasedBy, nowMs, r.id, r.hash);
|
||||
if (Number(up.changes) !== 1) return;
|
||||
dropQueueCache(db);
|
||||
bury(db, r.id, r.hash, nowMs);
|
||||
if (r.runId !== null) finishRun(db, r.runId, { state: "failed", error: why, summary: "returned to the queue" });
|
||||
}
|
||||
@@ -144,8 +148,8 @@ function unlease(db: DatabaseSync, r: { id: number; runId: number | null; hash:
|
||||
* lease still preparing PREPARE_MAX_S after the claim, or one running past its time limit plus LEASE_MARGIN_MS goes back to
|
||||
* the queue (attempt + 1, up to the prompt's attempts); a call whose caller stopped polling fails. Leases end only while the
|
||||
* dashboard serves, and for lack of heartbeats only when it served for the whole idle window (liveness.ts): helpers reach
|
||||
* the server only through it. The lost lease counts toward its login's cool-off. Run by each claim (every call, and old
|
||||
* rows are pruned) and by the caller's poll (`id`: that call only).
|
||||
* the server only through it. The lost lease counts toward its login's cool-off. Run by each claim (every call) and by the
|
||||
* caller's poll (`id`: that call only); old rows go with pruneRemote.
|
||||
*/
|
||||
export function expireLeases(db: DatabaseSync, nowMs: number = Date.now(), id?: number): void {
|
||||
const one = id === undefined ? "" : " AND id = ?";
|
||||
@@ -164,10 +168,22 @@ export function expireLeases(db: DatabaseSync, nowMs: number = Date.now(), id?:
|
||||
}
|
||||
const gone = db.prepare(`SELECT id FROM main.remote_calls WHERE state IN ('queued', 'leased') AND seen_at < ?${one}`).all(nowMs - CALLER_GONE_MS, ...(id === undefined ? [] : [id])) as { id: number }[];
|
||||
for (const r of gone) withdrawCall(db, Number(r.id), "the caller stopped waiting", undefined, nowMs);
|
||||
if (id === undefined) {
|
||||
db.prepare("DELETE FROM main.remote_calls WHERE state IN ('done', 'failed') AND COALESCE(ended_at, since) < ?").run(nowMs - KEEP_MS);
|
||||
db.prepare("DELETE FROM main.remote_checks WHERE state = 'done' AND COALESCE(ended_at, requested_at) < ?").run(nowMs - KEEP_MS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes ended calls, finished check relays and lease tombstones older than KEEP_MS, lease drops and cool-offs that no
|
||||
* longer count (cooloff.ts), and the last status of deleted tokens. The dashboard runs it once a minute.
|
||||
*/
|
||||
export function pruneRemote(db: DatabaseSync, nowMs: number = Date.now()): void {
|
||||
const old = nowMs - KEEP_MS;
|
||||
// Each condition is a range of the (state, ended_at) indexes; a row without ended_at goes by when it began.
|
||||
db.prepare("DELETE FROM main.remote_calls WHERE state IN ('done', 'failed') AND ended_at < ?").run(old);
|
||||
db.prepare("DELETE FROM main.remote_calls WHERE state IN ('done', 'failed') AND ended_at IS NULL AND since < ?").run(old);
|
||||
db.prepare("DELETE FROM main.remote_checks WHERE state = 'done' AND ended_at < ?").run(old);
|
||||
db.prepare("DELETE FROM main.remote_checks WHERE state = 'done' AND ended_at IS NULL AND requested_at < ?").run(old);
|
||||
db.prepare("DELETE FROM main.remote_lease_tombstones WHERE at < ?").run(old);
|
||||
pruneCooloffs(db, nowMs);
|
||||
db.prepare("DELETE FROM main.remote_helpers WHERE NOT EXISTS (SELECT 1 FROM main.mcp_tokens t WHERE t.id = remote_helpers.token_id)").run();
|
||||
}
|
||||
|
||||
/** The call a lease secret belongs to while its lease is live (expired leases are ended first), or null. For the per-lease routes: bundle, heartbeat, submit, the task MCP servers and the tarball. */
|
||||
@@ -209,53 +225,77 @@ export type Caller = { tokenId: number; login: string; role: Role };
|
||||
|
||||
const sameLogin = (a: string | null, b: string): boolean => a !== null && a.toLowerCase() === b.toLowerCase();
|
||||
|
||||
/** Whether `login` authored any of the items, or authored or co-authored (a Co-authored-by trailer, as GitHub lists the commit's authors) a commit of one. */
|
||||
export function authorOf(db: DatabaseSync, refs: ItemRef[], login: string): boolean {
|
||||
const item = db.prepare("SELECT 1 FROM main.items WHERE repo = ? AND number = ? AND author = ? COLLATE NOCASE");
|
||||
const commit = db.prepare(`SELECT 1 FROM main.pr_commits WHERE repo = ? AND number = ?
|
||||
AND (author = ? COLLATE NOCASE OR EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(co_authors) THEN co_authors ELSE '[]' END) WHERE value = ? COLLATE NOCASE)) LIMIT 1`);
|
||||
return refs.some((r) => item.get(r.repo, r.number, login) !== undefined || commit.get(r.repo, r.number, login, login) !== undefined);
|
||||
/** The lowercase logins that authored any of the items, or authored or co-authored (a Co-authored-by trailer, as GitHub lists the commit's authors) a commit of one. */
|
||||
export function authorsOf(db: DatabaseSync, refs: readonly ItemRef[]): string[] {
|
||||
if (!refs.length) return [];
|
||||
const item = db.prepare("SELECT author FROM main.items WHERE repo = ? AND number = ? AND author IS NOT NULL");
|
||||
const commits = db.prepare("SELECT author, co_authors FROM main.pr_commits WHERE repo = ? AND number = ?");
|
||||
const out = new Set<string>();
|
||||
for (const r of refs) {
|
||||
const a = item.get(r.repo, r.number) as { author: string } | undefined;
|
||||
if (a) out.add(a.author.toLowerCase());
|
||||
for (const c of commits.all(r.repo, r.number) as { author: string | null; co_authors: string | null }[]) {
|
||||
if (c.author) out.add(c.author.toLowerCase());
|
||||
let co: unknown = [];
|
||||
try { co = c.co_authors ? JSON.parse(c.co_authors) : []; } catch { /* not JSON: no co-authors */ }
|
||||
if (Array.isArray(co)) for (const x of co) if (typeof x === "string") out.add(x.toLowerCase());
|
||||
}
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
type CallScope = Pick<Row, "prompt_id" | "items" | "repo" | "tier">;
|
||||
const reposOf = (r: CallScope, refs: ItemRef[]): string[] => [...new Set([...refs.map((x) => x.repo), ...(r.repo ? [r.repo] : [])])];
|
||||
/** A queued call as claims read it: the items parsed, the repos it names and its authors. */
|
||||
type Cand = Waiter & Pick<Row, "prompt_id" | "tier" | "parent_id" | "sticky_login" | "seen_at"> & {
|
||||
refs: ItemRef[]; repos: string[]; authors: ReadonlySet<string>; releasedBy: string | null; releasedAt: number | null;
|
||||
};
|
||||
|
||||
/** The role rules: maintainers and operators; discord.* calls and calls that name no repo go to operators only. */
|
||||
const roleFits = (role: string, r: CallScope, repos: string[]): boolean =>
|
||||
(role === "operator" || role === "maintainer") && !((r.prompt_id.startsWith("discord.") || !repos.length) && role !== "operator");
|
||||
const roleFits = (role: string, c: Pick<Cand, "prompt_id" | "repos">): boolean =>
|
||||
(role === "operator" || role === "maintainer") && !((c.prompt_id.startsWith("discord.") || !c.repos.length) && role !== "operator");
|
||||
|
||||
type IdleHelper = { login: string; role: string; tiers: ReadonlySet<string>; only: ReadonlySet<string> | null };
|
||||
|
||||
/**
|
||||
* Whether a login other than `login` could take the call now: its helper's last claim found nothing within IDLE_FRESH_MS, that
|
||||
* claim covered the call's tier and repos, the login fits the role rules, its cached write permission covers every repo and
|
||||
* it authored no item of the call. A state check made at each claim; nothing waits on it.
|
||||
* Whether a login other than the caller could take a call now: its helper's last claim found nothing within IDLE_FRESH_MS,
|
||||
* that claim covered the call's tier and repos, the login fits the role rules, its cached write permission covers every repo
|
||||
* and it authored no item of the call. A state check made at each claim; nothing waits on it. The idle helpers and their
|
||||
* permissions are read once per claim, on the first call that needs them.
|
||||
*/
|
||||
function otherHelperIdle(db: DatabaseSync, login: string, r: CallScope, refs: ItemRef[], repos: string[], nowMs: number): boolean {
|
||||
const idle = db.prepare(`SELECT t.login, a.role, t.idle_tiers, t.idle_repos FROM main.mcp_tokens t JOIN main.access a ON a.login = t.login
|
||||
WHERE t.can_run = 1 AND t.expires_at > ? AND t.idle_claim_at >= ? AND t.login <> ? COLLATE NOCASE`).all(new Date(nowMs).toISOString(), nowMs - IDLE_FRESH_MS, login) as
|
||||
{ login: string; role: string; idle_tiers: string | null; idle_repos: string | null }[];
|
||||
const perm = db.prepare("SELECT permission, checked_at FROM main.repo_permissions WHERE login = ? AND repo = ?");
|
||||
const canWrite = (who: string, repo: string): boolean => {
|
||||
const p = perm.get(who, repo) as { permission: string; checked_at: string } | undefined;
|
||||
return p !== undefined && WRITE_PERMISSIONS.has(p.permission) && nowMs - Date.parse(p.checked_at) < PERM_READ_TTL;
|
||||
function idleOthers(db: DatabaseSync, login: string, nowMs: number): (c: Cand) => boolean {
|
||||
let idle: IdleHelper[] | null = null;
|
||||
// The cached write permissions of the idle logins, read in one query with the idle helpers.
|
||||
const writable = new Set<string>();
|
||||
const canWrite = (who: string, repo: string): boolean => writable.has(`${who.toLowerCase()}\n${repo}`);
|
||||
// The idle helpers that could take a call of this tier, prompt kind and repos, apart from authorship: calls share them.
|
||||
const takers = new Map<string, string[]>();
|
||||
return (c) => {
|
||||
if (!idle) {
|
||||
idle = (db.prepare(`SELECT t.login, a.role, t.idle_tiers, t.idle_repos FROM main.mcp_tokens t JOIN main.access a ON a.login = t.login
|
||||
WHERE t.can_run = 1 AND t.expires_at > ? AND t.idle_claim_at >= ? AND t.login <> ? COLLATE NOCASE`).all(new Date(nowMs).toISOString(), nowMs - IDLE_FRESH_MS, login) as
|
||||
{ login: string; role: string; idle_tiers: string | null; idle_repos: string | null }[])
|
||||
.map((o) => ({ login: o.login, role: o.role, tiers: new Set(o.idle_tiers ? JSON.parse(o.idle_tiers) as string[] : []), only: o.idle_repos ? new Set(JSON.parse(o.idle_repos) as string[]) : null }));
|
||||
for (const p of db.prepare("SELECT login, repo, permission, checked_at FROM main.repo_permissions WHERE login IN (SELECT value FROM json_each(?))").all(JSON.stringify(idle.map((o) => o.login))) as { login: string; repo: string; permission: string; checked_at: string }[])
|
||||
if (WRITE_PERMISSIONS.has(p.permission) && nowMs - Date.parse(p.checked_at) < PERM_READ_TTL) writable.add(`${p.login.toLowerCase()}\n${p.repo}`);
|
||||
}
|
||||
const key = `${c.tier}\n${c.prompt_id.startsWith("discord.")}\n${c.repos.join("\n")}`;
|
||||
let logins = takers.get(key);
|
||||
if (!logins) {
|
||||
logins = idle.filter((o) => o.tiers.has(c.tier) && (!o.only || c.repos.every((x) => o.only!.has(x))) && roleFits(o.role, c) && c.repos.every((x) => canWrite(o.login, x))).map((o) => o.login.toLowerCase());
|
||||
takers.set(key, logins);
|
||||
}
|
||||
return logins.some((l) => !c.authors.has(l));
|
||||
};
|
||||
return idle.some((o) => {
|
||||
const tiers = o.idle_tiers ? JSON.parse(o.idle_tiers) as string[] : [];
|
||||
const only = o.idle_repos ? new Set(JSON.parse(o.idle_repos) as string[]) : null;
|
||||
return tiers.includes(r.tier) && (!only || repos.every((x) => only.has(x))) && roleFits(o.role, r, repos)
|
||||
&& repos.every((x) => canWrite(o.login, x)) && !authorOf(db, refs, o.login);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Who may take a call: a maintainer or operator with write permission on every repo of the call (which covers reading a
|
||||
* private one); discord.* calls and calls that name no repo go to operators only. An author or co-author of an item a judging
|
||||
* prompt judges is passed over only while another helper that could take the call is asking for work (otherHelperIdle).
|
||||
* prompt judges is passed over only while another helper that could take the call is asking for work (idleOthers).
|
||||
*/
|
||||
async function eligible(db: DatabaseSync, caller: Caller, r: CallScope, canWrite: (repo: string) => Promise<boolean>, nowMs: number): Promise<boolean> {
|
||||
const refs = JSON.parse(r.items) as ItemRef[];
|
||||
const repos = reposOf(r, refs);
|
||||
if (!roleFits(caller.role, r, repos)) return false;
|
||||
for (const repo of repos) if (!(await canWrite(repo))) return false;
|
||||
return !(judges(r.prompt_id) && authorOf(db, refs, caller.login) && otherHelperIdle(db, caller.login, r, refs, repos, nowMs));
|
||||
async function eligible(caller: Caller, c: Cand, canWrite: (repo: string) => Promise<boolean>, othersIdle: (c: Cand) => boolean): Promise<boolean> {
|
||||
if (!roleFits(caller.role, c)) return false;
|
||||
for (const repo of c.repos) if (!(await canWrite(repo))) return false;
|
||||
return !(judges(c.prompt_id) && c.authors.has(caller.login.toLowerCase()) && othersIdle(c));
|
||||
}
|
||||
|
||||
const HARNESSES: HarnessId[] = ["claude", "codex"];
|
||||
@@ -325,16 +365,60 @@ function leaseCall(db: DatabaseSync, id: number, caller: Caller, claim: Claim, m
|
||||
}
|
||||
}
|
||||
|
||||
type Cand = Waiter & Pick<Row, "prompt_id" | "tier" | "items" | "parent_id" | "sticky_login">;
|
||||
/** How long claims reuse the queued calls in queue order (queueOrder) before reading them again. */
|
||||
export const QUEUE_CACHE_MS = 2_000;
|
||||
type QueueCache = { at: number; sig: string; followUps: Cand[]; ordered: Cand[] };
|
||||
const queueCaches = new WeakMap<DatabaseSync, QueueCache>();
|
||||
/** The parsed items, repos and authors of each queued call by id: they never change, so a rebuild reads them only for new calls. */
|
||||
type Parsed = Pick<Cand, "refs" | "repos" | "authors">;
|
||||
const parsedCalls = new WeakMap<DatabaseSync, Map<number, Parsed>>();
|
||||
/** Drops the cached queue order: a call was queued or leased by this process. Other processes' changes show in the signature (count and newest id of the queued calls) or within QUEUE_CACHE_MS. */
|
||||
const dropQueueCache = (db: DatabaseSync): void => void queueCaches.delete(db);
|
||||
|
||||
/** Every queued call, read once per QUEUE_CACHE_MS: follow-ups by age, the rest in queue order. Callers filter it and must not change it. */
|
||||
function queuedCalls(db: DatabaseSync, nowMs: number): QueueCache {
|
||||
const q = db.prepare("SELECT COUNT(*) AS n, MAX(id) AS m FROM main.remote_calls WHERE state = 'queued'").get() as { n: number; m: number | null };
|
||||
const sig = `${q.n}:${q.m}`;
|
||||
const hit = queueCaches.get(db);
|
||||
if (hit && hit.sig === sig && nowMs >= hit.at && nowMs - hit.at < QUEUE_CACHE_MS) return hit;
|
||||
const known = parsedCalls.get(db) ?? new Map<number, Parsed>(), seen = new Map<number, Parsed>();
|
||||
const extra = db.prepare("SELECT items, authors FROM main.remote_calls WHERE id = ?");
|
||||
const rows = (db.prepare(`SELECT id, class AS cls, level, step, repo, since, seen_at, prompt_id, tier, parent_id, sticky_login, released_by, released_at FROM main.remote_calls INDEXED BY remote_calls_queued WHERE state = 'queued'`).all() as
|
||||
(Waiter & Pick<Row, "prompt_id" | "tier" | "parent_id" | "sticky_login" | "seen_at"> & { released_by: string | null; released_at: number | null })[])
|
||||
.map((r): Cand => {
|
||||
const id = Number(r.id);
|
||||
let p = known.get(id);
|
||||
if (!p) {
|
||||
const x = extra.get(id) as { items: string; authors: string | null };
|
||||
const refs = JSON.parse(x.items) as ItemRef[];
|
||||
// Calls queued before authors were stored on the row are read now.
|
||||
const authors = x.authors !== null ? JSON.parse(x.authors) as string[] : judges(r.prompt_id) ? authorsOf(db, refs) : [];
|
||||
p = { refs, repos: [...new Set([...refs.map((i) => i.repo), ...(r.repo ? [r.repo] : [])])], authors: new Set(authors) };
|
||||
}
|
||||
seen.set(id, p);
|
||||
return {
|
||||
id, cls: r.cls, level: r.level, step: r.step, repo: r.repo, since: r.since, seen_at: r.seen_at, prompt_id: r.prompt_id, tier: r.tier, parent_id: r.parent_id, sticky_login: r.sticky_login,
|
||||
...p, releasedBy: r.released_by?.toLowerCase() ?? null, releasedAt: r.released_at,
|
||||
};
|
||||
});
|
||||
parsedCalls.set(db, seen);
|
||||
const c: QueueCache = {
|
||||
at: nowMs, sig,
|
||||
followUps: rows.filter((r) => r.parent_id !== null).sort((a, b) => a.since - b.since || a.id - b.id),
|
||||
ordered: queueOrder(db, nowMs, rows.filter((r) => r.parent_id === null)),
|
||||
};
|
||||
queueCaches.set(db, c);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** The queued calls a claim could take in the order it takes them, before eligibility: follow-up turns of the sessions its helper holds first, then the model queue's order, filtered by tiers and repos (claimRepos: every repo a call names must be in the set). */
|
||||
function claimOrder(db: DatabaseSync, caller: Caller, tiers: ReadonlySet<Tier>, repos: ReadonlySet<string> | null, sessionIds: readonly number[], nowMs: number): Cand[] {
|
||||
const rows = (db.prepare(`SELECT id, class AS cls, level, step, repo, since, prompt_id, tier, items, parent_id, sticky_login FROM main.remote_calls
|
||||
WHERE state = 'queued' AND seen_at >= ? AND NOT COALESCE(released_by = ? COLLATE NOCASE AND released_at >= ?, 0)`).all(nowMs - CALLER_STALE_MS, caller.login, nowMs - RELEASE_SKIP_MS) as Cand[])
|
||||
.filter((r) => tiers.has(r.tier) && (!repos || (JSON.parse(r.items) as ItemRef[]).every((x) => repos.has(x.repo)) && (!r.repo || repos.has(r.repo))));
|
||||
const q = queuedCalls(db, nowMs);
|
||||
const login = caller.login.toLowerCase();
|
||||
const fits = (r: Cand): boolean => r.seen_at >= nowMs - CALLER_STALE_MS && !(r.releasedBy === login && r.releasedAt !== null && r.releasedAt >= nowMs - RELEASE_SKIP_MS)
|
||||
&& tiers.has(r.tier) && (!repos || r.repos.every((x) => repos.has(x)));
|
||||
const sessions = new Set(sessionIds);
|
||||
const followUps = rows.filter((r) => r.parent_id !== null && sessions.has(r.parent_id) && sameLogin(r.sticky_login, caller.login)).sort((a, b) => a.since - b.since || a.id - b.id);
|
||||
return [...followUps, ...queueOrder(db, nowMs, rows.filter((r) => r.parent_id === null))];
|
||||
return [...q.followUps.filter((r) => sessions.has(r.parent_id!) && sameLogin(r.sticky_login, caller.login) && fits(r)), ...q.ordered.filter(fits)];
|
||||
}
|
||||
|
||||
/** Memoises the caller's write permission per repo; a failed lookup counts as no permission. */
|
||||
@@ -354,9 +438,9 @@ export async function claimableCalls(db: DatabaseSync, caller: Caller, opts: { t
|
||||
const accepted = acceptedModels(db);
|
||||
// A tier counts when the model the helper would use for it is of an accepted family; without a model, when the tier accepts any.
|
||||
const tiers = new Set((opts.tiers ?? TIERS).filter((t) => accepted[t].length > 0 && (opts.models?.[t] === undefined || familyOf(opts.models[t]!, accepted[t]) !== null)));
|
||||
const can = memoWrite(canWrite);
|
||||
const can = memoWrite(canWrite), others = idleOthers(db, caller.login, nowMs);
|
||||
let n = 0;
|
||||
for (const r of claimOrder(db, caller, tiers, claimRepos(db, caller.login, undefined), [], nowMs)) if (await eligible(db, caller, r, can, nowMs)) n++;
|
||||
for (const r of claimOrder(db, caller, tiers, claimRepos(db, caller.login, undefined), [], nowMs)) if (await eligible(caller, r, can, others)) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -381,7 +465,8 @@ const claimReplies = new Map<string, { at: number; reply: Promise<ClaimReply> }>
|
||||
* gets the first one's reply.
|
||||
*/
|
||||
export function claimCall(db: DatabaseSync, caller: Caller, claim: Claim, canWrite: (repo: string) => Promise<boolean>, nowMs: number = Date.now()): Promise<ClaimReply> {
|
||||
for (const [k, v] of claimReplies) if (v.at < nowMs - CLAIM_ID_TTL_S * 1000) claimReplies.delete(k);
|
||||
// Entries are in claim order, so the expired ones come first.
|
||||
for (const [k, v] of claimReplies) { if (v.at >= nowMs - 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;
|
||||
@@ -403,16 +488,17 @@ async function claimNew(db: DatabaseSync, caller: Caller, claim: Claim, canWrite
|
||||
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);
|
||||
const can = memoWrite(canWrite), others = idleOthers(db, caller.login, nowMs);
|
||||
const repos = claimRepos(db, caller.login, claim.repos);
|
||||
for (const r of claimOrder(db, caller, tiers, repos, claim.sessions ?? [], nowMs)) {
|
||||
if (!(await eligible(db, caller, r, can, nowMs))) continue;
|
||||
if (!(await eligible(caller, r, can, others))) continue;
|
||||
const lease = leaseCall(db, Number(r.id), caller, claim, claim.tiers[r.tier]!, Date.now());
|
||||
if (!lease) continue;
|
||||
dropQueueCache(db);
|
||||
db.prepare("UPDATE main.mcp_tokens SET idle_claim_at = NULL WHERE id = ?").run(caller.tokenId);
|
||||
return { lease, 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 (otherHelperIdle).
|
||||
// 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) };
|
||||
}
|
||||
@@ -562,10 +648,14 @@ export async function awaitCall(db: DatabaseSync, id: number, opts: { onProgress
|
||||
|
||||
async function pollCall(db: DatabaseSync, id: number, opts: { onProgress?: (line: string) => void; maxWaitMs?: number; log?: (line: string) => void; check?: Pick<CheckTool, "run"> }): Promise<Outcome> {
|
||||
const log = opts.log ?? console.log;
|
||||
let lastProgress: string | null = null, lastLog = 0;
|
||||
let lastProgress: string | null = null, lastLog = 0, lastSeen = 0;
|
||||
for (;;) {
|
||||
const nowMs = Date.now();
|
||||
db.prepare("UPDATE main.remote_calls SET seen_at = ? WHERE id = ?").run(nowMs, id);
|
||||
// The caller's liveness stamp; claims and the room count a call while it is fresher than CALLER_STALE_MS.
|
||||
if (nowMs - lastSeen >= SEEN_EVERY_MS) {
|
||||
db.prepare("UPDATE main.remote_calls SET seen_at = ? WHERE id = ?").run(nowMs, id);
|
||||
lastSeen = nowMs;
|
||||
}
|
||||
expireLeases(db, nowMs, id);
|
||||
const r = rowOf(db, id);
|
||||
if (!r) return { state: "failed", error: "the call is gone", tokens: null, runId: null };
|
||||
|
||||
@@ -30,9 +30,8 @@ function coolOff(db: DatabaseSync, login: string, until: number, reason: string)
|
||||
/** Records a lost lease of `tokenId`, held by `login`; the DROP_LIMIT-th drop of the login within the window starts the cool-off. */
|
||||
export function noteDrop(db: DatabaseSync, tokenId: number, login: string, nowMs: number): void {
|
||||
if (db.prepare("SELECT 1 FROM main.remote_lease_drops WHERE token_id = ? AND at > ?").get(tokenId, nowMs - DROP_DEDUPE_MS)) return;
|
||||
db.prepare("DELETE FROM main.remote_lease_drops WHERE at < ?").run(nowMs - DROP_WINDOW_MS);
|
||||
db.prepare("INSERT INTO main.remote_lease_drops (token_id, login, at) VALUES (?, ?, ?)").run(tokenId, login, nowMs);
|
||||
const n = Number((db.prepare("SELECT COUNT(*) AS n FROM main.remote_lease_drops WHERE login = ?").get(login) as { n: number }).n);
|
||||
const n = Number((db.prepare("SELECT COUNT(*) AS n FROM main.remote_lease_drops WHERE login = ? AND at >= ?").get(login, nowMs - DROP_WINDOW_MS) as { n: number }).n);
|
||||
if (n >= DROP_LIMIT) coolOff(db, login, nowMs + COOLOFF_MS, DROP_REASON);
|
||||
}
|
||||
|
||||
@@ -57,6 +56,12 @@ export function cooloffOf(db: DatabaseSync, login: string, nowMs: number): { unt
|
||||
return r?.until != null && Number(r.until) > nowMs ? { until: Number(r.until), reason: r.reason ?? DROP_REASON } : null;
|
||||
}
|
||||
|
||||
/** Deletes drops older than the window and cool-off rows that neither hold a login nor count failures (calls.ts pruneRemote). */
|
||||
export function pruneCooloffs(db: DatabaseSync, nowMs: number): void {
|
||||
db.prepare("DELETE FROM main.remote_lease_drops WHERE at < ?").run(nowMs - DROP_WINDOW_MS);
|
||||
db.prepare("DELETE FROM main.remote_cooloffs WHERE COALESCE(until, 0) <= ? AND (failures = 0 OR failures_since < ?)").run(nowMs, nowMs - FAILURE_WINDOW_MS);
|
||||
}
|
||||
|
||||
/** Ends the login's cool-off and forgets its drops and failures; false when it was not cooling off. */
|
||||
export function clearCooloff(db: DatabaseSync, login: string, by: string, nowMs: number = Date.now()): boolean {
|
||||
const was = cooloffOf(db, login, nowMs) !== null;
|
||||
|
||||
@@ -67,13 +67,12 @@ export function parseStatus(raw: unknown): HelperStatus {
|
||||
};
|
||||
}
|
||||
|
||||
/** Keeps a helper's status as the last one of its token; rows of deleted tokens go. */
|
||||
/** Keeps a helper's status as the last one of its token. Rows of deleted tokens go with the dashboard's minute maintenance (pruneRemote). */
|
||||
export function storeStatus(db: DatabaseSync, tokenId: number, login: string, s: HelperStatus, nowMs: number = Date.now()): void {
|
||||
db.prepare(`INSERT INTO main.remote_helpers (token_id, login, readiness, until, reason, harness, models, reserve, usage, reported_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (token_id) DO UPDATE SET login = excluded.login, readiness = excluded.readiness, until = excluded.until, reason = excluded.reason, harness = excluded.harness,
|
||||
models = excluded.models, reserve = excluded.reserve, usage = excluded.usage, reported_at = excluded.reported_at`)
|
||||
.run(tokenId, login, s.readiness, s.until ?? null, s.reason ?? null, s.harness, JSON.stringify(s.models), JSON.stringify(s.reserve), s.usage ? JSON.stringify(s.usage) : null, nowMs);
|
||||
db.prepare("DELETE FROM main.remote_helpers WHERE token_id NOT IN (SELECT id FROM main.mcp_tokens)").run();
|
||||
}
|
||||
|
||||
/** The login's helpers: every live token that may run tasks, with its last status. */
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// restarting no heartbeat can arrive, and a lease must not be counted as lost for that. The dashboard stamps the
|
||||
// `remote_liveness` row every ALIVE_EVERY_MS; job processes, which expire leases (calls.ts expireLeases), read it.
|
||||
import type { DatabaseSync } from "node:sqlite";
|
||||
import { isBusy } from "../db.ts";
|
||||
|
||||
export const ALIVE_EVERY_MS = 5_000;
|
||||
/** A stamp older than this means the dashboard is not serving: down, stalled or restarting. */
|
||||
@@ -46,7 +47,7 @@ export function dashboardAlive(db: DatabaseSync, nowMs: number): { alive: boolea
|
||||
/** Starts the stamp timer in the dashboard process; returns the function that stops it. */
|
||||
export function startLiveness(db: DatabaseSync): () => void {
|
||||
const tick = (): void => {
|
||||
try { stampAlive(db); } catch (e) { console.log(`liveness stamp not written: ${(e as Error).message}`); }
|
||||
try { stampAlive(db); } catch (e) { if (!isBusy(e)) console.log(`liveness stamp not written: ${(e as Error).message}`); }
|
||||
};
|
||||
tick();
|
||||
const t = setInterval(tick, ALIVE_EVERY_MS);
|
||||
|
||||
+5
-3
@@ -7,12 +7,14 @@ import { STATUS_FRESH_MS } from "./helpers.ts";
|
||||
|
||||
/** How long an empty claim counts as an idle helper: two claim intervals and some slack. */
|
||||
export const IDLE_FRESH_MS = 45_000;
|
||||
/** A queued call whose caller has not polled for this long has lost its caller and is not counted or claimed. */
|
||||
export const CALLER_STALE_MS = 30_000;
|
||||
/** How often a waiting caller stamps its call's `seen_at` (it polls more often, but writes only this often). */
|
||||
export const SEEN_EVERY_MS = 30_000;
|
||||
/** A queued call whose caller has not stamped it for this long has lost its caller and is not counted or claimed: two stamps and some slack. */
|
||||
export const CALLER_STALE_MS = 2 * SEEN_EVERY_MS + 15_000;
|
||||
|
||||
export function remoteRoom(db: DatabaseSync, cls: number, nowMs: number = Date.now()): number {
|
||||
const idle = (db.prepare(`SELECT COUNT(*) AS n FROM main.mcp_tokens t JOIN main.remote_helpers h ON h.token_id = t.id
|
||||
WHERE t.can_run = 1 AND t.idle_claim_at >= ? AND h.readiness = 'ready' AND h.reported_at >= ?`).get(nowMs - IDLE_FRESH_MS, nowMs - STATUS_FRESH_MS) as { n: number }).n;
|
||||
const ahead = (db.prepare("SELECT COUNT(*) AS n FROM main.remote_calls WHERE state = 'queued' AND class >= ? AND seen_at >= ?").get(cls, nowMs - CALLER_STALE_MS) as { n: number }).n;
|
||||
const ahead = (db.prepare("SELECT COUNT(*) AS n FROM main.remote_calls INDEXED BY remote_calls_queued WHERE state = 'queued' AND class >= ? AND seen_at >= ?").get(cls, nowMs - CALLER_STALE_MS) as { n: number }).n;
|
||||
return Math.max(0, Number(idle) - Number(ahead));
|
||||
}
|
||||
+6
-1
@@ -263,6 +263,7 @@ CREATE TABLE IF NOT EXISTS remote_lease_tombstones (
|
||||
call_id INTEGER NOT NULL,
|
||||
at INTEGER NOT NULL -- ms since epoch
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS remote_lease_tombstones_at ON remote_lease_tombstones(at);
|
||||
-- The dashboard's liveness stamp (src/remote/liveness.ts), one row: written every 5 seconds; `since` is when the current
|
||||
-- unbroken run of stamps began. Leases expire only while the dashboard was alive for the whole idle window.
|
||||
CREATE TABLE IF NOT EXISTS remote_liveness (
|
||||
@@ -795,9 +796,12 @@ CREATE TABLE IF NOT EXISTS remote_calls (
|
||||
error TEXT,
|
||||
ended_at INTEGER,
|
||||
reference_repo TEXT, -- the repo whose reference documentation the call's reference tools search
|
||||
root TEXT -- the lease's path root: the claim's directory the sandbox paths are placed below (macOS helpers), or NULL for the fixed paths
|
||||
root TEXT, -- the lease's path root: the claim's directory the sandbox paths are placed below (macOS helpers), or NULL for the fixed paths
|
||||
authors TEXT -- JSON: lowercase logins that authored or co-authored an item of the call, read when it was queued (author preference)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS remote_calls_state ON remote_calls(state, tier);
|
||||
CREATE INDEX IF NOT EXISTS remote_calls_ended ON remote_calls(state, ended_at);
|
||||
CREATE INDEX IF NOT EXISTS remote_calls_seen ON remote_calls(state, seen_at);
|
||||
CREATE INDEX IF NOT EXISTS remote_calls_job ON remote_calls(job_id) WHERE job_id IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS remote_calls_secret ON remote_calls(lease_secret_hash) WHERE lease_secret_hash IS NOT NULL;
|
||||
|
||||
@@ -814,6 +818,7 @@ CREATE TABLE IF NOT EXISTS remote_checks (
|
||||
ended_at INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS remote_checks_call ON remote_checks(call_id, state);
|
||||
CREATE INDEX IF NOT EXISTS remote_checks_ended ON remote_checks(state, ended_at);
|
||||
|
||||
-- Reference passages served to remote calls (src/remote/tools.ts): each lease gets a limited number, and every one is recorded.
|
||||
CREATE TABLE IF NOT EXISTS remote_passages (
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// The helper routes use their own connection with a short busy timeout: while another process holds SQLite's write lock,
|
||||
// a helper request answers 503 with Retry-After instead of holding the dashboard's event loop.
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { after, test } from "node:test";
|
||||
import { addLogin } from "../src/access.ts";
|
||||
import { apiRoutes } from "../src/dash/api/index.ts";
|
||||
import { createToken } from "../src/dash/mcp/tokens.ts";
|
||||
import { loadConfig } from "../src/dash/server/config.ts";
|
||||
import { startServer } from "../src/dash/server/index.ts";
|
||||
import { FakeProvider } from "../src/dash/server/provider.ts";
|
||||
import { RateLimiter } from "../src/dash/server/util.ts";
|
||||
import { connect } from "../src/db.ts";
|
||||
import { setInferenceMode } from "../src/remote/mode.ts";
|
||||
import { ROUTES } from "../src/remote/protocol.ts";
|
||||
import { SCRATCH } from "./scratch.ts";
|
||||
|
||||
mkdirSync(SCRATCH, { recursive: true });
|
||||
const dir = mkdtempSync(join(SCRATCH, "remote-busy-"));
|
||||
after(() => rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
test("a helper route answers 503 with Retry-After while the database is locked, and 200 once it is free", 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");
|
||||
addLogin(db, "cli", "bob", "maintainer", null);
|
||||
const { token } = createToken(db, "bob", "helper", false, true);
|
||||
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 }) });
|
||||
try {
|
||||
const status = () => fetch(`${s.url}${ROUTES.status}`, {
|
||||
method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({ readiness: "ready", harness: "claude", models: { top: "opus" }, reserve: { fiveHour: 20, weekly: 20 }, slots: 1, busy: 0 }),
|
||||
});
|
||||
assert.equal((await status()).status, 200);
|
||||
other.exec("BEGIN IMMEDIATE");
|
||||
const started = Date.now();
|
||||
const r = await status();
|
||||
assert.equal(r.status, 503);
|
||||
assert.equal(r.headers.get("retry-after"), "5");
|
||||
assert.ok(Date.now() - started < 5_000, "answered after the short busy timeout");
|
||||
other.exec("COMMIT");
|
||||
assert.equal((await status()).status, 200);
|
||||
} finally {
|
||||
await s.close();
|
||||
for (const c of [other, remoteDb, db]) c.close();
|
||||
}
|
||||
});
|
||||
+1
-1
@@ -12,5 +12,5 @@
|
||||
"types": ["node"],
|
||||
"allowJs": true
|
||||
},
|
||||
"include": ["src", "test", "worker", "scripts/golive-gate.ts"]
|
||||
"include": ["src", "test", "worker", "scripts/golive-gate.ts", "scripts/remote-claim-bench.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user