Files
PaperClipAI/server/src/modules/wake-queue/index.ts
T
Dotta 5e6bfe698d 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
2026-11-25 15:32:47 -06:00

175 lines
8.0 KiB
TypeScript

import type { Db, heartbeatRuns } from "@paperclipai/db";
import { forbidden } from "../../errors.js";
import {
createIssueWakePreflightReader,
createPostgresIssueWakeAdmission,
createPostgresWakeQueueAdapter,
FreshIssueAdmissionRollbackError,
type IssueAdmissionDbTransaction,
type IssueAdmissionRow,
type IssueAdmissionTarget,
type IssueWakeContinuationInput,
type IssueWakeContinuationResult,
} from "./adapters/postgres.js";
import { createQueuedCommentIssueLockWriter } from "./adapters/queued-comment-postgres.js";
import { createQueuedCommentSteeringAdapter, lockBoardQueuedComments, readBoardQueuedComments } from "./adapters/queued-comment-board-postgres.js";
import type { QueuedCommentQueuePostgresAdapterDeps } from "./adapters/queued-comment-postgres.js";
import { createFreshIssueRunAdmission } from "./application/fresh-issue-run.js";
import { createWakeRecoveryAdmission } from "./application/recovery-admission.js";
import type { ActivityPublication } from "../../services/activity-log.js";
import { admitIssueWake, createIssueWakePreflight, type IssueWakeAdmissionEffects, type IssueWakeAdmissionOutcome } from "./application/issue-wake-admission.js";
import { createAdmitWakeBehindIssueExecution, createReleaseIssueExecution } from "./application/use-cases.js";
import {
createDiscardQueuedComment,
createEditQueuedComment,
createReorderQueuedComments,
createSteerQueuedComment,
} from "./application/queued-comment-use-cases.js";
import type {
IssueSnapshot,
RecoveryEscalationPort,
RunSnapshot,
WakeAdmissionHeartbeatHelpers,
WakeQueueHost,
} from "./application/ports.js";
export type {
IssueAttributionSnapshot,
PostCommitEffect,
ReleaseOutcome,
RunSummary,
} from "./application/types.js";
export { createAutomaticGoalCommentSteering } from "./application/automatic-goal-comment-steering.js";
export { WakeQueueApplicationError } from "./application/types.js";
export { hasRetainedExternalChatRetry } from "./domain/context.js";
export { QUEUED_MESSAGES_DELIVERED_REASON } from "./domain/policy.js";
export type {
IssueSnapshot,
RunSnapshot,
RecoveryEscalationPort,
ReleaseRecoveryBlockedNoticeKind,
} from "./application/ports.js";
export type { ReleaseIssueExecutionInput } from "./application/use-cases.js";
export {
QueuedCommentMutationError,
QueuedCommentMutationForbiddenError,
requireQueuedCommentMutationTarget,
} from "./application/queued-comment-use-cases.js";
export type {
DiscardQueuedCommentInput,
DiscardQueuedCommentResult,
EditQueuedCommentInput,
EditQueuedCommentResult,
QueuedCommentMutationErrorCode,
ReorderQueuedCommentsInput,
ReorderQueuedCommentsResult,
} from "./application/queued-comment-use-cases.js";
export type {
QueuedCommentActivityPublication,
QueuedCommentActor,
QueuedCommentIssueContext,
QueuedCommentQueueSnapshot,
} from "./application/queued-comment-ports.js";
export type { QueuedCommentQueuePostgresAdapterDeps } from "./adapters/queued-comment-postgres.js";
export type WakeQueueDeps = {
/** Stays in `heartbeat.ts`; resolves the responsible user for a promoted or recovery run seed. */
resolveResponsibleUserId: WakeQueueHost["resolveResponsibleUserId"];
/** Stays in `heartbeat.ts`; reads the routine environment context for an execution issue. */
getRoutineEnv: WakeQueueHost["getRoutineEnv"];
/** Stays in `heartbeat.ts`; resolves the session-before display id for a wakeup. */
resolveSessionBeforeForWakeup: WakeQueueHost["resolveSessionBeforeForWakeup"];
/**
* The four wake-admission decision helpers stay in `heartbeat.ts` today;
* the module receives them here so it never imports the service it is
* extracted from.
*/
wakeAdmissionHelpers: WakeAdmissionHeartbeatHelpers;
/** `services/recovery`'s stranded-issue escalation, called only after the release transaction commits. */
recovery: RecoveryEscalationPort;
};
type HeartbeatRun = typeof heartbeatRuns.$inferSelect;
type LockedIssueAdmission = {
lockedIssue: IssueAdmissionRow | null;
lockIssue: () => Promise<IssueAdmissionRow | null>;
prepareRecovery: ReturnType<typeof createWakeRecoveryAdmission<
IssueWakeContinuationInput, IssueWakeContinuationResult, ReturnType<typeof createAdmitWakeBehindIssueExecution>,
ReturnType<typeof createFreshIssueRunAdmission<HeartbeatRun>>, ActivityPublication
>>;
};
/** Composes the issue admission and release workflows with their Postgres locks. */
export function createWakeQueue(db: Db, deps: WakeQueueDeps) {
const issueLock = createPostgresWakeQueueAdapter(db, {
resolveResponsibleUserId: deps.resolveResponsibleUserId,
getRoutineEnv: deps.getRoutineEnv,
resolveSessionBeforeForWakeup: deps.resolveSessionBeforeForWakeup,
});
const withIssueAdmission = createPostgresIssueWakeAdmission(db);
const preflight = createIssueWakePreflight(createIssueWakePreflightReader(db));
return {
async preflightIssueWake(input: Parameters<typeof preflight>[0]) {
const outcome = await preflight(input);
if (outcome.kind === "conversation_owner_required") {
throw forbidden(`Only the conversation owner can ${outcome.action} a chat run`);
}
return outcome;
},
releaseIssueExecution: createReleaseIssueExecution({ issueLock, recovery: deps.recovery }),
admitIssueWake(
{ companyId, issueId, durableChatRequest }: IssueAdmissionTarget,
// Specialized heartbeat gates and continuation writes still use this locked transaction.
evaluateHeartbeatPolicy: (tx: IssueAdmissionDbTransaction, admission: LockedIssueAdmission) => Promise<IssueWakeAdmissionOutcome<HeartbeatRun>>,
effects: IssueWakeAdmissionEffects<HeartbeatRun>,
) {
return admitIssueWake(() => withIssueAdmission({ companyId, issueId, durableChatRequest }, (tx, { lockedIssue, lockIssue, recovery, deferBlockedWake, reader, writer, fresh }) => {
const admitBusy = createAdmitWakeBehindIssueExecution({ reader, writer, helpers: deps.wakeAdmissionHelpers });
const admitFresh = createFreshIssueRunAdmission(fresh);
return evaluateHeartbeatPolicy(tx, {
lockedIssue,
lockIssue,
prepareRecovery: createWakeRecoveryAdmission(recovery, async (input: Parameters<typeof admitBusy>[0]) => {
if (input.companyId !== companyId || input.issueId !== issueId || input.contextSnapshot.issueId !== issueId) {
throw new Error("wake-queue: admission does not match the locked company and issue");
}
return admitBusy(input);
}, async (input: Parameters<typeof admitFresh>[0]) => {
if (input.issue.id !== issueId || input.contextSnapshot.issueId !== issueId) {
throw new Error("wake-queue: admission does not match the locked issue");
}
const run = await admitFresh(input);
if (!run && input.explicitContinuationRunId) throw new FreshIssueAdmissionRollbackError();
return run;
}, deferBlockedWake),
});
}), effects);
},
};
}
export type WakeQueue = ReturnType<typeof createWakeQueue>;
/**
* Composes the queued-comment reads and mutations with their Postgres
* adapters. This is a separate factory
* from `createWakeQueue` because these mutations need none of the release
* or admission host callbacks -- only the small set of comment-reference
* and external-object sync callbacks in `deps`, which a caller outside
* `heartbeat.ts` (the queued-comment route) can supply directly.
*/
export function createQueuedCommentQueue(db: Db, deps: QueuedCommentQueuePostgresAdapterDeps) {
const issueLock = createQueuedCommentIssueLockWriter(db, deps);
return {
readBoardQueue: readBoardQueuedComments,
lockBoardQueue: lockBoardQueuedComments,
steerQueuedComment: createSteerQueuedComment(createQueuedCommentSteeringAdapter(db)),
editQueuedComment: createEditQueuedComment({ issueLock }),
reorderQueuedComments: createReorderQueuedComments({ issueLock }),
discardQueuedComment: createDiscardQueuedComment({ issueLock }),
};
}
export type QueuedCommentQueue = ReturnType<typeof createQueuedCommentQueue>;