PEP-209: пустой SET в updateTask/updateSession/updateGoal, один агент на общую рабочую копию
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
401c64d2f0
commit
721d4324b0
@ -70,7 +70,9 @@ export interface GoalPatch {
|
||||
}
|
||||
|
||||
export async function updateGoal(db: Db, projectId: number, goalId: number, patch: GoalPatch): Promise<Goal> {
|
||||
await getGoal(db, projectId, goalId);
|
||||
const cur = await getGoal(db, projectId, goalId);
|
||||
// PEP-209: nothing to change → no empty SET (drizzle: «No values to set»).
|
||||
if (!Object.values(patch).some((v) => v !== undefined)) return cur;
|
||||
const [row] = await db.update(goals).set(patch).where(and(eq(goals.id, goalId), eq(goals.projectId, projectId))).returning();
|
||||
return row!;
|
||||
}
|
||||
|
||||
@ -97,6 +97,12 @@ export async function updateSession(
|
||||
id: number,
|
||||
patch: Partial<Pick<Session, "status" | "tmuxName" | "conversationId" | "generation" | "autoNudges" | "lastActivityAt" | "endedAt" | "resumeAt" | "limitProbeMin" | "limitResumes" | "limitResumesDay" | "limitResumedAt" | "subscriptionId" | "rotateReason" | "name" | "workspacePath" | "taskId" | "watchState" | "hostId" | "container" | "provider">>,
|
||||
): Promise<Session> {
|
||||
// PEP-209: nothing to change → no empty SET (drizzle: «No values to set»).
|
||||
if (!Object.values(patch).some((v) => v !== undefined)) {
|
||||
const [cur] = await db.select().from(sessions).where(eq(sessions.id, id));
|
||||
if (!cur) throw new PeppaError(`Session #${id} not found`);
|
||||
return cur;
|
||||
}
|
||||
const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning();
|
||||
if (!row) throw new PeppaError(`Session #${id} not found`);
|
||||
if (patch.status) await notify(db, { type: "session_updated", sessionId: id });
|
||||
|
||||
@ -219,7 +219,14 @@ export interface TaskPatch {
|
||||
/** `login`: the person who changed it from the web (PEP-32: authors in Activity). */
|
||||
export async function updateTask(db: Db, ref: TaskRef, patch: TaskPatch, sessionId?: number, login?: string): Promise<Task> {
|
||||
if (patch.goalId != null) await getGoal(db, ref.project.id, patch.goalId);
|
||||
const [task] = await db.update(tasks).set(patch).where(eq(tasks.id, ref.task.id)).returning();
|
||||
// PEP-209: a patch of undefined fields only (MCP update_task with nothing but `status: review` while
|
||||
// the checks run) — drizzle refuses an empty SET («No values to set»): nothing to write, the story as it is.
|
||||
const defined = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== undefined)) as TaskPatch;
|
||||
if (!Object.keys(defined).length) {
|
||||
const [cur] = await db.select().from(tasks).where(eq(tasks.id, ref.task.id));
|
||||
return cur!;
|
||||
}
|
||||
const [task] = await db.update(tasks).set(defined).where(eq(tasks.id, ref.task.id)).returning();
|
||||
const changed = Object.fromEntries(
|
||||
Object.entries(patch).filter(([k, v]) => v !== undefined && ref.task[k as keyof Task] !== v),
|
||||
);
|
||||
|
||||
@ -34,7 +34,7 @@ import { wakeOnGreen } from "./ci-feedback.ts";
|
||||
import { moveTask } from "./flow.ts";
|
||||
import { LIMIT_REQUEST, limitHintKey, limitOver, TURN_RETRY_MAX, type LimitHint } from "./limit-delay.ts";
|
||||
import { onAnswer, resolveTaskById, sendToSession } from "./sessions.ts";
|
||||
import { restartAgent } from "./stuck-tasks.ts";
|
||||
import { restartAgent, sharedCopyBusy } from "./stuck-tasks.ts";
|
||||
import { requestFromLimitAnswer } from "./subscription-request.ts";
|
||||
|
||||
type Log = (m: string) => void;
|
||||
@ -267,6 +267,9 @@ async function sweep(db: Db, d: PlatformDelay, now: number, log: Log, commit: st
|
||||
// platform — the error may be fixed since (Codex `danger-full-access`, `account/read failed`):
|
||||
// the card goes, the restart count is reset and the story is tried again.
|
||||
if (STALE_AFTER_RELEASE.includes(d.reason) && d.exhausted && commit && d.commit !== commit) {
|
||||
// One agent per shared working copy (PEP-209): the card stays until the copy is free.
|
||||
const [last] = (await listSessions(db, { taskId: ref.task.id })).sort((a, b) => b.id - a.id);
|
||||
if (await sharedCopyBusy(db, ref, last ?? null)) return;
|
||||
await clear();
|
||||
await retryAfterRelease(db, ref, log);
|
||||
return;
|
||||
|
||||
@ -27,6 +27,7 @@ import {
|
||||
pendingQuestions,
|
||||
pendingReview,
|
||||
platformDelay,
|
||||
resolveRunnerSettings,
|
||||
prGate,
|
||||
setSetting,
|
||||
taskPrNumber,
|
||||
@ -149,6 +150,20 @@ export async function restartAgent(db: Db, ref: TaskRef, s: SessionView | null,
|
||||
await resumeSession(db, s.id, { prompt });
|
||||
}
|
||||
|
||||
/**
|
||||
* PEP-209: the agent would run in a working copy another agent of the project works in right now
|
||||
* (workspace «shared» — QLFW had 8–10 agents switching each other's branches). One agent per copy:
|
||||
* the healing waits its turn. Idle agents don't touch git; a separate host has its own clone.
|
||||
*/
|
||||
export async function sharedCopyBusy(db: Db, ref: TaskRef, s: SessionView | null): Promise<boolean> {
|
||||
if (s?.hostId) return false;
|
||||
const rs = s ? null : await resolveRunnerSettings(db, ref.project.id, ref.task.id);
|
||||
const shared = s ? !s.workspacePath : rs!.workspace !== "worktree" && rs!.isolation === "none" && !rs!.hosts.length;
|
||||
if (!shared) return false;
|
||||
return (await listSessions(db, { active: true, projectId: ref.project.id })).some((x) => x.id !== s?.id && !x.workspacePath && !x.hostId && WORKING.includes(x.status));
|
||||
}
|
||||
const WORKING = ["starting", "running"];
|
||||
|
||||
const STOPPED = ["idle", "waiting_input", "done", "failed"];
|
||||
/** Delays other than `stuck` whose own path still works on the story. */
|
||||
const OTHER_PATHS = ["agent", "limit", "checks", "start", "switch", "turn", "accept", "ci"];
|
||||
@ -224,6 +239,14 @@ async function healOne(db: Db, ref: TaskRef, delays: Awaited<ReturnType<typeof l
|
||||
log(`${ref.key}: stuck — ${attempts} attempts failed, the superadmin is asked`);
|
||||
return true;
|
||||
}
|
||||
if (await sharedCopyBusy(db, ref, s)) {
|
||||
// Not an attempt: the story waits for the shared working copy, the owner sees when it is tried again.
|
||||
const at = now + STUCK_RETRY_MIN[0]! * 60_000;
|
||||
if (heal) await setSetting(db, healKey(ref.task.id), { ...heal, nextAt: at });
|
||||
await platformDelay(db, scope, { reason: "stuck", state: "queued", quiet: true, attempts: attempts, retryAt: at, details: m("⏳ {key}: ждёт, пока освободится общая рабочая копия проекта", { key: ref.key }), action: d.reason, now: new Date(now), log });
|
||||
log(`${ref.key}: stuck (${d.reason}) — the shared working copy is busy, waits its turn`);
|
||||
return false;
|
||||
}
|
||||
let action: string = d.reason;
|
||||
try {
|
||||
await restartAgent(db, ref, s, d.agent);
|
||||
|
||||
@ -85,4 +85,5 @@ export const acceptScreen: Dict = {
|
||||
"✖️ Закрыть": "✖️ Close",
|
||||
"📤 Перевести на ревью": "📤 Move to review",
|
||||
"Закрыть": "Close",
|
||||
"⏳ {key}: ждёт, пока освободится общая рабочая копия проекта": "⏳ {key}: waits for the project's shared working copy to be free",
|
||||
};
|
||||
|
||||
@ -85,4 +85,5 @@ export const acceptScreen: Dict = {
|
||||
"✖️ Закрыть": "✖️ Жабу",
|
||||
"📤 Перевести на ревью": "📤 Тексеруге беру",
|
||||
"Закрыть": "Жабу",
|
||||
"⏳ {key}: ждёт, пока освободится общая рабочая копия проекта": "⏳ {key}: жобаның ортақ жұмыс көшірмесі босағанын күтуде",
|
||||
};
|
||||
|
||||
@ -8,6 +8,10 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { after, before, describe, test } from "node:test";
|
||||
import { core, db, project, runner, setDefaultOwner, teardown, waitFor } from "./helpers.ts";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||
|
||||
const { createAgentServer } = await import("@peppa/mcp/agent");
|
||||
import { MockGitea } from "../src/mock-gitea.ts";
|
||||
import { events, questions, sessions, telegramOutbox, users } from "@peppa/db";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
@ -202,3 +206,53 @@ describe("Владелец видит время следующей попытк
|
||||
delete process.env.PEPPA_TZ;
|
||||
});
|
||||
});
|
||||
|
||||
describe("Пустой SET и общая рабочая копия (находки на живой системе)", () => {
|
||||
test("update_task(status: review) при идущих проверках — без ошибки «No values to set»", async () => {
|
||||
const t = await stuck({ checks: null });
|
||||
gitea.setStatus(t.proj.giteaOwner, t.proj.giteaRepo, gitea.sha(t.proj.giteaOwner, t.proj.giteaRepo, `task/${t.tp.taskKey}`), "peppa/test", "pending");
|
||||
const [a, b] = InMemoryTransport.createLinkedPair();
|
||||
await createAgentServer(db, { defaultKey: t.tp.key }).connect(a);
|
||||
const client = new Client({ name: "mock-agent", version: "0" });
|
||||
await client.connect(b);
|
||||
const r = await client.callTool({ name: "update_task", arguments: { task: t.tp.taskKey, status: "review" } });
|
||||
const text = (r.content as Array<{ text: string }>)[0]!.text;
|
||||
assert.equal(!!r.isError, false, text);
|
||||
assert.match(text, /still running/);
|
||||
assert.ok(await runner.getReviewWanted(db, t.ref.task.id), "the request is remembered");
|
||||
// The same at the core: a patch of undefined fields changes nothing and does not throw.
|
||||
const same = await core.updateTask(db, t.ref, { prUrl: undefined, title: undefined });
|
||||
assert.equal(same.id, t.ref.task.id);
|
||||
await client.close();
|
||||
});
|
||||
|
||||
test("Общая рабочая копия: один агент на копию, вторая задача ждёт очереди", async () => {
|
||||
const t = await stuck({ checks: "failure" });
|
||||
// A second stuck story of the same project, same shared copy.
|
||||
const other = await core.createTask(db, { projectId: t.proj.id, title: "Вторая" });
|
||||
const sha2 = gitea.commit(t.proj.giteaOwner, t.proj.giteaRepo, `task/${other.key}`, { "g.txt": "2" });
|
||||
const pr2 = gitea.openPull(t.proj.giteaOwner, t.proj.giteaRepo, `task/${other.key}`);
|
||||
gitea.setStatus(t.proj.giteaOwner, t.proj.giteaRepo, sha2, "peppa/test", "failure");
|
||||
await core.updateTask(db, other, { status: "in_progress", prUrl: `${gitea.url}/${t.proj.giteaOwner}/${t.proj.giteaRepo}/pulls/${pr2.number}` });
|
||||
const s2 = await core.createSession(db, { projectId: t.proj.id, taskId: other.task.id });
|
||||
await db.update(sessions).set({ status: "idle", lastActivityAt: new Date(Date.now() - 40 * MIN) }).where(eq(sessions.id, s2.id));
|
||||
// Somebody already works in the shared copy.
|
||||
const busy = await core.createSession(db, { projectId: t.proj.id, taskId: null });
|
||||
await db.update(sessions).set({ status: "running" }).where(eq(sessions.id, busy.id));
|
||||
await tick(Date.now());
|
||||
for (const id of [t.ref.task.id, other.task.id]) {
|
||||
const d = await core.getPlatformDelay(db, { projectId: t.proj.id, taskId: id }, "stuck");
|
||||
assert.equal(d?.state, "queued", "waits for the copy");
|
||||
assert.equal(d?.attempts, 0, "not an attempt");
|
||||
}
|
||||
// The copy is free: exactly one agent is relaunched, the other one waits for it.
|
||||
await db.update(sessions).set({ status: "done" }).where(eq(sessions.id, busy.id));
|
||||
await tick(Date.now() + 6 * MIN);
|
||||
const healed = [await runner.getStuckHeal(db, t.ref.task.id), await runner.getStuckHeal(db, other.task.id)].filter((h) => (h?.attempts ?? 0) > 0);
|
||||
assert.equal(healed.length, 1, "one agent per shared copy");
|
||||
for (const id of [t.sid, s2.id]) {
|
||||
await waitFor("settled", async () => ((await core.getSession(db, id)).status !== "starting" ? true : null));
|
||||
await runner.stopSession(db, id).catch(() => {});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Loading…
Reference in New Issue
Block a user