mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-28 13:09:40 +01:00
fix(server): permit verified question-delivery history to sleep (#15851)
Treat completed question-response deliveries as history only after their exact same-company handoff finishes. Preserve missing evidence, retries, accounting debt, and idle-sleep fences. Add a concurrent all-state question history index with interrupted-build repair. Keep migrations serialized without waiting snapshots that deadlock concurrent index builds. Validated by 118 focused sleep tests, six migration/snapshot tests, full repository typecheck, all CI gates, and Apex 5/5. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
42ecc96556
commit
b36960b758
11 files changed
+2558
-18
No files matched your search
@@ -5,7 +5,8 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest
|
||||
import {
|
||||
agentInstructionWorkingCopies, agents, agentApiKeys, agentWakeupRequests, companies, companySecretProposals, createDb,
|
||||
adapterAuthSessions, environments, environmentLeases, executionWorkspaces,
|
||||
heartbeatRuns, issues, issueWatchdogs, projects, routines, type Db,
|
||||
heartbeatRuns, issues, issueWatchdogs, issueThreadInteractions, issueQuestionResponseDeliveries,
|
||||
projects, routines, type Db,
|
||||
} from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { readIdleSleepSafety, type IdleSleepDrainStatus } from "../services/idle-sleep-safety.js";
|
||||
@@ -184,6 +185,152 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${supp
|
||||
return { companyId, agentId, runId };
|
||||
}
|
||||
|
||||
async function seedQuestionDelivery(change: Partial<typeof issueQuestionResponseDeliveries.$inferInsert> = {}) {
|
||||
const seeded = await seed();
|
||||
await db.update(heartbeatRuns).set({ finishedAt: new Date(now) }).where(eq(heartbeatRuns.id, seeded.runId));
|
||||
const issueId = randomUUID();
|
||||
const interactionId = randomUUID();
|
||||
await db.insert(issues).values({ id: issueId, companyId: seeded.companyId, title: "Finished question", status: "done" });
|
||||
await db.insert(issueThreadInteractions).values({
|
||||
id: interactionId, companyId: seeded.companyId, issueId,
|
||||
kind: "ask_user_questions", status: "answered", payload: {},
|
||||
});
|
||||
await db.insert(issueQuestionResponseDeliveries).values({
|
||||
companyId: seeded.companyId, issueId, interactionId, sourceRunId: seeded.runId,
|
||||
targetRunId: seeded.runId, correlationId: randomUUID(), payloadSha256: "fixture",
|
||||
status: "fallback_queued", deliveryMode: "wake_fallback", acknowledgedAt: new Date(now), ...change,
|
||||
});
|
||||
return { ...seeded, issueId, interactionId };
|
||||
}
|
||||
|
||||
async function seedQuestionWake(
|
||||
delivery: Awaited<ReturnType<typeof seedQuestionDelivery>>,
|
||||
change: Partial<typeof agentWakeupRequests.$inferInsert> = {},
|
||||
) {
|
||||
await db.insert(agentWakeupRequests).values({
|
||||
companyId: delivery.companyId, agentId: delivery.agentId, source: "automation",
|
||||
idempotencyKey: `question-response:${delivery.interactionId}`,
|
||||
status: "completed", finishedAt: new Date(now), ...change,
|
||||
});
|
||||
}
|
||||
|
||||
it.each(["pending", "delivering"])("keeps a %s question delivery awake", async status => {
|
||||
await seedQuestionDelivery({ status, acknowledgedAt: null });
|
||||
expect(await read()).toEqual(present);
|
||||
});
|
||||
|
||||
it.each(["delivered", "fallback_queued"])("permits acknowledged %s history after its target run finishes", async status => {
|
||||
await seedQuestionDelivery({ status });
|
||||
expect(await read()).toEqual(none);
|
||||
});
|
||||
|
||||
it.each(["delivered", "fallback_queued"])("keeps an unacknowledged %s question delivery awake", async status => {
|
||||
await seedQuestionDelivery({ status, acknowledgedAt: null });
|
||||
expect(await read()).toEqual(present);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["queued", { status: "queued", finishedAt: null }],
|
||||
["running", { status: "running", finishedAt: null }],
|
||||
["unfinished", { finishedAt: null }],
|
||||
["retry", { scheduledRetryAt: new Date(now + 1000) }],
|
||||
["accounting", { costAccountingPending: true }],
|
||||
] as const)("keeps an acknowledged question delivery awake with %s target evidence", async (_name, change) => {
|
||||
const { runId } = await seedQuestionDelivery();
|
||||
await db.update(heartbeatRuns).set(change).where(eq(heartbeatRuns.id, runId));
|
||||
expect(await read()).toEqual(present);
|
||||
});
|
||||
|
||||
it("does not accept a foreign company's finished question target", async () => {
|
||||
const foreign = await seedQuestionDelivery({ status: "failed", targetRunId: null });
|
||||
await seedQuestionDelivery({ targetRunId: foreign.runId });
|
||||
expect(await read()).toEqual(present);
|
||||
});
|
||||
|
||||
it("keeps delivered history with a missing target awake", async () => {
|
||||
await seedQuestionDelivery({ status: "delivered", targetRunId: null });
|
||||
expect(await read()).toEqual(present);
|
||||
});
|
||||
|
||||
it("keeps fallback history without a durable wake receipt awake", async () => {
|
||||
await seedQuestionDelivery({ targetRunId: null });
|
||||
expect(await read()).toEqual(present);
|
||||
});
|
||||
|
||||
it.each(["completed", "failed", "cancelled", "skipped", "timed_out"])(
|
||||
"permits fallback history after its exact durable wake is %s and finished", async status => {
|
||||
const delivery = await seedQuestionDelivery({ targetRunId: null });
|
||||
await seedQuestionWake(delivery, { status });
|
||||
expect(await read()).toEqual(none);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["queued", "deferred_issue_execution", "coalesced"])("keeps an unresolved %s question wake awake", async status => {
|
||||
const delivery = await seedQuestionDelivery({ targetRunId: null });
|
||||
await seedQuestionWake(delivery, { status, finishedAt: null });
|
||||
expect(await read()).toEqual(present);
|
||||
});
|
||||
|
||||
it("keeps a terminal question wake without completion evidence awake", async () => {
|
||||
const delivery = await seedQuestionDelivery({ targetRunId: null });
|
||||
await seedQuestionWake(delivery, { finishedAt: null });
|
||||
expect(await read()).toEqual(present);
|
||||
});
|
||||
|
||||
it("permits a deferred question fallback after its coalesced continuation finishes", async () => {
|
||||
const delivery = await seedQuestionDelivery({ targetRunId: null });
|
||||
await seedQuestionWake(delivery, { status: "deferred_issue_execution", finishedAt: null });
|
||||
expect(await read()).toEqual(present);
|
||||
await db.update(agentWakeupRequests).set({
|
||||
status: "coalesced", runId: delivery.runId, finishedAt: new Date(now),
|
||||
}).where(eq(agentWakeupRequests.companyId, delivery.companyId));
|
||||
expect(await read()).toEqual(none);
|
||||
});
|
||||
|
||||
it.each(["missing_run", "wrong_company", "wrong_agent", "unfinished", "retry", "accounting"])(
|
||||
"keeps a coalesced question fallback awake with %s linked-run evidence", async kind => {
|
||||
const delivery = await seedQuestionDelivery({ targetRunId: null });
|
||||
let runId = delivery.runId;
|
||||
if (kind === "missing_run") runId = randomUUID();
|
||||
if (kind === "wrong_company") runId = (await seedQuestionDelivery({ status: "failed", targetRunId: null })).runId;
|
||||
if (kind === "wrong_agent") {
|
||||
const otherAgent = randomUUID();
|
||||
await db.insert(agents).values({ id: otherAgent, companyId: delivery.companyId, name: "Other", role: "engineer", status: "idle", adapterType: "process" });
|
||||
await db.update(heartbeatRuns).set({ agentId: otherAgent }).where(eq(heartbeatRuns.id, runId));
|
||||
}
|
||||
if (kind === "unfinished") await db.update(heartbeatRuns).set({ finishedAt: null }).where(eq(heartbeatRuns.id, runId));
|
||||
if (kind === "retry") await db.update(heartbeatRuns).set({ scheduledRetryAt: new Date(now + 1000) }).where(eq(heartbeatRuns.id, runId));
|
||||
if (kind === "accounting") await db.update(heartbeatRuns).set({ costAccountingPending: true }).where(eq(heartbeatRuns.id, runId));
|
||||
await seedQuestionWake(delivery, { status: "coalesced", runId });
|
||||
expect(await read()).toEqual(present);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not accept another interaction's or company's question wake receipt", async () => {
|
||||
const delivery = await seedQuestionDelivery({ targetRunId: null });
|
||||
await seedQuestionWake(delivery, { idempotencyKey: `question-response:${randomUUID()}` });
|
||||
const foreign = await seedQuestionDelivery({ status: "failed", targetRunId: null });
|
||||
await seedQuestionWake(delivery, { companyId: foreign.companyId, agentId: foreign.agentId });
|
||||
expect(await read()).toEqual(present);
|
||||
});
|
||||
|
||||
it("permits failed question-delivery history without a pending target", async () => {
|
||||
await seedQuestionDelivery({ status: "failed", targetRunId: null, acknowledgedAt: null });
|
||||
expect(await read()).toEqual(none);
|
||||
});
|
||||
|
||||
it("still blocks other work after a question handoff finishes", async () => {
|
||||
const { issueId } = await seedQuestionDelivery();
|
||||
await db.update(issues).set({ status: "todo" }).where(eq(issues.id, issueId));
|
||||
expect(await read()).toEqual(present);
|
||||
});
|
||||
|
||||
it("requires a current quiet owner even with completed question history", async () => {
|
||||
await seedQuestionDelivery();
|
||||
expect(await readIdleSleepSafety(db, owned, () => now, "stale-owner", emptyLocal)).toEqual(unknown);
|
||||
expect(await readIdleSleepSafety(db, owned, () => now + 60_001, ownerId, emptyLocal)).toEqual(unknown);
|
||||
});
|
||||
|
||||
it("keeps saved agent files awake until deferred cleanup completes", async () => {
|
||||
const { companyId, agentId, runId } = await seed();
|
||||
await db.insert(agentInstructionWorkingCopies).values({
|
||||
|
||||
@@ -93,13 +93,38 @@ const WORK_CHECKS = [
|
||||
THEN s.provider_lease_id::uuid END)
|
||||
AND (l.status IN ('released', 'expired') AND l.cleanup_status = 'success'
|
||||
AND l.released_at IS NOT NULL) IS NOT TRUE))`,
|
||||
// Answer delivery history is not work once its acknowledged handoff has
|
||||
// finished. Keep pending deliveries, unfinished target runs, and missing or
|
||||
// unfinished fallback wake receipts awake. Other work checks still apply.
|
||||
`SELECT 1 FROM issue_question_response_deliveries d WHERE
|
||||
d.status NOT IN ('delivered', 'fallback_queued', 'failed')
|
||||
OR (d.status IN ('delivered', 'fallback_queued') AND d.acknowledged_at IS NULL)
|
||||
OR (d.status = 'delivered' AND d.target_run_id IS NULL)
|
||||
OR (d.target_run_id IS NOT NULL AND NOT EXISTS (
|
||||
SELECT 1 FROM heartbeat_runs r WHERE r.id = d.target_run_id
|
||||
AND r.company_id = d.company_id
|
||||
AND r.status IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted')
|
||||
AND r.finished_at IS NOT NULL AND r.scheduled_retry_at IS NULL
|
||||
AND r.cost_accounting_pending = false))
|
||||
OR (d.status = 'fallback_queued' AND d.target_run_id IS NULL AND NOT EXISTS (
|
||||
SELECT 1 FROM agent_wakeup_requests w WHERE w.company_id = d.company_id
|
||||
AND w.idempotency_key = 'question-response:' || d.interaction_id::text
|
||||
AND w.idempotency_key LIKE 'question-response:%'
|
||||
AND w.finished_at IS NOT NULL
|
||||
AND (w.status IN ('completed', 'failed', 'cancelled', 'skipped', 'timed_out')
|
||||
OR (w.status = 'coalesced' AND EXISTS (
|
||||
SELECT 1 FROM heartbeat_runs r WHERE r.id = w.run_id
|
||||
AND r.company_id = w.company_id AND r.agent_id = w.agent_id
|
||||
AND r.status IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted')
|
||||
AND r.finished_at IS NOT NULL AND r.scheduled_retry_at IS NULL
|
||||
AND r.cost_accounting_pending = false)))))`,
|
||||
// These less common work sources fail closed on any retained state. Their
|
||||
// terminal-state exceptions can be added with tests for the owning service.
|
||||
...[
|
||||
"chat_endpoints", "chat_deliveries", "chat_publications", "chat_actions",
|
||||
"chat_completion_deliveries", "connection_event_deliveries",
|
||||
"connection_intent_deliveries", "tool_action_requests", "tool_action_deliveries",
|
||||
"issue_question_response_deliveries", "workspace_runtime_services",
|
||||
"workspace_runtime_services",
|
||||
"execution_workspace_runtime_leases", "pipeline_automation_executions",
|
||||
"native_run_finalizations", "company_transfer_runs", "decisions", "decision_effect_executions",
|
||||
"decision_archive_notification_outbox", "browser_use_sessions", "browser_use_runs",
|
||||
|
||||
Reference in new issue
Block a user