mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
fix(heartbeat): guarantee queued interrupt receipt coalescing on admission (#22984)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - When an agent is busy on a chat or task, a person's follow-up
message parks as a `deferred_issue_execution` wake and can be sent
immediately via Interrupt (`queued-comment-interrupt:<queueId>`)
> - At claim time, `explicitOperatorRunIdentity` requires that
`<queueId>` was atomically coalesced into the replacement run (`status =
'coalesced'`, `runId = run.id`), or it rejects the claim with `403
Queued-message interrupt authority is unavailable`
> - Three admission paths still allowed a replacement wake or run to be
written without coalescing `<queueId>`: `/new` conversation resets
bypassed `readBlocker` but not `readCommentCandidates`,
`admitFreshIssueRun` inserted the primary wake and queued run even when
`readCommentCandidates` returned `[]` under an execution blocker, and
resuming an interrupt behind an active conversation run fell through to
`admitBusy` and inserted a duplicate deferred wake carrying
`queued-comment-interrupt:<queueId>`
> - This pull request aligns execution-blocker checks between admission
and candidate adoption, aborts fresh admission before creating a wake or
run when a required resumed receipt cannot be adopted, and stops
already-deferred interrupt/retry receipts from duplicating behind an
active execution run
> - The benefit is that queued messages sent while an agent is busy
coalesce cleanly with valid operator interrupt authority, while
legitimate execution blockers continue to hold non-reset work safely
## Linked Issues or Issue Description
Refs #14865, #20698
**What happened**
Even after #14857 and #20698 (card-answer interrupts), queued chat
interrupts can still leave their interrupt receipt uncoalesced (`status
= 'deferred_issue_execution'`, `runId = null`) while creating a
replacement wake/run carrying `idempotencyKey =
queued-comment-interrupt:<queueId>`:
1. A verified `/new` chat interrupt passes `readBlocker` (which forwards
`conversationResetCommentId`), but `readCommentCandidates` called
`getExecutionBlocker(tx, companyId, issueId)` without
`conversationResetCommentId`, returned `candidates: []`, and still
inserted a queued run whose claim immediately failed with `403
Queued-message interrupt authority is unavailable`.
2. If any execution blocker (including a concurrent `READ COMMITTED`
lease/recovery hold or multiple pre-boundary `restoreHold` rows) made
`readCommentCandidates` return `[]`, `admitFreshIssueRun` still inserted
both the primary wake request and a doomed queued run without coalescing
`queuedCommentInterruptId`.
3. When `resumeQueuedCommentInterrupt` entered `enqueueWakeup` while
`activeExecutionRun` held the issue on a conversation
(`allowRunCoalescing: false`), it fell through to `admitBusy` and
inserted a second `deferred_issue_execution` wake with `idempotencyKey =
queued-comment-interrupt:<queueId>`; once promoted after the active run
finished, that duplicate run failed claim with `403 Queued-message
interrupt authority is unavailable`.
**Expected behavior**
A queued interrupt run is only created when its interrupt receipt is
atomically coalesced into that run in the same transaction; otherwise
admission defers cleanly without inserting a duplicate wake or doomed
run. Legitimate execution blockers continue to hold non-reset messages.
## What Changed
- `server/src/modules/wake-queue/application/recovery-admission.ts` &
`server/src/services/heartbeat/queue.ts`: expose
`conversationResetCommentId` from `prepareRecovery` and pass it into
`admitFresh`, so `readCommentCandidates` applies the same verified
`/new` reset policy as `readBlocker`.
- `server/src/modules/wake-queue/adapters/postgres.ts`: forward optional
`conversationResetCommentId` to `getExecutionBlocker` in
`readCommentCandidates` (preserving the 3-argument call when absent),
and add `FreshIssueAdmissionRollbackError` handling in
`withIssueAdmission`.
- `server/src/modules/wake-queue/application/fresh-issue-run.ts` &
`server/src/modules/wake-queue/index.ts`: read comment candidates before
inserting the primary wake receipt for non-promoted fresh runs; if a
required resumed receipt (`queuedCommentInterruptId`,
`queuedCommentRequestId`, or `boardRetryReceiptId`) is not adopted,
return `undefined` without creating a wake or run (and roll back the
transaction if `explicitContinuationRunId` already wrote recovery
state).
- `server/src/services/heartbeat/queue.ts`: return `{ kind: "deferred"
}` immediately under `if (activeExecutionRun)` when resuming an
already-deferred `queuedCommentInterruptId`, `queuedCommentRequestId`,
or `taskRetryRequestId`, preventing `admitBusy` from folding it into
another run or inserting a duplicate deferred wake.
- `server/src/services/explicit-native-continuation.ts`: include
`restoreHoldPredicate()` in the conversation-boundary recovery action
query so multiple pre-boundary restore holds are resolved together
rather than leaving a residual hold for `readCommentCandidates`.
- `server/src/__tests__/heartbeat-queued-run-claim-isolation.test.ts` &
`server/src/modules/wake-queue/adapters/postgres.test.ts`: add
embedded-Postgres regression tests covering queued `/new` interrupts
under an active ownership hold, interrupt resumes racing an active chat
run (no duplicate `queued-comment-interrupt:` wakes and clean delivery
once the run ends), `admitFresh` aborting before creating a doomed run
when a blocker hides a required interrupt receipt, and confirming
non-reset ordinary chat messages still remain held behind an active
ownership blocker until released.
## Verification
- **RED (before production edits on
`2d065677959b585065ff3fec8718156a4cf6f41d`):**
- `cd server && npx vitest run
src/__tests__/heartbeat-queued-run-claim-isolation.test.ts`: failed on
queued `/new` interrupt (`receipt.status` stayed
`"deferred_issue_execution"` instead of `"coalesced"`) and on
active-chat interrupt race (`duplicateInterruptWakes` contained a newly
inserted duplicate wake instead of `[]`).
- `cd server && npx vitest run
src/modules/wake-queue/adapters/postgres.test.ts -t "checks execution
holds only when the scoped saved receipt exists"`: failed with
`AssertionError: expected { status: "queued", ... } to be undefined`
because `admitFresh` inserted a queued run despite
`readCommentCandidates` returning `[]`.
- **GREEN (after fix):**
- `pnpm --filter @paperclipai/server typecheck`: PASS (0 errors across
all 7 layers).
- `node scripts/check-module-boundaries.mjs`: PASS.
- `node scripts/check-test-budget.mjs --files
server/src/__tests__/heartbeat-queued-run-claim-isolation.test.ts
server/src/modules/wake-queue/adapters/postgres.test.ts`: PASS (`110
nightly suites validated, 2 test file(s) checked`).
- `cd server && npx vitest run --no-file-parallelism
src/__tests__/heartbeat-queued-run-claim-isolation.test.ts
src/modules/wake-queue/application/recovery-admission.test.ts
src/modules/wake-queue/adapters/postgres.test.ts`: **3/3 files, 148/148
passed**.
- `cd server && npx vitest run src/__tests__/run-identity.test.ts
src/__tests__/heartbeat-responsible-user-invariant.test.ts`: **all
passed**.
- `cd server && npx vitest run --no-file-parallelism
src/__tests__/issue-queued-comments-dispatch-routes.test.ts
src/services/heartbeat/queue.test.ts`: **158/158 test assertions
passed** (`issue-queued-comments-dispatch-routes.test.ts` 40/40 passed;
`queue.test.ts` 118/118 tests passed, with only its `afterAll`
embedded-Postgres shutdown hitting the 30s default hook timeout on a
loaded host).
- `pnpm verify --base 2d06567795
--explain`: selects 1,947/2,301 Vitest files (shared hub `queue.ts`);
focused suites passed locally and PR CI supplies full sharded coverage.
## Risks
- Low risk. Legitimate execution blockers (including active ownership
holds and unresolved reconciliation holds on non-reset messages) are
preserved and explicitly covered by a new regression test.
- Moving `readCommentCandidates` before `saveReceipt` only applies to
non-promoted fresh runs; promoted durable chat wakes keep their existing
promote-before-read order so they cannot be re-adopted as secondary
candidates.
- No database migrations or schema changes.
## Model Used
- Google Gemini (Antigravity agent with tool use and local code/test
execution).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
1 parent
1299d1d776
commit
5e6bfe698d
8 files changed
+305
-17
No files matched your search
@@ -8,8 +8,10 @@ import {
|
||||
companies,
|
||||
companyMemberships,
|
||||
createDb,
|
||||
environmentLeases,
|
||||
heartbeatRuns,
|
||||
externalAgentHolds,
|
||||
issueComments,
|
||||
issues,
|
||||
issueThreadInteractions,
|
||||
} from "@paperclipai/db";
|
||||
@@ -363,4 +365,210 @@ describeEmbeddedPostgres("heartbeat queued-run claim isolation", () => {
|
||||
expect(await runStatus(rejectedRunId)).toMatchObject({ status: "cancelled" });
|
||||
expect(await runStatus(healthyRunId)).toMatchObject({ status: "succeeded" });
|
||||
});
|
||||
|
||||
it("coalesces and claims a queued /new chat interrupt when a non-restore execution blocker exists", async () => {
|
||||
const { companyId, agentId } = await insertAgent();
|
||||
const userId = `chat-owner-${randomUUID()}`;
|
||||
await db.insert(authUsers).values({
|
||||
id: userId, name: "Chat owner", email: `${userId}@paperclip.test`,
|
||||
createdAt: new Date(), updatedAt: new Date(),
|
||||
});
|
||||
await db.insert(companyMemberships).values({
|
||||
companyId, principalType: "user", principalId: userId, status: "active", membershipRole: "owner",
|
||||
});
|
||||
const issueId = randomUUID();
|
||||
await db.insert(issues).values({
|
||||
id: issueId, companyId, title: "Agent chat", status: "in_progress",
|
||||
assigneeAgentId: agentId, conversationAgentId: agentId, conversationUserId: userId,
|
||||
conversationState: "active", responsibleUserId: userId,
|
||||
});
|
||||
// An active conversation ownership hold (unreleased environment lease on a
|
||||
// prior stopped run). A verified user `/new` is permitted past non-restore
|
||||
// holds, so admission and receipt coalescing must agree.
|
||||
const priorRunId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: priorRunId, companyId, agentId, runtimeMode: "legacy", status: "cancelled",
|
||||
finishedAt: new Date(Date.now() - 5_000),
|
||||
contextSnapshot: { issueId },
|
||||
runnerProfileJson: { adapterDispatch: { adapterType: "codex_local" } },
|
||||
});
|
||||
await db.insert(environmentLeases).values({
|
||||
companyId, heartbeatRunId: priorRunId, status: "active",
|
||||
});
|
||||
|
||||
const commentId = randomUUID();
|
||||
await db.insert(issueComments).values({
|
||||
id: commentId, companyId, issueId, authorType: "user", authorUserId: userId, body: "/new",
|
||||
});
|
||||
const queueId = randomUUID();
|
||||
await db.insert(agentWakeupRequests).values({
|
||||
id: queueId, companyId, agentId, source: "on_demand", triggerDetail: "manual",
|
||||
reason: "issue_execution_deferred", status: "deferred_issue_execution",
|
||||
requestedByActorType: "user", requestedByActorId: userId,
|
||||
payload: {
|
||||
issueId, commentId,
|
||||
queuedCommentInterrupt: { actorId: userId, requestedAt: new Date().toISOString() },
|
||||
_paperclipWakeContext: { issueId, commentId, wakeCommentId: commentId, wakeCommentIds: [commentId] },
|
||||
},
|
||||
});
|
||||
|
||||
await heartbeat.resumeQueuedCommentInterrupt(companyId, queueId);
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
|
||||
const [receipt] = await db.select({ status: agentWakeupRequests.status, runId: agentWakeupRequests.runId })
|
||||
.from(agentWakeupRequests).where(sql`${agentWakeupRequests.id} = ${queueId}`);
|
||||
expect(receipt).toMatchObject({ status: "coalesced" });
|
||||
expect(receipt?.runId).toBeTruthy();
|
||||
expect(await runStatus(receipt!.runId!)).toMatchObject({ status: "succeeded", errorCode: null });
|
||||
const [successor] = await db.select({ responsibleUserId: heartbeatRuns.responsibleUserId })
|
||||
.from(heartbeatRuns).where(sql`${heartbeatRuns.id} = ${receipt!.runId!}`);
|
||||
expect(successor).toMatchObject({ responsibleUserId: userId });
|
||||
const [updatedIssue] = await db.select({ conversationBoundaryCommentId: issues.conversationBoundaryCommentId })
|
||||
.from(issues).where(sql`${issues.id} = ${issueId}`);
|
||||
expect(updatedIssue).toMatchObject({ conversationBoundaryCommentId: commentId });
|
||||
});
|
||||
|
||||
it("does not duplicate an interrupt receipt behind an active chat run and delivers cleanly once the run ends", async () => {
|
||||
const { companyId, agentId } = await insertAgent();
|
||||
const otherAgentId = randomUUID();
|
||||
await db.insert(agents).values({
|
||||
id: otherAgentId, companyId, name: "Other Agent", role: "engineer", status: "idle",
|
||||
adapterType: "codex_local", adapterConfig: {},
|
||||
runtimeConfig: { heartbeat: { enabled: true, intervalSec: 60, wakeOnDemand: true, maxConcurrentRuns: 1 } },
|
||||
permissions: {},
|
||||
});
|
||||
const userId = `chat-owner-${randomUUID()}`;
|
||||
await db.insert(authUsers).values({
|
||||
id: userId, name: "Chat owner", email: `${userId}@paperclip.test`,
|
||||
createdAt: new Date(), updatedAt: new Date(),
|
||||
});
|
||||
await db.insert(companyMemberships).values({
|
||||
companyId, principalType: "user", principalId: userId, status: "active", membershipRole: "owner",
|
||||
});
|
||||
const issueId = randomUUID();
|
||||
const activeRunId = randomUUID();
|
||||
await db.insert(issues).values({
|
||||
id: issueId, companyId, title: "Busy agent chat", status: "in_progress",
|
||||
assigneeAgentId: agentId, conversationAgentId: agentId, conversationUserId: userId,
|
||||
conversationState: "active", responsibleUserId: userId,
|
||||
});
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: activeRunId, companyId, agentId: otherAgentId, status: "running",
|
||||
invocationSource: "on_demand", contextSnapshot: { issueId },
|
||||
});
|
||||
await db.update(issues).set({ executionRunId: activeRunId }).where(sql`${issues.id} = ${issueId}`);
|
||||
const commentId = randomUUID();
|
||||
await db.insert(issueComments).values({
|
||||
id: commentId, companyId, issueId, authorType: "user", authorUserId: userId,
|
||||
body: "Follow-up message sent while busy",
|
||||
});
|
||||
const queueId = randomUUID();
|
||||
await db.insert(agentWakeupRequests).values({
|
||||
id: queueId, companyId, agentId, source: "on_demand", triggerDetail: "manual",
|
||||
reason: "issue_execution_deferred", status: "deferred_issue_execution",
|
||||
requestedByActorType: "user", requestedByActorId: userId,
|
||||
payload: {
|
||||
issueId, commentId,
|
||||
queuedCommentInterrupt: { actorId: userId, requestedAt: new Date().toISOString() },
|
||||
_paperclipWakeContext: { issueId, commentId, wakeCommentId: commentId, wakeCommentIds: [commentId] },
|
||||
},
|
||||
});
|
||||
|
||||
// Resume attempts while an active execution still holds the issue must leave
|
||||
// the original receipt deferred without inserting a second wake carrying
|
||||
// `queued-comment-interrupt:<queueId>` (which would later promote uncoalesced
|
||||
// and fail claim with 403).
|
||||
await heartbeat.resumeQueuedCommentInterrupt(companyId, queueId);
|
||||
const duplicateInterruptWakes = await db.select({ id: agentWakeupRequests.id })
|
||||
.from(agentWakeupRequests)
|
||||
.where(sql`${agentWakeupRequests.idempotencyKey} = ${`queued-comment-interrupt:${queueId}`}`);
|
||||
expect(duplicateInterruptWakes).toEqual([]);
|
||||
const [stillDeferred] = await db.select({ status: agentWakeupRequests.status, runId: agentWakeupRequests.runId })
|
||||
.from(agentWakeupRequests).where(sql`${agentWakeupRequests.id} = ${queueId}`);
|
||||
expect(stillDeferred).toMatchObject({ status: "deferred_issue_execution", runId: null });
|
||||
|
||||
// Once the active run completes and releases the lock, resuming delivers once.
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() })
|
||||
.where(sql`${heartbeatRuns.id} = ${activeRunId}`);
|
||||
await db.update(issues).set({ executionRunId: null }).where(sql`${issues.id} = ${issueId}`);
|
||||
|
||||
await heartbeat.resumeQueuedCommentInterrupt(companyId, queueId);
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
|
||||
const [receipt] = await db.select({ status: agentWakeupRequests.status, runId: agentWakeupRequests.runId })
|
||||
.from(agentWakeupRequests).where(sql`${agentWakeupRequests.id} = ${queueId}`);
|
||||
expect(receipt).toMatchObject({ status: "coalesced" });
|
||||
expect(receipt?.runId).toBeTruthy();
|
||||
expect(await runStatus(receipt!.runId!)).toMatchObject({ status: "succeeded", errorCode: null });
|
||||
const [successor] = await db.select({ responsibleUserId: heartbeatRuns.responsibleUserId })
|
||||
.from(heartbeatRuns).where(sql`${heartbeatRuns.id} = ${receipt!.runId!}`);
|
||||
expect(successor).toMatchObject({ responsibleUserId: userId });
|
||||
expect(mockAdapterExecute).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("still holds a non-reset ordinary chat message behind an active ownership blocker without creating a doomed run", async () => {
|
||||
const { companyId, agentId } = await insertAgent();
|
||||
const userId = `chat-owner-${randomUUID()}`;
|
||||
await db.insert(authUsers).values({
|
||||
id: userId, name: "Chat owner", email: `${userId}@paperclip.test`,
|
||||
createdAt: new Date(), updatedAt: new Date(),
|
||||
});
|
||||
await db.insert(companyMemberships).values({
|
||||
companyId, principalType: "user", principalId: userId, status: "active", membershipRole: "owner",
|
||||
});
|
||||
const issueId = randomUUID();
|
||||
await db.insert(issues).values({
|
||||
id: issueId, companyId, title: "Held chat", status: "in_progress",
|
||||
assigneeAgentId: agentId, conversationAgentId: agentId, conversationUserId: userId,
|
||||
conversationState: "active", responsibleUserId: userId,
|
||||
});
|
||||
const priorRunId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({
|
||||
id: priorRunId, companyId, agentId, runtimeMode: "legacy", status: "cancelled",
|
||||
finishedAt: new Date(Date.now() - 5_000),
|
||||
contextSnapshot: { issueId },
|
||||
runnerProfileJson: { adapterDispatch: { adapterType: "codex_local" } },
|
||||
});
|
||||
await db.insert(environmentLeases).values({
|
||||
companyId, heartbeatRunId: priorRunId, status: "active",
|
||||
});
|
||||
const commentId = randomUUID();
|
||||
await db.insert(issueComments).values({
|
||||
id: commentId, companyId, issueId, authorType: "user", authorUserId: userId, body: "Regular follow-up",
|
||||
});
|
||||
const queueId = randomUUID();
|
||||
await db.insert(agentWakeupRequests).values({
|
||||
id: queueId, companyId, agentId, source: "on_demand", triggerDetail: "manual",
|
||||
reason: "issue_execution_deferred", status: "deferred_issue_execution",
|
||||
requestedByActorType: "user", requestedByActorId: userId,
|
||||
payload: {
|
||||
issueId, commentId,
|
||||
queuedCommentInterrupt: { actorId: userId, requestedAt: new Date().toISOString() },
|
||||
_paperclipWakeContext: { issueId, commentId, wakeCommentId: commentId, wakeCommentIds: [commentId] },
|
||||
},
|
||||
});
|
||||
|
||||
await heartbeat.resumeQueuedCommentInterrupt(companyId, queueId);
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
|
||||
const [receipt] = await db.select({ status: agentWakeupRequests.status, runId: agentWakeupRequests.runId })
|
||||
.from(agentWakeupRequests).where(sql`${agentWakeupRequests.id} = ${queueId}`);
|
||||
expect(receipt).toMatchObject({ status: "deferred_issue_execution", runId: null });
|
||||
const runs = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns)
|
||||
.where(sql`${heartbeatRuns.companyId} = ${companyId} and ${heartbeatRuns.id} <> ${priorRunId}`);
|
||||
expect(runs).toEqual([]);
|
||||
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
||||
|
||||
// Releasing the ownership blocker allows the interrupt to coalesce and succeed.
|
||||
await db.update(environmentLeases).set({ status: "released", releasedAt: new Date(), cleanupStatus: "success" })
|
||||
.where(sql`${environmentLeases.heartbeatRunId} = ${priorRunId}`);
|
||||
await heartbeat.resumeQueuedCommentInterrupt(companyId, queueId);
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
|
||||
const [delivered] = await db.select({ status: agentWakeupRequests.status, runId: agentWakeupRequests.runId })
|
||||
.from(agentWakeupRequests).where(sql`${agentWakeupRequests.id} = ${queueId}`);
|
||||
expect(delivered).toMatchObject({ status: "coalesced" });
|
||||
expect(await runStatus(delivered!.runId!)).toMatchObject({ status: "succeeded", errorCode: null });
|
||||
expect(mockAdapterExecute).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
} from "./postgres.js";
|
||||
import type { WakeQueuePostgresAdapterDeps } from "./postgres.js";
|
||||
import { createReleaseIssueExecution } from "../application/use-cases.js";
|
||||
import { createFreshIssueRunAdmission } from "../application/fresh-issue-run.js";
|
||||
import { withQueuedCommentIdsInRunContext, withQueuedCommentIdsInWakePayload } from "../../../services/issue-queued-comment-queue.js";
|
||||
|
||||
// Proves the atomicity and company-scope properties the security review
|
||||
@@ -242,6 +243,43 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => {
|
||||
.resolves.toMatchObject({ handoffAgentId: formerAgentId, candidates: [{ id: wakeId }] });
|
||||
expect(blocker).toHaveBeenCalledTimes(1);
|
||||
|
||||
// When a required interrupt receipt owned by the admitting agent cannot
|
||||
// be adopted because an execution blocker is active, fresh admission
|
||||
// must consult the blocker and abort before inserting a wake request or
|
||||
// queued run that would fail claim-time interrupt authority.
|
||||
const interruptWakeId = await seedDeferredWake({ companyId, agentId, issueId });
|
||||
const admitFresh = createFreshIssueRunAdmission(fresh);
|
||||
const commentId = randomUUID();
|
||||
const blockedInterruptRun = await admitFresh({
|
||||
receipt: {
|
||||
agentId, source: "on_demand", triggerDetail: "manual", reason: "issue_commented",
|
||||
payload: { issueId, commentId }, requestedByActorType: "user", requestedByActorId: "operator-1",
|
||||
idempotencyKey: `queued-comment-interrupt:${interruptWakeId}`,
|
||||
},
|
||||
issue: { id: issueId, assigneeAgentId: agentId, isConversation: true },
|
||||
executionWaitRequestId: interruptWakeId,
|
||||
queuedCommentInterruptId: interruptWakeId,
|
||||
ownsReconstructionContinuation: false,
|
||||
contextSnapshot: { issueId, wakeCommentId: commentId, wakeCommentIds: [commentId] },
|
||||
resolveSessionIdBefore: async () => null,
|
||||
continuationAttempt: 0,
|
||||
explicitContinuationRunId: null,
|
||||
retryOfRunId: null,
|
||||
reconciledSourceRunId: null,
|
||||
reconciledRestoreRetryCount: null,
|
||||
resolveResponsibleUserId: async () => "operator-1",
|
||||
recordContinuationDelivery: async () => {},
|
||||
});
|
||||
expect(blockedInterruptRun).toBeUndefined();
|
||||
expect(blocker).toHaveBeenCalledTimes(2);
|
||||
expect(blocker).toHaveBeenLastCalledWith(tx, companyId, issueId);
|
||||
const insertedInterruptWakes = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests)
|
||||
.where(and(eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.idempotencyKey, `queued-comment-interrupt:${interruptWakeId}`)));
|
||||
expect(insertedInterruptWakes).toEqual([]);
|
||||
const insertedQueuedRuns = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.status, "queued")));
|
||||
expect(insertedQueuedRuns).toEqual([]);
|
||||
|
||||
const select = vi.spyOn(tx, "select");
|
||||
try {
|
||||
expect(await executionBlocker.getExecutionBlocker(tx as unknown as Db, companyId, issueId, {
|
||||
|
||||
@@ -1329,6 +1329,13 @@ export type IssueAdmissionRow = Pick<IssueRow, keyof typeof issueAdmissionFields
|
||||
export type IssueWakeContinuationInput = Omit<Parameters<typeof admitExplicitNativeContinuation>[0], "db" | "companyId" | "issueId" | "dryRun" | "onBlocked">;
|
||||
export type IssueWakeContinuationResult = NonNullable<Awaited<ReturnType<typeof admitExplicitNativeContinuation>>>;
|
||||
|
||||
export class FreshIssueAdmissionRollbackError extends Error {
|
||||
constructor() {
|
||||
super("wake-queue: fresh issue admission aborted after continuation write");
|
||||
this.name = "FreshIssueAdmissionRollbackError";
|
||||
}
|
||||
}
|
||||
|
||||
export function createPostgresIssueWakeAdmission(db: Db) {
|
||||
return async function withIssueAdmission(
|
||||
{ companyId, issueId, durableChatRequest }: IssueAdmissionTarget,
|
||||
@@ -1415,7 +1422,7 @@ export function createPostgresIssueWakeAdmission(db: Db) {
|
||||
});
|
||||
}));
|
||||
} catch (error) {
|
||||
if (isExternalChatWaitAuthorizationContention(error)) return null;
|
||||
if (isExternalChatWaitAuthorizationContention(error) || error instanceof FreshIssueAdmissionRollbackError) return null;
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -1707,7 +1714,7 @@ export function createFreshIssueRunStore(
|
||||
)).returning();
|
||||
return receipt;
|
||||
},
|
||||
async readCommentCandidates({ issueId, agentId, handoffRunId, receiptScope, checkExecutionBlocker }) {
|
||||
async readCommentCandidates({ issueId, agentId, handoffRunId, receiptScope, checkExecutionBlocker, conversationResetCommentId }) {
|
||||
const [handoff] = handoffRunId ? await tx.select({ agentId: heartbeatRuns.agentId }).from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.id, handoffRunId), eq(heartbeatRuns.companyId, companyId),
|
||||
eq(heartbeatRuns.status, "cancelled"), eq(heartbeatRuns.errorCode, "issue_reassigned"),
|
||||
@@ -1729,7 +1736,11 @@ export function createFreshIssueRunStore(
|
||||
receiptScope.kind === "exact" ? eq(agentWakeupRequests.id, receiptScope.wakeId) : undefined,
|
||||
)).orderBy(asc(agentWakeupRequests.requestedAt))
|
||||
: [];
|
||||
const blocked = candidates.length > 0 && checkExecutionBlocker && await getExecutionBlocker(tx, companyId, issueId);
|
||||
const blocked = candidates.length > 0 && checkExecutionBlocker && await (
|
||||
conversationResetCommentId
|
||||
? getExecutionBlocker(tx, companyId, issueId, { conversationResetCommentId })
|
||||
: getExecutionBlocker(tx, companyId, issueId)
|
||||
);
|
||||
return { handoffAgentId: handoff?.agentId ?? null, candidates: blocked ? [] : candidates };
|
||||
},
|
||||
readUndeliveredLegacyCommentIds(issueId, agentId, commentIds) {
|
||||
|
||||
@@ -46,6 +46,7 @@ export type FreshIssueRunStore<Run> = {
|
||||
handoffRunId: string | null;
|
||||
receiptScope: { kind: "all" } | { kind: "exact"; wakeId: string } | null;
|
||||
checkExecutionBlocker: boolean;
|
||||
conversationResetCommentId?: string | null;
|
||||
}): Promise<{ handoffAgentId: string | null; candidates: DeferredCommentCandidate[] }>;
|
||||
readUndeliveredLegacyCommentIds(issueId: string, agentId: string, commentIds: string[]): Promise<string[]>;
|
||||
notifyRunMilestones(issueId: string): Promise<void>;
|
||||
@@ -70,6 +71,7 @@ type FreshIssueRunInput = {
|
||||
boardRetryReceiptId?: string;
|
||||
failedChatRetryReceiptId?: string;
|
||||
ownsReconstructionContinuation: boolean;
|
||||
conversationResetCommentId?: string | null;
|
||||
contextSnapshot: Record<string, unknown>;
|
||||
resolveSessionIdBefore(): Promise<string | null>;
|
||||
continuationAttempt: number;
|
||||
@@ -98,15 +100,6 @@ export function createFreshIssueRunAdmission<Run extends { id: string }>(store:
|
||||
const { receipt, durableReceipt, durableChatReceiptId, executionWaitRequestId, issue, contextSnapshot } = input;
|
||||
const { agentId, source, triggerDetail, reason, payload } = receipt;
|
||||
|
||||
// A deferred durable chat wake keeps its original identity and source.
|
||||
const primary = await store.saveReceipt(durableChatReceiptId && durableChatReceiptId === executionWaitRequestId
|
||||
? { kind: "promote", wakeId: durableChatReceiptId, agentId, payload }
|
||||
: {
|
||||
kind: "insert",
|
||||
seed: durableReceipt ? { ...receipt, id: durableReceipt.id, requestedAt: durableReceipt.requestedAt } : receipt,
|
||||
});
|
||||
if (!primary) return undefined;
|
||||
|
||||
// Only a verified reassignment can bring a previous executor's saved comments.
|
||||
const interruptedRunId = readNonEmptyString(contextSnapshot.interruptedRunId);
|
||||
const handoffRunId = source === "assignment" && reason === "issue_assigned" &&
|
||||
@@ -115,19 +108,45 @@ export function createFreshIssueRunAdmission<Run extends { id: string }>(store:
|
||||
|
||||
// Chat keeps separate batches, but an exact resumed receipt must be consumed with its successor.
|
||||
const canCoalesceComments = !durableChatReceiptId && !issue.isConversation && input.allowRunCoalescing !== false;
|
||||
const { handoffAgentId, candidates } = await store.readCommentCandidates({
|
||||
const isPromotedDurableChat = Boolean(durableChatReceiptId && durableChatReceiptId === executionWaitRequestId);
|
||||
const rawRequiredReceiptId = input.queuedCommentInterruptId ?? input.queuedCommentRequestId ?? input.boardRetryReceiptId ?? null;
|
||||
if (isPromotedDurableChat && rawRequiredReceiptId && rawRequiredReceiptId !== durableChatReceiptId) {
|
||||
throw new Error("wake-queue: promoted durable chat wake cannot require a separate resumed receipt");
|
||||
}
|
||||
const requiredReceiptId = isPromotedDurableChat ? null : rawRequiredReceiptId;
|
||||
const exactWakeId = executionWaitRequestId ?? requiredReceiptId;
|
||||
const readCandidates = () => store.readCommentCandidates({
|
||||
issueId: issue.id,
|
||||
agentId,
|
||||
handoffRunId,
|
||||
receiptScope: canCoalesceComments || (executionWaitRequestId && input.boardRetryReceiptId)
|
||||
? { kind: "all" }
|
||||
: executionWaitRequestId ? { kind: "exact", wakeId: executionWaitRequestId } : null,
|
||||
: exactWakeId ? { kind: "exact", wakeId: exactWakeId } : null,
|
||||
checkExecutionBlocker: !input.ownsReconstructionContinuation,
|
||||
...(input.conversationResetCommentId ? { conversationResetCommentId: input.conversationResetCommentId } : {}),
|
||||
});
|
||||
|
||||
// A deferred durable chat wake keeps its original identity and source, so it
|
||||
// must be promoted off `deferred_issue_execution` before reading secondary
|
||||
// candidates. Every other fresh run reads candidates first so a missing or
|
||||
// blocked required receipt aborts before writing a wake or doomed run.
|
||||
const promotedPrimary = isPromotedDurableChat
|
||||
? await store.saveReceipt({ kind: "promote", wakeId: durableChatReceiptId!, agentId, payload })
|
||||
: undefined;
|
||||
if (isPromotedDurableChat && !promotedPrimary) return undefined;
|
||||
|
||||
const { handoffAgentId, candidates } = await readCandidates();
|
||||
const adopted = candidates.filter((wake) => wake.id === executionWaitRequestId ||
|
||||
wake.id === input.queuedCommentInterruptId || wake.id === input.queuedCommentRequestId ||
|
||||
isOrdinaryBoardComment(wake));
|
||||
wake.id === input.boardRetryReceiptId || isOrdinaryBoardComment(wake));
|
||||
const adoptedWakeIds = adopted.map((wake) => wake.id);
|
||||
if (requiredReceiptId && !adoptedWakeIds.includes(requiredReceiptId)) return undefined;
|
||||
|
||||
const primary = promotedPrimary ?? await store.saveReceipt({
|
||||
kind: "insert",
|
||||
seed: durableReceipt ? { ...receipt, id: durableReceipt.id, requestedAt: durableReceipt.requestedAt } : receipt,
|
||||
});
|
||||
if (!primary) return undefined;
|
||||
let commentIds = [...new Set([
|
||||
...adopted.flatMap((wake) => queuedCommentIdsFromWakePayload(wake.payload)),
|
||||
...queuedCommentIdsFromRunContext(contextSnapshot),
|
||||
|
||||
@@ -38,6 +38,7 @@ export function createWakeRecoveryAdmission<ExplicitInput extends ExplicitContin
|
||||
return {
|
||||
blocker,
|
||||
ownsReconstruction,
|
||||
conversationResetCommentId: verifiedReset ? input.commentId : null,
|
||||
defer,
|
||||
async checkBusyAdmission() {
|
||||
let wait: ContinuationWait | undefined;
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
createIssueWakePreflightReader,
|
||||
createPostgresIssueWakeAdmission,
|
||||
createPostgresWakeQueueAdapter,
|
||||
FreshIssueAdmissionRollbackError,
|
||||
type IssueAdmissionDbTransaction,
|
||||
type IssueAdmissionRow,
|
||||
type IssueAdmissionTarget,
|
||||
@@ -138,7 +139,9 @@ export function createWakeQueue(db: Db, deps: WakeQueueDeps) {
|
||||
if (input.issue.id !== issueId || input.contextSnapshot.issueId !== issueId) {
|
||||
throw new Error("wake-queue: admission does not match the locked issue");
|
||||
}
|
||||
return admitFresh(input);
|
||||
const run = await admitFresh(input);
|
||||
if (!run && input.explicitContinuationRunId) throw new FreshIssueAdmissionRollbackError();
|
||||
return run;
|
||||
}, deferBlockedWake),
|
||||
});
|
||||
}), effects);
|
||||
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
environmentLeases, heartbeatRuns, issueComments, issueRecoveryActions,
|
||||
issues, nativeRunFinalizations, nativeRunResults, type Db,
|
||||
} from "@paperclipai/db";
|
||||
import { executionBlockerPredicate, getExecutionBlocker, hasPendingRunCleanup, nativeExecutionRecoveryActionPredicate, restoreHoldReleasedForCurrentOwnerPredicate } from "./execution-blocker.js";
|
||||
import { executionBlockerPredicate, getExecutionBlocker, hasPendingRunCleanup, nativeExecutionRecoveryActionPredicate, restoreHoldPredicate, restoreHoldReleasedForCurrentOwnerPredicate } from "./execution-blocker.js";
|
||||
import { buildExecutionContinuation } from "./execution-continuation.js";
|
||||
import { adapterExecutionControls } from "./adapter-execution-control.js";
|
||||
import { persistActivity } from "./activity-log.js";
|
||||
@@ -294,6 +294,7 @@ export async function admitExplicitNativeContinuation(input: {
|
||||
const actions = await db.select().from(issueRecoveryActions).where(and(
|
||||
eq(issueRecoveryActions.companyId, companyId), eq(issueRecoveryActions.sourceIssueId, issueId),
|
||||
boundary ? or(gt(issueRecoveryActions.createdAt, boundary.createdAt), nativeExecutionRecoveryActionPredicate(),
|
||||
restoreHoldPredicate(),
|
||||
blocker?.recoveryActionId ? eq(issueRecoveryActions.id, blocker.recoveryActionId) : undefined) : undefined,
|
||||
not(restoreHoldReleasedForCurrentOwnerPredicate()),
|
||||
or(executionBlockerPredicate(), and(
|
||||
|
||||
@@ -4851,6 +4851,12 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
// its fresh-session contract into unrelated work or create a second
|
||||
// deferred wake that could later replay the same reconciliation.
|
||||
if (reconciledSourceRunId) return { kind: "deferred" as const };
|
||||
// An already-deferred interrupt, saved-comment, or task-retry receipt
|
||||
// is its own durable outbox. Never fold it into an active run or insert
|
||||
// a second deferred wake that loses its exact receipt-binding authority.
|
||||
if (opts.queuedCommentInterruptId || opts.queuedCommentRequestId || opts.taskRetryRequestId) {
|
||||
return { kind: "deferred" as const };
|
||||
}
|
||||
|
||||
// Offer the input to the active external agent, but keep a durable queued wake
|
||||
// until it reads the comment. A finish racing the event tick must
|
||||
@@ -5187,6 +5193,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
boardRetryReceiptId: failedChatRetry ? undefined : opts.taskRetryRequestId,
|
||||
failedChatRetryReceiptId: failedChatRetry ? opts.taskRetryRequestId : undefined,
|
||||
ownsReconstructionContinuation: Boolean(ownsReconstructionContinuation),
|
||||
conversationResetCommentId: recovery.conversationResetCommentId,
|
||||
explicitContinuationRunId: explicitContinuation ? explicitContinuationRunId : null,
|
||||
retryOfRunId: failedChatRetry
|
||||
? durableRequest!.failedRunRetry!.failedRunId
|
||||
|
||||
Reference in new issue
Block a user