Own the issue admission lock and dispatch after commit in wake-queue (#22272)

## Thinking Path

> - Paperclip admits work for a task while other agents and users may
also act on it.
> - A fresh run and a wake behind an active execution both require the
same issue lock.
> - Heartbeat previously opened that transaction and passed handles
across the module boundary.
> - The wake-queue module can bind both admission operations to the
locked company and issue.
> - The result of the database commit determines whether to emit a
queued event, dispatch a run, or return a saved result.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The transaction and handoff used by task-bound wake admission.

**Subsystem affected**

Server task admission.

**Current behavior**

Heartbeat opens the transaction, builds a scope for the busy path, and
dispatches based on the result. Its contention handler can reach
buffered side effects after a rollback.

**Proposed behavior**

Wake-queue owns the lock and the durable acknowledgement. The
application hands off a committed result. A rolled-back contention
attempt returns without publishing its buffered effects.

**Additional context**

Depends on #22268 and #22266.

## What Changed

- Bind the busy and fresh admission operations to a single company and
issue in Postgres. Remove the transaction scope object.
- Keep specialized heartbeat gates and continuation writes on the
acquired transaction.
- Buffer the workspace preflight activity publication until the
transaction commits.
- Centralize the handoff for new, coalesced, replayed, deferred, skipped
and durable results.

## Verification

On 1c5a069406, local qualification passed 94 application tests, 33
focused Postgres scenarios, and all four fresh/busy rollback cases.
Server typecheck and the module boundary check passed.

Run the wake-queue application and adapter tests and the heartbeat queue
and comment wake suites. Verify the rollback, replay, chat
acknowledgement, and tenant and issue mismatch cases. Run the server
typecheck and module boundary check.

## Risks

The ordering of commit, saved notification and dispatch is observable. A
recognized chat authorization contention now discards buffered effects
from the rolled-back transaction. Specialized heartbeat policy still
uses the locked database transaction.

## Model Used

OpenAI GPT-6.2 Sol (`gpt-6.2-sol`) implemented the change. OpenAI Codex
directed the work, reviewed the diff, and ran qualification.

## 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

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Nicky LeachandPaperclip authored and GitHub committed 2026-11-18 19:24:40 -08:00
1 parent eca7f85778
commit ebb98120dc
21 files changed
+440 -363

No files matched your search

@@ -103,7 +103,7 @@ function isOrdinaryBoardComment(wake: DeferredCommentCandidate): boolean {
queuedCommentIdsFromWakePayload(payload).length > 0;
}
/** Admit one new run and its saved inputs using the caller's existing issue lock. */
/** Admit one new run and its saved inputs under the issue admission lock. */
export function createFreshIssueRunAdmission<Run extends { id: string }>(store: FreshIssueRunStore<Run>) {
return async function admitFreshIssueRun(input: FreshIssueRunInput): Promise<Run | undefined> {
const { receipt, durableReceipt, durableChatReceiptId, executionWaitRequestId, issue, contextSnapshot } = input;
@@ -0,0 +1,69 @@
import { describe, expect, it } from "vitest";
import { admitIssueWake, type IssueWakeAdmissionEffects, type IssueWakeAdmissionOutcome } from "./issue-wake-admission.js";
const queuedRun = { id: "run", companyId: "company", agentId: "agent", status: "queued",
invocationSource: "assignment", triggerDetail: null, wakeupRequestId: "wake" };
type Run = typeof queuedRun;
const runningRun = { ...queuedRun, status: "running" };
function recordEffects(trace: string[]): IssueWakeAdmissionEffects<Run> {
return {
saved: () => { trace.push("saved"); },
publishIssueActivity: () => { trace.push("issue activity"); },
executeIssueActions: async () => { trace.push("issue actions"); },
cancelledRuns: [{ ...queuedRun, status: "cancelled" }],
emitCancelledRun: (run) => {
trace.push(run.status);
return new Promise(() => {});
},
readRun: async (runId) => { trace.push(`read ${runId}`); return runningRun; },
publishQueuedRun: () => { trace.push("queued event"); },
attachSetupRequest: async () => { trace.push("attach setup"); },
dispatch: async () => { trace.push("dispatch"); },
};
}
describe("issue wake admission handoff", () => {
it("waits for commit before publishing or dispatching and leaves telemetry in the background", async () => {
const trace: string[] = [];
let commit!: (outcome: IssueWakeAdmissionOutcome<Run>) => void;
const transaction = new Promise<IssueWakeAdmissionOutcome<Run>>((resolve) => { commit = resolve; });
const result = admitIssueWake(() => transaction, recordEffects(trace));
expect(trace).toEqual([]);
commit({ kind: "queued", run: queuedRun });
await expect(result).resolves.toBe(queuedRun);
expect(trace).toEqual(["saved", "issue activity", "issue actions", "cancelled", "queued event", "attach setup", "dispatch"]);
});
it.each<{ outcome: IssueWakeAdmissionOutcome<Run>; returned: Run | null; handoff: string[] }>([
{ outcome: { kind: "coalesced", run: runningRun }, returned: runningRun, handoff: ["attach setup", "dispatch"] },
{ outcome: { kind: "replayed", run: queuedRun }, returned: queuedRun, handoff: ["attach setup", "dispatch"] },
{ outcome: { kind: "replayed", run: runningRun }, returned: runningRun, handoff: [] },
{ outcome: { kind: "durable", receipt: { runId: "run" } }, returned: runningRun, handoff: ["read run"] },
{ outcome: { kind: "durable", receipt: { runId: null } }, returned: null, handoff: [] },
{ outcome: { kind: "deferred", admitted: true }, returned: null, handoff: [] },
{ outcome: { kind: "skipped" }, returned: null, handoff: [] },
])("hands off $outcome.kind with the persisted run or receipt", async ({ outcome, returned, handoff }) => {
const trace: string[] = [];
await expect(admitIssueWake(async () => outcome, recordEffects(trace))).resolves.toBe(returned);
const saved = outcome.kind === "deferred" || outcome.kind === "skipped" ? [] : ["saved"];
expect(trace).toEqual([...saved, "issue activity", "issue actions", "cancelled", ...handoff]);
});
it("discards all buffered work when commit rejects", async () => {
const trace: string[] = [];
const error = new Error("commit failed");
await expect(admitIssueWake(() => Promise.reject(error), recordEffects(trace))).rejects.toBe(error);
expect(trace).toEqual([]);
});
it("surfaces post-commit failures even when they look like authorization contention", async () => {
const trace: string[] = [];
const effects = recordEffects(trace);
const error = Object.assign(new Error("post-commit failure"), { code: "55P03" });
effects.executeIssueActions = async () => { throw error; };
await expect(admitIssueWake(async () => ({ kind: "queued", run: queuedRun }), effects)).rejects.toBe(error);
expect(trace).toEqual(["saved", "issue activity"]);
});
});
@@ -0,0 +1,47 @@
import type { RunSummary } from "./types.js";
export type IssueWakeAdmissionOutcome<Run> =
| { kind: "queued" | "coalesced" | "replayed"; run: Run }
| { kind: "durable"; receipt: { runId: string | null } }
| { kind: "deferred"; admitted?: boolean }
| { kind: "skipped" };
export type IssueWakeAdmissionEffects<Run> = {
saved?(): void;
publishIssueActivity(): void;
executeIssueActions(): Promise<void>;
cancelledRuns: readonly Run[];
emitCancelledRun(run: Run): Promise<unknown>;
readRun(runId: string): Promise<Run | null>;
publishQueuedRun(run: RunSummary): void;
attachSetupRequest(): Promise<unknown>;
dispatch(): Promise<unknown>;
};
/** Hand off only a committed admission. A contended authorization rolls back. */
export async function admitIssueWake<Run extends RunSummary & { status: string }>(
commit: () => Promise<IssueWakeAdmissionOutcome<Run> | null>,
effects: IssueWakeAdmissionEffects<Run>,
): Promise<Run | null> {
const outcome = await commit();
if (!outcome) return null;
if (outcome.kind !== "deferred" && outcome.kind !== "skipped") effects.saved?.();
effects.publishIssueActivity();
await effects.executeIssueActions();
// Cancellation telemetry does not gate dispatch or the admission result.
for (const run of effects.cancelledRuns) void effects.emitCancelledRun(run);
if (outcome.kind === "durable") {
return outcome.receipt.runId ? effects.readRun(outcome.receipt.runId) : null;
}
if (outcome.kind === "deferred" || outcome.kind === "skipped") return null;
if (outcome.kind === "queued") effects.publishQueuedRun(outcome.run);
if (outcome.kind !== "replayed" || outcome.run.status === "queued") {
await effects.attachSetupRequest();
await effects.dispatch();
}
return outcome.run;
}
@@ -305,49 +305,6 @@ export interface RecoveryEscalationPort {
export type { PostCommitEffect, ReleaseOutcome };
/**
* Temporary port: `heartbeat.ts` still opens and owns the transaction that
* admits a wake behind an active issue execution; the module does not own
* that transaction yet. A later change will decompose `enqueueWakeup` so
* the module owns the transaction itself. That change removes this handle
* and replaces it with a transaction the module opens on its own.
*
* Only this module builds a scope. `createWakeQueue` exposes a method that
* builds one for a caller outside the module. That caller receives an
* opaque handle back and never touches this class directly.
*/
export class TransactionScope {
private constructor(
private readonly companyId: string,
private readonly rawTx: unknown,
) {}
static create(companyId: string, rawTx: unknown): TransactionScope {
return new TransactionScope(companyId, rawTx);
}
/** Returns the bound transaction only when `companyId` matches the scope's own company. */
requireTx(companyId: string): unknown {
if (companyId !== this.companyId) {
throw new Error(
"wake-queue: the transaction scope belongs to a different company than the requested write",
);
}
return this.rawTx;
}
}
/** Reads a scope's bound transaction. Rejects a missing scope with the same clear error as a mismatched one; never falls back to any other executor. */
export function requireTransactionScopeTx(
scope: TransactionScope | null | undefined,
companyId: string,
): unknown {
if (!scope) {
throw new Error("wake-queue: this call carries no transaction scope");
}
return scope.requireTx(companyId);
}
/** The active execution run a new wake arrives behind. */
export type WakeAdmissionActiveExecutionRun = {
id: string;
@@ -422,11 +379,10 @@ export type AdmitWakeBehindIssueExecutionResult =
| { kind: "coalesced"; run: Record<string, unknown> }
| { kind: "deferred" };
/** Read-only lookups the admission use case needs, each scoped to a company. */
/** Read-only admission lookups bound to the issue admission transaction. */
export interface WakeAdmissionReader {
/** A durable incoming request may share an active run only with the exact actor on its persisted wake receipt. */
matchesActiveWakeActor(
scope: TransactionScope,
input: {
companyId: string;
wakeupRequestId: string | null;
@@ -436,7 +392,6 @@ export interface WakeAdmissionReader {
): Promise<boolean>;
/** True when the active execution run's agent and this wake's own agent share an execution-agent-name key. */
isSameExecutionAgent(
scope: TransactionScope,
input: {
companyId: string;
activeExecutionRunAgentId: string;
@@ -445,7 +400,6 @@ export interface WakeAdmissionReader {
},
): Promise<boolean>;
findExistingDeferredWake(
scope: TransactionScope,
input: {
companyId: string;
agentId: string;
@@ -461,7 +415,6 @@ export interface WakeAdmissionReader {
export interface WakeAdmissionWriter {
/** Merges the wake's context into the active execution run and records the wake as coalesced. Returns the updated run row. */
coalesceIntoActiveExecutionRun(
scope: TransactionScope,
input: {
companyId: string;
activeExecutionRunId: string;
@@ -479,7 +432,6 @@ export interface WakeAdmissionWriter {
): Promise<Record<string, unknown> | null>;
/** Merges the wake's context into an already-queued deferred wake, guarded by its current status. */
mergeIntoExistingDeferredWake(
scope: TransactionScope,
input: {
companyId: string;
existingDeferredWakeId: string;
@@ -493,7 +445,6 @@ export interface WakeAdmissionWriter {
): Promise<void>;
/** Queues a new deferred wake behind the active execution run. */
insertNewDeferredWake(
scope: TransactionScope,
input: {
companyId: string;
agentId: string;
@@ -11,7 +11,6 @@ import type {
RecoveryEscalationPort,
RunSnapshot,
RunSummary,
TransactionScope,
WakeAdmissionActiveExecutionRun,
WakeAdmissionHeartbeatHelpers,
WakeAdmissionReader,
@@ -914,9 +913,6 @@ const ACTIVE_EXECUTION_RUN: WakeAdmissionActiveExecutionRun = {
contextSnapshot: { taskKey: "issue-1" },
};
// The scope is opaque to the use case; the fakes below never inspect it.
const SCOPE = {} as TransactionScope;
function admissionInput(
overrides: Partial<AdmitWakeBehindIssueExecutionInput> = {},
): AdmitWakeBehindIssueExecutionInput {
@@ -1011,7 +1007,6 @@ describe("admitWakeBehindIssueExecution", () => {
};
const result = await admit(
SCOPE,
admissionInput({
activeExecutionRun: { ...ACTIVE_EXECUTION_RUN, status },
allowRunCoalescing: false,
@@ -1025,7 +1020,6 @@ describe("admitWakeBehindIssueExecution", () => {
expect(reader.findExistingDeferredWake).not.toHaveBeenCalled();
expect(writer.mergeIntoExistingDeferredWake).not.toHaveBeenCalled();
expect(writer.insertNewDeferredWake).toHaveBeenCalledExactlyOnceWith(
SCOPE,
expect.objectContaining({
durableReceipt,
payload: {
@@ -1047,7 +1041,7 @@ describe("admitWakeBehindIssueExecution", () => {
} : null),
});
const admit = createAdmitWakeBehindIssueExecution({ reader, writer, helpers: createFakeAdmissionHelpers() });
await admit(SCOPE, admissionInput({
await admit(admissionInput({
contextSnapshot: location === "incoming" ? { interactionId: "approval" } : {},
activeExecutionRun: { ...ACTIVE_EXECUTION_RUN, status: "queued",
contextSnapshot: location === "queued" ? { interactionId: "approval" } : {} },
@@ -1066,7 +1060,7 @@ describe("admitWakeBehindIssueExecution", () => {
const writer = createFakeAdmissionWriter();
const reader = createFakeAdmissionReader();
const admit = createAdmitWakeBehindIssueExecution({ reader, writer, helpers: createFakeAdmissionHelpers() });
await admit(SCOPE, admissionInput({
await admit(admissionInput({
contextSnapshot: incoming ? { chatConversationId: incoming } : {},
activeExecutionRun: { ...ACTIVE_EXECUTION_RUN, status: "queued",
contextSnapshot: active ? { chatConversationId: active } : {} },
@@ -1074,7 +1068,7 @@ describe("admitWakeBehindIssueExecution", () => {
expect(writer.coalesceIntoActiveExecutionRun).toHaveBeenCalledTimes(coalesces ? 1 : 0);
if (!coalesces) {
// The separated reply still merges with its own conversation's deferred wake.
expect(reader.findExistingDeferredWake).toHaveBeenCalledExactlyOnceWith(SCOPE,
expect(reader.findExistingDeferredWake).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ chatConversationId: incoming }));
expect(writer.insertNewDeferredWake).toHaveBeenCalledOnce();
}
@@ -1097,7 +1091,6 @@ describe("admitWakeBehindIssueExecution", () => {
});
const result = await admit(
SCOPE,
admissionInput({
activeExecutionRun: {
...ACTIVE_EXECUTION_RUN,
@@ -1111,7 +1104,6 @@ describe("admitWakeBehindIssueExecution", () => {
expect(result).toEqual({ kind: "deferred" });
expect(reader.matchesActiveWakeActor).toHaveBeenCalledExactlyOnceWith(
SCOPE,
{
companyId: "company-1",
wakeupRequestId: "active-wake",
@@ -1121,7 +1113,6 @@ describe("admitWakeBehindIssueExecution", () => {
);
expect(writer.coalesceIntoActiveExecutionRun).not.toHaveBeenCalled();
expect(reader.findExistingDeferredWake).toHaveBeenCalledExactlyOnceWith(
SCOPE,
{
companyId: "company-1",
agentId: "wake-agent",
@@ -1131,7 +1122,6 @@ describe("admitWakeBehindIssueExecution", () => {
},
);
expect(writer.insertNewDeferredWake).toHaveBeenCalledExactlyOnceWith(
SCOPE,
expect.objectContaining({ durableReceipt }),
);
});
@@ -1151,7 +1141,6 @@ describe("admitWakeBehindIssueExecution", () => {
});
const result = await admit(
SCOPE,
admissionInput({
activeExecutionRun: {
...ACTIVE_EXECUTION_RUN,
@@ -1163,7 +1152,6 @@ describe("admitWakeBehindIssueExecution", () => {
expect(result).toEqual({ kind: "coalesced", run: { id: "merged-run-1" } });
expect(reader.matchesActiveWakeActor).toHaveBeenCalledExactlyOnceWith(
SCOPE,
{
companyId: "company-1",
wakeupRequestId: "active-wake",
@@ -1174,7 +1162,6 @@ describe("admitWakeBehindIssueExecution", () => {
expect(
writer.coalesceIntoActiveExecutionRun,
).toHaveBeenCalledExactlyOnceWith(
SCOPE,
expect.objectContaining({ durableReceipt }),
);
expect(reader.findExistingDeferredWake).not.toHaveBeenCalled();
@@ -1204,7 +1191,6 @@ describe("admitWakeBehindIssueExecution", () => {
});
const result = await admit(
SCOPE,
admissionInput({
durableReceipt,
reason: "question_response",
@@ -1216,7 +1202,6 @@ describe("admitWakeBehindIssueExecution", () => {
expect(
writer.mergeIntoExistingDeferredWake,
).toHaveBeenCalledExactlyOnceWith(
SCOPE,
expect.objectContaining({
existingDeferredWakeId: "existing-deferred-wake",
nextCoalescedCount: 3,
@@ -1256,10 +1241,10 @@ describe("admitWakeBehindIssueExecution", () => {
})) });
const admit = createAdmitWakeBehindIssueExecution({ reader, writer,
helpers: createFakeAdmissionHelpers({ shouldDeferFollowupWakeForSameIssue: vi.fn(() => true) }) });
await expect(admit(SCOPE, admissionInput({ wakeCommentId: "second-comment", requestedByActorId: "second-user",
await expect(admit(admissionInput({ wakeCommentId: "second-comment", requestedByActorId: "second-user",
payload: { commentId: "second-comment", coalescedIntoWakeupRequestId: "forged-target" },
}))).resolves.toEqual({ kind: "deferred" });
const input = vi.mocked(writer.mergeIntoExistingDeferredWake).mock.calls[0][1];
const input = vi.mocked(writer.mergeIntoExistingDeferredWake).mock.calls[0][0];
expect(input.coalescedReceipt).toEqual({ agentId: "wake-agent", source: "on_demand", triggerDetail: null,
reason: null, payload: { issueId: "issue-1", commentId: "second-comment", coalescedIntoWakeupRequestId: "existing-deferred-wake" },
requestedByActorType: "user", requestedByActorId: "second-user", idempotencyKey: null, runId: null });
@@ -1275,8 +1260,8 @@ describe("admitWakeBehindIssueExecution", () => {
reader: createFakeAdmissionReader({ findExistingDeferredWake: vi.fn(async () => ({
id: "saved-wake", runId: null, payload: { issueId: "issue-1" }, deferredContext: {}, coalescedCount: 0,
})) }), helpers: createFakeAdmissionHelpers({ shouldDeferFollowupWakeForSameIssue: vi.fn(() => true) }) });
await admit(SCOPE, admissionInput({ durableReceipt, payload: { text: "saved input" } }));
expect(vi.mocked(writer.mergeIntoExistingDeferredWake).mock.calls[0][1].coalescedReceipt).toEqual(expect.objectContaining({
await admit(admissionInput({ durableReceipt, payload: { text: "saved input" } }));
expect(vi.mocked(writer.mergeIntoExistingDeferredWake).mock.calls[0][0].coalescedReceipt).toEqual(expect.objectContaining({
...durableReceipt, payload: { text: "saved input", issueId: "issue-1", coalescedIntoWakeupRequestId: "saved-wake" },
}));
});
@@ -1287,8 +1272,8 @@ describe("admitWakeBehindIssueExecution", () => {
reader: createFakeAdmissionReader({ findExistingDeferredWake: vi.fn(async () => ({
id: "existing-deferred-wake", runId: null, payload: { issueId: "issue-1" }, deferredContext: {}, coalescedCount: 1,
})) }), helpers: createFakeAdmissionHelpers({ shouldDeferFollowupWakeForSameIssue: vi.fn(() => true) }) });
await admit(SCOPE, admissionInput({ wakeCommentId: "second-comment", requestedByActorType: actor }));
expect(vi.mocked(writer.mergeIntoExistingDeferredWake).mock.calls[0][1]).not.toHaveProperty("coalescedReceipt");
await admit(admissionInput({ wakeCommentId: "second-comment", requestedByActorType: actor }));
expect(vi.mocked(writer.mergeIntoExistingDeferredWake).mock.calls[0][0]).not.toHaveProperty("coalescedReceipt");
});
it("gives manual input its own run boundary even when the active receipt has the same requester", async () => {
@@ -1296,7 +1281,7 @@ describe("admitWakeBehindIssueExecution", () => {
const admit = createAdmitWakeBehindIssueExecution({
reader: createFakeAdmissionReader(), writer, helpers: createFakeAdmissionHelpers(),
});
expect(await admit(SCOPE, admissionInput({ payload: { issueId: "issue-1", manualUserWake: true } })))
expect(await admit(admissionInput({ payload: { issueId: "issue-1", manualUserWake: true } })))
.toEqual({ kind: "deferred" });
expect(writer.coalesceIntoActiveExecutionRun).not.toHaveBeenCalled();
expect(writer.insertNewDeferredWake).toHaveBeenCalledTimes(1);
@@ -1314,7 +1299,7 @@ describe("admitWakeBehindIssueExecution", () => {
helpers,
});
expect(await admit(SCOPE, admissionInput())).toEqual({
expect(await admit(admissionInput())).toEqual({
kind: "coalesced",
run: { id: "merged-run-1" },
});
@@ -1328,7 +1313,7 @@ describe("admitWakeBehindIssueExecution", () => {
const helpers = createFakeAdmissionHelpers();
const admit = createAdmitWakeBehindIssueExecution({ reader, writer, helpers });
const result = await admit(SCOPE, admissionInput());
const result = await admit(admissionInput());
expect(result).toEqual({ kind: "coalesced", run: { id: "merged-run-1" } });
expect(writer.coalesceIntoActiveExecutionRun).toHaveBeenCalledTimes(1);
@@ -1342,7 +1327,7 @@ describe("admitWakeBehindIssueExecution", () => {
const helpers = createFakeAdmissionHelpers();
const admit = createAdmitWakeBehindIssueExecution({ reader, writer, helpers });
const result = await admit(SCOPE, admissionInput());
const result = await admit(admissionInput());
expect(result.kind).toBe("coalesced");
expect(reader.findExistingDeferredWake).not.toHaveBeenCalled();
@@ -1353,10 +1338,10 @@ describe("admitWakeBehindIssueExecution", () => {
const reader = createFakeAdmissionReader();
const admit = createAdmitWakeBehindIssueExecution({ reader, writer, helpers: createFakeAdmissionHelpers() });
const durableReceipt = { id: "incoming-source", requestedAt: new Date("2026-11-04T00:00:00Z") };
expect(await admit(SCOPE, admissionInput({ durableReceipt, wakeCommentId: "new-comment",
expect(await admit(admissionInput({ durableReceipt, wakeCommentId: "new-comment",
contextSnapshot: { issueId: "issue-1", wakeCommentId: "new-comment" }, payload: { issueId: "issue-1", commentId: "new-comment" },
}))).toEqual({ kind: "deferred" });
expect(writer.insertNewDeferredWake).toHaveBeenCalledWith(SCOPE, expect.objectContaining({
expect(writer.insertNewDeferredWake).toHaveBeenCalledWith(expect.objectContaining({
companyId: "company-1", agentId: "wake-agent", durableReceipt,
requestedByActorType: "user", requestedByActorId: "user-1",
payload: expect.objectContaining({ issueId: "issue-1", commentId: "new-comment" }),
@@ -1366,7 +1351,7 @@ describe("admitWakeBehindIssueExecution", () => {
it("merges into the existing deferred wake when the policy returns a merge target", async () => {
const mergeIntoExistingDeferredWake = vi.fn(
async (_scope: TransactionScope, _input: Parameters<WakeAdmissionWriter["mergeIntoExistingDeferredWake"]>[1]) => {},
async (_input: Parameters<WakeAdmissionWriter["mergeIntoExistingDeferredWake"]>[0]) => {},
);
const writer = createFakeAdmissionWriter({ mergeIntoExistingDeferredWake });
const reader = createFakeAdmissionReader({
@@ -1381,11 +1366,11 @@ describe("admitWakeBehindIssueExecution", () => {
const helpers = createFakeAdmissionHelpers();
const admit = createAdmitWakeBehindIssueExecution({ reader, writer, helpers });
const result = await admit(SCOPE, admissionInput());
const result = await admit(admissionInput());
expect(result).toEqual({ kind: "deferred" });
expect(mergeIntoExistingDeferredWake).toHaveBeenCalledTimes(1);
const call = mergeIntoExistingDeferredWake.mock.calls[0]![1];
const call = mergeIntoExistingDeferredWake.mock.calls[0]![0];
expect(call.existingDeferredWakeId).toBe("deferred-1");
expect(call.nextCoalescedCount).toBe(3);
expect(call.mergedPayload.foo).toBe("bar");
@@ -1399,7 +1384,7 @@ describe("admitWakeBehindIssueExecution", () => {
const helpers = createFakeAdmissionHelpers();
const admit = createAdmitWakeBehindIssueExecution({ reader, writer, helpers });
const result = await admit(SCOPE, admissionInput());
const result = await admit(admissionInput());
expect(result).toEqual({ kind: "deferred" });
expect(writer.insertNewDeferredWake).toHaveBeenCalledTimes(1);
@@ -1413,7 +1398,7 @@ describe("admitWakeBehindIssueExecution", () => {
const helpers = createFakeAdmissionHelpers();
const admit = createAdmitWakeBehindIssueExecution({ reader, writer, helpers });
const result = await admit(SCOPE, admissionInput({ liveRunExecutions: { has: () => false } }));
const result = await admit(admissionInput({ liveRunExecutions: { has: () => false } }));
expect(result).toEqual({ kind: "proceed" });
expect(reader.findExistingDeferredWake).not.toHaveBeenCalled();
@@ -26,7 +26,6 @@ import type {
RecoveryEscalationPort,
ReleaseTransactionResult,
RunSnapshot,
TransactionScope,
WakeAdmissionActiveExecutionRun,
WakeAdmissionHeartbeatHelpers,
WakeAdmissionReader,
@@ -868,7 +867,6 @@ export function createAdmitWakeBehindIssueExecution(deps: {
helpers: WakeAdmissionHeartbeatHelpers;
}) {
return async function admitWakeBehindIssueExecution(
scope: TransactionScope,
input: AdmitWakeBehindIssueExecutionInput,
): Promise<AdmitWakeBehindIssueExecutionResult> {
const manualUserWakeActorId = input.payload?.manualUserWake === true
@@ -877,7 +875,7 @@ export function createAdmitWakeBehindIssueExecution(deps: {
(input.requestedByActorType !== "user" || !manualUserWakeActorId)) {
throw new Error("wake-queue: manual wake requires an authenticated user");
}
const isSameExecutionAgent = await deps.reader.isSameExecutionAgent(scope, {
const isSameExecutionAgent = await deps.reader.isSameExecutionAgent({
companyId: input.companyId,
activeExecutionRunAgentId: input.activeExecutionRun.agentId,
issueExecutionAgentNameKey: input.issueExecutionAgentNameKey,
@@ -909,7 +907,7 @@ export function createAdmitWakeBehindIssueExecution(deps: {
const sameDurableActor =
!input.durableReceipt ||
(await deps.reader.matchesActiveWakeActor(scope, {
(await deps.reader.matchesActiveWakeActor({
companyId: input.companyId,
wakeupRequestId: availableActiveExecutionRun?.wakeupRequestId ?? null,
requestedByActorType: input.requestedByActorType,
@@ -940,7 +938,7 @@ export function createAdmitWakeBehindIssueExecution(deps: {
target.status === "queued" || target.status === "scheduled_retry",
},
);
const run = await deps.writer.coalesceIntoActiveExecutionRun(scope, {
const run = await deps.writer.coalesceIntoActiveExecutionRun({
companyId: input.companyId,
activeExecutionRunId: target.id,
activeExecutionRunStatus: target.status,
@@ -962,7 +960,7 @@ export function createAdmitWakeBehindIssueExecution(deps: {
const existingDeferred =
(interactionReceipt || input.allowRunCoalescing === false)
? null
: await deps.reader.findExistingDeferredWake(scope, {
: await deps.reader.findExistingDeferredWake({
companyId: input.companyId,
agentId: input.agentId,
issueId: input.issueId,
@@ -995,7 +993,7 @@ export function createAdmitWakeBehindIssueExecution(deps: {
issueId: input.issueId,
[DEFERRED_WAKE_CONTEXT_KEY]: mergedDeferredContext,
};
await deps.writer.mergeIntoExistingDeferredWake(scope, {
await deps.writer.mergeIntoExistingDeferredWake({
companyId: input.companyId,
existingDeferredWakeId: existingDeferred.id,
mergedPayload,
@@ -1031,7 +1029,7 @@ export function createAdmitWakeBehindIssueExecution(deps: {
issueId: input.issueId,
[DEFERRED_WAKE_CONTEXT_KEY]: input.contextSnapshot,
};
await deps.writer.insertNewDeferredWake(scope, {
await deps.writer.insertNewDeferredWake({
companyId: input.companyId,
agentId: input.agentId,
source: input.source,