mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-19 16:29:42 +01:00
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:
1 parent
eca7f85778
commit
ebb98120dc
21 files changed
+440
-363
No files matched your search
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { and, asc, eq, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { agentWakeupRequests, chatConversations, chatDeliveries, chatMessageLinks, createDb, heartbeatRuns,
|
||||
issueComments, issues, type Db } from "@paperclipai/db";
|
||||
issueComments, issues } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
|
||||
import { seedBoundChatAuthorization } from "../../../__tests__/helpers/bound-chat-authorization.js";
|
||||
import { authorizeChatConversationForBoundRun } from "../../../services/native-runtime/chat-attachment-reuse.js";
|
||||
@@ -11,7 +11,7 @@ import { saveUndeliveredUserComments } from "../../../services/work-intent-outbo
|
||||
import { queuedCommentIdsFromWakePayload } from "../../../services/issue-queued-comment-queue.js";
|
||||
import { createAdmitWakeBehindIssueExecution, createReleaseIssueExecution } from "../application/use-cases.js";
|
||||
import type { WakeAdmissionActiveExecutionRun } from "../application/ports.js";
|
||||
import { createAdmissionTransactionScope, createPostgresWakeQueueAdapter, createWakeAdmissionReader,
|
||||
import { createPostgresWakeQueueAdapter, createWakeAdmissionReader,
|
||||
createWakeAdmissionWriter } from "./postgres.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
@@ -31,17 +31,6 @@ describe.skipIf(!support.supported)("chat wake batches stay within one conversat
|
||||
let otherConversationId: string;
|
||||
let deferOnly = true;
|
||||
|
||||
const admit = createAdmitWakeBehindIssueExecution({
|
||||
reader: createWakeAdmissionReader(),
|
||||
writer: createWakeAdmissionWriter(),
|
||||
helpers: {
|
||||
filterZombieCoalesceTarget: (target) => target,
|
||||
mergeCoalescedContextSnapshot,
|
||||
shouldDeferFollowupWakeForSameIssue: () => deferOnly,
|
||||
shouldQueueFollowupForRunningIssueWake: () => false,
|
||||
},
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
database = await startEmbeddedPostgresTestDatabase("wake-chat-conversation-batch-");
|
||||
db = createDb(database.connectionString);
|
||||
@@ -102,7 +91,16 @@ describe.skipIf(!support.supported)("chat wake batches stay within one conversat
|
||||
async function admitWake(contextSnapshot: Record<string, unknown>, activeExecutionRun?: WakeAdmissionActiveExecutionRun) {
|
||||
const commentId = contextSnapshot.wakeCommentId as string;
|
||||
const chat = contextSnapshot.source === "chat:slack";
|
||||
return db.transaction(async (tx) => admit(createAdmissionTransactionScope(f.companyId, tx as unknown as Db), {
|
||||
return db.transaction((tx) => createAdmitWakeBehindIssueExecution({
|
||||
reader: createWakeAdmissionReader(tx, f.companyId),
|
||||
writer: createWakeAdmissionWriter(tx, f.companyId),
|
||||
helpers: {
|
||||
filterZombieCoalesceTarget: (target) => target,
|
||||
mergeCoalescedContextSnapshot,
|
||||
shouldDeferFollowupWakeForSameIssue: () => deferOnly,
|
||||
shouldQueueFollowupForRunningIssueWake: () => false,
|
||||
},
|
||||
})({
|
||||
companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, agentNameKey: "chat runner",
|
||||
issueExecutionAgentNameKey: null,
|
||||
activeExecutionRun: activeExecutionRun ?? { id: f.runId, agentId: f.agentId, status: "running",
|
||||
|
||||
@@ -26,13 +26,11 @@ import {
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "../../../__tests__/helpers/embedded-postgres.js";
|
||||
import {
|
||||
createAdmissionTransactionScope,
|
||||
createPostgresWakeQueueAdapter,
|
||||
createWakeAdmissionWriter,
|
||||
} from "./postgres.js";
|
||||
import type { WakeQueuePostgresAdapterDeps } from "./postgres.js";
|
||||
import { createReleaseIssueExecution } from "../application/use-cases.js";
|
||||
import type { TransactionScope } from "../application/ports.js";
|
||||
import { withQueuedCommentIdsInRunContext, withQueuedCommentIdsInWakePayload } from "../../../services/issue-queued-comment-queue.js";
|
||||
|
||||
// Proves the atomicity and company-scope properties the security review
|
||||
@@ -1426,8 +1424,7 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => {
|
||||
}).returning();
|
||||
await db.update(heartbeatRuns).set({ wakeupRequestId: wake.id }).where(eq(heartbeatRuns.id, runId));
|
||||
const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
||||
const operation = db.transaction(async tx => createWakeAdmissionWriter().coalesceIntoActiveExecutionRun(
|
||||
createAdmissionTransactionScope(companyId, tx as unknown as Db), {
|
||||
const operation = db.transaction(async tx => createWakeAdmissionWriter(tx, companyId).coalesceIntoActiveExecutionRun({
|
||||
companyId, agentId, activeExecutionRunId: runId, activeExecutionRunStatus: "queued",
|
||||
mergedContextSnapshot: withQueuedCommentIdsInRunContext({ issueId }, [oldComment.id, newComment.id]),
|
||||
source: "on_demand", triggerDetail: "manual", payload: { issueId, commentId: newComment.id },
|
||||
@@ -1463,15 +1460,10 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => {
|
||||
.from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.companyId, companyId))
|
||||
.orderBy(agentWakeupRequests.id);
|
||||
const writer = createWakeAdmissionWriter();
|
||||
|
||||
await expect(
|
||||
db.transaction(async (tx) => {
|
||||
const scope = createAdmissionTransactionScope(
|
||||
companyId,
|
||||
tx as unknown as Db,
|
||||
);
|
||||
await writer.mergeIntoExistingDeferredWake(scope, {
|
||||
await createWakeAdmissionWriter(tx, companyId).mergeIntoExistingDeferredWake({
|
||||
companyId,
|
||||
existingDeferredWakeId: wakeId,
|
||||
mergedPayload: { issueId, changedByMerge: true },
|
||||
@@ -1512,12 +1504,10 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => {
|
||||
const agentId = await seedAgent({ companyId });
|
||||
const issueId = await seedIssue({ companyId, assigneeAgentId: agentId });
|
||||
const wakeId = await seedDeferredWake({ companyId, agentId, issueId });
|
||||
const writer = createWakeAdmissionWriter();
|
||||
|
||||
await expect(
|
||||
db.transaction(async (tx) => {
|
||||
const scope = createAdmissionTransactionScope(otherCompanyId, tx as unknown as Db);
|
||||
await writer.mergeIntoExistingDeferredWake(scope, {
|
||||
await createWakeAdmissionWriter(tx, otherCompanyId).mergeIntoExistingDeferredWake({
|
||||
companyId: otherCompanyId,
|
||||
existingDeferredWakeId: wakeId,
|
||||
mergedPayload: { issueId, foo: "bar" },
|
||||
@@ -1543,7 +1533,7 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => {
|
||||
});
|
||||
try {
|
||||
await db.transaction(async tx => {
|
||||
await createWakeAdmissionWriter().coalesceIntoActiveExecutionRun(createAdmissionTransactionScope(companyId, tx as unknown as Db), {
|
||||
await createWakeAdmissionWriter(tx, companyId).coalesceIntoActiveExecutionRun({
|
||||
companyId, activeExecutionRunId: runId, activeExecutionRunStatus: "running", mergedContextSnapshot: { commentId: "fresh-input" },
|
||||
agentId, source: "on_demand", triggerDetail: null, payload: null,
|
||||
requestedByActorType: "user", requestedByActorId: null, idempotencyKey: null,
|
||||
@@ -1565,8 +1555,7 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => {
|
||||
paperclipOutputSecretRedactions: [{ fingerprintSha256: "b".repeat(64), material: { scheme: "synthetic" } }],
|
||||
};
|
||||
const runId = await seedRun({ companyId, agentId, status: "running", contextSnapshot: { taskKey: "issue-1", ...history } });
|
||||
await db.transaction(async (tx) => createWakeAdmissionWriter().coalesceIntoActiveExecutionRun(
|
||||
createAdmissionTransactionScope(companyId, tx as unknown as Db), {
|
||||
await db.transaction(async (tx) => createWakeAdmissionWriter(tx, companyId).coalesceIntoActiveExecutionRun({
|
||||
companyId, agentId, activeExecutionRunId: runId, activeExecutionRunStatus: "running",
|
||||
mergedContextSnapshot: { taskKey: "issue-1", commentId: "fresh-input" },
|
||||
source: "on_demand", triggerDetail: null, payload: null,
|
||||
@@ -1583,12 +1572,10 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => {
|
||||
const otherCompanyId = await seedCompany();
|
||||
const agentId = await seedAgent({ companyId });
|
||||
const runId = await seedRun({ companyId, agentId, status: "running", contextSnapshot: { taskKey: "issue-1" } });
|
||||
const writer = createWakeAdmissionWriter();
|
||||
|
||||
await expect(
|
||||
db.transaction(async (tx) => {
|
||||
const scope = createAdmissionTransactionScope(otherCompanyId, tx as unknown as Db);
|
||||
await writer.coalesceIntoActiveExecutionRun(scope, {
|
||||
await createWakeAdmissionWriter(tx, otherCompanyId).coalesceIntoActiveExecutionRun({
|
||||
companyId: otherCompanyId,
|
||||
activeExecutionRunId: runId,
|
||||
activeExecutionRunStatus: "running",
|
||||
@@ -1610,15 +1597,11 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => {
|
||||
expect(wakeRows).toHaveLength(0);
|
||||
});
|
||||
|
||||
// Review test (d): a transaction-port call cannot use the root database
|
||||
// executor. The module rejects a missing scope handle and a mismatched
|
||||
// scope handle, and neither case writes a row.
|
||||
it("rejects a missing transaction scope and a mismatched one, without writing through the root executor", async () => {
|
||||
it("rejects input for another company before writing a deferred receipt", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const otherCompanyId = await seedCompany();
|
||||
const agentId = await seedAgent({ companyId });
|
||||
const issueId = await seedIssue({ companyId, assigneeAgentId: agentId });
|
||||
const writer = createWakeAdmissionWriter();
|
||||
const newWakeInput = {
|
||||
companyId,
|
||||
agentId,
|
||||
@@ -1630,14 +1613,9 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => {
|
||||
idempotencyKey: null,
|
||||
};
|
||||
|
||||
await expect(
|
||||
writer.insertNewDeferredWake(undefined as unknown as TransactionScope, newWakeInput),
|
||||
).rejects.toThrow(/transaction scope/);
|
||||
|
||||
await expect(
|
||||
db.transaction(async (tx) => {
|
||||
const mismatchedScope = createAdmissionTransactionScope(otherCompanyId, tx as unknown as Db);
|
||||
await writer.insertNewDeferredWake(mismatchedScope, newWakeInput);
|
||||
await createWakeAdmissionWriter(tx, otherCompanyId).insertNewDeferredWake(newWakeInput);
|
||||
}),
|
||||
).rejects.toThrow(/different company/);
|
||||
|
||||
|
||||
@@ -42,7 +42,10 @@ import { legacyExecutionNeedsReconciliationWithEvidence } from "../../../service
|
||||
import {
|
||||
authorizeFailedChatRunRetryWake,
|
||||
FailedChatRunRetryAuthorizationError,
|
||||
withDurableChatAdmission,
|
||||
type DurableChatWakeupRequest,
|
||||
} from "../../../services/durable-chat-wakeup.js";
|
||||
import { isExternalChatWaitAuthorizationContention } from "../../../services/native-runtime/chat-attachment-reuse.js";
|
||||
import { isRetiredExternalChatQuestionSource } from "../../../services/question-response-delivery.js";
|
||||
import { HttpError } from "../../../errors.js";
|
||||
import { evaluateAgentInvokabilityFromDb } from "../../../services/agent-invokability.js";
|
||||
@@ -73,7 +76,6 @@ import {
|
||||
parseObject,
|
||||
readNonEmptyString,
|
||||
} from "../domain/values.js";
|
||||
import { requireTransactionScopeTx, TransactionScope } from "../application/ports.js";
|
||||
import type {
|
||||
DeferredWakeCandidate,
|
||||
InvokableAgentSnapshot,
|
||||
@@ -88,6 +90,7 @@ import type {
|
||||
WakeQueueTransaction,
|
||||
} from "../application/ports.js";
|
||||
import type { FreshIssueRunStore } from "../application/fresh-issue-run.js";
|
||||
import type { IssueWakeAdmissionOutcome } from "../application/issue-wake-admission.js";
|
||||
import type { RunSummary } from "../application/types.js";
|
||||
|
||||
const DEFERRED_WAKE_STATUS = "deferred_issue_execution";
|
||||
@@ -97,6 +100,12 @@ const EXECUTION_PATH_HEARTBEAT_RUN_STATUSES = ["queued", "running", "scheduled_r
|
||||
|
||||
type HeartbeatRunRow = typeof heartbeatRuns.$inferSelect;
|
||||
type IssueRow = typeof issues.$inferSelect;
|
||||
export type IssueAdmissionDbTransaction = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
||||
export type IssueAdmissionTarget = {
|
||||
companyId: string;
|
||||
issueId: string;
|
||||
durableChatRequest?: DurableChatWakeupRequest;
|
||||
};
|
||||
|
||||
function normalizeAgentNameKey(value: string | null | undefined): string | null {
|
||||
if (typeof value !== "string") return null;
|
||||
@@ -971,23 +980,17 @@ async function recordNativeTerminalRecoveryIfNeeded(tx: Db, run: ReleaseRun, iss
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the temporary transaction-scope handle the admission port needs.
|
||||
* `heartbeat.ts` calls this through `createWakeQueue`'s own wrapper; it
|
||||
* never builds a `TransactionScope` itself.
|
||||
*/
|
||||
export function createAdmissionTransactionScope(companyId: string, tx: Db): TransactionScope {
|
||||
return TransactionScope.create(companyId, tx);
|
||||
function assertAdmissionCompany(admittedCompanyId: string, companyId: string) {
|
||||
if (companyId !== admittedCompanyId) {
|
||||
throw new Error("wake-queue: admission is locked for a different company");
|
||||
}
|
||||
}
|
||||
|
||||
function requireAdmissionTx(scope: TransactionScope | null | undefined, companyId: string): Db {
|
||||
return requireTransactionScopeTx(scope, companyId) as Db;
|
||||
}
|
||||
|
||||
export function createWakeAdmissionReader(): WakeAdmissionReader {
|
||||
export function createWakeAdmissionReader(rawTx: IssueAdmissionDbTransaction, admittedCompanyId: string): WakeAdmissionReader {
|
||||
const tx = rawTx as unknown as Db;
|
||||
return {
|
||||
async matchesActiveWakeActor(scope, input) {
|
||||
const tx = requireAdmissionTx(scope, input.companyId);
|
||||
async matchesActiveWakeActor(input) {
|
||||
assertAdmissionCompany(admittedCompanyId, input.companyId);
|
||||
if (!input.wakeupRequestId) return false;
|
||||
const actor = await tx
|
||||
.select({
|
||||
@@ -1010,7 +1013,6 @@ export function createWakeAdmissionReader(): WakeAdmissionReader {
|
||||
);
|
||||
},
|
||||
async isSameExecutionAgent(
|
||||
scope,
|
||||
{
|
||||
companyId,
|
||||
activeExecutionRunAgentId,
|
||||
@@ -1018,7 +1020,7 @@ export function createWakeAdmissionReader(): WakeAdmissionReader {
|
||||
agentNameKey,
|
||||
},
|
||||
) {
|
||||
const tx = requireAdmissionTx(scope, companyId);
|
||||
assertAdmissionCompany(admittedCompanyId, companyId);
|
||||
const executionAgent = await tx
|
||||
.select({ name: agents.name })
|
||||
.from(agents)
|
||||
@@ -1038,10 +1040,9 @@ export function createWakeAdmissionReader(): WakeAdmissionReader {
|
||||
},
|
||||
|
||||
async findExistingDeferredWake(
|
||||
scope,
|
||||
{ companyId, agentId, issueId, chatConversationId, durableActor },
|
||||
) {
|
||||
const tx = requireAdmissionTx(scope, companyId);
|
||||
assertAdmissionCompany(admittedCompanyId, companyId);
|
||||
const row = await tx
|
||||
.select()
|
||||
.from(agentWakeupRequests)
|
||||
@@ -1098,10 +1099,11 @@ export function createWakeAdmissionReader(): WakeAdmissionReader {
|
||||
};
|
||||
}
|
||||
|
||||
export function createWakeAdmissionWriter(): WakeAdmissionWriter {
|
||||
export function createWakeAdmissionWriter(rawTx: IssueAdmissionDbTransaction, admittedCompanyId: string): WakeAdmissionWriter {
|
||||
const tx = rawTx as unknown as Db;
|
||||
return {
|
||||
async coalesceIntoActiveExecutionRun(scope, input) {
|
||||
const tx = requireAdmissionTx(scope, input.companyId);
|
||||
async coalesceIntoActiveExecutionRun(input) {
|
||||
assertAdmissionCompany(admittedCompanyId, input.companyId);
|
||||
const now = new Date();
|
||||
const [candidate] = await tx.select().from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.id, input.activeExecutionRunId), eq(heartbeatRuns.companyId, input.companyId),
|
||||
@@ -1173,8 +1175,8 @@ export function createWakeAdmissionWriter(): WakeAdmissionWriter {
|
||||
return mergedRun as unknown as Record<string, unknown>;
|
||||
},
|
||||
|
||||
async mergeIntoExistingDeferredWake(scope, input) {
|
||||
const tx = requireAdmissionTx(scope, input.companyId);
|
||||
async mergeIntoExistingDeferredWake(input) {
|
||||
assertAdmissionCompany(admittedCompanyId, input.companyId);
|
||||
if (input.manualUserWakeActorId) await notifyChatInboundWakeNotices(tx, { companyId: input.companyId });
|
||||
const [prior] = await tx.select().from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.id, input.existingDeferredWakeId),
|
||||
@@ -1256,8 +1258,8 @@ export function createWakeAdmissionWriter(): WakeAdmissionWriter {
|
||||
}
|
||||
},
|
||||
|
||||
async insertNewDeferredWake(scope, input) {
|
||||
const tx = requireAdmissionTx(scope, input.companyId);
|
||||
async insertNewDeferredWake(input) {
|
||||
assertAdmissionCompany(admittedCompanyId, input.companyId);
|
||||
await notifyDeferredExecutionWork(tx, { companyId: input.companyId });
|
||||
await tx.insert(agentWakeupRequests).values({
|
||||
...input.durableReceipt,
|
||||
@@ -1276,6 +1278,32 @@ export function createWakeAdmissionWriter(): WakeAdmissionWriter {
|
||||
};
|
||||
}
|
||||
|
||||
export function createPostgresIssueWakeAdmission(db: Db) {
|
||||
return async function withIssueAdmission(
|
||||
{ companyId, issueId, durableChatRequest }: IssueAdmissionTarget,
|
||||
evaluate: (tx: IssueAdmissionDbTransaction, stores: {
|
||||
reader: WakeAdmissionReader;
|
||||
writer: WakeAdmissionWriter;
|
||||
fresh: FreshIssueRunStore<HeartbeatRunRow>;
|
||||
}) => Promise<IssueWakeAdmissionOutcome<HeartbeatRunRow>>,
|
||||
): Promise<IssueWakeAdmissionOutcome<HeartbeatRunRow> | null> {
|
||||
try {
|
||||
return await db.transaction(withDurableChatAdmission(durableChatRequest, async (tx) => {
|
||||
// Mentions may target another agent, but every admission must share the issue lock.
|
||||
await tx.execute(sql`select id from issues where id = ${issueId} and company_id = ${companyId} for update`);
|
||||
return evaluate(tx, {
|
||||
reader: createWakeAdmissionReader(tx, companyId),
|
||||
writer: createWakeAdmissionWriter(tx, companyId),
|
||||
fresh: createFreshIssueRunStore(tx, companyId),
|
||||
});
|
||||
}));
|
||||
} catch (error) {
|
||||
if (isExternalChatWaitAuthorizationContention(error)) return null;
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function createPostgresWakeQueueAdapter(db: Db, deps: WakeQueuePostgresAdapterDeps): IssueLockWriter {
|
||||
return {
|
||||
async withIssueExecutionLock(input, fn): Promise<ReleaseTransactionResult & { run: RunSnapshot }> {
|
||||
@@ -1539,10 +1567,10 @@ export function createPostgresWakeQueueAdapter(db: Db, deps: WakeQueuePostgresAd
|
||||
}
|
||||
|
||||
export function createFreshIssueRunStore(
|
||||
scope: TransactionScope,
|
||||
rawTx: IssueAdmissionDbTransaction,
|
||||
companyId: string,
|
||||
): FreshIssueRunStore<HeartbeatRunRow> {
|
||||
const tx = requireAdmissionTx(scope, companyId);
|
||||
const tx = rawTx as unknown as Db;
|
||||
return {
|
||||
async saveReceipt(input) {
|
||||
if (input.kind === "insert") {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import type { Db, heartbeatRuns } from "@paperclipai/db";
|
||||
import {
|
||||
createAdmissionTransactionScope as buildAdmissionTransactionScope,
|
||||
createFreshIssueRunStore,
|
||||
createPostgresIssueWakeAdmission,
|
||||
createPostgresWakeQueueAdapter,
|
||||
createWakeAdmissionReader,
|
||||
createWakeAdmissionWriter,
|
||||
type IssueAdmissionDbTransaction,
|
||||
type IssueAdmissionTarget,
|
||||
} from "./adapters/postgres.js";
|
||||
import { createQueuedCommentIssueLockWriter } from "./adapters/queued-comment-postgres.js";
|
||||
import type { QueuedCommentQueuePostgresAdapterDeps } from "./adapters/queued-comment-postgres.js";
|
||||
import { createFreshIssueRunAdmission } from "./application/fresh-issue-run.js";
|
||||
import { admitIssueWake, type IssueWakeAdmissionEffects, type IssueWakeAdmissionOutcome } from "./application/issue-wake-admission.js";
|
||||
import { createAdmitWakeBehindIssueExecution, createReleaseIssueExecution } from "./application/use-cases.js";
|
||||
import {
|
||||
createDiscardQueuedComment,
|
||||
@@ -19,7 +19,6 @@ import type {
|
||||
IssueSnapshot,
|
||||
RecoveryEscalationPort,
|
||||
RunSnapshot,
|
||||
TransactionScope,
|
||||
WakeAdmissionHeartbeatHelpers,
|
||||
WakeQueueHost,
|
||||
} from "./application/ports.js";
|
||||
@@ -37,9 +36,8 @@ export type {
|
||||
RunSnapshot,
|
||||
RecoveryEscalationPort,
|
||||
ReleaseRecoveryBlockedNoticeKind,
|
||||
TransactionScope,
|
||||
} from "./application/ports.js";
|
||||
export type { AdmitWakeBehindIssueExecutionInput, AdmitWakeBehindIssueExecutionResult, ReleaseIssueExecutionInput } from "./application/use-cases.js";
|
||||
export type { ReleaseIssueExecutionInput } from "./application/use-cases.js";
|
||||
export {
|
||||
QueuedCommentMutationError,
|
||||
QueuedCommentMutationForbiddenError,
|
||||
@@ -78,45 +76,53 @@ export type WakeQueueDeps = {
|
||||
recovery: RecoveryEscalationPort;
|
||||
};
|
||||
|
||||
/**
|
||||
* Composes the wake-queue module: the Postgres adapter (which owns the
|
||||
* release transaction) and the release use case. `heartbeat.ts` holds the
|
||||
* only caller: it builds one instance per process next to
|
||||
* `createRunDispatch(db)` and delegates `releaseIssueExecutionAndPromote`'s
|
||||
* body to `releaseIssueExecution`.
|
||||
*
|
||||
* The admission half is temporary: `heartbeat.ts` still opens and owns the
|
||||
* transaction that admits a wake behind an active issue execution, so it
|
||||
* builds a `TransactionScope` through `createAdmissionTransactionScope`
|
||||
* before it calls `admitWakeBehindIssueExecution`.
|
||||
*/
|
||||
type HeartbeatRun = typeof heartbeatRuns.$inferSelect;
|
||||
type LockedIssueAdmission = {
|
||||
admitWakeBehindIssueExecution: ReturnType<typeof createAdmitWakeBehindIssueExecution>;
|
||||
admitFreshIssueRun: ReturnType<typeof createFreshIssueRunAdmission<HeartbeatRun>>;
|
||||
};
|
||||
|
||||
/** 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);
|
||||
|
||||
return {
|
||||
releaseIssueExecution: createReleaseIssueExecution({ issueLock, recovery: deps.recovery }),
|
||||
admitWakeBehindIssueExecution: createAdmitWakeBehindIssueExecution({
|
||||
reader: createWakeAdmissionReader(),
|
||||
writer: createWakeAdmissionWriter(),
|
||||
helpers: deps.wakeAdmissionHelpers,
|
||||
}),
|
||||
createAdmissionTransactionScope(companyId: string, tx: Db): TransactionScope {
|
||||
return buildAdmissionTransactionScope(companyId, tx);
|
||||
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, { reader, writer, fresh }) => {
|
||||
const admitBusy = createAdmitWakeBehindIssueExecution({ reader, writer, helpers: deps.wakeAdmissionHelpers });
|
||||
const admitFresh = createFreshIssueRunAdmission(fresh);
|
||||
return evaluateHeartbeatPolicy(tx, {
|
||||
async admitWakeBehindIssueExecution(input) {
|
||||
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 admitFreshIssueRun(input) {
|
||||
if (input.issue.id !== issueId || input.contextSnapshot.issueId !== issueId) {
|
||||
throw new Error("wake-queue: admission does not match the locked issue");
|
||||
}
|
||||
return admitFresh(input);
|
||||
},
|
||||
});
|
||||
}), effects);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type WakeQueue = ReturnType<typeof createWakeQueue>;
|
||||
|
||||
/** Uses the transaction that already owns the issue's admission lock. */
|
||||
export function bindFreshIssueRunAdmission(companyId: string, tx: Db) {
|
||||
return createFreshIssueRunAdmission(createFreshIssueRunStore(buildAdmissionTransactionScope(companyId, tx), companyId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Composes the three queued-comment queue mutations (edit, reorder,
|
||||
* discard): the Postgres adapter, which owns the one transaction each
|
||||
|
||||
Reference in new issue
Block a user