merge: bring retry module up to current master

Keep the retry module wired through the heartbeat service after the service split.

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
nickyleachandPaperclip committed 2026-10-09 15:05:09 +00:00
commit ba5c01e08b
35 files changed
+3682 -1346

No files matched your search

@@ -1,3 +1,5 @@
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { subscribeDeliveryWork, DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
import { randomUUID } from "node:crypto";
import { and, asc, eq } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
@@ -7,7 +9,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro
import { settleInterruptedNativeBootstrap, terminalizeLegacyExecution } from "../services/legacy-execution-recovery.js";
import { getExecutionBlocker } from "../services/execution-blocker.js";
import { settleUnrecoverableExecutions } from "../services/execution-recovery-resolution.js";
import { issueService } from "../services/issues.js";
import { executeIssuePostCommitActions, type IssuePostCommitAction, issueService } from "../services/issues.js";
import { buildLowTrustSourceTrust } from "../services/source-trust.js";
import { documentService } from "../services/documents.js";
import { instanceSettingsService } from "../services/instance-settings.js";
@@ -51,6 +53,57 @@ const support = await getEmbeddedPostgresTestSupport();
};
return { companyId, agentId, sourceId, runId, task, create, finish, rows, due, wakeup, service, run };
}
it("dispatches a committed completion without activity publication and recovers after restart", async () => {
const f = await seed();
const run = vi.fn(() => f.service.sweepPending());
const makeWorker = () => {
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => { throw error; } });
const worker = coordinator.register(DELIVERY_QUEUES.chatCompletion, { retryMs: 60_000, run, hasPending: f.service.hasPending });
return { ...worker, stop: coordinator.stop };
};
const worker = makeWorker();
try {
await worker.ready;
expect(await f.service.hasPending()).toBe(false);
expect(run).toHaveBeenCalledTimes(1);
await f.finish(); // Service mutation alone: no route activity callback.
await vi.waitFor(() => expect(f.wakeup).toHaveBeenCalledTimes(1));
expect(await f.service.hasPending()).toBe(true); // queued receipt still owed
} finally { await worker.stop(); }
// Admit the first reporting turn; later completions need a new turn.
await f.run();
// A second task commits while no consumer is registered.
const next = await f.create();
await f.finish(next.id);
const restarted = makeWorker();
try {
await restarted.ready;
expect(f.wakeup).toHaveBeenCalledTimes(2);
} finally { await restarted.stop(); }
});
it("automatically notifies after a caller-owned transaction commits", async () => {
const f = await seed();
const notified = vi.fn();
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.chatCompletion, notified);
try {
const actions: IssuePostCommitAction[] = [];
await db.transaction(async tx => {
await issueService(db).update(f.task.id, { status: "done" }, tx, [], actions);
expect(notified).not.toHaveBeenCalled();
});
expect(notified).toHaveBeenCalledTimes(1);
expect(actions).toEqual([]);
await executeIssuePostCommitActions(db, actions);
expect(notified).toHaveBeenCalledTimes(1);
const rolledBack: IssuePostCommitAction[] = [];
await expect(db.transaction(async tx => {
await issueService(db).update(f.task.id, { status: "todo" }, tx, [], rolledBack);
throw new Error("rollback");
})).rejects.toThrow("rollback");
expect(notified).toHaveBeenCalledTimes(1);
expect((await f.rows())[0]?.status).toBe("pending");
} finally { unsubscribe(); }
});
it("records authenticated origins and atomically creates one event per Done transition", async () => {
const f = await seed();
expect(await db.select().from(handoffs).where(eq(handoffs.taskId, f.task.id))).toMatchObject([{ conversationId: f.sourceId, sessionGeneration: 0 }]);
@@ -1,3 +1,5 @@
import { subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
import { randomUUID } from "node:crypto";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
@@ -773,7 +775,11 @@ describeEmbeddedPostgres("connectionIntentService", () => {
it("recovers a resolution after a failed dispatch and acknowledges an already queued wake exactly once", async () => {
const service = connectionIntentService(db);
const pending = await service.request(claims, "airtable");
const notified = vi.fn();
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.connection, notified);
await service.decline(pending.interactionId!, claims.responsible_user_id);
unsubscribe();
expect(notified).toHaveBeenCalledTimes(1);
const wakeup = vi.fn().mockRejectedValueOnce(new Error("simulated crash before durable enqueue"));
const deliveries = connectionIntentDeliveryService(db, { wakeup } as never);
await expect(deliveries.deliver(pending.interactionId!)).rejects.toThrow("simulated crash");
@@ -0,0 +1,192 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { installDatabaseWorkSignals } from "../../../packages/db/src/work-signals.js";
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { notifyDeliveryWork, DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
import { idleWorkSnapshot } from "../services/task-admission.js";
const coordinators: ReturnType<typeof createDeliveryWorkCoordinator>[] = [];
afterEach(async () => { for (const c of coordinators.splice(0)) await c.stop(); vi.useRealTimers(); });
function setup() {
vi.useFakeTimers();
let outcome = "committed";
let rejectCommit = false;
const execute = vi.fn(async () => [{ xid: "42", status: outcome }]);
const owner = installDatabaseWorkSignals({ execute, async transaction(callback: (tx: any) => Promise<any>) {
const result = await callback({ execute, transaction: owner.transaction });
if (rejectCommit) throw new Error("lost commit reply");
return result;
} });
const canRun = vi.fn(() => true), canReconcile = vi.fn(() => false), onError = vi.fn();
const coordinator = createDeliveryWorkCoordinator({ owner, canRun, canReconcile, onError });
coordinators.push(coordinator);
const enqueue = (queue = DELIVERY_QUEUES.feedback as typeof DELIVERY_QUEUES[keyof typeof DELIVERY_QUEUES]) =>
owner.transaction(tx => notifyDeliveryWork(tx, queue));
return { owner, canRun, canReconcile, onError, coordinator, enqueue, execute,
failCommit: () => { rejectCommit = true; outcome = "in progress"; }, settle: (status = "committed") => { outcome = status; } };
}
function task() { return { retryMs: 5000, run: vi.fn(async () => {}), hasPending: vi.fn(async () => false) }; }
describe("delivery work coordinator", () => {
it("leaves five empty queues with no deadlines, timers, or periodic queries", async () => {
const s = setup();
const tasks = Object.values(DELIVERY_QUEUES).map(queue => {
const t = task(); return { queue, t, worker: s.coordinator.register(queue, t) };
});
await Promise.all(tasks.map(t => t.worker.ready));
expect(vi.getTimerCount()).toBe(0);
expect(s.coordinator.nextWakeAt()).toBeNull();
await vi.advanceTimersByTimeAsync(3_600_000);
for (const { queue, t } of tasks) {
expect(t.run).toHaveBeenCalledTimes(1);
await s.enqueue(queue); await s.enqueue(queue);
}
await vi.advanceTimersByTimeAsync(1);
for (const { t } of tasks) expect(t.run).toHaveBeenCalledTimes(2);
expect(vi.getTimerCount()).toBe(0);
expect(idleWorkSnapshot().active).toBe(0);
});
it("does not postpone an already committed wake when another producer starts writing", async () => {
const s = setup(), t = task();
await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready;
await s.enqueue();
let release!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
const writing = s.owner.transaction(async tx => {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.feedback);
await gate;
});
await vi.advanceTimersByTimeAsync(1);
expect(t.run).toHaveBeenCalledTimes(2);
release(); await writing;
await vi.advanceTimersByTimeAsync(1);
expect(t.run).toHaveBeenCalledTimes(3);
expect(idleWorkSnapshot().active).toBe(0);
});
it("fences unresolved writes until the server settles, then scans and releases the idle hold", async () => {
const s = setup(), t = task();
await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready;
s.failCommit();
await expect(s.enqueue()).rejects.toThrow("lost commit reply");
expect(idleWorkSnapshot().active).toBe(1);
await vi.advanceTimersByTimeAsync(1);
expect(t.run).toHaveBeenCalledTimes(2); // Empty scan cannot clear unresolved write.
expect(idleWorkSnapshot().active).toBe(1);
expect(s.coordinator.nextWakeAt()).not.toBeNull();
s.settle();
await vi.advanceTimersByTimeAsync(5001);
expect(t.run.mock.calls.length).toBeGreaterThanOrEqual(3);
expect(idleWorkSnapshot().active).toBe(0);
expect(vi.getTimerCount()).toBe(0);
});
it("retains unresolved intent across coordinator replacement", async () => {
const s = setup(), t = task();
await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready;
s.failCommit(); await expect(s.enqueue()).rejects.toThrow();
await s.coordinator.stop();
expect(idleWorkSnapshot().active).toBe(0);
const replacement = createDeliveryWorkCoordinator({ owner: s.owner, canRun: () => true, onError: vi.fn() });
coordinators.push(replacement);
await replacement.register(DELIVERY_QUEUES.feedback, t).ready;
expect(idleWorkSnapshot().active).toBe(1);
s.settle(); await vi.advanceTimersByTimeAsync(5001);
expect(idleWorkSnapshot().active).toBe(0);
expect(replacement.nextWakeAt()).toBeNull();
});
it("retries pending deliveries and transient failures, then goes quiet", async () => {
const s = setup(), t = task();
t.run.mockRejectedValueOnce(new Error("database disconnected"));
t.hasPending.mockResolvedValueOnce(true);
await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready;
expect(s.onError).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(10_000);
expect(t.run).toHaveBeenCalledTimes(3);
expect(s.coordinator.nextWakeAt()).toBeNull();
expect(idleWorkSnapshot().active).toBe(0);
});
it("does not overlap a sweep or lose a commit during its final pending check", async () => {
const s = setup(), t = task();
let release!: (pending: boolean) => void;
t.hasPending.mockImplementationOnce(() => new Promise(resolve => { release = resolve; }));
s.coordinator.register(DELIVERY_QUEUES.connection, t);
await vi.advanceTimersByTimeAsync(1);
await s.enqueue(DELIVERY_QUEUES.connection);
await vi.advanceTimersByTimeAsync(1000);
expect(t.run).toHaveBeenCalledTimes(1);
release(false);
await vi.advanceTimersByTimeAsync(1);
expect(t.run).toHaveBeenCalledTimes(2);
});
it("reconciles a rollback during idle drain and releases the empty-queue hold without dispatching", async () => {
const s = setup(), t = task();
await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready;
s.canRun.mockReturnValue(false);
s.canReconcile.mockReturnValue(true);
s.failCommit(); await expect(s.enqueue()).rejects.toThrow("lost commit reply");
await vi.advanceTimersByTimeAsync(1);
expect(idleWorkSnapshot().active).toBe(1);
expect(t.run).toHaveBeenCalledTimes(1);
s.settle("aborted");
await vi.advanceTimersByTimeAsync(5001);
expect(t.run).toHaveBeenCalledTimes(1);
expect(t.hasPending).toHaveBeenCalled();
expect(idleWorkSnapshot().active).toBe(0);
expect(s.coordinator.nextWakeAt()).toBeNull();
});
it("keeps committed pending work recoverable during drain without starting deliveries", async () => {
const s = setup(), t = task();
await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready;
s.canRun.mockReturnValue(false);
s.canReconcile.mockReturnValue(true);
t.hasPending.mockResolvedValue(true);
await s.enqueue();
await vi.advanceTimersByTimeAsync(1);
expect(t.run).toHaveBeenCalledTimes(1);
expect(s.coordinator.nextWakeAt()).not.toBeNull();
s.canRun.mockReturnValue(true);
t.hasPending.mockResolvedValue(false);
await vi.advanceTimersByTimeAsync(5001);
expect(t.run).toHaveBeenCalledTimes(2);
expect(idleWorkSnapshot().active).toBe(0);
});
it("does not query during standby and resumes when admission opens", async () => {
const s = setup(), t = task(); s.canRun.mockReturnValue(false);
await s.coordinator.register(DELIVERY_QUEUES.toolAction, t).ready;
await s.enqueue(DELIVERY_QUEUES.toolAction);
await vi.advanceTimersByTimeAsync(120_000);
expect(t.run).not.toHaveBeenCalled();
expect(t.hasPending).not.toHaveBeenCalled();
s.canRun.mockReturnValue(true);
await vi.advanceTimersByTimeAsync(5001);
expect(t.run).toHaveBeenCalledTimes(1);
expect(idleWorkSnapshot().active).toBe(0);
});
it("awaits in-flight work on shutdown and releases the subscription for restart", async () => {
const s = setup(), t = task();
let release!: () => void;
t.run.mockImplementationOnce(() => new Promise(resolve => { release = resolve; }));
s.coordinator.register(DELIVERY_QUEUES.chatCompletion, t);
await vi.advanceTimersByTimeAsync(1);
const stopped = vi.fn();
const stopping = s.coordinator.stop().then(stopped);
await s.enqueue(DELIVERY_QUEUES.chatCompletion);
expect(stopped).not.toHaveBeenCalled();
release(); await stopping;
expect(vi.getTimerCount()).toBe(0);
expect(idleWorkSnapshot().active).toBe(0);
});
it("cancels an abortable delivery before awaiting shutdown", async () => {
const s = setup();
const hasPending = vi.fn(async () => false);
const run = vi.fn((signal: AbortSignal) => new Promise<void>((_resolve, reject) => {
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
}));
s.coordinator.register(DELIVERY_QUEUES.feedback, { retryMs: 5000, run, hasPending });
await vi.advanceTimersByTimeAsync(1);
await s.coordinator.stop();
expect(run.mock.calls[0]?.[0].aborted).toBe(true);
expect(hasPending).not.toHaveBeenCalled();
expect(s.onError).not.toHaveBeenCalled();
expect(idleWorkSnapshot().active).toBe(0);
expect(vi.getTimerCount()).toBe(0);
});
});
+34 -1
View File
@@ -1,3 +1,5 @@
import { subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
import { randomUUID } from "node:crypto";
import fs from "node:fs";
import os from "node:os";
@@ -800,6 +802,8 @@ describeEmbeddedPostgres("feedbackService.saveIssueVote", () => {
sessionId,
});
const notified = vi.fn();
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.feedback, notified);
await flushingSvc.saveIssueVote({
issueId,
targetType: "issue_comment",
@@ -808,7 +812,12 @@ describeEmbeddedPostgres("feedbackService.saveIssueVote", () => {
authorUserId: "user-1",
allowSharing: true,
});
await flushingSvc.flushPendingFeedbackTraces();
unsubscribe();
expect(notified).toHaveBeenCalledTimes(1);
expect(await flushingSvc.hasPendingFeedbackTraces()).toBe(true);
// The route and worker may request a flush together after the commit.
await Promise.all([flushingSvc.flushPendingFeedbackTraces(), flushingSvc.flushPendingFeedbackTraces()]);
expect(await flushingSvc.hasPendingFeedbackTraces()).toBe(false);
expect(uploadTraceBundle).toHaveBeenCalledTimes(1);
const bundle = uploadTraceBundle.mock.calls[0]?.[0] as Record<string, unknown> | undefined;
@@ -1152,6 +1161,30 @@ describeEmbeddedPostgres("feedbackService.saveIssueVote", () => {
expect(uploadTraceBundle).toHaveBeenCalledTimes(1);
});
it("leaves aborted and unstarted exports available for recovery after shutdown", async () => {
const first = await seedIssueWithAgentComment();
const second = await seedIssueWithAgentComment();
const shutdown = new AbortController();
const uploadTraceBundle = vi.fn().mockResolvedValue({ objectKey: "saved" })
.mockImplementationOnce(async (_bundle, signal: AbortSignal) => {
shutdown.abort(new Error("shutdown"));
signal.throwIfAborted();
});
const flushingSvc = feedbackService(db, { shareClient: { uploadTraceBundle } });
for (const item of [first, second]) {
await flushingSvc.saveIssueVote({ issueId: item.issueId, targetType: "issue_comment",
targetId: item.commentId, vote: "up", authorUserId: "user-1", allowSharing: true });
}
expect(await flushingSvc.flushPendingFeedbackTraces({ signal: shutdown.signal }))
.toMatchObject({ attempted: 1, sent: 0, failed: 1 });
const rows = await db.select().from(feedbackExports);
expect(rows.filter(row => row.status === "failed")).toHaveLength(1);
expect(rows.filter(row => row.status === "pending")).toHaveLength(1);
expect(await flushingSvc.hasPendingFeedbackTraces()).toBe(true);
expect(await flushingSvc.flushPendingFeedbackTraces()).toMatchObject({ attempted: 2, sent: 2, failed: 0 });
expect(await flushingSvc.hasPendingFeedbackTraces()).toBe(false);
});
it("marks pending shared traces as failed when no feedback export backend is configured", async () => {
const { companyId, issueId, commentId } = await seedIssueWithAgentComment();
@@ -1,6 +1,6 @@
import { gunzipSync } from "node:zlib";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createFeedbackTraceShareClientFromConfig } from "../services/feedback-share-client.js";
import { FEEDBACK_UPLOAD_TIMEOUT_MS, createFeedbackTraceShareClientFromConfig } from "../services/feedback-share-client.js";
describe("feedback trace share client", () => {
beforeEach(() => {
@@ -12,6 +12,7 @@ describe("feedback trace share client", () => {
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
it("defaults to telemetry.paperclip.ing when no backend url is configured", async () => {
@@ -98,4 +99,43 @@ describe("feedback trace share client", () => {
expect(parsed.objectKey.endsWith("/export-1.json")).toBe(true);
expect(parsed.bundle.envelope).toEqual({ hello: "world" });
});
it.each(["headers", "body"])("cancels a stalled upload at its deadline while waiting for %s", async phase => {
const deadline = new AbortController();
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(deadline.signal);
let started!: () => void;
const waiting = new Promise<void>(resolve => { started = resolve; });
vi.mocked(fetch).mockImplementation(async (_url, options) => {
const block = () => new Promise<never>((_resolve, reject) => {
options!.signal!.addEventListener("abort", () => reject(options!.signal!.reason), { once: true });
started();
});
if (phase === "headers") return block();
return { ok: true, json: block } as unknown as Response;
});
const client = createFeedbackTraceShareClientFromConfig({ feedbackExportBackendUrl: undefined, feedbackExportBackendToken: undefined });
const bundle = { companyId: "company", traceId: "trace" } as Parameters<typeof client.uploadTraceBundle>[0];
const uploading = client.uploadTraceBundle(bundle);
const rejected = expect(uploading).rejects.toThrow("upload deadline");
await waiting;
expect(timeout).toHaveBeenCalledWith(FEEDBACK_UPLOAD_TIMEOUT_MS);
deadline.abort(new Error("upload deadline"));
await rejected;
});
it("passes shutdown cancellation through to a pending upload", async () => {
const shutdown = new AbortController();
let started!: () => void;
const waiting = new Promise<void>(resolve => { started = resolve; });
vi.mocked(fetch).mockImplementation((_url, options) => new Promise((_resolve, reject) => {
options!.signal!.addEventListener("abort", () => reject(options!.signal!.reason), { once: true });
started();
}));
const client = createFeedbackTraceShareClientFromConfig({ feedbackExportBackendUrl: undefined, feedbackExportBackendToken: undefined });
const bundle = { companyId: "company", traceId: "trace" } as Parameters<typeof client.uploadTraceBundle>[0];
const rejected = expect(client.uploadTraceBundle(bundle, shutdown.signal)).rejects.toThrow("shutdown");
await waiting;
shutdown.abort(new Error("shutdown"));
await rejected;
});
});
@@ -8,6 +8,7 @@ const mockFeedbackService = vi.hoisted(() => ({
listIssueVotesForUser: vi.fn(),
listFeedbackTraces: vi.fn(),
saveIssueVote: vi.fn(),
flushPendingFeedbackTraces: vi.fn(() => new Promise(() => {})),
}));
const mockIssueService = vi.hoisted(() => ({
@@ -18,9 +19,6 @@ const mockIssueService = vi.hoisted(() => ({
findMentionedAgents: vi.fn(),
}));
const mockFeedbackExportService = vi.hoisted(() => ({
flushPendingFeedbackTraces: vi.fn(async () => ({ attempted: 1, sent: 1, failed: 0 })),
}));
const mockAccessService = vi.hoisted(() => ({
canUser: vi.fn(),
hasPermission: vi.fn(),
@@ -138,7 +136,7 @@ async function createApp(actor: Record<string, unknown>) {
(req as any).actor = actor;
next();
});
app.use("/api", issueRoutes({} as any, {} as any, { feedbackExportService: mockFeedbackExportService }));
app.use("/api", issueRoutes({} as any, {} as any));
const routeErrors: string[] = [];
app.locals.routeErrors = routeErrors;
app.use((error: unknown, _req: express.Request, _res: express.Response, next: express.NextFunction) => {
@@ -152,11 +150,6 @@ async function createApp(actor: Record<string, unknown>) {
describe("issue feedback trace routes", () => {
beforeEach(() => {
vi.clearAllMocks();
mockFeedbackExportService.flushPendingFeedbackTraces.mockResolvedValue({
attempted: 1,
sent: 1,
failed: 0,
});
mockHeartbeatService.wakeup.mockResolvedValue(undefined);
mockHeartbeatService.reportRunActivity.mockResolvedValue(undefined);
mockHeartbeatService.getRun.mockResolvedValue(null);
@@ -174,7 +167,7 @@ describe("issue feedback trace routes", () => {
mockLogActivity.mockResolvedValue(undefined);
});
it("flushes a newly shared feedback trace immediately after saving the vote", async () => {
it("returns the saved vote without waiting for feedback uploads", async () => {
const targetId = "11111111-1111-4111-8111-111111111111";
mockIssueService.getById.mockResolvedValue({
id: "issue-1",
@@ -211,11 +204,9 @@ describe("issue feedback trace routes", () => {
});
expect([200, 201]).toContain(res.status);
expect(mockFeedbackExportService.flushPendingFeedbackTraces).toHaveBeenCalledWith({
companyId: "company-1",
traceId: "trace-1",
limit: 1,
});
expect(mockFeedbackService.saveIssueVote).toHaveBeenCalledTimes(1);
expect(mockFeedbackService.flushPendingFeedbackTraces).not.toHaveBeenCalled();
});
it("rejects non-board callers before fetching a feedback trace", async () => {
@@ -1,3 +1,5 @@
import { subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
import { randomUUID } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
@@ -231,11 +233,15 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => {
expect(created.payload.questions.map((question) => question.id)).toEqual(["repo", "scope", "hosting"]);
expect(await interactionsSvc.create(issue, input, { userId: "local-board" })).toEqual(created);
await expect(interactionsSvc.answerQuestions(issue, created.id, { answers: [{ questionId: "repo", optionIds: [], otherText: "https://example.com/repo" }] }, { userId: "local-board" })).rejects.toThrow("requires an answer");
const notified = vi.fn();
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.question, notified);
const answered = await interactionsSvc.answerQuestions(issue, created.id, { answers: [
{ questionId: "repo", optionIds: [], otherText: "https://example.com/repo" },
{ questionId: "scope", optionIds: ["all"] },
{ questionId: "hosting", optionIds: ["existing", "new"] },
] }, { userId: "local-board" });
unsubscribe();
expect(notified).toHaveBeenCalledTimes(1);
expect(answered.status).toBe("answered");
});
@@ -44,11 +44,17 @@ const {
const completionSweepMock = vi.fn(async () => undefined);
const createAppMock = vi.fn(async () => Object.assign((_: unknown, __: unknown) => {}, {
locals: {
deliveryWork: {
register: (_queue: string, task: { run: () => Promise<unknown> }) => ({
ready: task.run().catch(() => undefined), wake: vi.fn(),
}),
stop: vi.fn(async () => {}),
},
toolGateway: {
sweepActionReviews: vi.fn(async () => ({ scanned: 0 })),
cleanupExpiredSessions: vi.fn(async () => ({ deletedCount: 0 })),
},
toolActionDeliveries: { sweepPending: vi.fn(async () => ({ scanned: 0, delivered: 0 })) },
toolActionDeliveries: { hasPending: vi.fn(async () => false), sweepPending: vi.fn(async () => ({ scanned: 0, delivered: 0 })) },
},
}) as never);
const createBetterAuthInstanceMock = vi.fn(() => ({}));
@@ -133,6 +139,7 @@ const {
};
const routineServiceFactoryMock = vi.fn(() => routineServiceMock);
const feedbackExportServiceMock = {
hasPendingFeedbackTraces: vi.fn(async () => false),
flushPendingFeedbackTraces: vi.fn(async () => ({ attempted: 0, sent: 0, failed: 0 })),
};
const feedbackServiceFactoryMock = vi.fn(() => feedbackExportServiceMock);
@@ -363,16 +370,18 @@ vi.mock("../services/index.js", () => ({
})),
}));
vi.mock("../services/chat-completion-delivery.js", () => ({ chatCompletionDeliveryService: () => ({ sweepPending: completionSweepMock }) }));
vi.mock("../services/chat-completion-delivery.js", () => ({ chatCompletionDeliveryService: () => ({ hasPending: vi.fn(async () => false), sweepPending: completionSweepMock }) }));
vi.mock("../services/connection-intent-delivery.js", () => ({
connectionIntentDeliveryService: vi.fn(() => ({
hasPending: vi.fn(async () => false),
sweepPending: vi.fn(async () => ({ scanned: 0, failed: 0 })),
})),
}));
vi.mock("../services/question-response-delivery.js", () => ({
questionResponseDeliveryService: vi.fn(() => ({
hasPending: vi.fn(async () => false),
sweepPending: vi.fn(async () => ({
scanned: 0,
steered: 0,
@@ -675,6 +684,22 @@ describe("startServer feedback export wiring", () => {
expect(completionSweepMock).toHaveBeenCalled();
});
it("keeps activity-driven completion scans scoped to the changed task", async () => {
await startServer();
completionSweepMock.mockClear();
const { publishLiveEvent } = await import("../services/live-events.js");
publishLiveEvent({ companyId: "company-one", type: "activity.logged", payload: {
action: "issue.updated", entityId: "task-one",
} });
expect(completionSweepMock).toHaveBeenCalled();
for (const args of completionSweepMock.mock.calls) {
expect(args).toEqual([{ companyId: "company-one", taskId: "task-one" }]);
}
completionSweepMock.mockClear();
publishLiveEvent({ companyId: "company-two", type: "activity.logged", payload: { action: "issue.updated" } });
expect(completionSweepMock).not.toHaveBeenCalled();
});
it("never invokes the retired review detector at startup or on periodic recovery", async () => {
loadConfigMock.mockReturnValue(buildTestConfig({
heartbeatSchedulerEnabled: true,
@@ -1,3 +1,5 @@
import { subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
@@ -219,6 +221,8 @@ describeEmbeddedPostgres("tool gateway service", () => {
runId: run.id,
});
const notified = vi.fn();
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.toolAction, notified);
await expect(gateway.executeTool({
sessionToken: session.token,
tool: "mcp-remote-fixture:update_note",
@@ -228,6 +232,9 @@ describeEmbeddedPostgres("tool gateway service", () => {
details: { instructions: expect.stringContaining("A human approval card was posted on task") },
});
unsubscribe();
expect(notified).toHaveBeenCalledTimes(1);
await expect(gateway.executeTool({
sessionToken: session.token,
tool: "mcp-remote-fixture:update_note",
@@ -0,0 +1,47 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createWorkScheduler } from "../services/work-scheduler.js";
afterEach(() => vi.useRealTimers());
describe("work scheduler", () => {
it("owns one timer, replaces named deadlines, and exposes the earliest wake", async () => {
vi.useFakeTimers(); vi.setSystemTime(0);
const s = createWorkScheduler();
const first = vi.fn(), second = vi.fn();
s.schedule("first", 100, first);
s.schedule("second", 50, second);
s.schedule("first", 20, first);
expect(vi.getTimerCount()).toBe(1);
expect(s.nextWakeAt()).toBe(20);
await vi.advanceTimersByTimeAsync(20);
expect(first).toHaveBeenCalledTimes(1);
expect(second).not.toHaveBeenCalled();
expect(s.nextWakeAt()).toBe(50);
s.cancel("second");
expect(s.nextWakeAt()).toBeNull();
expect(vi.getTimerCount()).toBe(0);
});
it("honors cancellation during dispatch and isolates a failing callback", async () => {
vi.useFakeTimers(); vi.setSystemTime(0);
const warn = vi.spyOn(process, "emitWarning").mockImplementation(() => {});
const s = createWorkScheduler(), cancelled = vi.fn(), later = vi.fn();
s.schedule("first", 10, () => { s.cancel("cancelled"); throw new Error("failure"); });
s.schedule("cancelled", 10, cancelled);
s.schedule("later", 20, later);
await vi.advanceTimersByTimeAsync(20);
expect(cancelled).not.toHaveBeenCalled();
expect(later).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledTimes(1);
warn.mockRestore(); s.stop();
});
it("does not fire distant deadlines early and cannot restart after stop", async () => {
vi.useFakeTimers(); vi.setSystemTime(0);
const s = createWorkScheduler(), run = vi.fn();
s.schedule("far", 3_000_000_000, run);
await vi.advanceTimersByTimeAsync(2_147_483_647);
expect(run).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(852_516_353);
expect(run).toHaveBeenCalledTimes(1);
s.stop(); s.schedule("late", Date.now(), run);
expect(vi.getTimerCount()).toBe(0);
expect(() => createWorkScheduler().schedule("bad", NaN, run)).toThrow("finite");
});
});
+17 -35
View File
@@ -1,3 +1,5 @@
import { createDeliveryWorkCoordinator } from "./services/delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "./services/delivery-work-notifications.js";
import { idleAdmissionMiddleware, trackIdleRequestHandlers } from "./middleware/idle-admission.js";
import { isIdleTaskDrainActive, trackIdleWork } from "./services/task-admission.js";
import { customerSuccessRoutes } from "./routes/customer-success.js";
@@ -483,11 +485,13 @@ export async function createApp(
serverPort: number;
storageService: StorageService;
feedbackExportService?: {
hasPendingFeedbackTraces(): Promise<boolean>;
flushPendingFeedbackTraces(input?: {
companyId?: string;
traceId?: string;
limit?: number;
now?: Date;
signal?: AbortSignal;
}): Promise<unknown>;
};
databaseBackupService?: InstanceDatabaseBackupService;
@@ -877,7 +881,6 @@ export async function createApp(
// route prefixes, so this dependency does not change issue-route precedence.
api.use(issueRoutes(db, opts.storageService, {
chatRunRetries: chatChannels,
feedbackExportService: opts.feedbackExportService,
pluginWorkerManager: workerManager,
approveToolActionRequest: (input) => toolGateway.approveActionRequest(input),
declineToolActionRequest: (input) => toolGateway.declineActionRequest(input),
@@ -1190,40 +1193,19 @@ export async function createApp(
jobCoordinator.start();
scheduler.start();
let feedbackExportShuttingDown = false;
let feedbackExportTimer: ReturnType<typeof setInterval> | null = null;
const disableFeedbackExportFlushes = () => {
feedbackExportShuttingDown = true;
if (feedbackExportTimer) {
clearInterval(feedbackExportTimer);
feedbackExportTimer = null;
}
};
const flushPendingFeedbackExports = async () => {
if (feedbackExportShuttingDown || isWarmStandby() || isIdleTaskDrainActive()) return;
try {
await opts.feedbackExportService?.flushPendingFeedbackTraces();
} catch (err) {
if (isDatabaseConnectionUnavailableError(err)) {
disableFeedbackExportFlushes();
logger.warn(
{ err },
"Disabling pending feedback export flushes because the database is unavailable",
);
return;
}
logger.error({ err }, "Failed to flush pending feedback exports");
}
};
feedbackExportTimer = opts.feedbackExportService
? setInterval(() => {
void flushPendingFeedbackExports();
}, FEEDBACK_EXPORT_FLUSH_INTERVAL_MS)
: null;
feedbackExportTimer?.unref?.();
const deliveryWork = createDeliveryWorkCoordinator({
owner: db,
canRun: () => !isWarmStandby() && !isIdleTaskDrainActive(),
canReconcile: () => !isWarmStandby(),
onError: (err, queue) => logger.error({ err, queue }, "Delivery reconciliation failed"),
});
app.locals.deliveryWork = deliveryWork;
if (opts.feedbackExportService) {
void flushPendingFeedbackExports();
deliveryWork.register(DELIVERY_QUEUES.feedback, {
retryMs: FEEDBACK_EXPORT_FLUSH_INTERVAL_MS,
run: (signal) => opts.feedbackExportService!.flushPendingFeedbackTraces({ signal }),
hasPending: () => opts.feedbackExportService!.hasPendingFeedbackTraces(),
});
}
emailChannels.start();
const flushChatPublications = async () => {
@@ -1389,7 +1371,7 @@ export async function createApp(
await publicMcpEvents?.stop();
await dotMcpEvents?.stop();
jobCoordinator.stop();
disableFeedbackExportFlushes();
await deliveryWork.stop();
unsubscribeChatPublicationSignals();
chatReconciliation.stop();
if (chatPublicationTimer) {
+25 -33
View File
@@ -1,9 +1,11 @@
import { subscribeAllCompanyLiveEvents } from "./services/live-events.js";
import { DELIVERY_QUEUES } from "./services/delivery-work-notifications.js";
import type { createDeliveryWorkCoordinator } from "./services/delivery-work-coordinator.js";
import { isIdleTaskDrainActive, beginIdleTrackedWork, trackIdleWork } from "./services/task-admission.js";
import { markIdleStartupComplete } from "./services/idle-local-work.js";
import { clearIdleBackupWakeRequired, idleBackupWakeMarker, markIdleBackupWakeRequired, verifyIdleDatabaseBackup } from "./services/idle-database-backup.js";
import { cloudWarmStandbyServerOptions } from "./middleware/cloud-warm-standby.js";
import { createCloudWarmStandby } from "./services/cloud-warm-standby.js";
import { subscribeAllCompanyLiveEvents } from "./services/live-events.js";
import { chatCompletionDeliveryService } from "./services/chat-completion-delivery.js";
/// <reference path="./types/express.d.ts" />
// Kicks off the OTel bootstrap as early as possible (no-op unless
@@ -1252,20 +1254,31 @@ async function startServerWithDatabaseTeardown(
const ENVIRONMENT_LEASE_CLEANUP_SWEEP_BACKOFF_MS = 5 * 60 * 1000;
const environmentLeaseCleanupHeartbeat = accountingHeartbeat;
const chatCompletionDeliveries = chatCompletionDeliveryService(db as any, environmentLeaseCleanupHeartbeat);
// Activity publication happens after the status transaction commits. This is
// a best-effort fast path; the durable outbox and sweeps remain authoritative.
const unsubscribeChatCompletions = subscribeAllCompanyLiveEvents(event => {
if (isIdleTaskDrainActive() || heartbeatSchedulerStopped || event.type !== "activity.logged" ||
event.payload.action !== "issue.updated" || typeof event.payload.entityId !== "string") return;
trackHeartbeatSchedulerWork(chatCompletionDeliveries.sweepPending({ companyId: event.companyId, taskId: event.payload.entityId })
.catch(err => logger.error({ err }, "post-commit chat completion delivery failed")));
});
server.on("close", unsubscribeChatCompletions);
const connectionDeliveries = connectionIntentDeliveryService(db as any, environmentLeaseCleanupHeartbeat);
const questionResponseDeliveries = questionResponseDeliveryService(db as any, {
heartbeat: environmentLeaseCleanupHeartbeat,
resolveNativeQuestion: (interaction) => deliverNativeQuestionResponse(db as any, interaction),
});
const deliveryWork = app.locals.deliveryWork as ReturnType<typeof createDeliveryWorkCoordinator>;
const deliveryWorkers = ([
[DELIVERY_QUEUES.chatCompletion, chatCompletionDeliveries],
[DELIVERY_QUEUES.connection, connectionDeliveries],
[DELIVERY_QUEUES.question, questionResponseDeliveries],
[DELIVERY_QUEUES.toolAction, app.locals.toolActionDeliveries as ReturnType<typeof import("./services/tool-action-delivery.js").toolActionDeliveryService>],
] as const).map(([queue, service]) => deliveryWork.register(queue, {
retryMs: config.heartbeatSchedulerIntervalMs,
run: () => service.sweepPending(),
hasPending: () => service.hasPending(),
}));
// Preserve the existing task-scoped activity fast path. Claims in the
// delivery service arbitrate with the coordinator's startup/recovery sweep.
const unsubscribeChatCompletions = subscribeAllCompanyLiveEvents(event => {
if (isIdleTaskDrainActive() || isWarmStandby() || heartbeatSchedulerStopped || event.type !== "activity.logged" ||
event.payload.action !== "issue.updated" || typeof event.payload.entityId !== "string") return;
trackHeartbeatSchedulerWork(chatCompletionDeliveries.sweepPending({ companyId: event.companyId, taskId: event.payload.entityId })
.catch(err => logger.error({ err }, "post-commit chat completion delivery failed")));
});
server.on("close", unsubscribeChatCompletions);
const runEnvironmentLeaseCleanupSweep = (backoffMs: number) =>
environmentLeaseCleanupHeartbeat
.sweepPendingCleanupLeases({ backoffMs })
@@ -1316,18 +1329,9 @@ async function startServerWithDatabaseTeardown(
}));
};
await chatCompletionDeliveries.sweepPending().catch((err) => logger.error({ err }, "startup chat completion delivery recovery failed"));
await connectionDeliveries.sweepPending();
await app.locals.toolGateway.sweepActionReviews().catch((err: unknown) => logger.error({ err }, "startup tool review recovery failed"));
await app.locals.toolGateway.cleanupExpiredSessions().catch((err: unknown) => logger.error({ err }, "startup gateway token cleanup failed"));
await app.locals.toolActionDeliveries.sweepPending().catch((err: unknown) => logger.error({ err }, "startup tool review delivery sweep failed"));
await questionResponseDeliveries.sweepPending().then((result) => {
if (result.scanned > 0) {
logger.info(result, "startup question-response delivery sweep completed");
}
}).catch((err) => {
logger.error({ err }, "startup question-response delivery sweep failed");
});
await Promise.all(deliveryWorkers.map(worker => worker.ready));
scheduleGitHubConnectionEventPoll();
scheduleGitHubConnectionContinuitySweep();
@@ -1781,23 +1785,10 @@ async function startServerWithDatabaseTeardown(
logger.error({ err }, "periodic secret proposal expiry sweep failed");
}));
trackHeartbeatSchedulerWork(chatCompletionDeliveries.sweepPending().catch((err) => logger.error({ err }, "chat completion delivery failed")));
trackHeartbeatSchedulerWork(accountingHeartbeat.reconcileCostAccounting().catch((err) => logger.error({ err }, "Cost accounting recovery failed")));
trackHeartbeatSchedulerWork(connectionDeliveries.sweepPending().catch((err) => logger.error({ err }, "connection continuation delivery failed")));
trackHeartbeatSchedulerWork(app.locals.toolGateway.sweepActionReviews().catch((err: unknown) => logger.error({ err }, "tool review recovery failed")));
trackHeartbeatSchedulerWork(app.locals.toolGateway.cleanupExpiredSessions().catch((err: unknown) => logger.error({ err }, "gateway token cleanup failed")));
trackHeartbeatSchedulerWork(app.locals.toolActionDeliveries.sweepPending().catch((err: unknown) => logger.error({ err }, "tool review delivery sweep failed")));
trackHeartbeatSchedulerWork(questionResponseDeliveries.sweepPending()
.then((result) => {
if (result.scanned > 0) {
logger.info(result, "periodic question-response delivery sweep completed");
}
})
.catch((err) => {
logger.error({ err }, "periodic question-response delivery sweep failed");
}));
if (isIdleTaskDrainActive() || heartbeatSchedulerStopped) return;
if (!(await heartbeat.resolveSchedulingSuppression()).suppressed) {
@@ -1974,6 +1965,7 @@ async function startServerWithDatabaseTeardown(
await systemdNotify(["--stopping", `--status=Stopping after ${signal}`]);
heartbeatSchedulerStopped = true;
unsubscribeChatCompletions();
await deliveryWork.stop();
clearInterval(executionControlInterval);
if (heartbeatSchedulerInterval) {
clearInterval(heartbeatSchedulerInterval);
+2 -24
View File
@@ -3384,14 +3384,6 @@ export function issueRoutes(
ChatChannelService,
"prepareFailedChatRunRetry" | "processFailedChatRunRetry"
>;
feedbackExportService?: {
flushPendingFeedbackTraces(input?: {
companyId?: string;
traceId?: string;
limit?: number;
now?: Date;
}): Promise<unknown>;
};
searchService?: CompanySearchService;
searchRateLimiter?: CompanySearchRateLimiter;
pluginWorkerManager?: PluginWorkerManager;
@@ -3647,7 +3639,6 @@ export function issueRoutes(
const treeControlSvc = issueTreeControlFactory?.(db) ?? {
getActivePauseHoldGate: async () => null,
};
const feedbackExportService = opts?.feedbackExportService;
const environmentsSvc = environmentService(db);
async function queueTaskWatchdogEvaluation(
@@ -19005,21 +18996,8 @@ export function issueRoutes(
);
}
if (result.sharingEnabled && result.traceId && feedbackExportService) {
try {
await feedbackExportService.flushPendingFeedbackTraces({
companyId: issue.companyId,
traceId: result.traceId,
limit: 1,
});
} catch (err) {
logger.warn(
{ err, issueId: issue.id, traceId: result.traceId },
"failed to flush shared feedback trace immediately",
);
}
}
// saveIssueVote has committed the export and notified its worker.
// Return the saved vote without waiting for an upload or backlog.
res.status(201).json(result.vote);
},
);
@@ -1,3 +1,4 @@
import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { and, asc, eq, inArray, lte, sql } from "drizzle-orm";
import { agents, agentWakeupRequests, chatCompletionDeliveries as deliveries, chatTaskHandoffs as handoffs,
heartbeatRuns, issueComments, issueDocuments, issues, type Db } from "@paperclipai/db";
@@ -31,13 +32,16 @@ export async function recordChatHandoff(tx: Connection, task: Issue, actorRunId:
}
/** Must run on the same transaction as status projection (including native arbitration). */
export async function recordChatCompletion(tx: Connection, before: Issue, after: Issue) {
if (before.status === after.status) return;
export async function recordChatCompletion(tx: Connection, before: Issue, after: Issue): Promise<boolean> {
if (before.status === after.status) return false;
await tx.update(deliveries).set({ status: "superseded" }).where(and(eq(deliveries.taskId, after.id),
eq(deliveries.companyId, after.companyId), inArray(deliveries.status, [...pending])));
if (after.status !== "done") return;
if (after.status !== "done") return false;
const [handoff] = await tx.select().from(handoffs).where(and(eq(handoffs.taskId, after.id), eq(handoffs.companyId, after.companyId)));
if (handoff) await tx.insert(deliveries).values({ companyId: after.companyId, taskId: after.id, statusVersion: after.statusVersion }).onConflictDoNothing();
if (!handoff) return false;
await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatCompletion);
await tx.insert(deliveries).values({ companyId: after.companyId, taskId: after.id, statusVersion: after.statusVersion }).onConflictDoNothing();
return true;
}
async function loadAudience(tx: Connection, deliveryId: string) {
@@ -243,5 +247,9 @@ export function chatCompletionDeliveryService(db: Db, heartbeat: { wakeup(agentI
.orderBy(asc(deliveries.nextAttemptAt)).limit(100);
for (const row of due) await deliver(row.id);
}
return { deliver, sweepPending };
async function hasPending() {
return (await db.select({ id: deliveries.id }).from(deliveries)
.where(inArray(deliveries.status, [...pending])).limit(1)).length > 0;
}
return { deliver, sweepPending, hasPending };
}
@@ -167,7 +167,11 @@ export function connectionIntentDeliveryService(db: Db, heartbeat: Pick<Heartbea
await db.update(connectionIntentDeliveries).set({ deliveredAt: new Date() }).where(eq(connectionIntentDeliveries.interactionId, interactionId));
}
}
return { deliver, tryDeliver: async (id: string) => { try { await deliver(id); } catch { /* Persisted delivery remains due after its lease. */ } }, sweepPending: async () => {
async function hasPending() {
return (await db.select({ id: connectionIntentDeliveries.interactionId }).from(connectionIntentDeliveries)
.where(isNull(connectionIntentDeliveries.deliveredAt)).limit(1)).length > 0;
}
return { deliver, hasPending, tryDeliver: async (id: string) => { try { await deliver(id); } catch { /* Persisted delivery remains due after its lease. */ } }, sweepPending: async () => {
const rows = await db.select().from(connectionIntentDeliveries).where(and(isNull(connectionIntentDeliveries.deliveredAt), lte(connectionIntentDeliveries.nextAttemptAt, new Date())))
.orderBy(asc(connectionIntentDeliveries.nextAttemptAt)).limit(50);
let failed = 0;
@@ -0,0 +1,100 @@
import { subscribeDatabaseWork, databaseWorkPending, reconcileDatabaseWork } from "@paperclipai/db";
import { createWorkScheduler } from "./work-scheduler.js";
import { type DeliveryQueue } from "./delivery-work-notifications.js";
import { beginIdleTrackedWork } from "./task-admission.js";
export function createDeliveryWorkCoordinator(input: {
owner: object;
canRun: () => boolean;
// Idle drain may reconcile admitted writes without dispatching new work.
// Warm standby can disable both operations.
canReconcile?: () => boolean;
onError: (error: unknown, queue: DeliveryQueue) => void;
}) {
const scheduler = createWorkScheduler();
const workers = new Map<DeliveryQueue, { wake: () => void; stop: () => Promise<void> }>();
let stopped = false;
return {
// Only these registered tasks are represented; not yet the whole instance.
nextWakeAt: scheduler.nextWakeAt,
register(queue: DeliveryQueue, task: {
retryMs: number;
run: (signal: AbortSignal) => Promise<unknown>;
hasPending: () => Promise<boolean>;
}) {
if (stopped) throw new Error("Delivery coordinator is stopped");
if (workers.has(queue)) throw new Error(`Delivery worker already registered: ${queue}`);
let dirty = false;
let scheduledAt: number | null = null;
let running: Promise<void> | null = null;
let workerStopped = false;
let controller: AbortController | null = null;
let finishIntent: (() => void) | undefined;
function schedule(delay: number) {
if (workerStopped) return;
const at = Date.now() + delay;
if (scheduledAt !== null && scheduledAt <= at) return;
scheduledAt = at;
scheduler.schedule(queue, at, start);
}
function start() {
if (workerStopped || running) return;
scheduler.cancel(queue);
scheduledAt = null;
if (!input.canRun() && !(input.canReconcile?.() ?? false)) { schedule(task.retryMs); return; }
dirty = false;
const finish = beginIdleTrackedWork();
const attempt = new AbortController();
controller = attempt;
running = Promise.resolve().then(() => reconcileDatabaseWork(input.owner, queue))
.then(() => workerStopped || !input.canRun() ? undefined : task.run(attempt.signal)).then(() => workerStopped ? false : task.hasPending()).then(pending => {
if (pending || databaseWorkPending(input.owner, queue)) schedule(task.retryMs);
else { finishIntent?.(); finishIntent = undefined; }
}).catch(error => {
schedule(task.retryMs);
// Logging must never turn a recoverable sweep failure into an
// unhandled rejection or prevent other queues from running.
try { if (!workerStopped) input.onError(error, queue); } catch { /* Recovery remains scheduled. */ }
}).finally(() => {
running = null;
controller = null;
finish();
if (dirty) schedule(0);
});
}
function wake() {
if (workerStopped) return;
dirty = true;
if (!running) schedule(0);
}
const unsubscribe = subscribeDatabaseWork(input.owner, queue, event => {
if (workerStopped) return;
if (databaseWorkPending(input.owner, queue)) {
finishIntent ??= beginIdleTrackedWork();
// Give the transaction time to settle. Its settlement notification
// replaces this deadline with an immediate wake on the normal path.
if (!running) schedule(task.retryMs);
}
if (event === "settled") wake();
});
const worker = { wake, async stop() {
workerStopped = true;
controller?.abort(new Error("Delivery worker stopped"));
unsubscribe();
scheduler.cancel(queue);
await running;
finishIntent?.(); finishIntent = undefined;
} };
workers.set(queue, worker);
const ready = Promise.resolve().then(() => { start(); return running; });
return { ready, wake };
},
async stop() {
stopped = true;
scheduler.stop();
await Promise.all(Array.from(workers.values(), worker => worker.stop()));
workers.clear();
},
};
}
@@ -0,0 +1,22 @@
import { signalDatabaseWork, subscribeDatabaseWork } from "@paperclipai/db";
/** Topics for existing durable queues; register intent before their writes. */
export const DELIVERY_QUEUES = {
feedback: "feedback-exports",
chatCompletion: "chat-completions",
connection: "connection-continuations",
question: "question-responses",
toolAction: "tool-action-receipts",
} as const;
export type DeliveryQueue = typeof DELIVERY_QUEUES[keyof typeof DELIVERY_QUEUES];
export async function notifyDeliveryWork(transaction: object, queue: DeliveryQueue): Promise<void> {
await signalDatabaseWork(transaction, queue);
}
// Public delivery notification observers only see settled work. The coordinator
// uses the lower-level lifecycle subscription to also fence in-flight writes.
export function subscribeDeliveryWork(owner: object, queue: DeliveryQueue, wake: () => void): () => void {
return subscribeDatabaseWork(owner, queue, event => {
if (event === "settled") wake();
});
}
+10 -2
View File
@@ -2,6 +2,8 @@ import { gzipSync } from "node:zlib";
import type { FeedbackTraceBundle } from "@paperclipai/shared";
import type { Config } from "../config.js";
export const FEEDBACK_UPLOAD_TIMEOUT_MS = 30_000;
const DEFAULT_FEEDBACK_EXPORT_BACKEND_URL = "https://telemetry.paperclip.ing";
function buildFeedbackShareObjectKey(bundle: FeedbackTraceBundle, exportedAt: Date) {
@@ -12,7 +14,7 @@ function buildFeedbackShareObjectKey(bundle: FeedbackTraceBundle, exportedAt: Da
}
export interface FeedbackTraceShareClient {
uploadTraceBundle(bundle: FeedbackTraceBundle): Promise<{ objectKey: string }>;
uploadTraceBundle(bundle: FeedbackTraceBundle, signal?: AbortSignal): Promise<{ objectKey: string }>;
}
export function createFeedbackTraceShareClientFromConfig(
@@ -23,7 +25,10 @@ export function createFeedbackTraceShareClientFromConfig(
const endpoint = new URL("/feedback-traces", baseUrl).toString();
return {
async uploadTraceBundle(bundle) {
async uploadTraceBundle(bundle, shutdownSignal) {
const deadline = AbortSignal.timeout(FEEDBACK_UPLOAD_TIMEOUT_MS);
const signal = shutdownSignal ? AbortSignal.any([shutdownSignal, deadline]) : deadline;
signal.throwIfAborted();
const exportedAt = new Date();
const objectKey = buildFeedbackShareObjectKey(bundle, exportedAt);
const requestBody = JSON.stringify({
@@ -33,6 +38,7 @@ export function createFeedbackTraceShareClientFromConfig(
});
const response = await fetch(endpoint, {
method: "POST",
signal,
headers: {
"content-type": "application/json",
...(token ? { authorization: `Bearer ${token}` } : {}),
@@ -49,6 +55,8 @@ export function createFeedbackTraceShareClientFromConfig(
}
const payload = await response.json().catch(() => null) as { objectKey?: unknown } | null;
// A timed-out response body is not a successful upload acknowledgement.
signal.throwIfAborted();
return {
objectKey: typeof payload?.objectKey === "string" && payload.objectKey.trim().length > 0
? payload.objectKey
+26 -4
View File
@@ -1,3 +1,4 @@
import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { readFile, readdir } from "node:fs/promises";
import path from "node:path";
import { and, asc, desc, eq, getTableColumns, gte, isNull, lte, ne, or } from "drizzle-orm";
@@ -111,7 +112,7 @@ const feedbackExportColumns = getTableColumns(feedbackExports);
const instructionsSvc = agentInstructionsService();
type FeedbackTraceShareClient = {
uploadTraceBundle(bundle: FeedbackTraceBundle): Promise<{ objectKey: string }>;
uploadTraceBundle(bundle: FeedbackTraceBundle, signal?: AbortSignal): Promise<{ objectKey: string }>;
};
type FeedbackServiceOptions = {
@@ -1715,6 +1716,15 @@ async function buildFeedbackTraceBundleFromRow(
}
export function feedbackService(db: Db, options: FeedbackServiceOptions = {}) {
// Serialize explicit flushes and the worker's batches so callers cannot
// upload the same trace concurrently. HTTP vote handlers only save and notify.
let exportFlush: Promise<unknown> = Promise.resolve();
function serializeExportFlush<T>(operation: () => Promise<T>): Promise<T> {
const result = exportFlush.then(operation, operation);
exportFlush = result.catch(() => undefined);
return result;
}
return {
listIssueVotesForUser: async (issueId: string, authorUserId: string) =>
db
@@ -1786,13 +1796,23 @@ export function feedbackService(db: Db, options: FeedbackServiceOptions = {}) {
return row ? buildFeedbackTraceBundleFromRow(db, row) : null;
},
hasPendingFeedbackTraces: async () => {
const pending = options.shareClient
? or(eq(feedbackExports.status, "pending"), eq(feedbackExports.status, "failed"))
: eq(feedbackExports.status, "pending");
return (await db.select({ id: feedbackExports.id }).from(feedbackExports)
.where(pending).limit(1)).length > 0;
},
flushPendingFeedbackTraces: async (input?: {
companyId?: string;
traceId?: string;
limit?: number;
now?: Date;
}) => {
signal?: AbortSignal;
}) => serializeExportFlush(async () => {
const shareClient = options.shareClient;
input?.signal?.throwIfAborted();
if (!shareClient) {
const filters = [eq(feedbackExports.status, "pending")];
if (input?.companyId) {
@@ -1861,12 +1881,13 @@ export function feedbackService(db: Db, options: FeedbackServiceOptions = {}) {
let failed = 0;
for (const row of rows) {
if (input?.signal?.aborted) break;
const attemptAt = input?.now ?? new Date();
attempted += 1;
try {
const bundle = await buildFeedbackTraceBundleFromRow(db, row);
await shareClient.uploadTraceBundle(bundle);
await shareClient.uploadTraceBundle(bundle, input?.signal);
await db
.update(feedbackExports)
@@ -1900,7 +1921,7 @@ export function feedbackService(db: Db, options: FeedbackServiceOptions = {}) {
sent,
failed,
};
},
}),
saveIssueVote: async (input: {
issueId: string;
@@ -2071,6 +2092,7 @@ export function feedbackService(db: Db, options: FeedbackServiceOptions = {}) {
})
.where(eq(feedbackVotes.id, savedVote.id));
if (sharedWithLabs) await notifyDeliveryWork(tx, DELIVERY_QUEUES.feedback);
const [savedTrace] = await tx
.insert(feedbackExports)
.values({
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,310 @@
import { randomUUID } from "node:crypto";
import type { Db } from "@paperclipai/db";
import { agents, agentWakeupRequests, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issues, projects } from "@paperclipai/db";
import { eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { runningProcesses } from "../../adapters/index.js";
import { adapterExecutionControls } from "../adapter-execution-control.js";
import { terminateLocalService } from "../local-service-supervisor.js";
import { createHeartbeatRunState } from "./run-state.js";
import { createHeartbeatRunPreparation } from "./run-preparation.js";
import { createHeartbeatLifecycle, type HeartbeatLifecycleDependencies } from "./run-lifecycle.js";
import { createHeartbeatRunControl, type HeartbeatRunControlDependencies } from "./run-control.js";
vi.mock("../live-events.js", () => ({ publishLiveEvent: vi.fn() }));
vi.mock("../local-service-supervisor.js", async (importOriginal) => ({
...await importOriginal<typeof import("../local-service-supervisor.js")>(),
terminateLocalService: vi.fn(async () => undefined),
}));
type Run = typeof heartbeatRuns.$inferSelect;
function callbacks(db: Db) {
const state = createHeartbeatRunState(db);
const lifecycleDependencies = {
...state,
...createHeartbeatRunPreparation(db),
issuesSvc: {
addComment: vi.fn<HeartbeatLifecycleDependencies["issuesSvc"]["addComment"]>(),
listReviewAttention: vi.fn<HeartbeatLifecycleDependencies["issuesSvc"]["listReviewAttention"]>(),
},
recovery: { escalateStrandedAssignedIssue: vi.fn<HeartbeatLifecycleDependencies["recovery"]["escalateStrandedAssignedIssue"]>() },
companySkills: { completeTestRunForIssue: vi.fn<HeartbeatLifecycleDependencies["companySkills"]["completeTestRunForIssue"]>() },
budgets: { getInvocationBlock: vi.fn(async () => null) },
treeControlSvc: { getActivePauseHoldGate: vi.fn(async () => null) },
enqueueWakeup: vi.fn<HeartbeatLifecycleDependencies["enqueueWakeup"]>(),
getCurrentUserRedactionOptions: vi.fn(async () => ({})),
getAgentInvokability: vi.fn<HeartbeatLifecycleDependencies["getAgentInvokability"]>(async () => ({ invokable: true })),
emitTerminalAgentTaskRun: vi.fn<HeartbeatLifecycleDependencies["emitTerminalAgentTaskRun"]>(),
budgetHooks: {},
} satisfies HeartbeatLifecycleDependencies;
const lifecycle = createHeartbeatLifecycle(db, lifecycleDependencies);
return {
...state,
...lifecycle,
getRun: vi.fn(state.getRun),
getAgent: vi.fn(state.getAgent),
setRunStatusFromLive: vi.fn(lifecycle.setRunStatusFromLive),
setRunStatus: vi.fn(lifecycle.setRunStatus),
setWakeupStatus: vi.fn(lifecycle.setWakeupStatus),
appendRunEvent: vi.fn(lifecycle.appendRunEvent),
finalizeAgentStatus: vi.fn<HeartbeatRunControlDependencies["finalizeAgentStatus"]>(),
options: { closeWarmNativeSessionsForRun: vi.fn(async () => ({ closed: 1, busy: 0, failed: 0 })) },
envOrchestrator: { releaseForRun: vi.fn<HeartbeatRunControlDependencies["envOrchestrator"]["releaseForRun"]>(async () => ({ released: [], errors: [] })) },
enqueueWakeup: lifecycleDependencies.enqueueWakeup,
startNextQueuedRunForAgent: vi.fn<HeartbeatRunControlDependencies["startNextQueuedRunForAgent"]>(),
sweepPendingCleanupLeases: vi.fn<HeartbeatRunControlDependencies["sweepPendingCleanupLeases"]>(),
timerClaimWasFirstHeartbeat: vi.fn<HeartbeatRunControlDependencies["timerClaimWasFirstHeartbeat"]>(() => undefined),
wakeQueue: { releaseIssueExecution: vi.fn<HeartbeatRunControlDependencies["wakeQueue"]["releaseIssueExecution"]>(async () => ({ outcome: { kind: "released" }, postCommitEffects: [] })) },
applyWakeQueuePostCommitEffects: vi.fn(async () => undefined),
getSchedulingSuppression: vi.fn(async () => ({ suppressed: false })),
activeRunExecutions: new Set<string>(),
processRunCancellationSettlements: new Map<string, { settled: Promise<void>; failed: boolean; error?: unknown }>(),
failedProcessRunCancellations: new Map<string, { settled: Promise<void>; failed: boolean; error?: unknown }>(),
} satisfies HeartbeatRunControlDependencies;
}
function guardedDatabase() {
const access = vi.fn(() => { throw new Error("Unexpected run-control database access"); });
return { db: new Proxy({}, { get: access }) as Db, access };
}
describe("heartbeat run-control module boundary", () => {
afterEach(() => adapterExecutionControls.clear());
it("constructs without database access, cancellation, or cleanup", () => {
const database = guardedDatabase();
const deps = callbacks(database.db);
createHeartbeatRunControl(database.db, deps);
expect(database.access).not.toHaveBeenCalled();
for (const callback of Object.values(deps)) if (vi.isMockFunction(callback)) expect(callback).not.toHaveBeenCalled();
expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled();
expect(deps.options.closeWarmNativeSessionsForRun).not.toHaveBeenCalled();
});
it("keeps an already completed run out of cancellation effects", async () => {
const database = guardedDatabase();
const deps = callbacks(database.db);
const run = { id: "finished", status: "succeeded", runtimeMode: "legacy" } as Run;
deps.getRun.mockResolvedValue(run);
expect(await createHeartbeatRunControl(database.db, deps).cancelRunInternal(run.id)).toBe(run);
expect(database.access).not.toHaveBeenCalled();
expect(deps.getAgent).not.toHaveBeenCalled();
expect(deps.appendRunEvent).not.toHaveBeenCalled();
});
it("keeps a suppressed saved-input scan out of the database and wake admission", async () => {
const database = guardedDatabase();
const deps = callbacks(database.db);
deps.getSchedulingSuppression.mockResolvedValue({ suppressed: true });
await createHeartbeatRunControl(database.db, deps).resumeExecutionWaitComments();
expect(database.access).not.toHaveBeenCalled();
expect(deps.enqueueWakeup).not.toHaveBeenCalled();
});
it("ignores an empty cancellation batch", async () => {
const database = guardedDatabase();
const deps = callbacks(database.db);
expect(await createHeartbeatRunControl(database.db, deps).cancelInvocationsForAgentsInternal(["", ""], "pause")).toEqual({ agentIds: [], runsCancelled: 0, wakeupsCancelled: 0 });
expect(database.access).not.toHaveBeenCalled();
expect(deps.getAgent).not.toHaveBeenCalled();
});
it("waits for an owned adapter before admitting saved comments", async () => {
const database = guardedDatabase();
const deps = callbacks(database.db);
const run = { id: "owned", status: "cancelled", runtimeMode: "legacy" } as Run;
adapterExecutionControls.set(run.id, {} as never);
await createHeartbeatRunControl(database.db, deps).resumeRemoteStopComments(run);
expect(database.access).not.toHaveBeenCalled();
expect(deps.enqueueWakeup).not.toHaveBeenCalled();
});
it("retains leases while native execution ownership is unverified", async () => {
const database = guardedDatabase();
const deps = callbacks(database.db);
deps.getRun.mockResolvedValue({ runtimeMode: "native", status: "running", nativePhase: "terminal_failure", errorCode: "native_execution_ownership_unverified" } as Run);
await createHeartbeatRunControl(database.db, deps).releaseEnvironmentLeasesForRun({ runId: "held", companyId: "company", agentId: "agent", status: "failed", providerResourceDisposition: "destroy" });
expect(database.access).not.toHaveBeenCalled();
expect(deps.options.closeWarmNativeSessionsForRun).not.toHaveBeenCalled();
expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled();
});
it("uses the persisted terminal outcome when choosing warm resource retention", async () => {
const database = guardedDatabase();
const deps = callbacks(database.db);
deps.getRun.mockResolvedValue({ status: "failed", runtimeMode: "legacy" } as Run);
await createHeartbeatRunControl(database.db, deps).releaseEnvironmentLeasesForRun({ runId: "failed", companyId: "company", agentId: "agent", status: "succeeded", providerResourceDisposition: "keep_running" });
expect(deps.envOrchestrator.releaseForRun).toHaveBeenCalledWith(expect.objectContaining({ heartbeatRunId: "failed", status: "failed", providerResourceDisposition: "stop_and_retain" }));
expect(database.access).not.toHaveBeenCalled();
});
it("defers destruction when a warm session remains busy", async () => {
const database = guardedDatabase();
const deps = callbacks(database.db);
deps.getRun.mockResolvedValue({ status: "failed", runtimeMode: "legacy" } as Run);
deps.options.closeWarmNativeSessionsForRun.mockResolvedValue({ closed: 0, busy: 1, failed: 0 });
await createHeartbeatRunControl(database.db, deps).releaseEnvironmentLeasesForRun({ runId: "busy", companyId: "company", agentId: "agent", status: "failed", providerResourceDisposition: "destroy" });
expect(deps.options.closeWarmNativeSessionsForRun).toHaveBeenCalledWith({ runId: "busy", reason: "terminal heartbeat run destroyed its environment lease" });
expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled();
expect(database.access).not.toHaveBeenCalled();
});
});
const support = await getEmbeddedPostgresTestSupport();
if (!support.supported) console.warn(`Skipping run-control database tests: ${support.reason}`);
describe.skipIf(!support.supported)("heartbeat run-control database wiring", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("paperclip-heartbeat-run-control-module");
db = createDb(database.connectionString);
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
afterAll(async () => {
await db?.$client.end();
await database?.cleanup();
});
beforeEach(async () => {
vi.mocked(terminateLocalService).mockReset().mockResolvedValue(undefined);
await db.execute(sql`truncate table companies restart identity cascade`);
});
afterEach(() => runningProcesses.clear());
async function fixture() {
const [company] = await db.insert(companies).values({ name: "Run control", issuePrefix: "RC" }).returning();
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Controlled agent", adapterType: "codex_local" }).returning();
return { company, agent };
}
async function liveRun(companyId: string, agentId: string) {
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "running", runtimeMode: "legacy", runtimeModeResolvedAt: new Date() }).returning();
runningProcesses.set(run.id, { child: { pid: 424242 } as never, graceSec: 4, processGroupId: 424242 });
return run;
}
it("reports a missing run without entering cancellation", async () => {
const deps = callbacks(db);
await expect(createHeartbeatRunControl(db, deps).cancelRunInternal(randomUUID())).rejects.toThrow("Heartbeat run not found");
expect(deps.getAgent).not.toHaveBeenCalled();
expect(deps.setRunStatusFromLive).not.toHaveBeenCalled();
expect(deps.appendRunEvent).not.toHaveBeenCalled();
});
it("joins concurrent Stop requests across factories through the shared process barrier", async () => {
const { company, agent } = await fixture();
const run = await liveRun(company.id, agent.id);
const deps = callbacks(db);
const cancellationLookup = vi.spyOn(deps.processRunCancellationSettlements, "get");
let releaseTermination!: () => void;
const terminating = new Promise<void>(resolve => { releaseTermination = resolve; });
vi.mocked(terminateLocalService).mockReturnValue(terminating);
const first = createHeartbeatRunControl(db, deps).cancelRunInternal(run.id, "Stop", { terminationGraceMs: 1 });
await vi.waitFor(() => expect(deps.processRunCancellationSettlements.has(run.id)).toBe(true));
const second = createHeartbeatRunControl(db, deps).cancelRunInternal(run.id, "Stop again");
await vi.waitFor(() => expect(cancellationLookup).toHaveBeenCalledTimes(2));
expect(deps.setRunStatusFromLive).not.toHaveBeenCalled();
expect(terminateLocalService).toHaveBeenCalledTimes(1);
releaseTermination();
const results = await Promise.all([first, second]);
expect(results.map(result => result?.status)).toEqual(["cancelled", "cancelled"]);
expect(deps.setRunStatusFromLive).toHaveBeenCalledTimes(1);
expect(deps.appendRunEvent).toHaveBeenCalledTimes(1);
expect(deps.finalizeAgentStatus).toHaveBeenCalledTimes(1);
expect(deps.startNextQueuedRunForAgent).toHaveBeenCalledTimes(1);
expect(deps.processRunCancellationSettlements.size).toBe(0);
expect(runningProcesses.has(run.id)).toBe(false);
expect(terminateLocalService).toHaveBeenCalledWith({ pid: 424242, processGroupId: 424242 }, { forceAfterMs: 100, signal: "SIGINT" });
});
it("settles every joined Stop caller with the same termination failure", async () => {
const { company, agent } = await fixture();
const run = await liveRun(company.id, agent.id);
const deps = callbacks(db);
const cancellationLookup = vi.spyOn(deps.processRunCancellationSettlements, "get");
deps.activeRunExecutions.add(run.id);
let rejectTermination!: (error: Error) => void;
vi.mocked(terminateLocalService).mockReturnValue(new Promise<void>((_resolve, reject) => { rejectTermination = reject; }));
const first = createHeartbeatRunControl(db, deps).cancelRunInternal(run.id);
await vi.waitFor(() => expect(deps.processRunCancellationSettlements.has(run.id)).toBe(true));
const second = createHeartbeatRunControl(db, deps).cancelRunInternal(run.id);
const results = Promise.allSettled([first, second]);
await vi.waitFor(() => expect(cancellationLookup).toHaveBeenCalledTimes(2));
const failure = new Error("provider did not stop");
rejectTermination(failure);
expect(await results).toEqual([{ status: "rejected", reason: failure }, { status: "rejected", reason: failure }]);
expect(terminateLocalService).toHaveBeenCalledTimes(1);
expect(deps.processRunCancellationSettlements.size).toBe(0);
expect(deps.failedProcessRunCancellations.get(run.id)?.error).toBe(failure);
expect(deps.setRunStatusFromLive).not.toHaveBeenCalled();
expect((await deps.getRun(run.id))?.status).toBe("running");
});
it("retains failed Stop evidence and the owned process until a later request succeeds", async () => {
const { company, agent } = await fixture();
const run = await liveRun(company.id, agent.id);
const deps = callbacks(db);
deps.activeRunExecutions.add(run.id);
const failure = new Error("termination failed");
vi.mocked(terminateLocalService).mockRejectedValueOnce(failure);
await expect(createHeartbeatRunControl(db, deps).cancelRunInternal(run.id)).rejects.toBe(failure);
expect(deps.failedProcessRunCancellations.get(run.id)).toMatchObject({ failed: true, error: failure });
expect(deps.processRunCancellationSettlements.size).toBe(0);
expect(runningProcesses.has(run.id)).toBe(true);
expect((await deps.getRun(run.id))?.status).toBe("running");
expect(deps.finalizeAgentStatus).not.toHaveBeenCalled();
expect(await createHeartbeatRunControl(db, deps).cancelRunInternal(run.id)).toMatchObject({ status: "cancelled" });
expect(terminateLocalService).toHaveBeenCalledTimes(2);
// The executor still owns removal of this evidence after it observes Stop.
expect(deps.failedProcessRunCancellations.get(run.id)?.error).toBe(failure);
});
it("deduplicates agent batches and cancels only unclaimed pending wakes", async () => {
const { company, agent } = await fixture();
const [otherAgent] = await db.insert(agents).values({ companyId: company.id, name: "Other agent" }).returning();
const [finished] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, status: "succeeded" }).returning();
const wakes = await db.insert(agentWakeupRequests).values([
{ companyId: company.id, agentId: agent.id, source: "assignment", status: "queued" },
{ companyId: company.id, agentId: agent.id, source: "assignment", status: "deferred_issue_execution" },
{ companyId: company.id, agentId: agent.id, source: "assignment", status: "claimed" },
{ companyId: company.id, agentId: agent.id, source: "assignment", status: "queued", runId: finished.id },
{ companyId: company.id, agentId: otherAgent.id, source: "assignment", status: "queued" },
]).returning();
const deps = callbacks(db);
expect(await createHeartbeatRunControl(db, deps).cancelInvocationsForAgentsInternal([agent.id, "", agent.id], "pause")).toEqual({ agentIds: [agent.id], runsCancelled: 0, wakeupsCancelled: 2 });
const persisted = await db.select().from(agentWakeupRequests);
expect(wakes.map(wake => persisted.find(row => row.id === wake.id)?.status)).toEqual(["cancelled", "cancelled", "claimed", "queued", "queued"]);
expect(deps.getAgent).toHaveBeenCalledTimes(1);
});
it("rechecks stale budget enforcement before cancelling runs or queued wakes", async () => {
const { company, agent } = await fixture();
const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, status: "queued", runtimeMode: "legacy" }).returning();
const [wake] = await db.insert(agentWakeupRequests).values({ companyId: company.id, agentId: agent.id, source: "assignment", status: "queued" }).returning();
const deps = callbacks(db);
await createHeartbeatRunControl(db, deps).cancelBudgetScopeWork({ companyId: company.id, scopeType: "agent", scopeId: agent.id, enforcement: { policyId: randomUUID(), version: 1 } });
expect((await deps.getRun(run.id))?.status).toBe("queued");
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id)))[0].status).toBe("queued");
expect(deps.setRunStatusFromLive).not.toHaveBeenCalled();
expect(deps.finalizeAgentStatus).not.toHaveBeenCalled();
expect(terminateLocalService).not.toHaveBeenCalled();
});
it("limits project budget cancellation by company, effective project, and admission cutoff", async () => {
const { company, agent } = await fixture();
const [otherCompany] = await db.insert(companies).values({ name: "Other company", issuePrefix: "OC" }).returning();
const [otherAgent] = await db.insert(agents).values({ companyId: otherCompany.id, name: "Other company agent" }).returning();
const projectRows = await db.insert(projects).values([
{ companyId: company.id, name: "Target" }, { companyId: company.id, name: "Override" },
]).returning();
const [issue] = await db.insert(issues).values({ companyId: company.id, projectId: projectRows[0].id, title: "Bound task", issueNumber: 1, identifier: "RC-1" }).returning();
const old = new Date("2026-01-01T00:00:00Z");
const cutoff = new Date("2026-01-02T00:00:00Z");
const wakes = await db.insert(agentWakeupRequests).values([
{ companyId: company.id, agentId: agent.id, source: "assignment", status: "queued", createdAt: old, payload: { issueId: issue.id } },
{ companyId: company.id, agentId: agent.id, source: "assignment", status: "queued", createdAt: old, payload: { issueId: issue.id, projectId: projectRows[1].id } },
{ companyId: company.id, agentId: agent.id, source: "assignment", status: "queued", createdAt: cutoff, payload: { projectId: projectRows[0].id } },
{ companyId: otherCompany.id, agentId: otherAgent.id, source: "assignment", status: "queued", createdAt: old, payload: { projectId: projectRows[0].id } },
]).returning();
await createHeartbeatRunControl(db, callbacks(db)).cancelBudgetScopeWork({ companyId: company.id, scopeType: "project", scopeId: projectRows[0].id, createdBefore: cutoff });
const persisted = await db.select().from(agentWakeupRequests);
expect(wakes.map(wake => persisted.find(row => row.id === wake.id)?.status)).toEqual(["cancelled", "queued", "queued", "queued"]);
});
});
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,5 @@
import { normalizeEscapedLineBreaks } from "@paperclipai/shared/validators/text";
import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { activeIssueInteractionCondition, historicalQuestionCondition } from "./issue-question-context.js";
import {
currentContinuationOrigins,
@@ -2829,6 +2830,7 @@ export function issueThreadInteractionService(
.returning();
if (!row) throw interactionAlreadyResolvedError();
if (status === "accepted" || status === "rejected") {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.connection);
await tx.insert(connectionIntentDeliveries).values({ interactionId, companyId: issue.companyId }).onConflictDoNothing();
}
return row;
@@ -5026,6 +5028,7 @@ export function issueThreadInteractionService(
// This answer updates conversation history only. It must not resume
// the completed source run or enqueue new work for the closed task.
if (!historicalAnswer) {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.question);
await tx
.insert(issueQuestionResponseDeliveries)
.values(questionResponseDeliveryValues(answered));
@@ -1340,5 +1340,9 @@ export function questionResponseDeliveryService(
return counts;
}
return { deliver, sweepPending };
async function hasPending() {
return (await db.select({ id: issueQuestionResponseDeliveries.id }).from(issueQuestionResponseDeliveries)
.where(inArray(issueQuestionResponseDeliveries.status, ["pending", "delivering"])).limit(1)).length > 0;
}
return { deliver, sweepPending, hasPending };
}
@@ -345,6 +345,12 @@ export function toolActionDeliveryService(
}
return {
deliver,
async hasPending() {
// Include receipts awaiting review/execution: their later terminal write
// must remain recoverable even if its optional fast-path callback fails.
return (await db.select({ id: toolActionDeliveries.actionRequestId }).from(toolActionDeliveries)
.where(isNull(toolActionDeliveries.deliveredAt)).limit(1)).length > 0;
},
async deliverForRun(input: { companyId: string; runId: string }) {
// A review can settle before its source run yields. Retry that run's
// receipts as soon as execution cleanup finishes; the periodic sweep
@@ -1,3 +1,4 @@
import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { and, eq } from "drizzle-orm";
import {
issues,
@@ -206,6 +207,7 @@ export async function commitToolActionReview(
: { version: 1, outcome: "rejected", reason: input.reason },
})
.where(eq(issueThreadInteractions.id, interaction.id));
await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolAction);
await tx
.insert(toolActionDeliveries)
.values({
+13 -9
View File
@@ -1,3 +1,4 @@
import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notifications.js";
import { composeConnectionInstructions } from "./connection-instructions.js";
import { isInsufficientConnectionScope, INSUFFICIENT_CONNECTION_SCOPE_MESSAGE } from "./connection-permission-errors.js";
import { boundedMcpToolName } from "./mcp-tool-names.js";
@@ -2615,15 +2616,18 @@ export function createToolGatewayService(
);
}
await db
.insert(toolActionDeliveries)
.values({
companyId: input.session.companyId,
actionRequestId: actionRequest.id,
issueId: input.session.issueId,
interactionId: interaction.id,
})
.onConflictDoNothing();
await db.transaction(async tx => {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.toolAction);
await tx
.insert(toolActionDeliveries)
.values({
companyId: input.session.companyId,
actionRequestId: actionRequest.id,
issueId: input.session.issueId!,
interactionId: interaction.id,
})
.onConflictDoNothing();
});
await writeToolCallEvent({
invocationId: input.invocation.id,
+45
View File
@@ -0,0 +1,45 @@
/** In-process deadlines. Owners restore durable tasks at startup. */
export function createWorkScheduler() {
const tasks = new Map<string, { at: number; run: () => void }>();
let timer: ReturnType<typeof setTimeout> | null = null;
let stopped = false;
const nextWakeAt = () => tasks.size ? Math.min(...Array.from(tasks.values(), task => task.at)) : null;
function arm() {
if (timer) clearTimeout(timer);
timer = null;
const next = nextWakeAt();
if (stopped || next === null) return;
timer = setTimeout(() => {
timer = null;
const now = Date.now();
const due = Array.from(tasks.entries()).filter(([, task]) => task.at <= now);
for (const [key, task] of due) {
// Another due callback can cancel or replace this task.
if (tasks.get(key) !== task) continue;
tasks.delete(key);
try { task.run(); }
catch (error) { process.emitWarning(`Scheduled work failed: ${String(error)}`); }
}
arm();
}, Math.min(2_147_483_647, Math.max(0, next - Date.now())));
timer.unref?.();
}
return {
nextWakeAt,
schedule(key: string, at: number, run: () => void) {
if (stopped) return;
if (!Number.isFinite(at)) throw new Error("Work deadline must be finite");
tasks.set(key, { at, run });
arm();
},
cancel(key: string) { tasks.delete(key); arm(); },
stop() {
stopped = true;
tasks.clear();
if (timer) clearTimeout(timer);
timer = null;
},
};
}