"use strict"; const test = require("node:test"); const assert = require("node:assert/strict"); const fs = require("node:fs"); const path = require("node:path"); const { AGENT_JOB_GENERATION_SQL, createServerAgentJobPump } = require("../services/server-agent-queue"); const { claimAgentJob, failAgentClaim, publishAgentResult } = require("../AgentWorker/job-store"); const { RUN_TIMEOUT_MS, LIVE_CONCURRENCY, BACKGROUND_CONCURRENCY } = require("../AgentWorker/budgets"); const { AiAgentJobDeadlineExceeded, assertAiAgentJobDeadline } = require("../AgentWorker/run-deadline"); const root = path.join(__dirname, ".."); const read = (name) => fs.readFileSync(path.join(root, name), "utf8"); const index = read("index.js"); const worker = read("AgentWorker/worker.js"); const runner = read("AgentWorker/run-job.js"); const store = read("AgentWorker/job-store.js"); const conversation = read("AgentWorker/conversation.js").replace(/^ {2}(?=\S)/gm, ""); test("the background capacity policy and effective worker ceilings bound queue dispatch", async () => { for (const [waiting, otherRuns, ceiling, expected] of [ [0, 0, undefined, 0], [9, 0, undefined, 200], [10, 0, undefined, 205], [19, 0, undefined, 205], [20, 0, undefined, 210], [20, 12, undefined, 198], [20, 210, undefined, 0], [20, 0, 40, 40], [800, 0, undefined, 500], [300, 0, LIVE_CONCURRENCY, 12], [300, 0, BACKGROUND_CONCURRENCY, 4], ]) { const started = []; let reads = 0; const pump = createServerAgentJobPump({ query: async (sql) => { reads += 1; if (reads === 1) { assert.match(sql, /COUNT\(DISTINCT CASE WHEN status = 'queued' THEN user_id END\)/); assert.match(sql, /COUNT\(CASE WHEN status = 'running' THEN 1 END\)/); return [{ waiting_accounts: String(waiting), running_count: String(otherRuns) }]; } assert.match(sql, new RegExp(`WHERE status = 'queued'\\s+ORDER BY created_at ASC, id ASC LIMIT ${expected}$`)); return Array.from({ length: expected }, (_, index) => ({ id: index + 1 })); }, canPump: () => true, runJob: async (id) => { started.push(id); }, onJobError: (_id, error) => assert.fail(error), onJobSettled: () => {}, maxActive: ceiling, }); await pump(); assert.equal(started.length, expected); assert.equal(reads, expected ? 2 : 1); } }); test("overlapping wake-ups do not overbook and a shrinking limit leaves active runs alone", async () => { let waiting = 10; let finishRead; const blockedRead = new Promise((resolve) => { finishRead = resolve; }); const active = new Map(); let aggregateReads = 0; let nextId = 1; let started = 0; const pump = createServerAgentJobPump({ query: async (sql, params) => { assert.deepEqual(params, [...active.keys()]); if (sql.includes("AS waiting_accounts")) { aggregateReads += 1; if (aggregateReads === 1) await blockedRead; if (active.size) assert.match(sql, /AND id NOT IN \(/); return [{ waiting_accounts: waiting, running_count: 0 }]; } const limit = Number(sql.match(/LIMIT (\d+)$/)[1]); return Array.from({ length: limit }, () => ({ id: nextId++ })); }, canPump: () => true, runJob: (id) => new Promise((resolve) => { started += 1; active.set(id, resolve); }), onJobError: (_id, error) => assert.fail(error), onJobSettled: () => {}, }); const first = pump(); await pump(); assert.equal(aggregateReads, 1); finishRead(); await first; assert.equal(active.size, 205); waiting = 9; await pump(); assert.equal(active.size, 205); for (const [id, finish] of [...active].slice(0, 6)) { active.delete(id); finish(); } await new Promise(setImmediate); await pump(); assert.equal(active.size, 200); assert.equal(started, 206); for (const finish of active.values()) finish(); }); test("only the worker lock holder recovers running jobs and neither process requeues them", () => { const lock = worker.indexOf('SELECT GET_LOCK(?, 0)'); const rejectDuplicate = worker.indexOf('if (Number(lock.acquired) !== 1) throw'); const bootRecovery = worker.indexOf('await recoverInterruptedAgentJobs(db);'); const confirmOwner = worker.indexOf('if (Number(ownership.owned) !== 1'); const periodicRecovery = worker.indexOf('await recoverInterruptedAgentJobs(db, STALE_RUN_SECONDS);'); assert.ok(lock >= 0 && lock < rejectDuplicate && rejectDuplicate < bootRecovery); assert.ok(bootRecovery < confirmOwner && confirmOwner < periodicRecovery); assert.match(worker, /STALE_RUN_SECONDS = Math\.ceil\(RUN_TIMEOUT_MS \/ 1000\) \+ 60/); assert.match(worker, /if \(polling \|\| stopping\) return/); assert.match(worker, /if \(Date\.now\(\) - lastRecovery >= RECOVERY_INTERVAL_MS\)/); assert.doesNotMatch(index, /createServerAgentJobPump\(|recoverInterruptedAgentJobs\(/); assert.doesNotMatch(index + worker + runner + store, /UPDATE ai_agent_jobs SET status = 'queued'/); }); function transactionFixture(answer, generation = "3") { const events = []; const connection = { beginTransaction: async () => { events.push("begin"); }, commit: async () => { events.push("commit"); }, rollback: async () => { events.push("rollback"); }, release: () => { events.push("release"); }, execute: async (sql, params) => { if (sql.includes("FROM ai_agent_worker_state")) { assert.match(sql, /FOR UPDATE/); return [[{ enabled: 1, generation }]]; } return answer(sql, params); }, }; return { db: { pool: { getConnection: async () => connection } }, events }; } test("claim is queued-only and generation-scoped and creates a fresh attempt token", async () => { let attempt; const { db, events } = transactionFixture((sql, params) => { if (sql.includes("SELECT running.id")) return [[]]; if (sql.includes("UPDATE ai_agent_jobs")) { assert.match(sql, /SET status = 'running', started_at = NOW\(\)/); assert.ok(sql.includes(`claim_token = ?, feature_generation = ? WHERE id = ? AND status = 'queued' AND ${AGENT_JOB_GENERATION_SQL}`)); assert.match(AGENT_JOB_GENERATION_SQL, /\(auto_approve_file_edits = FALSE AND feature_generation = \?\)/); assert.match(AGENT_JOB_GENERATION_SQL, /auto_approve_file_edits = TRUE AND auto_file_edit_generation = \?\s+AND \(\(status = 'queued' AND feature_generation IS NULL\)/); [attempt] = params; assert.match(attempt, /^[0-9a-f-]{36}$/); assert.deepEqual(params.slice(1), ["3", 17, "3", "3"]); return [{ affectedRows: 1 }]; } assert.match(sql, /WHERE id = \? AND claim_token = \?/); assert.deepEqual(params, [17, attempt]); return [[{ claim_token: attempt }]]; }); assert.deepEqual(await claimAgentJob(db, 17, "3"), { claim_token: attempt }); assert.deepEqual(events, ["begin", "commit", "release"]); const stale = transactionFixture(() => assert.fail("stale generation must not claim"), "4"); assert.equal(await claimAgentJob(stale.db, 17, "3"), null); }); test("cancelled or superseded jobs cannot publish a reply, and failure writes use the same fence", async () => { const row = { id: 17, chat_id: 11, user_id: 2, claim_token: "attempt", feature_generation: "3" }; const { db } = transactionFixture((sql, params) => { if (sql.includes("SELECT id FROM ai_chats")) { assert.deepEqual(params, [11, 2]); return [[{ id: 11 }]]; } assert.match(sql, /WHERE job\.id = \? AND job\.status = 'running' AND job\.claim_token = \? AND job\.feature_generation = \?/); assert.match(sql, /account\.suspended = FALSE/); assert.match(sql, /account\.session_epoch = job\.account_epoch/); assert.deepEqual(params, [17, "attempt", "3"]); return [{ affectedRows: 0 }]; }); assert.equal(await publishAgentResult(db, row, { content: "late" }, "fixture", new AbortController().signal), false); await failAgentClaim({ query: async (sql, params) => { assert.match(sql, /WHERE id = \? AND status = 'running' AND claim_token = \? AND feature_generation = \?/); assert.deepEqual(params, ["interrupted", 17, "attempt", "3"]); } }, row, "interrupted"); }); test("a failed transcript insert rolls back completion, and Planner completion follows publication", async () => { const row = { id: 17, chat_id: 11, user_id: 2, claim_token: "attempt", feature_generation: "3" }; let statusUpdated = false; const { db, events } = transactionFixture((sql) => { if (sql.includes("SELECT id FROM ai_chats")) return [[{ id: 11 }]]; if (sql.includes("UPDATE ai_agent_jobs")) { statusUpdated = true; return [{ affectedRows: 1 }]; } assert.match(sql, /INSERT INTO ai_messages/); assert.equal(statusUpdated, true); throw new Error("fixture database failure"); }); await assert.rejects(publishAgentResult(db, row, { content: "reply" }, "fixture", new AbortController().signal), /fixture database failure/); assert.deepEqual(events, ["begin", "rollback", "release"]); assert.match(runner, /const published = await publishAgentResult[^\n]+\n\s+if \(!published\) throw[^\n]+\n\s+if \(context\.clamped && !result\.automaticEditFailed\) await call\("plannerDone"\)/); }); test("an incomplete automatic Planner edit is terminally failed, held and retains the assistant receipt", async () => { const row = { id: 17, chat_id: 11, user_id: 2, claim_token: "attempt", feature_generation: "3", source: "planner_send", server_id: "6", server_name: "fixture", source_ref: "12", account_epoch: 1, read_only: 0, auto_approve_file_edits: 1 }; const receipt = "The edit was not confirmed. No further edits were sent."; const { db, events } = transactionFixture((sql, params) => { if (sql.includes("FROM server_planner_items")) { assert.match(sql, /FOR UPDATE/); assert.deepEqual(params, ["12", "fixture"]); events.push("lock-item"); return [[{ id: 12 }]]; } if (sql.includes("SELECT id FROM ai_chats")) return [[{ id: 11 }]]; if (sql.startsWith("UPDATE server_planner_items")) { assert.deepEqual(params, [17, "12", "attempt"]); events.push("hold-item"); } if (sql.includes("UPDATE ai_agent_jobs job")) { assert.match(sql, /SET status = 'failed'.*error = 'agent_automatic_edits_incomplete'/); assert.match(sql, /job\.status = 'running' AND job\.claim_token = \?/); } if (sql.includes("INSERT INTO ai_messages")) { assert.equal(params[1], receipt); return [{ insertId: 42 }]; } if (sql.includes("SET result_message_id")) assert.deepEqual(params, [42, null, row.id]); return [{ affectedRows: 1 }]; }); assert.equal(await publishAgentResult(db, row, { content: receipt, automaticEditFailed: true }, "fixture", new AbortController().signal), true); assert.deepEqual(events, ["begin", "lock-item", "hold-item", "commit", "release"]); }); test("the worker stamps one full-run deadline at claim and propagates cancellation", () => { assert.equal(RUN_TIMEOUT_MS, 180_000); assert.throws(() => assertAiAgentJobDeadline({ aiAgentJobDeadlineMs: Date.now() - 1 }), (error) => error instanceof AiAgentJobDeadlineExceeded && error.status === 504); assert.throws(() => assertAiAgentJobDeadline({ aiAgentChatSignal: AbortSignal.abort() }), { name: "AbortError" }); assert.match(runner, /await claimAgentJob\([^)]+\);\s+if \(!row\) return;\s+const deadline = Date\.now\(\) \+ RUN_TIMEOUT_MS;/); assert.match(runner, /AbortSignal\.any\(\[controller\.signal, AbortSignal\.timeout\(RUN_TIMEOUT_MS\)\]\)/); assert.match(runner, /aiAgentChatSignal: signal, aiAgentJobDeadlineMs: deadline/); assert.match(runner, /withProviderBudget\(provider\.provider, lane, signal,/); assert.doesNotMatch(index + conversation, /function assertAiAgentJobDeadline\(/); }); function checkedBody(anchor, minimum, multiline = false) { const start = conversation.indexOf(anchor); assert.notEqual(start, -1, anchor); const bodyStart = multiline ? conversation.indexOf("}) {", start) : start; const end = conversation.indexOf("\n}", bodyStart); assert.ok(end > bodyStart, anchor); const body = conversation.slice(start, end); assert.ok((body.match(/assertAiAgentJobDeadline\(req\);/g) || []).length >= minimum, anchor); return body; } test("every provider and tool loop still checks the shared deadline", () => { for (const protocol of ["OpenAi", "Cohere", "Google", "Anthropic"]) { checkedBody(`async function completeAiChatConversationWith${protocol}NativeTools({`, 2, true); } const generic = checkedBody("async function completeAiChatConversation({ req,", 4); assert.match(generic, /await requestBotToolPlanRepair\(provider, settings, model, workingMessages, content, req\);/); checkedBody("async function requestBotToolPlanRepair", 1); });