diff --git a/src/dash/api/admin.ts b/src/dash/api/admin.ts index 286cb1536..ca7e611b2 100644 --- a/src/dash/api/admin.ts +++ b/src/dash/api/admin.ts @@ -21,7 +21,7 @@ const AUDIT_PAGE = 50; export const AUDIT_ACTIONS = [ "answer", "undo", "adopt", "opinion", "opinion-retract", "comment", "override", "rule", "access-add", "access-remove", "access-role", "session-revoke", "sign-in", "sign-in-refused", "repo-track", "repo-untrack", "labels-approve", "labels-revoke", "labels-apply", - "job-request", "job-cancel", "schedule-change", + "job-request", "job-cancel", "pipeline-switch", "stage-limit", ]; const isOperator = (req: Req): boolean => req.user.role === "operator"; diff --git a/src/dash/api/index.ts b/src/dash/api/index.ts index 33e5e5f9f..35921003a 100644 --- a/src/dash/api/index.ts +++ b/src/dash/api/index.ts @@ -245,7 +245,9 @@ export function apiRoutes(opts: ApiOptions = {}): Route[] { get("/api/pipeline/jobs/:id", pipeline.job), { method: "POST", pattern: "/api/pipeline/jobs", operator: true, handler: ok(pipeline.request) }, { method: "POST", pattern: "/api/pipeline/jobs/:id/cancel", operator: true, handler: ok(pipeline.cancel) }, - { method: "POST", pattern: "/api/pipeline/schedules/:step", operator: true, handler: ok(pipeline.schedule) }, + get("/api/pipeline/state", (db) => pipeline.state(db)), + { method: "PUT", pattern: "/api/pipeline/state", operator: true, handler: ok(pipeline.putState) }, + { method: "PUT", pattern: "/api/pipeline/limits/:step", operator: true, handler: ok(pipeline.putLimit) }, get("/api/prompts", prompts), get("/api/queue", queue), get("/api/similar/:repo/:n", (db, req) => sim.similar(db, req, vectors)), diff --git a/src/dash/api/pipeline.ts b/src/dash/api/pipeline.ts index f08a77295..36ea1338a 100644 --- a/src/dash/api/pipeline.ts +++ b/src/dash/api/pipeline.ts @@ -1,10 +1,12 @@ -// The Pipeline page over JSON. Everyone signed in reads steps, jobs, logs and -// schedules; only operators request or cancel jobs and change schedules. The +// The Pipeline page over JSON. Everyone signed in reads steps, jobs, logs, the +// pipeline switch and the stage limits; only operators request or cancel jobs, +// flip the switch and change limits. The // dashboard never runs a step: it writes job rows that the runner picks up. import type { DatabaseSync } from "node:sqlite"; import type { Job, JobState, PipelineOverview, PipelineStage, PipelineStep, StepParam, SyncRun } from "../../../web/src/api/types.ts"; import { trackedNames } from "../../repos.ts"; -import { enqueue, getJob, jobDetail, JobError, JOB_STATES, listJobs, requestCancel, saveSchedule, scheduleOf, schedules, toJob } from "../../runner/jobs.ts"; +import { enqueue, getJob, jobDetail, JobError, JOB_STATES, listJobs, requestCancel, toJob } from "../../runner/jobs.ts"; +import { LimitError, pipelineState, setEnabled, setLimit } from "../../runner/autopilot.ts"; import { HEARTBEAT_KEY } from "../../runner/runner.ts"; import { loadSteps, type StepDef } from "../../runner/steps.ts"; import { audit } from "../audit.ts"; @@ -26,7 +28,7 @@ const STAGES: { n: number; name: string; automatic?: boolean }[] = [ const RUNNER_ALIVE_MS = 30_000; function requireOperator(req: Req, step?: StepDef): void { - if (req.user.role !== "operator" || (step && step.requires !== "operator")) throw new HttpError(403, "only operators run, cancel or schedule pipeline steps"); + if (req.user.role !== "operator" || (step && step.requires !== "operator")) throw new HttpError(403, "only operators run or cancel pipeline steps and change the pipeline switch and limits"); } const wrap = async (f: () => T | Promise): Promise => { @@ -71,11 +73,10 @@ function stageState(db: DatabaseSync, steps: string[], syncFailed: boolean | nul export async function overview(db: DatabaseSync): Promise { const all = [...(await loadSteps()).values()]; const repos = trackedNames(db); - const sched = schedules(db); const steps: PipelineStep[] = all.map((s) => ({ name: s.name, title: s.title, description: s.description, stage: s.stage, requires: s.requires, group: s.group, params: wireParams(s, repos), unavailable: s.available?.() ?? null, - schedule: sched.get(s.name) ?? scheduleOf(db, s.name), lastJob: lastJob(db, s.name), + lastJob: lastJob(db, s.name), })); const runs = db.prepare("SELECT started_at AS startedAt, ended_at AS endedAt, mode, items, error FROM sync_runs ORDER BY started_at DESC LIMIT 10").all() as unknown as SyncRun[]; const lastSync = runs.find((r) => r.endedAt); @@ -148,12 +149,25 @@ export async function cancel(db: DatabaseSync, req: Req): Promise { return j; } -export async function schedule(db: DatabaseSync, req: Req) { +export const state = (db: DatabaseSync) => pipelineState(db); + +export async function putState(db: DatabaseSync, req: Req) { requireOperator(req); - const step = (await loadSteps()).get(req.params.step ?? ""); - if (!step) throw new HttpError(404, "no such step"); - requireOperator(req, step); - const s = await wrap(() => saveSchedule(db, step.name, req.json, req.user.login)); - audit(db, req.user.login, "schedule-change", `step:${step.name}`, { enabled: s.enabled, trigger: s.trigger, intervalMinutes: s.intervalMinutes, params: s.params }); - return s; + const b = body(req); + if (typeof b.enabled !== "boolean") throw new HttpError(400, "enabled must be true or false"); + const was = (await pipelineState(db)).enabled; + setEnabled(db, b.enabled, req.user.login); + audit(db, req.user.login, "pipeline-switch", "pipeline", { enabled: b.enabled, was }); + return pipelineState(db); +} + +export async function putLimit(db: DatabaseSync, req: Req) { + requireOperator(req); + try { + setLimit(db, req.params.step, req.json, req.user.login); + } catch (e) { + if (e instanceof LimitError) throw new HttpError(e.status, e.message); + throw e; + } + return (await pipelineState(db)).limits.find((l) => l.step === req.params.step)!; } diff --git a/src/dash/server/index.ts b/src/dash/server/index.ts index 9bd6614a8..0a2f54139 100644 --- a/src/dash/server/index.ts +++ b/src/dash/server/index.ts @@ -202,9 +202,10 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { const method = req.method; const out = (r: Res, cookies?: string[]) => send(res, nonce, { ...r, headers: { ...r.headers, [CSRF_HEADER]: session.csrf } }, cookies); - if (method !== "GET" && method !== "POST") return out(apiError(405, "method not allowed")); + if (method !== "GET" && method !== "POST" && method !== "PUT") return out(apiError(405, "method not allowed")); + const writes = method !== "GET"; let json: unknown; - if (method === "POST") { + if (writes) { if (!sameOrigin(req)) return out(apiError(403, "cross-origin request refused")); if (!writeLimitSession.allow(session.idHash) || !writeLimitIp.allow(clientIp(req))) return out(apiError(429, "too many requests; wait a minute")); json = await readJson(req); @@ -219,7 +220,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { if (route.operator && session.role !== "operator") return out(apiError(403, "operators only")); const r: Req = { method, path: url.pathname, params: params!, query: url.searchParams, form: new URLSearchParams(), json, - user: makeUser(db, box, provider, session, method === "POST"), + user: makeUser(db, box, provider, session, writes), csrf: session.csrf, nonce, }; return out(await route.handler(db, r)); diff --git a/src/dash/types.ts b/src/dash/types.ts index d69ce33fa..c0200db31 100644 --- a/src/dash/types.ts +++ b/src/dash/types.ts @@ -15,7 +15,7 @@ export type User = { }; export type Req = { - method: "GET" | "POST"; + method: "GET" | "POST" | "PUT"; path: string; params: Record; // from the route pattern, e.g. /item/:repo/:n query: URLSearchParams; @@ -35,7 +35,7 @@ export type Res = { }; export type Route = { - method: "GET" | "POST"; + method: "GET" | "POST" | "PUT"; pattern: string; // "/api/items/:repo/:n" operator?: boolean; // server returns 403 unless user.role is operator handler: (db: DatabaseSync, req: Req) => Res | Promise; diff --git a/src/db.ts b/src/db.ts index 9a1ba6455..b390ebb3a 100644 --- a/src/db.ts +++ b/src/db.ts @@ -19,6 +19,7 @@ const ADDED_COLUMNS: [table: string, column: string, type: string][] = [ ["classifications", "probs", "TEXT"], ["token_usage", "cost_usd", "REAL"], ["classifications", "input_hash", "TEXT"], + ["jobs", "items", "INTEGER"], ]; function addColumns(db: DatabaseSync): void { diff --git a/src/decide/select.ts b/src/decide/select.ts index d2297d99f..92985a3aa 100644 --- a/src/decide/select.ts +++ b/src/decide/select.ts @@ -54,7 +54,7 @@ function covered(db: DatabaseSync): Set { type Row = { repo: string; number: number; jl: string; jf: string | null; probs: string | null; hl: string | null; hf: string | null }; -/** Candidates in the given repos (default: every tracked repo), oldest first. */ +/** Candidates in the given repos (default: every tracked repo), pull requests before issues, oldest first. */ export function selectCandidates(db: DatabaseSync, run: string, repos?: string[]): Candidate[] { const tracked = new Set(trackedNames(db)); const want = (repos?.length ? repos : [...tracked]).filter((r) => tracked.has(r)); @@ -66,7 +66,7 @@ export function selectCandidates(db: DatabaseSync, run: string, repos?: string[] LEFT JOIN classifications h ON h.repo = j.repo AND h.number = j.number AND h.classifier = 'haiku' AND h.run_id = j.run_id WHERE j.run_id = ? AND j.classifier = 'jev' AND i.state = 'OPEN' AND COALESCE(i.is_draft, 0) = 0 AND j.repo IN (SELECT value FROM json_each(?)) - ORDER BY i.created_at, j.repo, j.number`).all(run, JSON.stringify(want)) as Row[]; + ORDER BY i.kind = 'pr' DESC, i.created_at, j.repo, j.number`).all(run, JSON.stringify(want)) as Row[]; const out: Candidate[] = []; for (const r of rows) { if (skip.has(`${r.repo}#${r.number}`)) continue; diff --git a/src/runner/autopilot.ts b/src/runner/autopilot.ts new file mode 100644 index 000000000..25dda4c18 --- /dev/null +++ b/src/runner/autopilot.ts @@ -0,0 +1,285 @@ +// The pipeline switch and the autopilot behind it. With the switch on, the +// runner looks for work after every sync and at least every 15 minutes, and +// queues one job per stage that has work, no job of its own queued or running, +// and an item limit left for the day. Stages run in pipeline order; a failure in one does +// not stop the others. Turned off, no new jobs are queued and running jobs +// finish. +// +// The planner only reads the database and queues jobs; the runner starts them. +// Each lane's `detect` reuses the candidate code of the stage it feeds. +import type { DatabaseSync } from "node:sqlite"; +import type { PipelineState, StageLimit } from "../../web/src/api/types.ts"; +import { latestJevRun, selectCandidates as decideCandidates } from "../decide/select.ts"; +import { embedderId, modelName } from "../embed/model.ts"; +import { pending as embedPending } from "../embed/store.ts"; +import { approvalOf } from "../labels/approval.ts"; +import { countPlan, planLabels } from "../labels/plan.ts"; +import { buildQueue, eligible } from "../merge/queue.ts"; +import { trackedNames } from "../repos.ts"; +import { selectCandidates as reviewCandidates } from "../review/candidates.ts"; +import { audit } from "../dash/audit.ts"; +import { currentRun, dueItems, haikuDue } from "./classify.ts"; +import { enqueue, JobError, now } from "./jobs.ts"; +import { loadSteps, type Params } from "./steps.ts"; + +export const PLAN_EVERY_MS = 15 * 60_000; +/** A stage that handled nothing waits this long before it is tried again. */ +export const COOLDOWN_MS = 15 * 60_000; +/** A stage whose last BACKOFF_AFTER autopilot jobs all failed waits this long. */ +export const BACKOFF_MS = 60 * 60_000; +export const BACKOFF_AFTER = 3; +/** Checks younger than this count as current for the review that follows. */ +export const CHECKS_FRESH_MS = 30 * 60_000; +export const AUTOPILOT_USER = "pipeline"; + +export const KEY_ENABLED = "pipeline_enabled"; +const KEY_BY = "pipeline_changed_by", KEY_AT = "pipeline_changed_at"; +const KEY_SYNC_SEEN = "pipeline_sync_seen", KEY_SYNC_AT = "pipeline_sync_at", KEY_PLANNED_AT = "pipeline_planned_at"; +const KEY_CURSOR = "pipeline_review_cursor"; + +const getSetting = (db: DatabaseSync, key: string): string | null => + (db.prepare("SELECT value FROM settings WHERE key = ?").get(key) as { value: string } | undefined)?.value ?? null; +const setSetting = (db: DatabaseSync, key: string, value: string): void => { + db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(key, value); +}; + +// ---- lanes --------------------------------------------------------------------- + +/** One job the autopilot may queue; `params` leaves out `limit`, which the planner sets. */ +export type Candidate = { step: string; params: Params }; +/** A pipeline stage in order. `detect` lists the jobs that have work, best first. */ +export type Lane = { name: string; detect: (db: DatabaseSync) => Candidate[]; chosen?: (db: DatabaseSync, c: Candidate) => void }; + +const repoOf = (c: Candidate): string | null => (typeof c.params.repo === "string" ? c.params.repo : null); + +function lastJobEnd(db: DatabaseSync, step: string, repo: string | null, requestedBy?: string): { endedAt: string; state: string; items: number | null } | undefined { + return db.prepare(`SELECT ended_at AS endedAt, state, items FROM jobs WHERE step = ? AND (? IS NULL OR json_extract(params, '$.repo') = ?) + AND ended_at IS NOT NULL AND (? IS NULL OR requested_by = ?) ORDER BY id DESC LIMIT 1`) + .get(step, repo, repo, requestedBy ?? null, requestedBy ?? null) as { endedAt: string; state: string; items: number | null } | undefined; +} + +/** True when the autopilot already queued `step` (for `repo`) since the planner last saw a new sync. */ +function queuedSinceSync(db: DatabaseSync, step: string, repo: string): boolean { + const since = getSetting(db, KEY_SYNC_AT) ?? ""; + return !!db.prepare("SELECT 1 FROM jobs WHERE step = ? AND requested_by = ? AND json_extract(params, '$.repo') = ? AND requested_at >= ?") + .get(step, AUTOPILOT_USER, repo, since); +} + +/** Tracked repos after `cursor` first, wrapping round. */ +export function roundRobin(repos: string[], cursor: string | null): string[] { + const sorted = [...repos].sort(); + const after = sorted.filter((r) => cursor !== null && r > cursor); + return [...after, ...sorted.filter((r) => !after.includes(r))]; +} + +export const LANES: Lane[] = [ + { + name: "classify", + detect: (db) => { + const run = currentRun(db); + if (!run) return []; + return dueItems(db, run, "new").due.length || haikuDue(db, run, 1).length ? [{ step: "classify-new", params: {} }] : []; + }, + }, + { + name: "embed", + detect: (db) => (embedPending(db, embedderId(modelName())).length ? [{ step: "embed", params: {} }] : []), + }, + { + name: "decide", + detect: (db) => { + const run = latestJevRun(db); + return run && decideCandidates(db, run).length ? [{ step: "decide", params: {} }] : []; + }, + }, + { + // One repo per job, round robin; the repo's checks come before its review. + name: "review", + detect: (db) => { + const out: Candidate[] = []; + for (const repo of roundRobin(trackedNames(db), getSetting(db, KEY_CURSOR))) { + if (!reviewCandidates(db, repo).length) continue; + const checks = lastJobEnd(db, "checks", repo); + const fresh = checks?.state === "done" && Date.now() - Date.parse(checks.endedAt) < CHECKS_FRESH_MS; + out.push({ step: fresh ? "review-batch" : "checks", params: { repo } }); + } + return out; + }, + chosen: (db, c) => { + if (c.step === "review-batch") setSetting(db, KEY_CURSOR, String(c.params.repo)); + }, + }, + { + name: "labels", + detect: (db) => { + const run = currentRun(db); + if (!run) return []; + return trackedNames(db) + .filter((repo) => approvalOf(db, repo) && !queuedSinceSync(db, "labels-apply", repo) && countPlan(planLabels(db, repo, run)).toAdd > 0) + .map((repo) => ({ step: "labels-apply", params: { repo } })); + }, + }, + { + name: "merge", + detect: (db) => { + const repos = [...new Set(buildQueue(db).filter(eligible).map((e) => e.repo))].sort(); + return repos.map((repo) => ({ step: "merge", params: { repo } })); + }, + }, +]; + +// ---- limits and usage ---------------------------------------------------------- + +export const dayStart = (ms: number = Date.now()): string => `${new Date(ms).toISOString().slice(0, 10)}T00:00:00.000Z`; + +type LimitRow = { step: string; per_day: number | null; updated_by: string | null; updated_at: string | null }; + +export const limitRow = (db: DatabaseSync, step: string): LimitRow => + (db.prepare("SELECT * FROM stage_limits WHERE step = ?").get(step) as LimitRow | undefined) ?? { step, per_day: null, updated_by: null, updated_at: null }; + +/** Items handled by the step's jobs that started today (UTC). */ +export function usageToday(db: DatabaseSync, step: string, ms: number = Date.now()): number { + return (db.prepare("SELECT COALESCE(SUM(items), 0) AS n FROM jobs WHERE step = ? AND started_at >= ?").get(step, dayStart(ms)) as { n: number }).n; +} + +/** After BACKOFF_AFTER failed autopilot jobs in a row: when the stage may run again, else null. */ +export function backoffUntil(db: DatabaseSync, step: string, ms: number = Date.now()): number | null { + const rows = db.prepare("SELECT state, ended_at FROM jobs WHERE step = ? AND requested_by = ? AND state IN ('done', 'failed') ORDER BY id DESC LIMIT ?") + .all(step, AUTOPILOT_USER, BACKOFF_AFTER) as { state: string; ended_at: string | null }[]; + if (rows.length < BACKOFF_AFTER || rows.some((r) => r.state !== "failed" || !r.ended_at)) return null; + const until = Date.parse(rows[0]!.ended_at!) + BACKOFF_MS; + return until > ms ? until : null; +} + +/** Why the stage cannot start jobs now, or null. The one place a stage's pause is decided. */ +export function pauseReason(db: DatabaseSync, step: string, ms: number = Date.now()): string | null { + const l = limitRow(db, step), used = usageToday(db, step, ms); + if (l.per_day === 0) return "paused: the daily limit is 0"; + if (l.per_day !== null && used >= l.per_day) return `daily limit of ${l.per_day} items reached`; + const b = backoffUntil(db, step, ms); + if (b !== null) return `last ${BACKOFF_AFTER} automatic jobs failed; waiting until ${new Date(b).toISOString().slice(11, 16)} UTC`; + return null; +} + +// ---- state --------------------------------------------------------------------- + +export const isEnabled = (db: DatabaseSync): boolean => getSetting(db, KEY_ENABLED) === "1"; + +export function setEnabled(db: DatabaseSync, enabled: boolean, by: string): void { + setSetting(db, KEY_ENABLED, enabled ? "1" : "0"); + setSetting(db, KEY_BY, by); + setSetting(db, KEY_AT, now()); + // Turning on plans at once; the sync that already happened is not new. + if (enabled) db.prepare("DELETE FROM settings WHERE key = ?").run(KEY_PLANNED_AT); +} + +/** Steps that have a row in stage_limits, in pipeline order. */ +export const LIMIT_STEPS = ["classify-new", "embed", "decide", "checks", "review-batch", "labels-apply", "merge"]; + +export class LimitError extends Error { + status = 400; +} + +export function setLimit(db: DatabaseSync, step: unknown, input: unknown, by: string): { perDay: number | null } { + if (typeof step !== "string" || !LIMIT_STEPS.includes(step)) throw Object.assign(new LimitError("no such stage"), { status: 404 }); + if (!input || typeof input !== "object" || Array.isArray(input)) throw new LimitError("the body must be a JSON object"); + const keys = Object.keys(input); + if (keys.some((k) => k !== "perDay")) throw new LimitError("only perDay can be set"); + const perDay = (input as { perDay?: unknown }).perDay; + if (perDay === undefined) throw new LimitError("perDay is required (null means no limit)"); + if (perDay !== null && (typeof perDay !== "number" || !Number.isInteger(perDay) || perDay < 0 || perDay > 100_000)) throw new LimitError("perDay must be null or a whole number from 0 to 100000"); + db.prepare(`INSERT INTO stage_limits (step, per_day, updated_by, updated_at) VALUES (?, ?, ?, ?) + ON CONFLICT (step) DO UPDATE SET per_day = excluded.per_day, updated_by = excluded.updated_by, updated_at = excluded.updated_at`) + .run(step, perDay, by, now()); + audit(db, by, "stage-limit", `step:${step}`, { perDay }); + return { perDay }; +} + +export async function stageLimits(db: DatabaseSync): Promise { + const steps = await loadSteps(); + return LIMIT_STEPS.map((step) => { + const l = limitRow(db, step); + return { step, title: steps.get(step)?.title ?? step, perDay: l.per_day, usedToday: usageToday(db, step), pausedReason: pauseReason(db, step) }; + }); +} + +export async function pipelineState(db: DatabaseSync): Promise { + return { + enabled: isEnabled(db), changedBy: getSetting(db, KEY_BY), changedAt: getSetting(db, KEY_AT), + heartbeat: getSetting(db, "runner_heartbeat"), limits: await stageLimits(db), + }; +} + +// ---- planner ------------------------------------------------------------------- + +export type PlanOptions = { lanes?: Lane[]; nowMs?: number; log?: (line: string) => void }; + +const warned = new Set(); + +/** + * Queues the jobs the autopilot wants now: per lane the first candidate whose step is idle, not cooling + * down or backing off and has limit left. Returns the queued job ids. + */ +export async function planAutopilot(db: DatabaseSync, opts: PlanOptions = {}): Promise { + const lanes = opts.lanes ?? LANES, ms = opts.nowMs ?? Date.now(), log = opts.log ?? (() => {}); + const steps = await loadSteps(); + const queued: number[] = []; + for (const lane of lanes) { + try { + for (const c of lane.detect(db)) { + const step = steps.get(c.step); + if (!step) continue; + if (db.prepare("SELECT 1 FROM jobs WHERE step = ? AND state IN ('queued', 'running')").get(c.step)) continue; + const l = limitRow(db, c.step), used = usageToday(db, c.step, ms); + const reason = pauseReason(db, c.step, ms); + if (reason) { + if (backoffUntil(db, c.step, ms) !== null && !warned.has(`${c.step}:${backoffUntil(db, c.step, ms)}`)) { + warned.add(`${c.step}:${backoffUntil(db, c.step, ms)}`); + log(`autopilot: ${c.step}: ${reason}`); + } + continue; + } + const last = lastJobEnd(db, c.step, repoOf(c), AUTOPILOT_USER); + if (last && !last.items && ms - Date.parse(last.endedAt) < COOLDOWN_MS) continue; + const params: Params = { ...c.params }; + const lp = step.params.find((p) => p.name === "limit" && p.kind === "int"); + if (lp && lp.kind === "int") { + const remaining = l.per_day === null ? Infinity : l.per_day - used; + params.limit = Math.min(lp.default ?? lp.max, lp.max, remaining); + if (params.limit < lp.min) continue; + } + try { + const job = await enqueue(db, c.step, params, AUTOPILOT_USER); + queued.push(job.id); + lane.chosen?.(db, c); + log(`autopilot: job ${job.id}: ${c.step} ${JSON.stringify(job.params)}`); + break; + } catch (e) { + if (!(e instanceof JobError)) throw e; + log(`autopilot: ${c.step}: not queued: ${e.message}`); + } + } + } catch (e) { + log(`autopilot: ${lane.name}: ${(e as Error).message}`); + } + } + return queued; +} + +/** One runner tick: plans when enabled and a sync, a finished autopilot job or 15 minutes call for it. */ +export async function autopilotTick(db: DatabaseSync, opts: PlanOptions = {}): Promise { + if (!isEnabled(db)) return []; + const t = opts.nowMs ?? Date.now(); + const sync = getSetting(db, "org_high_water"); + const syncChanged = sync !== getSetting(db, KEY_SYNC_SEEN); + const plannedAt = getSetting(db, KEY_PLANNED_AT); + const planned = plannedAt === null ? 0 : Date.parse(plannedAt); + const finished = db.prepare("SELECT 1 FROM jobs WHERE requested_by = ? AND ended_at > ?").get(AUTOPILOT_USER, plannedAt ?? ""); + if (!syncChanged && plannedAt !== null && t - planned < PLAN_EVERY_MS && !finished) return []; + if (syncChanged) { + setSetting(db, KEY_SYNC_SEEN, sync ?? ""); + setSetting(db, KEY_SYNC_AT, new Date(t).toISOString()); + } + setSetting(db, KEY_PLANNED_AT, new Date(t).toISOString()); + return planAutopilot(db, opts); +} diff --git a/src/runner/classify.ts b/src/runner/classify.ts index f38d13717..f77f5d10f 100644 --- a/src/runner/classify.ts +++ b/src/runner/classify.ts @@ -69,7 +69,7 @@ async function jevPass(ctx: StepContext, run: string, todo: Item[], hashes: Map< } /** Items Jev is unsure of in `run` without a Haiku verdict as new as Jev's. */ -function haikuDue(db: DatabaseSync, run: string, limit: number): Item[] { +export function haikuDue(db: DatabaseSync, run: string, limit: number): Item[] { return db.prepare(`SELECT ${ITEM_COLUMNS} FROM items i JOIN tracked_repos t ON t.name = i.repo JOIN classifications j ON j.repo = i.repo AND j.number = i.number AND j.classifier = 'jev' AND j.run_id = :run LEFT JOIN classifications h ON h.repo = i.repo AND h.number = i.number AND h.classifier = 'haiku' AND h.run_id = :run @@ -125,6 +125,7 @@ export async function classifyNew(ctx: StepContext): Promise { const run = currentRun(ctx.db); if (!run) throw new Error("There is no classification run yet; start a classification pass first."); const r = await pass(ctx, run, "new"); + ctx.handled(r.jev); if (!r.due && !r.haikuDue) return `Nothing to classify in run ${run}.`; return `Run ${run}: Jev classified ${r.jev} of ${r.due} new or changed items${r.left ? ` (${r.left} left)` : ""}; Haiku gave a second opinion on ${r.haiku} of ${r.haikuDue}.`; } @@ -132,6 +133,7 @@ export async function classifyNew(ctx: StepContext): Promise { export async function classifyAll(ctx: StepContext): Promise { const run = String(ctx.params.run); const r = await pass(ctx, run, "all"); + ctx.handled(r.jev); const complete = r.left === 0 && !ctx.cancelled(); if (complete) ctx.db.prepare("INSERT INTO settings (key, value) VALUES ('classify_run', ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(run); return `Run ${run}: Jev classified ${r.jev} of ${r.due} items without a verdict${r.left ? ` (${r.left} left; start it again to continue)` : ""}; Haiku gave a second opinion on ${r.haiku} of ${r.haikuDue}.${complete ? " The run is now the current one." : ""}`; diff --git a/src/runner/exec.ts b/src/runner/exec.ts index 2e43647bd..bc3c8da9a 100644 --- a/src/runner/exec.ts +++ b/src/runner/exec.ts @@ -70,6 +70,7 @@ export async function execJob(id: number): Promise { }, log: (line) => console.log(line), usageRun: (r) => void runs.add(r), + handled: (n) => void db.prepare("UPDATE jobs SET items = ? WHERE id = ?").run(n, id), cancelled: () => !!(db.prepare("SELECT cancel_requested_at FROM jobs WHERE id = ?").get(id) as { cancel_requested_at: string | null }).cancel_requested_at, }; try { diff --git a/src/runner/jobs.ts b/src/runner/jobs.ts index 0b4be8bb4..cae077721 100644 --- a/src/runner/jobs.ts +++ b/src/runner/jobs.ts @@ -1,9 +1,9 @@ -// The jobs and job_schedules tables: requests from the dashboard and the CLI, +// The jobs table: requests from the dashboard, the CLI and the autopilot, // state written by the runner. Shared by the API, the runner and the CLI. import { closeSync, fstatSync, openSync, readSync } from "node:fs"; import { homedir } from "node:os"; import type { DatabaseSync } from "node:sqlite"; -import type { Job, JobDetail, JobFilter, JobList, JobParams, JobState, JobUsage, Schedule, ScheduleInput } from "../../web/src/api/types.ts"; +import type { Job, JobDetail, JobFilter, JobList, JobParams, JobState, JobUsage } from "../../web/src/api/types.ts"; import { trackedNames } from "../repos.ts"; import { loadSteps, ParamError, validateParams, type StepDef } from "./steps.ts"; @@ -22,7 +22,7 @@ type JobRow = { id: number; step: string; params: string; requested_by: string; requested_at: string; state: JobState; started_at: string | null; ended_at: string | null; progress: string | null; summary: string | null; error: string | null; usage: string | null; log_path: string | null; pid: number | null; cancel_requested_at: string | null; cancel_requested_by: string | null; - schedule: string | null; + items: number | null; }; function parseJson(s: string | null, fallback: T): T { @@ -93,14 +93,14 @@ export async function checkRequest(db: DatabaseSync, stepName: unknown, rawParam } /** Queues a job. The same step with the same params already waiting is refused. */ -export async function enqueue(db: DatabaseSync, stepName: unknown, rawParams: unknown, by: string, schedule: string | null = null): Promise { +export async function enqueue(db: DatabaseSync, stepName: unknown, rawParams: unknown, by: string): Promise { const { step, params } = await checkRequest(db, stepName, rawParams); const json = JSON.stringify(params); if (db.prepare("SELECT 1 FROM jobs WHERE step = ? AND params = ? AND state = 'queued'").get(step.name, json)) { throw new JobError(409, `${step.name} with these settings is already queued`); } - const id = Number(db.prepare("INSERT INTO jobs (step, params, requested_by, requested_at, state, schedule) VALUES (?, ?, ?, ?, 'queued', ?)") - .run(step.name, json, by, now(), schedule).lastInsertRowid); + const id = Number(db.prepare("INSERT INTO jobs (step, params, requested_by, requested_at, state) VALUES (?, ?, ?, ?, 'queued')") + .run(step.name, json, by, now()).lastInsertRowid); return getJob(db, id); } @@ -120,67 +120,6 @@ export function requestCancel(db: DatabaseSync, id: number, by: string): Job { return getJob(db, id); } -// ---- schedules --------------------------------------------------------------- - -type ScheduleRow = { - step: string; enabled: number; trigger: string; interval_minutes: number | null; params: string; - updated_by: string | null; updated_at: string | null; last_enqueued_at: string | null; last_sync_seen: string | null; -}; - -const OFF: Schedule = { enabled: false, trigger: "interval", intervalMinutes: 60, params: {}, updatedBy: null, updatedAt: null, lastEnqueuedAt: null }; - -const toSchedule = (r: ScheduleRow | undefined): Schedule => - r - ? { - enabled: r.enabled === 1, trigger: r.trigger === "after-sync" ? "after-sync" : "interval", intervalMinutes: r.interval_minutes, - params: parseJson(r.params, {}), updatedBy: r.updated_by, updatedAt: r.updated_at, lastEnqueuedAt: r.last_enqueued_at, - } - : { ...OFF }; - -export function scheduleRows(db: DatabaseSync): ScheduleRow[] { - return db.prepare("SELECT * FROM job_schedules").all() as ScheduleRow[]; -} - -export function schedules(db: DatabaseSync): Map { - return new Map(scheduleRows(db).map((r) => [r.step, toSchedule(r)])); -} - -export const scheduleOf = (db: DatabaseSync, step: string): Schedule => - toSchedule(db.prepare("SELECT * FROM job_schedules WHERE step = ?").get(step) as ScheduleRow | undefined); - -export const MIN_INTERVAL = 5, MAX_INTERVAL = 7 * 24 * 60; - -export async function saveSchedule(db: DatabaseSync, stepName: string, input: unknown, by: string): Promise { - const step = await stepOf(stepName); - if (!input || typeof input !== "object" || Array.isArray(input)) throw new JobError(400, "the body must be a JSON object"); - const b = input as Partial; - if (typeof b.enabled !== "boolean") throw new JobError(400, "enabled must be true or false"); - if (b.trigger !== "interval" && b.trigger !== "after-sync") throw new JobError(400, "trigger must be interval or after-sync"); - let minutes: number | null = null; - if (b.trigger === "interval") { - minutes = b.intervalMinutes ?? null; - if (typeof minutes !== "number" || !Number.isInteger(minutes) || minutes < MIN_INTERVAL || minutes > MAX_INTERVAL) { - throw new JobError(400, `the interval must be a whole number of minutes from ${MIN_INTERVAL} to ${MAX_INTERVAL}`); - } - } - let params: JobParams; - try { - params = validateParams(step, b.params, trackedNames(db)); - } catch (e) { - if (e instanceof ParamError) throw new JobError(400, e.message); - throw e; - } - if (b.enabled && step.available?.()) throw new JobError(409, step.available()!); - // An after-sync schedule waits for the next sync, not the one that already happened. - const sync = (db.prepare("SELECT value FROM settings WHERE key = 'org_high_water'").get() as { value: string } | undefined)?.value ?? null; - db.prepare(`INSERT INTO job_schedules (step, enabled, trigger, interval_minutes, params, updated_by, updated_at, last_sync_seen) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (step) DO UPDATE SET enabled = excluded.enabled, trigger = excluded.trigger, - interval_minutes = excluded.interval_minutes, params = excluded.params, updated_by = excluded.updated_by, updated_at = excluded.updated_at, - last_sync_seen = excluded.last_sync_seen`) - .run(step.name, b.enabled ? 1 : 0, b.trigger, minutes, JSON.stringify(params), by, now(), sync); - return scheduleOf(db, step.name); -} - // ---- logs ---------------------------------------------------------------------- // Replaces anything that looks like a credential. Logs hold step output only, diff --git a/src/runner/runner.ts b/src/runner/runner.ts index f9862734e..5cde12439 100644 --- a/src/runner/runner.ts +++ b/src/runner/runner.ts @@ -1,7 +1,8 @@ // `craft-auto runner serve`: the only process that runs pipeline steps. It // polls the jobs table, runs each job in its own child process (`craft-auto // runner exec `, its own process group, output to a per-job log file), -// stops jobs whose cancel was requested, enqueues scheduled jobs and marks +// stops jobs whose cancel was requested, runs the autopilot (queues jobs while the +// pipeline switch is on) and marks // jobs left running by an earlier runner as failed. import { spawn, type ChildProcess } from "node:child_process"; import { closeSync, mkdirSync, openSync, readFileSync, utimesSync } from "node:fs"; @@ -9,7 +10,8 @@ import { homedir } from "node:os"; import { basename, join } from "node:path"; import type { DatabaseSync } from "node:sqlite"; import { dbPath } from "../db.ts"; -import { enqueue, JobError, jobRow, now, scheduleRows } from "./jobs.ts"; +import { autopilotTick } from "./autopilot.ts"; +import { jobRow, now } from "./jobs.ts"; import { loadSteps } from "./steps.ts"; export const logsDir = (): string => process.env.CRAFT_AUTO_RUNNER_LOGS ?? join(homedir(), ".cache/craft-automation-logs/jobs"); @@ -83,7 +85,7 @@ export class Runner { return rows.length; } - /** One pass: heartbeat, cancels, schedules, new jobs. */ + /** One pass: heartbeat, cancels, autopilot, new jobs. */ async tick(): Promise { const t = now(); this.db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(HEARTBEAT_KEY, t); @@ -96,7 +98,7 @@ export class Runner { } this.cancels(); if (this.stopping) return; - await this.schedules(); + await autopilotTick(this.db, { log: this.o.log }); await this.startJobs(); } @@ -116,31 +118,6 @@ export class Runner { } } - private busy(step: string): boolean { - return !!this.db.prepare("SELECT 1 FROM jobs WHERE step = ? AND state IN ('queued', 'running')").get(step); - } - - private async schedules(): Promise { - const steps = await loadSteps(); - const sync = (this.db.prepare("SELECT value FROM settings WHERE key = 'org_high_water'").get() as { value: string } | undefined)?.value ?? null; - for (const s of scheduleRows(this.db)) { - if (!s.enabled || !steps.has(s.step) || this.busy(s.step)) continue; - const due = s.trigger === "after-sync" - ? sync !== null && sync !== s.last_sync_seen - : !s.last_enqueued_at || Date.now() - Date.parse(s.last_enqueued_at) >= (s.interval_minutes ?? 60) * 60_000; - if (!due) continue; - const t = now(); - this.db.prepare("UPDATE job_schedules SET last_enqueued_at = ?, last_sync_seen = ? WHERE step = ?").run(t, sync, s.step); - try { - const job = await enqueue(this.db, s.step, JSON.parse(s.params), "schedule", s.step); - this.o.log(`job ${job.id}: ${s.step} queued by its schedule`); - } catch (e) { - if (!(e instanceof JobError)) throw e; - this.o.log(`schedule ${s.step}: not queued: ${e.message}`); - } - } - } - private async startJobs(): Promise { const steps = await loadSteps(); const queued = this.db.prepare("SELECT id, step FROM jobs WHERE state = 'queued' ORDER BY id").all() as { id: number; step: string }[]; diff --git a/src/runner/steps.ts b/src/runner/steps.ts index 3bcc58f50..be5538c27 100644 --- a/src/runner/steps.ts +++ b/src/runner/steps.ts @@ -1,7 +1,7 @@ // The pipeline steps the runner can run. Each step is a declaration: who may // request it, a params schema, a concurrency group and the function that runs // it. Adding a step means adding one entry to STEPS (and the module its `run` -// imports); the dashboard, the API, schedules and the runner pick it up from here. +// imports); the dashboard, the API, the autopilot and the runner pick it up from here. // // Params are only enums, tracked repo names, bounded integers and run ids: // nothing a person types can reach a model's prompt or a shell. @@ -31,6 +31,8 @@ export type StepContext = { log(line: string): void; /** Model calls recorded in token_usage under this run id (from the job's start) count as the job's usage. */ usageRun(runId: string): void; + /** Items this job handled, counted against the stage's daily limit. Call once with the total, before returning. */ + handled(n: number): void; /** Set when a cancel was requested; long loops should stop between units of work. */ cancelled(): boolean; }; @@ -42,7 +44,7 @@ export type StepDef = { description: string; /** Stage number in docs/pipeline.md. */ stage: number; - /** Who may start, cancel or schedule it. Anything that writes to GitHub or spends model quota is operator-only. */ + /** Who may start or cancel it. Anything that writes to GitHub or spends model quota is operator-only. */ requires: "operator"; /** At most one job of a group runs at a time. */ group: "models" | "github-write" | "local" | (string & {}); @@ -141,6 +143,7 @@ export const STEPS: StepDef[] = [ const { applyLabels } = await import("../labels/github.ts"); const { Client } = await import("../mirror.ts"); const r = await applyLabels(ctx.db, new Client(500), repo, { runId, apply: true, login: ctx.job.requestedBy, log: ctx.log }); + ctx.handled(r.labeled); return `${repo}: labelled ${r.labeled} of ${r.planned} items in ${r.batches} batches, ${r.failed.length} failed`; }, }, @@ -164,6 +167,7 @@ export const STEPS: StepDef[] = [ model: String(ctx.params.model), }, ctx.log); if (r.usageRun) ctx.usageRun(r.usageRun); + ctx.handled(r.asked); return `asked ${r.asked} decisions; ${r.noSummary} items without a summary`; }, }, @@ -182,6 +186,7 @@ export const STEPS: StepDef[] = [ const { runReview } = await import("../review/index.ts"); const r = await runReview(ctx.db, { repo: String(ctx.params.repo), limit: Number(ctx.params.limit) }, ctx.log); ctx.usageRun(r.runId); + ctx.handled(r.reviewed); const v = Object.entries(r.verdicts).map(([k, n]) => `${n} ${k}`).join(", "); return `${r.repo}: reviewed ${r.reviewed} of ${r.candidates} candidates${v ? ` (${v})` : ""}; ${r.skipped.length} skipped, ${r.missing.length} without an answer`; }, @@ -197,6 +202,7 @@ export const STEPS: StepDef[] = [ run: async (ctx) => { const { runChecks } = await import("../review/index.ts"); const r = await runChecks(ctx.db, { repo: String(ctx.params.repo) }, ctx.log); + ctx.handled(r.prs); return `${ctx.params.repo}: refreshed ${r.prs} open pull requests`; }, }, @@ -214,6 +220,7 @@ export const STEPS: StepDef[] = [ run: async (ctx) => { const { runMerge } = await import("../merge/index.ts"); const r = await runMerge(ctx.db, { repo: String(ctx.params.repo), limit: Number(ctx.params.limit), dryRun: false }, ctx.log); + ctx.handled(r.merged.length); return `${r.repo}: merged ${r.merged.length} of ${r.attempted.length} tried, ${r.refused.length} refused, ${r.asked.length} decisions asked`; }, }, diff --git a/src/schema.sql b/src/schema.sql index 679ad18d2..8d3b02a42 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -199,7 +199,7 @@ CREATE TABLE IF NOT EXISTS oauth_states ( CREATE TABLE IF NOT EXISTS audit ( at TEXT NOT NULL, login TEXT NOT NULL, - action TEXT NOT NULL, -- answer | undo | adopt | opinion | opinion-retract | comment | override | rule | access-add | access-remove | access-role | session-revoke | sign-in | sign-in-refused | repo-track | repo-untrack | labels-approve | labels-revoke | labels-apply | assign | merge | merge-refused | job-request | job-cancel | schedule-change + action TEXT NOT NULL, -- answer | undo | adopt | opinion | opinion-retract | comment | override | rule | access-add | access-remove | access-role | session-revoke | sign-in | sign-in-refused | repo-track | repo-untrack | labels-approve | labels-revoke | labels-apply | assign | merge | merge-refused | job-request | job-cancel | pipeline-switch | stage-limit target TEXT, details TEXT -- JSON ); @@ -263,7 +263,7 @@ CREATE TABLE IF NOT EXISTS jobs ( id INTEGER PRIMARY KEY AUTOINCREMENT, step TEXT NOT NULL, params TEXT NOT NULL, -- JSON object, validated - requested_by TEXT NOT NULL, -- login, 'schedule' or 'cli' + requested_by TEXT NOT NULL, -- login, 'pipeline' (autopilot) or 'cli' requested_at TEXT NOT NULL, state TEXT NOT NULL, -- queued | running | done | failed | cancelled started_at TEXT, ended_at TEXT, @@ -275,22 +275,22 @@ CREATE TABLE IF NOT EXISTS jobs ( pid INTEGER, -- the job's child process while running cancel_requested_at TEXT, cancel_requested_by TEXT, - schedule TEXT -- the step whose schedule enqueued it + items INTEGER -- items the job handled (classified, asked, reviewed, merged ...), for the daily limits ); CREATE INDEX IF NOT EXISTS jobs_state ON jobs(state, id); CREATE INDEX IF NOT EXISTS jobs_step ON jobs(step, id); --- One schedule per step; a step without a row is not scheduled. -CREATE TABLE IF NOT EXISTS job_schedules ( +-- Daily limits per autopilot stage (UTC day); NULL means no limit, 0 pauses the +-- stage. The pipeline switch itself lives in settings (pipeline_enabled, +-- pipeline_changed_by, pipeline_changed_at). +CREATE TABLE IF NOT EXISTS stage_limits ( step TEXT PRIMARY KEY, - enabled INTEGER NOT NULL DEFAULT 0, - trigger TEXT NOT NULL, -- 'interval' | 'after-sync' - interval_minutes INTEGER, - params TEXT NOT NULL DEFAULT '{}', -- JSON, validated like a request - updated_by TEXT, updated_at TEXT, - last_enqueued_at TEXT, - last_sync_seen TEXT -- settings.org_high_water when it last enqueued + per_day INTEGER, -- items per day + updated_by TEXT, updated_at TEXT ); +INSERT OR IGNORE INTO stage_limits (step, per_day) VALUES + ('classify-new', 2000), ('embed', NULL), ('decide', 100), ('checks', NULL), + ('review-batch', 40), ('labels-apply', NULL), ('merge', 10); -- One row per `craft-auto sync` run, kept for two days, for the Pipeline page. CREATE TABLE IF NOT EXISTS sync_runs ( diff --git a/test/autopilot-steps.ts b/test/autopilot-steps.ts new file mode 100644 index 000000000..58686407e --- /dev/null +++ b/test/autopilot-steps.ts @@ -0,0 +1,9 @@ +// Fake steps for the autopilot planner tests (CRAFT_AUTO_EXTRA_STEPS). Never run. +import type { StepDef } from "../src/runner/steps.ts"; + +const base = { description: "Test step.", stage: 2, requires: "operator" as const, group: "test-a", run: async () => "ok" }; + +export const steps: StepDef[] = [ + { ...base, name: "test-limited", title: "Limited", params: [{ name: "limit", label: "At most", kind: "int", min: 1, max: 100, default: 50 }] }, + { ...base, name: "test-plain", title: "Plain", params: [] }, +]; diff --git a/test/autopilot.test.ts b/test/autopilot.test.ts new file mode 100644 index 000000000..598c86de9 --- /dev/null +++ b/test/autopilot.test.ts @@ -0,0 +1,120 @@ +// The autopilot planner: with the switch on it queues a job per stage that has +// work and limit left, sized to what remains of the day; off, used up, busy or +// backing off after repeated failures, it queues nothing. +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { after, beforeEach, describe, test } from "node:test"; +import { fileURLToPath } from "node:url"; + +process.env.CRAFT_AUTO_EXTRA_STEPS = fileURLToPath(new URL("./autopilot-steps.ts", import.meta.url)); + +const { connect } = await import("../src/db.ts"); +const { autopilotTick, backoffUntil, LANES, planAutopilot, roundRobin, setEnabled, BACKOFF_MS, COOLDOWN_MS } = await import("../src/runner/autopilot.ts"); +type Lane = import("../src/runner/autopilot.ts").Lane; + +const SCRATCH = join(homedir(), ".cache/craft-automation-scratch"); +mkdirSync(SCRATCH, { recursive: true }); +const dir = mkdtempSync(join(SCRATCH, "autopilot-test-")); +const db = connect(join(dir, "a.db")); +after(() => { + db.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +let work = true; +const lanes: Lane[] = [ + { name: "limited", detect: () => (work ? [{ step: "test-limited", params: {} }] : []) }, + { name: "plain", detect: () => [{ step: "test-plain", params: {} }] }, +]; +const jobs = (step: string) => db.prepare("SELECT * FROM jobs WHERE step = ? ORDER BY id").all(step) as { id: number; params: string; requested_by: string; state: string }[]; +const finish = (step: string, state: "done" | "failed", items: number | null, endedAt = new Date().toISOString()) => + db.prepare("INSERT INTO jobs (step, params, requested_by, requested_at, state, started_at, ended_at, items) VALUES (?, '{}', 'pipeline', ?, ?, ?, ?, ?)") + .run(step, endedAt, state, endedAt, endedAt, items); +const setLimit = (step: string, perDay: number | null) => db.prepare("INSERT OR REPLACE INTO stage_limits (step, per_day) VALUES (?, ?)").run(step, perDay); + +beforeEach(() => { + db.exec("DELETE FROM jobs; DELETE FROM stage_limits; DELETE FROM settings WHERE key LIKE 'pipeline_%' OR key = 'org_high_water'"); + work = true; +}); + +describe("autopilot", () => { + test("a stage with work gets a job sized to the day's remaining limit", async () => { + setLimit("test-limited", 80); + finish("test-limited", "done", 50, new Date(Date.now() - 2 * COOLDOWN_MS).toISOString()); + const ids = await planAutopilot(db, { lanes }); + assert.equal(ids.length, 2, "one job per lane"); + const j = jobs("test-limited").at(-1)!; + assert.equal(j.requested_by, "pipeline"); + assert.deepEqual(JSON.parse(j.params), { limit: 30 }, "min(step default 50, 80 - 50 used)"); + assert.equal(jobs("test-plain").length, 1); + }); + + test("no work, no job; a queued job of the stage blocks another", async () => { + work = false; + await planAutopilot(db, { lanes }); + assert.equal(jobs("test-limited").length, 0); + work = true; + await planAutopilot(db, { lanes }); + await planAutopilot(db, { lanes }); + assert.equal(jobs("test-limited").length, 1); + }); + + test("a used-up or zero limit queues nothing for that stage while others go on", async () => { + setLimit("test-limited", 50); + setLimit("test-plain", 0); + finish("test-limited", "done", 50, new Date(Date.now() - 2 * COOLDOWN_MS).toISOString()); + await planAutopilot(db, { lanes }); + assert.equal(jobs("test-limited").length, 1, "only the finished job"); + assert.equal(jobs("test-plain").length, 0, "0 pauses the stage"); + setLimit("test-plain", null); + await planAutopilot(db, { lanes }); + assert.equal(jobs("test-plain").length, 1); + }); + + test("switched off, the tick queues nothing; switched on, it plans after a sync and not again until something changes", async () => { + assert.deepEqual(await autopilotTick(db, { lanes }), []); + setEnabled(db, true, "boss"); + db.prepare("INSERT INTO settings (key, value) VALUES ('org_high_water', 't1')").run(); + assert.equal((await autopilotTick(db, { lanes })).length, 2); + assert.equal((await autopilotTick(db, { lanes })).length, 0, "nothing changed"); + db.prepare("UPDATE jobs SET state = 'cancelled'").run(); + assert.equal((await autopilotTick(db, { lanes, nowMs: Date.now() + 16 * 60_000 })).length, 2, "15 minutes later"); + setEnabled(db, false, "boss"); + db.prepare("UPDATE jobs SET state = 'cancelled'").run(); + assert.deepEqual(await autopilotTick(db, { lanes, nowMs: Date.now() + 40 * 60_000 }), []); + }); + + test("the review lane's repos go round robin and the cursor moves on a review", () => { + assert.deepEqual(roundRobin(["c", "a", "b"], null), ["a", "b", "c"]); + assert.deepEqual(roundRobin(["c", "a", "b"], "b"), ["c", "a", "b"]); + assert.deepEqual(roundRobin(["c", "a", "b"], "c"), ["a", "b", "c"]); + const review = LANES.find((l) => l.name === "review")!; + review.chosen!(db, { step: "checks", params: { repo: "a" } }); + assert.equal(db.prepare("SELECT value FROM settings WHERE key = 'pipeline_review_cursor'").get(), undefined, "checks do not move the cursor"); + review.chosen!(db, { step: "review-batch", params: { repo: "b" } }); + const cursor = (db.prepare("SELECT value FROM settings WHERE key = 'pipeline_review_cursor'").get() as { value: string }).value; + assert.deepEqual(roundRobin(["a", "b", "c"], cursor), ["c", "a", "b"]); + }); + + test("three failed automatic jobs in a row make the stage wait an hour; other stages go on", async () => { + for (let i = 0; i < 3; i++) finish("test-limited", "failed", null, new Date(Date.now() - 20 * 60_000 - i * 60_000).toISOString()); + const until = backoffUntil(db, "test-limited"); + assert.ok(until !== null && until > Date.now() && until <= Date.now() + BACKOFF_MS); + const logs: string[] = []; + await planAutopilot(db, { lanes, log: (l) => logs.push(l) }); + assert.equal(jobs("test-limited").length, 3, "no new job"); + assert.equal(jobs("test-plain").length, 1); + assert.ok(logs.some((l) => /test-limited.*failed/.test(l)), logs.join("\n")); + assert.equal(backoffUntil(db, "test-limited", Date.now() + BACKOFF_MS + 60 * 60_000), null, "an hour later it is free"); + db.prepare("UPDATE jobs SET state = 'done' WHERE id = (SELECT MAX(id) FROM jobs WHERE step = 'test-limited')").run(); + assert.equal(backoffUntil(db, "test-limited"), null, "a success in the last three ends it"); + }); + + test("a stage that handled nothing is not retried within 15 minutes", async () => { + finish("test-limited", "done", 0); + await planAutopilot(db, { lanes }); + assert.equal(jobs("test-limited").length, 1); + }); +}); diff --git a/test/pipeline-state.test.ts b/test/pipeline-state.test.ts new file mode 100644 index 000000000..5a9dd4f28 --- /dev/null +++ b/test/pipeline-state.test.ts @@ -0,0 +1,132 @@ +// The pipeline switch and stage limits over HTTP: everyone signed in reads; +// only operators write; bodies are validated and every write is audited. +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { after, before, describe, test } from "node:test"; +import { fileURLToPath } from "node:url"; +import type { PipelineState, StageLimit } from "../web/src/api/types.ts"; + +process.env.CRAFT_AUTO_EXTRA_STEPS = fileURLToPath(new URL("./runner-steps.ts", import.meta.url)); + +const { addLogin } = await import("../src/access.ts"); +const { connect } = await import("../src/db.ts"); +const { scopeToTracked } = await import("../src/repos.ts"); +const { apiRoutes } = await import("../src/dash/api/index.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 SCRATCH = join(homedir(), ".cache/craft-automation-scratch"); +mkdirSync(SCRATCH, { recursive: true }); +const dir = mkdtempSync(join(SCRATCH, "pipeline-state-test-")); +const dbFile = join(dir, "dash.db"); +const permsFile = join(dir, "perms.json"); +writeFileSync(permsFile, "{}"); + +const db = connect(dbFile); +let base = ""; +let close: () => Promise; + +before(async () => { + addLogin(db, "cli", "boss", "operator", null); + addLogin(db, "cli", "viewer1", "viewer", null); + addLogin(db, "cli", "maint", "maintainer", null); + scopeToTracked(db); + const config = loadConfig({ CRAFT_AUTO_DEV_AUTH: "1", CRAFT_AUTO_LISTEN: "127.0.0.1:0", CRAFT_AUTO_DB: dbFile, CRAFT_AUTO_DEV_PERMS: permsFile }); + const s = await startServer({ config, db, provider: new FakeProvider(permsFile), routes: apiRoutes() }); + base = s.url; + close = s.close; +}); +after(async () => { + await close(); + db.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +class Client { + jar = new Map(); + csrf = ""; + async req(method: string, path: string, body?: unknown): Promise { + const headers: Record = { cookie: [...this.jar].map(([k, v]) => `${k}=${v}`).join("; "), accept: "application/json" }; + if (method !== "GET") headers["x-csrf-token"] = this.csrf; + if (body !== undefined) headers["content-type"] = "application/json"; + const r = await fetch(new URL(path, base), { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: "manual" }); + for (const c of r.headers.getSetCookie()) { + const [kv] = c.split(";"); + const k = kv!.slice(0, kv!.indexOf("=")), v = kv!.slice(kv!.indexOf("=") + 1); + if (/Max-Age=0/.test(c)) this.jar.delete(k); + else this.jar.set(k, v); + } + return r; + } + async json(method: string, path: string, body?: unknown, status = 200): Promise { + const r = await this.req(method, path, body); + const text = await r.text(); + assert.equal(r.status, status, `${method} ${path}: ${text}`); + return (text ? JSON.parse(text) : undefined) as T; + } + get = (path: string, status = 200) => this.json("GET", path, undefined, status); + post = (path: string, body?: unknown, status = 200) => this.json("POST", path, body, status); + put = (path: string, body?: unknown, status = 200) => this.json("PUT", path, body, status); +} + +async function signedIn(login: string): Promise { + const c = new Client(); + const start = await c.req("GET", "/auth/signin?return_to=/"); + const auth = await c.req("GET", `${start.headers.get("location")}&login=${login}`); + const done = await c.req("GET", auth.headers.get("location")!); + assert.equal(done.status, 303, `sign-in of ${login}`); + c.csrf = (await c.req("GET", "/api/me")).headers.get("x-csrf-token") ?? ""; + return c; +} + + +const audits = (action: string) => (db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action = ?").get(action) as { n: number }).n; + +describe("pipeline state api", () => { + test("everyone signed in reads the state; the pipeline starts off with the default limits", async () => { + for (const login of ["viewer1", "maint", "boss"]) { + const s = await (await signedIn(login)).get("/api/pipeline/state"); + assert.equal(s.enabled, false); + assert.deepEqual(s.limits.map((l) => l.step), ["classify-new", "embed", "decide", "checks", "review-batch", "labels-apply", "merge"]); + const by = (step: string) => s.limits.find((l) => l.step === step)!; + assert.deepEqual([by("classify-new").perDay, by("embed").perDay, by("decide").perDay, by("review-batch").perDay, by("merge").perDay], [2000, null, 100, 40, 10]); + assert.equal(by("decide").usedToday, 0); + } + }); + + test("non-operators get 403 and nothing is audited", async () => { + const before = audits("pipeline-switch") + audits("stage-limit"); + for (const login of ["viewer1", "maint"]) { + const c = await signedIn(login); + await c.put("/api/pipeline/state", { enabled: true }, 403); + await c.put("/api/pipeline/limits/decide", { perDay: 5 }, 403); + } + assert.equal(audits("pipeline-switch") + audits("stage-limit"), before); + assert.equal((await (await signedIn("boss")).get("/api/pipeline/state")).enabled, false); + }); + + test("an operator turns the pipeline on and off and sets limits, each audited; bad bodies are refused", async () => { + const boss = await signedIn("boss"); + await boss.put("/api/pipeline/state", { enabled: "yes" }, 400); + await boss.put("/api/pipeline/state", {}, 400); + const on = await boss.put("/api/pipeline/state", { enabled: true }); + assert.deepEqual([on.enabled, on.changedBy], [true, "boss"]); + assert.ok(on.changedAt); + assert.equal((await boss.put("/api/pipeline/state", { enabled: false })).enabled, false); + assert.equal(audits("pipeline-switch"), 2); + + const l = await boss.put("/api/pipeline/limits/decide", { perDay: 7 }); + assert.equal(l.perDay, 7); + assert.equal((await boss.put("/api/pipeline/limits/decide", { perDay: null })).perDay, null); + assert.match((await boss.put("/api/pipeline/limits/merge", { perDay: 0 })).pausedReason ?? "", /limit is 0/); + const before = audits("stage-limit"); + for (const body of [{ perDay: -1 }, { perDay: 1.5 }, { perDay: "3" }, { perDay: 1e9 }, {}, { perDay: 1, usdPerDay: 3 }, [1]]) { + await boss.put("/api/pipeline/limits/decide", body, 400); + } + await boss.put("/api/pipeline/limits/classify-all", { perDay: 1 }, 404); + assert.equal(audits("stage-limit"), before); + }); +}); diff --git a/test/pipeline.test.ts b/test/pipeline.test.ts index 8b21ae90e..587b33b67 100644 --- a/test/pipeline.test.ts +++ b/test/pipeline.test.ts @@ -1,5 +1,5 @@ // The Pipeline API through HTTP with the fake OAuth provider: everyone signed -// in reads; only operators request, cancel and schedule, with params checked +// in reads; only operators request and cancel, with params checked // against the step's schema and one audit row per write. import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; @@ -7,7 +7,7 @@ import { homedir } from "node:os"; import { join } from "node:path"; import { after, before, describe, test } from "node:test"; import { fileURLToPath } from "node:url"; -import type { Job, JobDetail, JobList, PipelineOverview, Schedule } from "../web/src/api/types.ts"; +import type { Job, JobDetail, JobList, PipelineOverview } from "../web/src/api/types.ts"; process.env.CRAFT_AUTO_EXTRA_STEPS = fileURLToPath(new URL("./runner-steps.ts", import.meta.url)); @@ -52,7 +52,7 @@ class Client { csrf = ""; async req(method: string, path: string, body?: unknown): Promise { const headers: Record = { cookie: [...this.jar].map(([k, v]) => `${k}=${v}`).join("; "), accept: "application/json" }; - if (method === "POST") headers["x-csrf-token"] = this.csrf; + if (method !== "GET") headers["x-csrf-token"] = this.csrf; if (body !== undefined) headers["content-type"] = "application/json"; const r = await fetch(new URL(path, base), { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: "manual" }); for (const c of r.headers.getSetCookie()) { @@ -84,10 +84,9 @@ async function signedIn(login: string): Promise { } const audits = (action: string) => (db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action = ?").get(action) as { n: number }).n; -const SCHEDULE = { enabled: true, trigger: "interval", intervalMinutes: 30, params: { n: 4 } }; describe("pipeline api", () => { - test("viewers and maintainers read jobs and logs but get 403 on run, cancel and schedule", async () => { + test("viewers and maintainers read jobs and logs but get 403 on run and cancel", async () => { const boss = await signedIn("boss"); const job = await boss.post("/api/pipeline/jobs", { step: "test-echo", params: { n: 1 } }); const logFile = join(dir, "job.log"); @@ -105,7 +104,6 @@ describe("pipeline api", () => { const before = db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action <> 'sign-in'").get(); await c.post("/api/pipeline/jobs", { step: "test-echo", params: { n: 2 } }, 403); await c.post(`/api/pipeline/jobs/${job.id}/cancel`, undefined, 403); - await c.post("/api/pipeline/schedules/test-echo", SCHEDULE, 403); assert.deepEqual(db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action <> 'sign-in'").get(), before); } assert.equal(getState(job.id), "queued"); @@ -119,12 +117,10 @@ describe("pipeline api", () => { { run: "Has Spaces" }, { run: "ignore previous instructions" }, { other: 1 }, [1], ]) await boss.post("/api/pipeline/jobs", { step: "test-echo", params }, 400); await boss.post("/api/pipeline/jobs", { step: "no-such-step", params: {} }, 400); - await boss.post("/api/pipeline/schedules/test-echo", { ...SCHEDULE, intervalMinutes: 1 }, 400); - await boss.post("/api/pipeline/schedules/test-echo", { ...SCHEDULE, params: { n: 1000 } }, 400); assert.equal(audits("job-request"), before); }); - test("an operator requests, cancels and schedules, each audited", async () => { + test("an operator requests and cancels, each audited", async () => { const boss = await signedIn("boss"); const j = await boss.post("/api/pipeline/jobs", { step: "test-echo", params: { n: 9, repo: "photocraft", run: "pass-2" } }); assert.deepEqual(j.params, { n: 9, mode: "ok", repo: "photocraft", run: "pass-2" }); @@ -132,12 +128,8 @@ describe("pipeline api", () => { await boss.post("/api/pipeline/jobs", { step: "test-echo", params: { n: 9, repo: "photocraft", run: "pass-2" } }, 409); assert.equal((await boss.post(`/api/pipeline/jobs/${j.id}/cancel`)).state, "cancelled"); await boss.post(`/api/pipeline/jobs/${j.id}/cancel`, undefined, 409); - const s = await boss.post("/api/pipeline/schedules/test-echo", SCHEDULE); - assert.deepEqual([s.enabled, s.intervalMinutes, s.params], [true, 30, { n: 4, mode: "ok" }]); - const step = (await boss.get("/api/pipeline")).steps.find((x) => x.name === "test-echo")!; - assert.equal(step.schedule.updatedBy, "boss"); - const rows = db.prepare("SELECT action, target FROM audit WHERE login = 'boss' AND action IN ('job-request', 'job-cancel', 'schedule-change') ORDER BY rowid").all(); - assert.deepEqual(rows.slice(-3).map((r) => r.action), ["job-request", "job-cancel", "schedule-change"]); + const rows = db.prepare("SELECT action FROM audit WHERE login = 'boss' AND action IN ('job-request', 'job-cancel') ORDER BY rowid").all(); + assert.deepEqual(rows.slice(-2).map((r) => r.action), ["job-request", "job-cancel"]); }); }); diff --git a/test/runner.test.ts b/test/runner.test.ts index 318448755..147ce668a 100644 --- a/test/runner.test.ts +++ b/test/runner.test.ts @@ -1,6 +1,6 @@ // The runner on fake steps: it runs queued jobs in child processes, records // success, failure and usage, honours cancels, recovers jobs an earlier runner -// left running, enqueues scheduled jobs and runs one job per group at a time. +// left running, runs one job per group at a time. import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; import { homedir } from "node:os"; @@ -11,7 +11,7 @@ import { fileURLToPath } from "node:url"; process.env.CRAFT_AUTO_EXTRA_STEPS = fileURLToPath(new URL("./runner-steps.ts", import.meta.url)); const { connect } = await import("../src/db.ts"); -const { enqueue, getJob, jobDetail, requestCancel, saveSchedule } = await import("../src/runner/jobs.ts"); +const { enqueue, getJob, jobDetail, requestCancel } = await import("../src/runner/jobs.ts"); const { Runner } = await import("../src/runner/runner.ts"); const { FAKE_TOKEN } = await import("./runner-steps.ts"); const { dueItems, inputHash } = await import("../src/runner/classify.ts"); @@ -90,29 +90,6 @@ describe("runner", () => { await runner.idle(); }); - test("schedules enqueue jobs: an interval when due, after-sync when the sync moves on", async () => { - await saveSchedule(db, "test-echo", { enabled: true, trigger: "interval", intervalMinutes: 60, params: { n: 3 } }, "boss"); - db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('org_high_water', '2026-11-01T00:00:00Z')").run(); - await saveSchedule(db, "test-other", { enabled: true, trigger: "after-sync", intervalMinutes: null, params: { ms: 1 } }, "boss"); - const count = (step: string) => (db.prepare("SELECT COUNT(*) AS n FROM jobs WHERE step = ? AND requested_by = 'schedule'").get(step) as { n: number }).n; - await runner.tick(); - assert.equal(count("test-echo"), 1); - assert.equal(count("test-other"), 0, "after-sync waits for the next sync"); - await runner.idle(); - await runner.tick(); - await runner.idle(); - assert.equal(count("test-echo"), 1, "not again within the interval"); - db.prepare("UPDATE settings SET value = '2026-11-01T00:01:00Z' WHERE key = 'org_high_water'").run(); - await runner.tick(); - assert.equal(count("test-other"), 1); - await runner.idle(); - await runner.tick(); - assert.equal(count("test-other"), 1); - await saveSchedule(db, "test-echo", { enabled: false, trigger: "interval", intervalMinutes: 60, params: {} }, "boss"); - await saveSchedule(db, "test-other", { enabled: false, trigger: "after-sync", intervalMinutes: null, params: {} }, "boss"); - await runner.idle(); - }); - test("classify-new takes items without a verdict and items whose text changed; a pass takes only the first", () => { const ins = db.prepare("INSERT INTO items (repo, number, kind, state, title, body, updated_at) VALUES ('photocraft', ?, 'issue', ?, ?, 'body', ?)"); const verdict = db.prepare("INSERT INTO classifications (repo, number, classifier, run_id, at, type_label, input_hash) VALUES ('photocraft', ?, 'jev', 'r1', '2026-10-10T00:00:00Z', 'bugfix', ?)"); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index d8ce7de76..3e91c7785 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -37,8 +37,8 @@ import type { JobList, JobParams, PipelineOverview, - Schedule, - ScheduleInput, + PipelineState, + StageLimit, } from "./types"; /** The dashboard API as the frontend sees it. The mock and the HTTP client both implement it. */ @@ -98,14 +98,16 @@ export interface Api { cost(run?: string): Promise; /** The merge queue: every PR with a take or take-fix review at its head, and what it waits on. */ queue(filter: QueueFilter): Promise; - /** Steps, jobs and schedules: everyone reads; run, cancel and schedule are for operators. */ + /** Steps, jobs, the on/off switch and the stage limits: everyone reads; run, cancel, switch and limits are for operators. */ pipeline: { overview(): Promise; jobs(filter: JobFilter): Promise; job(id: number): Promise; run(step: string, params: JobParams): Promise; cancel(id: number): Promise; - schedule(step: string, input: ScheduleInput): Promise; + state(): Promise; + setEnabled(enabled: boolean): Promise; + setLimit(step: string, limit: { perDay: number | null }): Promise; }; /** Every registered model prompt, with the server's commit. */ prompts(): Promise; diff --git a/web/src/api/http.ts b/web/src/api/http.ts index a2676b6c2..fd3def2c7 100644 --- a/web/src/api/http.ts +++ b/web/src/api/http.ts @@ -25,9 +25,9 @@ export function createHttpApi(): Api { const listeners = new Set<() => void>(); const changed = () => listeners.forEach((fn) => fn()); - async function call(method: "GET" | "POST", path: string, body?: unknown): Promise { + async function call(method: "GET" | "POST" | "PUT", path: string, body?: unknown): Promise { const headers: Record = { accept: "application/json" }; - if (method === "POST") { + if (method !== "GET") { // Every /api/ response carries the session's token; a POST before any GET fetches it first. if (!csrf) await call("GET", "/api/me"); headers[CSRF_HEADER] = csrf ?? ""; @@ -72,6 +72,11 @@ export function createHttpApi(): Api { changed(); return v; } + async function put(path: string, body?: unknown): Promise { + const v = await call("PUT", path, body); + changed(); + return v; + } const dec = (id: string, rest = "") => `/api/decisions/${encodeURIComponent(id)}${rest}`; function query(f: DecisionFilter): string { @@ -148,7 +153,9 @@ export function createHttpApi(): Api { job: (id) => get(`/api/pipeline/jobs/${id}`), run: (step, params) => post("/api/pipeline/jobs", { step, params }), cancel: (id) => post(`/api/pipeline/jobs/${id}/cancel`), - schedule: (step, input) => post(`/api/pipeline/schedules/${encodeURIComponent(step)}`, input), + state: () => get("/api/pipeline/state"), + setEnabled: (enabled) => put("/api/pipeline/state", { enabled }), + setLimit: (step, limit) => put(`/api/pipeline/limits/${encodeURIComponent(step)}`, limit), }, prompts: () => get("/api/prompts"), queue: (f) => get(`/api/queue${qs(f)}`), diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 21ed3efea..f46205992 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -606,7 +606,7 @@ export interface CostReport { bucketSize: "hour" | "day"; } -// ---- pipeline (runner jobs, steps, schedules) ------------------------------ +// ---- pipeline (runner jobs, steps, the on/off switch and stage limits) ------------------------------ export type JobState = "queued" | "running" | "done" | "failed" | "cancelled"; @@ -632,7 +632,7 @@ export interface Job { id: number; step: string; params: JobParams; - /** A login, `schedule` or `cli`. */ + /** A login, `pipeline` (the autopilot) or `cli`. */ requestedBy: string; requestedAt: string; state: JobState; @@ -663,19 +663,8 @@ export interface JobFilter { offset?: number; } -export type ScheduleTrigger = "interval" | "after-sync"; - -export interface Schedule { - enabled: boolean; - trigger: ScheduleTrigger; - intervalMinutes: number | null; - params: JobParams; - updatedBy: string | null; - updatedAt: string | null; - lastEnqueuedAt: string | null; -} - -export type ScheduleInput = Pick; +export type StageLimit = { step: string; title: string; perDay: number | null; usedToday: number; pausedReason: string | null }; +export type PipelineState = { enabled: boolean; changedBy: string | null; changedAt: string | null; heartbeat: string | null; limits: StageLimit[] }; export interface PipelineStep { name: string; @@ -687,7 +676,6 @@ export interface PipelineStep { params: StepParam[]; /** null when the step can run; otherwise why not. */ unavailable: string | null; - schedule: Schedule; lastJob: Job | null; }