perf(wake-queue): preflight task admission without loading execution context (#22289)

## Thinking Path

> - Paperclip uses task admission to turn assignments and comments into
queued work.
> - Wake-queue owns the issue-admission transaction. Heartbeat
previously loaded full execution context to decide whether a
conversation wake could proceed.
> - After the conversation preflight, task state can change before
admission obtains its lock.
> - Wake-queue now exposes the preflight decision and obtains only the
fields it needs. It provides current task attribution from the locked
row.
> - Heartbeat uses the existing responsible-user and routine rules when
it creates a run.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

Admitting board assignments and saved task comments.

**Subsystem affected**

Server task admission.

**Current behavior**

Conversation preflight and fresh-run attribution load full task
execution context from heartbeat, including chat joins.

**Proposed behavior**

Give wake-queue ownership of conversation preflight and its PostgreSQL
read. Use the issue row already locked by wake-queue for fresh-run
attribution.

**Additional context**

Builds on #22280 and #22282. #17396 covers a separate workspace
inspection on task context reads.

## What Changed

- Give heartbeat a preflight decision. Keep storage and the five-field
query inside wake-queue.
- Reuse the conversation and retry predicates for all callers. Keep the
locked recheck after preflight, including durable chat authorization.
- Supply the task's responsible user, parent and routine origin from the
current locked row. A company-only admission supplies no issue.

## Verification

On `b89bed954a`, all 307 tests passed across the wake-queue preflight
and release application suites, heartbeat queue and run-preparation
suites, and Slack conversation lifecycle suite. The integration suites
used embedded PostgreSQL. Coverage includes the owner 403, a
conversation settling before admission locks the issue, saved-comment
attribution after reassignment, and routine ownership written inside the
admission transaction. The layered server typecheck and module
dependency check passed on the same revision.

In a repeated local comparison of base `90d985b8b9` and PR head
`b89bed954a`, we measured 34 samples per revision, scenario, and
recovery-history state, alternating the two revisions in ABBA order.
Server-side admission medians were:

| Recovery history | Assignment | One comment | Two serial comments |
| --- | ---: | ---: | ---: |
| Empty | 23.45 → 21.80 ms | 23.95 → 23.00 ms | 47.30 → 45.40 ms |
| Resolved | 23.35 → 21.30 ms | 23.70 → 22.05 ms | 46.70 → 45.40 ms |

Typical SQL statements fell from 36/37/74 to 35/36/73 for the three
scenarios. Lock statement counts were 2/2/6 for both revisions.
Throughput varied under local contention. These are local measurements.

Standard Greptile scored the exact head 5/5 with no review threads.
[Greptile
review](https://github.com/paperclipai/paperclip/pull/22289#issuecomment-6999578088)

GitHub CI passed on the exact head after one targeted retry of the
serialized server shard. The initial status-card maintenance case timed
out waiting for idle, passed when run locally on the same revision, and
passed in the retried shard. [CI workflow attempt
2](https://github.com/paperclipai/paperclip/actions/runs/44458613437/attempts/2)

## Risks

An early decision can go stale, and the caller must preserve
authenticated actor identity. The locked path retains its own
eligibility checks. A regression exercises the gap between the two
decisions. An attribution test inserts its evidence inside the
transaction to detect a read through a different connection.

## Model Used

OpenAI GPT-6.2 Sol (gpt-6.2-sol) implemented the change. OpenAI Codex
reviewed and qualified it.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Nicky Leach authored and GitHub committed 2026-11-19 07:23:02 -08:00
1 parent ffcd49f6aa
commit 503268b806
13 files changed
+262 -109

No files matched your search

@@ -1276,6 +1276,19 @@ export function createWakeAdmissionWriter(rawTx: IssueAdmissionDbTransaction, ad
};
}
export function createIssueWakePreflightReader(db: Db) {
return async (companyId: string, issueId: string) => {
const [issue] = await db.select({
conversationAgentId: issues.conversationAgentId,
conversationUserId: issues.conversationUserId,
conversationState: issues.conversationState,
status: issues.status,
originKind: issues.originKind,
}).from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, companyId)));
return issue ?? null;
};
}
const issueAdmissionFields = {
id: issues.id,
companyId: issues.companyId,
@@ -1298,6 +1311,11 @@ const issueAdmissionFields = {
checkoutRunId: issues.checkoutRunId,
executionRunId: issues.executionRunId,
executionAgentNameKey: issues.executionAgentNameKey,
responsibleUserId: issues.responsibleUserId,
parentId: issues.parentId,
originKind: issues.originKind,
originId: issues.originId,
originRunId: issues.originRunId,
createdAt: issues.createdAt,
};
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { admitIssueWake, type IssueWakeAdmissionEffects, type IssueWakeAdmissionOutcome } from "./issue-wake-admission.js";
import { admitIssueWake, createIssueWakePreflight, 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" };
@@ -23,6 +23,55 @@ function recordEffects(trace: string[]): IssueWakeAdmissionEffects<Run> {
};
}
describe("issue wake preflight", () => {
const input = {
companyId: "company",
issueId: "issue",
agentId: "agent",
reason: null,
wakeReason: null,
taskRetryActorId: null,
hasIndependentConversationWakeCause: false,
};
const activeConversation = {
conversationAgentId: "agent",
conversationUserId: "owner",
conversationState: "active",
status: "in_progress",
originKind: null,
};
const onboardingTask = {
...activeConversation,
conversationAgentId: null,
conversationUserId: null,
conversationState: null,
originKind: "onboarding_first_task",
};
it.each([
{ label: "onboarding completion", issue: onboardingTask, reasons: { reason: "issue_children_completed" },
result: { kind: "eligible", onboardingCompletion: true } },
{ label: "onboarding context fallback", issue: onboardingTask, reasons: { wakeReason: "issue_children_completed" },
result: { kind: "eligible", onboardingCompletion: false } },
{ label: "execution context fallback", issue: activeConversation, reasons: { wakeReason: "issue_children_completed" },
result: { kind: "skipped" } },
{ label: "explicit reason over execution context", issue: activeConversation,
reasons: { reason: "issue_commented", wakeReason: "issue_children_completed" },
result: { kind: "eligible", onboardingCompletion: false } },
])("handles $label", async ({ issue, reasons, result }) => {
const preflight = createIssueWakePreflight(async () => issue);
await expect(preflight({ ...input, ...reasons })).resolves.toEqual(result);
});
it("requires the owner of a conversation for a manual start or retry", async () => {
const preflight = createIssueWakePreflight(async () => activeConversation);
await expect(preflight({ ...input, manualUserWake: true, requestedByActorId: "someone-else" }))
.resolves.toEqual({ kind: "conversation_owner_required", action: "start" });
await expect(preflight({ ...input, taskRetryActorId: "someone-else", reason: "issue_children_completed" }))
.resolves.toEqual({ kind: "conversation_owner_required", action: "retry" });
});
});
describe("issue wake admission handoff", () => {
it("waits for commit before publishing or dispatching and leaves telemetry in the background", async () => {
const trace: string[] = [];
@@ -1,5 +1,51 @@
import { canActorRetryConversation, isConversation, isConversationExecutionWake, isWaitingConversation } from "../../../lib/conversation-wake-policy.js";
import type { RunSummary } from "./types.js";
type ConversationWakeIssue = {
conversationAgentId: string | null;
conversationUserId: string | null;
conversationState: string | null;
status: string;
originKind: string | null;
};
export function createIssueWakePreflight(readIssue: (companyId: string, issueId: string) => Promise<ConversationWakeIssue | null>) {
return async function preflightIssueWake(input: {
companyId: string;
issueId: string;
agentId: string;
reason: string | null;
wakeReason: string | null;
requestedByActorId?: string | null;
manualUserWake?: boolean;
taskRetryActorId: string | null;
hasIndependentConversationWakeCause: boolean;
}): Promise<
| { kind: "eligible"; onboardingCompletion: boolean }
| { kind: "skipped" }
| { kind: "conversation_owner_required"; action: "start" | "retry" }
> {
const issue = await readIssue(input.companyId, input.issueId);
if (input.taskRetryActorId && issue && !canActorRetryConversation(issue, input.taskRetryActorId)) {
return { kind: "conversation_owner_required", action: "retry" };
}
const onboardingCompletion = input.reason === "issue_children_completed" && issue?.originKind === "onboarding_first_task";
if (issue && isConversation(issue)) {
if (input.reason === "onboarding_chat_greeting" && (issue.originKind !== "onboarding_chat"
|| issue.conversationUserId !== input.requestedByActorId)) return { kind: "skipped" };
if (input.manualUserWake && issue.conversationUserId !== input.requestedByActorId) {
return { kind: "conversation_owner_required", action: "start" };
}
if (isConversationExecutionWake(issue, input.reason ?? input.wakeReason)
|| input.agentId !== issue.conversationAgentId
|| (isWaitingConversation(issue) && !input.hasIndependentConversationWakeCause)) {
return { kind: "skipped" };
}
}
return { kind: "eligible", onboardingCompletion };
};
}
export type IssueWakeAdmissionOutcome<Run> =
| { kind: "queued" | "coalesced" | "replayed"; run: Run }
| { kind: "durable"; receipt: { runId: string | null } }
@@ -1,6 +1,7 @@
import type { ReleaseRecoveryBlockedNoticeKind } from "../domain/policy.js";
import type {
InvokableAgentSnapshot,
IssueAttributionSnapshot,
IssueSnapshot,
PostCommitEffect,
ReleaseOutcome,
@@ -44,7 +45,7 @@ export interface WakeQueueHost {
resolveResponsibleUserId(input: {
companyId: string;
contextSnapshot: Record<string, unknown>;
issue: IssueSnapshot;
issue: IssueAttributionSnapshot;
/** From a prior `getRoutineEnv` call against the same issue; pass `{ routineId: null, env: null, responsibleUserId: null }` when the issue is not a routine execution. */
routineEnvContext: { routineId: string | null; env: unknown; responsibleUserId: string | null };
requestedByActorType: "user" | "agent" | "system" | null;
@@ -60,7 +61,7 @@ export interface WakeQueueHost {
*/
getRoutineEnv(input: {
companyId: string;
issue: IssueSnapshot;
issue: IssueAttributionSnapshot;
}): Promise<{ routineId: string | null; env: unknown; responsibleUserId: string | null }>;
resolveSessionBeforeForWakeup(input: {
companyId: string;
@@ -55,6 +55,8 @@ export type IssueSnapshot = {
originRunId: string | null;
};
export type IssueAttributionSnapshot = Pick<IssueSnapshot, "id" | "responsibleUserId" | "parentId" | "originKind" | "originId" | "originRunId">;
export type InvokableAgentSnapshot = {
id: string;
companyId: string;
+12 -1
View File
@@ -1,5 +1,7 @@
import type { Db, heartbeatRuns } from "@paperclipai/db";
import { forbidden } from "../../errors.js";
import {
createIssueWakePreflightReader,
createPostgresIssueWakeAdmission,
createPostgresWakeQueueAdapter,
type IssueAdmissionDbTransaction,
@@ -10,7 +12,7 @@ import { createQueuedCommentIssueLockWriter } from "./adapters/queued-comment-po
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 { admitIssueWake, type IssueWakeAdmissionEffects, type IssueWakeAdmissionOutcome } from "./application/issue-wake-admission.js";
import { admitIssueWake, createIssueWakePreflight, type IssueWakeAdmissionEffects, type IssueWakeAdmissionOutcome } from "./application/issue-wake-admission.js";
import { createAdmitWakeBehindIssueExecution, createReleaseIssueExecution } from "./application/use-cases.js";
import {
createDiscardQueuedComment,
@@ -27,6 +29,7 @@ import type {
} from "./application/ports.js";
export type {
IssueAttributionSnapshot,
PostCommitEffect,
ReleaseOutcome,
RunSummary,
@@ -97,8 +100,16 @@ export function createWakeQueue(db: Db, deps: WakeQueueDeps) {
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,