peppa/packages/testkit/test/rotation.test.ts
Асель 5f738942e0 PEP-149: remaining old tests follow the new end-of-turn behaviour
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-16 13:06:17 +05:00

229 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-39: a runner that hits a usage limit (or gets close to it) moves to another usable
// subscription of its pool at a turn boundary. Mock CLIs hit the limit only on a login that
// contains a marker (`limit.credential`), like the real one hits it on one account.
import assert from "node:assert/strict";
import { after, before, describe, test } from "node:test";
import { events } from "@peppa/db";
import { core, db, project, runner, setDefaultOwner, teardown, tick, waitFor } from "./helpers.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
type User = Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
let pm: User;
const CHAT = 5550039;
before(async () => {
pm = await core.upsertUserFromGitea(db, { id: 39, login: "mock-pm-39" }, { access_token: "x" });
db.$client.prepare("UPDATE users SET telegram_chat_id = ?, telegram_user_id = ? WHERE id = ?").run(CHAT, CHAT, pm.id);
setDefaultOwner(pm.id);
});
after(teardown);
const TOKEN = (tag: string) => `sk-ant-oat01-mock${"x".repeat(24)}${tag}`;
const claudeSub = (name: string, tag: string) => runner.addSubscription(db, { provider: "claude", name, method: "token", secret: TOKEN(tag), createdBy: pm.id });
const tail = (tag: string) => `…${TOKEN(tag).slice(-4)}`;
const sess = (id: number) => core.getSession(db, id);
const sub = (id: number) => core.getSubscription(db, id);
const tickAt = (now: Date) => runner.tick(db, { intervalMs: 0, stallMs: 3_600_000, now });
const starts = (p: { log(): Array<{ ev: string; [k: string]: unknown }> }) => p.log().filter((e) => e.ev === "start");
let seq = 0;
const poolFor = async (key: string, ids: number[]) => {
const pool = await core.createPool(db, { name: `Пул ${++seq}`, subscriptionIds: ids });
await core.setProjectPool(db, (await core.getProject(db, key)).id, pool.id);
return pool;
};
const switches = async (sid: number) =>
(await db.select().from(events)).filter((e) => e.sessionId === sid && e.type === runner.SWITCH_EVENT).map((e) => e.payload as Record<string, unknown>);
describe("Переключение на свободную подписку пула", () => {
test("Есть свободная подписка: тот же разговор на «B», подписка «A» — «лимит до …», PM получает сообщение", async () => {
const a = await claudeSub("Rot A", "rotlimA");
const b = await claudeSub("Rot B", "rotokB");
const p = await project({ turns: [[{ limit: { resetInSec: 3600, credential: "rotlimA" } }]], resumeTurns: [[{ say: "Продолжаю на B." }]] });
await poolFor(p.key, [a.id, b.id]);
const sid = await p.start();
assert.equal((await sess(sid)).subscriptionId, a.id);
await p.waitStatus(sid, "rate_limited");
const s = await sess(sid);
assert.equal(s.rotateReason, "limit");
assert.equal((await p.pending(sid)).length, 0, "no «остановлен по лимиту» ping — a switch is coming");
const la = await sub(a.id);
assert.equal(la.status, "limited");
assert.ok(Math.abs(la.limitedUntil!.getTime() - (Date.now() + 3600_000)) < 120_000, "limited until the reset time");
await tick();
const start = await p.waitLog("relaunched on B", (e) => e.ev === "start" && e.gen === "2");
assert.equal(start.resume, s.conversationId, "continues the same conversation");
assert.equal(start.oauthToken, tail("rotokB"));
await p.waitLog("resumed turn", (e) => e.ev === "action" && JSON.stringify(e.action).includes("Продолжаю на B"));
const after = await sess(sid);
assert.equal(after.subscriptionId, b.id);
assert.equal(after.subscriptionName, "Rot B");
assert.equal(after.subscriptionSwitches, 1);
assert.equal(after.rotateReason, null);
const [ev] = await switches(sid);
assert.deepEqual({ from: ev!.fromName, to: ev!.toName, reason: ev!.reason, carried: ev!.carried }, { from: "Rot A", to: "Rot B", reason: "limit", carried: "resume" });
const msg = await core.getOutbox(db, `rot:${sid}:g2:${CHAT}`);
assert.match(String((msg!.params as { text: string }).text), /перешёл на другую подписку \(лимит до \d\d:\d\d\), продолжает тот же разговор/);
// A new runner of the project doesn't start on the limited subscription.
const p2 = await project({ turns: [[{ say: "ok" }]] });
await poolFor(p2.key, [a.id, b.id]);
const s2 = await p2.start();
assert.equal((await sess(s2)).subscriptionId, b.id);
for (const id of [sid, s2]) await runner.stopSession(db, id);
});
test("Свободных нет: ждёт сброса и продолжает сам; освободилась подписка — переключается на неё", async () => {
const a = await claudeSub("Solo A", "sololimA");
const p = await project({ turns: [[{ limit: { resetInSec: 120, credential: "sololimA" } }], [{ say: "Сам после сброса." }]] });
const pool = await poolFor(p.key, [a.id]);
const sid = await p.start();
await p.waitStatus(sid, "rate_limited");
const s = await sess(sid);
assert.equal(s.rotateReason, null);
assert.match((await p.waitQuestion(sid, "attention")).text, /продолжит в \d\d:\d\d сам/);
await tick();
assert.equal((await sess(sid)).subscriptionId, a.id, "nowhere to go — stays");
await tickAt(new Date(s.resumeAt!.getTime() + 1000));
await p.waitLog("continued after reset", (e) => e.ev === "prompt" && String(e.prompt).includes("Лимит сброшен"));
assert.equal((await sess(sid)).subscriptionId, a.id);
await runner.stopSession(db, sid);
// Same, but a subscription is added to the pool while the runner waits.
const p2 = await project({ turns: [[{ limit: { resetInSec: 3600, credential: "sololimA" } }]], resumeTurns: [[{ say: "На новой." }]] });
const a2 = await claudeSub("Solo A2", "sololimA2");
await core.updatePool(db, pool.id, { subscriptionIds: [a2.id] });
await core.setProjectPool(db, (await core.getProject(db, p2.key)).id, pool.id);
const sid2 = await p2.start();
await p2.waitStatus(sid2, "rate_limited");
const fresh = await claudeSub("Solo C", "soloC");
await core.updatePool(db, pool.id, { subscriptionIds: [a2.id, fresh.id] });
await tick();
await p2.waitLog("switched to the new one", (e) => e.ev === "start" && e.gen === "2");
assert.equal((await sess(sid2)).subscriptionId, fresh.id);
await runner.stopSession(db, sid2);
});
test("Codex: новый запуск на второй подписке без resume, с подсказкой восстановить контекст", async () => {
const c1 = await runner.addSubscription(db, { provider: "codex", name: "Codex 1", method: "api_key", secret: "mock-limit-key-rot1", createdBy: pm.id });
const c2 = await runner.addSubscription(db, { provider: "codex", name: "Codex 2", method: "api_key", secret: "mock-openai-key-rot2", createdBy: pm.id });
const p = await project({ turns: [[{ limit: { resetInSec: 3600, credential: "limit" } }, { say: "Начал заново." }]] });
await poolFor(p.key, [c1.id, c2.id]);
const sid = await p.start({ provider: "codex" });
assert.equal((await sess(sid)).subscriptionId, c1.id);
await p.waitLog("banner", (e) => e.ev === "limit");
await waitFor("limit recorded", async () => {
await tick();
return (await sess(sid)).generation === 2 || (await sess(sid)).rotateReason === "limit";
});
await tick();
const start = await p.waitLog("relaunched", (e) => e.ev === "start" && e.gen === "2");
assert.equal(start.resume, null, "Codex threads don't move between accounts");
assert.equal(start.codexHome, runner.codexHome(c2.id));
assert.match(String((start.argv as string[]).at(-1)), /Восстанови контекст/);
const after = await sess(sid);
assert.equal(after.subscriptionId, c2.id);
assert.equal((await switches(sid))[0]!.carried, "fresh");
assert.match(String(((await core.getOutbox(db, `rot:${sid}:g2:${CHAT}`))!.params as { text: string }).text), /ChatGPT не переносит разговор/);
await runner.stopSession(db, sid);
});
});
describe("Порог использования", () => {
test("Предупреждение: ход доживает до конца без подталкивания, затем тот же разговор на свободной «B»", async () => {
const a = await claudeSub("Warn A", "warnA");
const b = await claudeSub("Warn B", "warnB");
const p = await project({ turns: [[{ warn: 90 }, { work: 2500 }, { say: "Ход закончен." }]], resumeTurns: [[{ say: "Дальше на B." }]] });
await poolFor(p.key, [a.id, b.id]);
const sid = await p.start();
await p.waitLog("warning on screen", (e) => e.ev === "warn");
await waitFor("threshold noticed", async () => {
await tick();
return (await sess(sid)).rotateReason === "threshold";
});
await p.waitStatus(sid, "idle");
assert.equal((await p.pending(sid)).length, 0, "no «закончила ход» ping");
assert.equal((await sub(a.id)).status, "active", "a warning is not a limit");
await tick();
const start = await p.waitLog("relaunched on B", (e) => e.ev === "start" && e.gen === "2");
assert.equal(start.oauthToken, tail("warnB"));
assert.ok(start.resume);
assert.equal((await switches(sid))[0]!.reason, "threshold");
await runner.stopSession(db, sid);
});
test("Предупреждение ниже порога ничего не меняет", () => {
assert.equal(runner.usageWarning("You've used 50% of your weekly limit"), false);
assert.equal(runner.usageWarning("You've used 92% of your weekly limit"), true);
assert.equal(runner.usageWarning("Approaching usage limit · resets at 5pm"), true);
});
});
describe("Предохранители", () => {
test("Предел переключений: после 3 за час раннер ждёт сброса, а не переключается", async () => {
const a = await claudeSub("Cap A", "caplimA");
const b = await claudeSub("Cap B", "capB");
const p = await project({ turns: [[{ say: "работаю" }], [{ limit: { resetInSec: 3600, credential: "caplimA" } }]] });
await poolFor(p.key, [a.id, b.id]);
const sid = await p.start();
await p.waitStatus(sid, "idle");
for (let i = 0; i < runner.maxRotationsPerHour(); i++) await core.logSessionEvent(db, await sess(sid), runner.SWITCH_EVENT, { reason: "limit" });
await runner.sendToSession(db, sid, "дальше");
await p.waitStatus(sid, "rate_limited");
assert.equal((await sess(sid)).rotateReason, null);
assert.match((await p.waitQuestion(sid, "attention")).text, /продолжит в \d\d:\d\d сам/);
await tick();
assert.equal((await sess(sid)).subscriptionId, a.id);
assert.equal((await sess(sid)).generation, 1);
await runner.stopSession(db, sid);
});
test("Выключено (PEPPA_ROTATE=off): нет переключений", async () => {
const a = await claudeSub("Off A", "offA");
const b = await claudeSub("Off B", "offB");
const p = await project({ turns: [] });
await poolFor(p.key, [a.id, b.id]);
const s = await core.createSession(db, { projectId: (await core.getProject(db, p.key)).id, subscriptionId: a.id });
process.env.PEPPA_ROTATE = "off";
try {
assert.equal(await runner.planRotation(db, await sess(s.id), "limit"), null);
} finally {
delete process.env.PEPPA_ROTATE;
}
assert.equal((await runner.planRotation(db, await sess(s.id), "limit"))?.id, b.id);
await core.updateSession(db, s.id, { status: "done" });
});
});
describe("Справедливость между проектами", () => {
test("Проект с 2 подписками пула не получает свободную, пока другой проект ждёт сброса", async () => {
const [a, b, c, d] = [await claudeSub("Fair A", "fairA"), await claudeSub("Fair B", "fairB"), await claudeSub("Fair C", "fairC"), await claudeSub("Fair D", "fairD")];
const pool = await core.createPool(db, { name: "Общий", subscriptionIds: [a.id, b.id, c.id, d.id] });
const x = await core.getProject(db, (await project({ turns: [] })).key);
const y = await core.getProject(db, (await project({ turns: [] })).key);
for (const pr of [x, y]) await core.setProjectPool(db, pr.id, pool.id);
// Y waits for a limit reset on A.
const ys = await core.createSession(db, { projectId: y.id, subscriptionId: a.id });
await core.updateSession(db, ys.id, { status: "rate_limited", resumeAt: new Date(Date.now() + 3600_000) });
await core.markSubscriptionLimited(db, a.id, new Date(Date.now() + 3600_000));
// X holds B and C.
const x1 = await core.createSession(db, { projectId: x.id, subscriptionId: b.id });
const x2 = await core.createSession(db, { projectId: x.id, subscriptionId: c.id });
for (const s of [x1, x2]) await core.updateSession(db, s.id, { status: "running" });
// A new X runner shares a busy subscription instead of taking the free D.
assert.equal((await core.pickSubscription(db, { projectId: x.id }))!.id, b.id);
// X can't move onto D either; the waiting Y gets it.
assert.notEqual((await core.rotationCandidate(db, { projectId: x.id, provider: "claude", subscriptionId: b.id }))?.id, d.id);
assert.equal((await core.rotationCandidate(db, { projectId: y.id, provider: "claude", subscriptionId: a.id }))?.id, d.id);
// No queue → the free subscription is X's.
await core.updateSession(db, ys.id, { status: "done" });
assert.equal((await core.pickSubscription(db, { projectId: x.id }))!.id, d.id);
const view = (await core.listSubscriptions(db)).find((s) => s.id === b.id)!;
assert.deepEqual(view.projectSessions, [{ key: x.key, n: 1 }]);
for (const s of [x1, x2]) await core.updateSession(db, s.id, { status: "done" });
});
});