Files
PaperClipAI/server/src/modules/wake-queue/application/issue-wake-admission.ts
T
Nicky Leach 503268b806 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
2026-11-19 07:23:02 -08:00

94 lines
3.8 KiB
TypeScript

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 } }
| { 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;
}