PEP-203: подбор специалиста не держит тик вачдога
specialistHold звал модель по очереди для каждой готовой задачи бэклога прямо в тике: на живой 125 задач — вачдог не писал heartbeat, выкатка откатывалась. Теперь тик читает только готовые подборы, недостающие считаются в фоне по одному и только для первых трёх задач очереди; пока подбор считается, такая задача ждёт. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
061ae93a48
commit
c2b5a46ee6
@ -43,17 +43,48 @@ export async function ensureTaskMatch(db: Db, taskId: number): Promise<TeamMatch
|
||||
}
|
||||
}
|
||||
|
||||
// PEP-203: the match is a model call of up to a minute; the watchdog's tick must not wait for it.
|
||||
// The tick only reads finished matches; missing ones are computed in the background, one at a
|
||||
// time, and only for the head of the queue (HOLD_SCAN stories) — those wait until it is known.
|
||||
const HOLD_SCAN = 3;
|
||||
const inflight = new Map<number, Promise<unknown>>();
|
||||
|
||||
function matchInBackground(db: Db, taskId: number): void {
|
||||
if (inflight.has(taskId) || inflight.size >= 1) return;
|
||||
const p = ensureTaskMatch(db, taskId)
|
||||
.catch(() => null)
|
||||
.finally(() => inflight.delete(taskId));
|
||||
inflight.set(taskId, p);
|
||||
}
|
||||
|
||||
/** Tests: wait for the background matches started so far. */
|
||||
export async function teamMatchesSettled(): Promise<void> {
|
||||
while (inflight.size) await Promise.all([...inflight.values()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stories the dispatcher must hold back: they fit a specialist who is busy right now and have
|
||||
* not waited longer than the platform's threshold. Not a failure — nobody is told.
|
||||
* not waited longer than the platform's threshold, or their match is still being computed
|
||||
* (head of the queue only). Not a failure — nobody is told.
|
||||
*/
|
||||
export async function specialistHold<T extends { id: number }>(db: Db, list: T[], now = new Date()): Promise<Set<number>> {
|
||||
const held = new Set<number>();
|
||||
if (!list.length || !(await listSpecialists(db)).length) return held;
|
||||
const { waitMin } = await getTeamSettings(db);
|
||||
let unknown = 0;
|
||||
for (const t of list) {
|
||||
const match = await ensureTaskMatch(db, t.id);
|
||||
if (!match?.agentId) continue;
|
||||
const match = await getTeamMatch(db, t.id);
|
||||
if (!match) {
|
||||
if (unknown >= HOLD_SCAN) continue;
|
||||
// The story already had an agent: the same one goes on, nothing to decide.
|
||||
const [prior] = await db.select({ id: sessions.id }).from(sessions).where(and(eq(sessions.taskId, t.id), isNotNull(sessions.agentId))).limit(1);
|
||||
if (prior) continue;
|
||||
unknown++;
|
||||
matchInBackground(db, t.id);
|
||||
held.add(t.id);
|
||||
continue;
|
||||
}
|
||||
if (!match.agentId) continue;
|
||||
const [a] = await db.select().from(agents).where(eq(agents.id, match.agentId));
|
||||
if (!a || !isSpecialist(a) || !(await agentIsBusy(db, a.id))) continue;
|
||||
const since = match.waitSince ?? now.getTime();
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
// mock-team (PEP-183): stands in for `claude -p` as the specialist matcher. The scenario file
|
||||
// (MOCK_TEAM_SCENARIO, JSON): { "rules": [{ "match": "безопасн", "agent": "Страж ИБ", "reason": "…" }], "fail": false }.
|
||||
// (MOCK_TEAM_SCENARIO, JSON): { "rules": [{ "match": "безопасн", "agent": "Страж ИБ", "reason": "…" }], "fail": false, "slowMs": 0 }.
|
||||
// The first rule whose regexp matches the story's title ("Задача: …") wins; none → agent null.
|
||||
// Every call is appended to <scenario>.log.jsonl.
|
||||
import { appendFileSync, existsSync, readFileSync } from "node:fs";
|
||||
@ -7,6 +7,8 @@ import { appendFileSync, existsSync, readFileSync } from "node:fs";
|
||||
interface Scenario {
|
||||
rules?: Array<{ match: string; agent: string | null; reason?: string }>;
|
||||
fail?: boolean;
|
||||
/** Answer after this many ms (a slow model). */
|
||||
slowMs?: number;
|
||||
}
|
||||
const file = process.env.MOCK_TEAM_SCENARIO;
|
||||
const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
|
||||
@ -17,6 +19,7 @@ if (!process.argv.includes("-p")) {
|
||||
console.error("mock-team: expected -p (non-interactive print mode)");
|
||||
process.exit(2);
|
||||
}
|
||||
if (sc.slowMs) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, sc.slowMs);
|
||||
if (sc.fail) {
|
||||
console.error("mock-team: API Error: 529 overloaded");
|
||||
process.exit(1);
|
||||
|
||||
@ -53,6 +53,9 @@ describe("Специалисты и задачи по профилю", () => {
|
||||
const t = await next.task();
|
||||
const [proj] = await core.listProjects(db).then((l) => l.filter((x) => x.key === next.key));
|
||||
const now = new Date();
|
||||
// PEP-203: the match is computed in the background; until then the head of the queue waits.
|
||||
assert.deepEqual([...(await runner.specialistHold(db, [t], now))], [t.id], "the match is being computed");
|
||||
await runner.teamMatchesSettled();
|
||||
assert.deepEqual([...(await runner.specialistHold(db, [t], now))], [t.id], "waits for the busy specialist");
|
||||
assert.deepEqual([...(await runner.specialistHold(db, [t], new Date(now.getTime() + 20 * 60_000)))], [t.id], "still within 30 min");
|
||||
assert.deepEqual([...(await runner.specialistHold(db, [t], new Date(now.getTime() + 31 * 60_000)))], [], "after the threshold it is free to go");
|
||||
@ -66,6 +69,29 @@ describe("Специалисты и задачи по профилю", () => {
|
||||
await core.setTeamSettings(db, { waitMin: 30 });
|
||||
});
|
||||
|
||||
test("Scenario: длинный бэклог — тик не ждёт модель, подбор только для головы очереди (PEP-203)", async () => {
|
||||
scenario({ rules: [{ match: "безопасн", agent: "Страж ИБ", reason: "про безопасность" }], slowMs: 400 });
|
||||
const list = [];
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const p = await project({ turns: [[{ say: "ok" }]] });
|
||||
await retitle(p, `Задача ${i}`);
|
||||
list.push(await p.task());
|
||||
}
|
||||
const t0 = Date.now();
|
||||
const held = await runner.specialistHold(db, list);
|
||||
assert.ok(Date.now() - t0 < 300, "the tick does not wait for the model");
|
||||
assert.deepEqual([...held], list.slice(0, 3).map((t) => t.id), "only the head of the queue waits");
|
||||
await runner.teamMatchesSettled();
|
||||
for (let i = 0; i < 3 && !(await core.getTeamMatch(db, list[2]!.id)); i++) {
|
||||
await runner.specialistHold(db, list);
|
||||
await runner.teamMatchesSettled();
|
||||
}
|
||||
for (const t of list.slice(0, 3)) assert.ok(await core.getTeamMatch(db, t.id), "head matched");
|
||||
for (const t of list.slice(3)) assert.equal(await core.getTeamMatch(db, t.id), null, "the rest is not matched yet");
|
||||
assert.deepEqual([...(await runner.specialistHold(db, list))], list.slice(3, 6).map((t) => t.id), "the next three are now the unknown head");
|
||||
await runner.teamMatchesSettled();
|
||||
});
|
||||
|
||||
test("Scenario: стёрли специализацию — следующая задача идёт как универсалу", async () => {
|
||||
await core.updateAgent(db, guard.id, { character: "" });
|
||||
await core.updateAgent(db, plain.id, { disabled: true });
|
||||
|
||||
Loading…
Reference in New Issue
Block a user