mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-23 21:24:45 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The heartbeat queue starts each agent's queued runs, up to the agent's `maxConcurrentRuns` > - #21234 starts person-initiated runs before system recovery runs, and it reads "person-initiated" from the run's own wake request > - When a person comments on a task that already has a queued system run, the comment joins that run. The run keeps its system wake, so dispatch ranks the person's message as system work > - Dispatch is event driven. The queued-run re-drive backstop covers only agents with no live run, so an agent with several slots keeps a free slot empty until one of its runs finishes, and runs can take hours > - This pull request makes dispatch read the person wakes that joined each queued run, and makes the re-drive backstop cover an agent that still has a free slot > - The benefit is that a person's comment starts first, and free slots fill within about a minute instead of waiting for an unrelated run to finish ## Linked Issues or Issue Description Refs #21234, #20986 **What happened?** On staging, one agent had `maxConcurrentRuns` 20, 18 running runs and 76 queued runs at 03:12Z. No run started on that agent from 03:01:33Z to 03:16:57Z (15.4 minutes). From 03:11:10Z, after a run finished, at least 2 slots were free. Other agents in the same company started runs during that time. Runs started again only after the next deploy restarted the server. Five queued runs came from a person: comments at 02:43Z, 02:44Z and 02:45Z, and Retries at 02:46Z, 02:49Z and 03:01Z. The comment runs had the wake reasons `issue_reopened_via_comment` and `issue_commented`, the invocation source `automation`, and no person on the run's own wake request. **Expected behavior** A run that carries a person's comment ranks as person-initiated, also when the comment joined an existing queued run. When an agent has a free slot and a queued run is ready, the run starts promptly, without waiting for another run on the agent to finish. **Steps to reproduce** 1. Give an agent `maxConcurrentRuns` 3. Start 2 runs on it. 2. Queue a third run while no dispatch signal reaches the queue (for example, a claim declines it while a gate is still closed, and the gate then clears). 3. See that `listUndispatchedQueuedRuns` returns nothing, because the agent has a live run. The run stays queued until one of the 2 running runs finishes. 4. Separately, queue a system run on a task, then post a person's comment on the task so that the comment wake coalesces into that queued run. Queue older system runs on other tasks of the same single-slot agent. 5. See that dispatch starts the older system runs first. **Root cause** 1. `coalesceIntoActiveExecutionRun` (`server/src/modules/wake-queue/adapters/postgres.ts`) merges the person's comment context into the queued run and records the person's wake as a separate `coalesced` row with `runId` set to that run. The run's own `wakeupRequestId` still points to the system wake. `queuedRunDispatcherForAgent` (`server/src/services/heartbeat/queue.ts`) only read the wake behind `wakeupRequestId`. The task routes do record the comment author as the requester (`requestedByActorType: "user"`). The person was lost only at dispatch time. 2. `listUndispatchedQueuedRunPage` (`server/src/services/queued-run-dispatch-liveness.ts`) skipped every agent with any `running` or `scheduled_retry` run. That rule assumes one slot per agent. For an agent with several slots, a lost or declined dispatch is not re-driven until a run on that agent finishes. This change is not in `claimQueuedRun`, the fresh-isolated preflight, the wake-queue promoter or `fresh-continuation-fallback.ts`. **Paperclip version or commit** Staging Core `ddc0aacad8` (contains #21234 `ade7e0643f`). This branch is based on master `6cb0dd0c6b`. **Deployment mode** Authenticated, public, Paperclip Cloud managed staging. **Agent adapter(s) involved** `paperclip_runner` (Codex native runtime). The fix is adapter-independent. ## What Changed - `queuedRunDispatcherForAgent` also reads person wakes whose `runId` is a queued run of the agent (by `run_id IN (queued run ids)`, so an earlier saved comment that a run adopted is included). A run with such a wake ranks as person-initiated and is never counted as system recovery. - `listUndispatchedQueuedRuns` now returns a queued run when its agent has fewer `running` plus `scheduled_retry` runs than its `maxConcurrentRuns`, and its task has no `running` or `scheduled_retry` run. The re-drive backstop and the ownership I7 check use this query. - The query counts each agent's live runs once, in one grouped subquery that is joined to the queued runs. - Migration 0476 adds `agent_wakeup_requests_company_run_idx` (`company_id`, `run_id`, partial on a non-null run) with `CREATE INDEX CONCURRENTLY IF NOT EXISTS`. It is listed in `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS` and classifies as `online_compatible`. `doc/DATABASE.md` describes it. - Added `maxConcurrentRunsSql()` to `timer-policy.ts`. It reads the same limit as `parseHeartbeatPolicy`, including the single-run runner providers, which now share one constant. ## Verification - Red/green: `server/src/__tests__/recovery-wake-herd.test.ts` "starts a queued run that a person's comment joined ahead of older system work". It fails on master (`expected null not to be null`: the older system run started first) and passes with this change. - Red/green: `server/src/__tests__/ownership-reconciliation-report.test.ts` "re-drives a queued run while its agent still has a free slot, and not once every slot is running". It fails on master (`expected [] to deeply equal [ Array(1) ]`) and passes with this change. - Red/green: "starts a queued run that adopted a person's comment saved before every queued run". It fails with a `requestedAt` bound and passes with the `run_id` lookup. - Red/green: "counts an agent's live runs in one grouped aggregate, not once per queued run" runs EXPLAIN on the page query. It fails with a per-row correlated count and passes with the grouped subquery. - New: "uses the agent's single-run limit for a runner provider that runs one turn at a time". - Two existing tests now set `maxConcurrentRuns: 1` so that they keep testing "the agent's only slot is busy". - `npx vitest run src/__tests__/recovery-wake-herd.test.ts src/services/heartbeat/queued-run-dispatch-order.test.ts src/__tests__/ownership-reconciliation-report.test.ts src/services/queued-run-dispatch-liveness.test.ts src/services/heartbeat/dispatch-work.test.ts`: 71 passed. - `npx tsc --noEmit -p server/tsconfig.json`: no errors. ## Risks - The re-drive backstop now also covers multi-slot agents with live runs. Each queued run is re-driven at most on its existing backoff (1 minute, then doubling to 15 minutes). A queued run whose task already has a live run is not re-driven. - The ownership I7 report can now list a queued run on a multi-slot agent that has a free slot. This is the stall that this change targets. - One more indexed read per dispatch pass (`agent_wakeup_requests` by company and run id). The new index is built concurrently, so the previous release keeps writing during the build. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, read-only staging API reads in a browser tab). ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
146 lines
7.8 KiB
TypeScript
146 lines
7.8 KiB
TypeScript
import { and, asc, eq, gte, inArray, notInArray, sql } from "drizzle-orm";
|
|
import { agents, companies, heartbeatRuns, type Db } from "@paperclipai/db";
|
|
import { instanceSettingsService, isTruthyRuntimeEnvValue, resolveWorktreeRunExecutionActivation } from "./instance-settings.js";
|
|
import { maxConcurrentRunsSql } from "./heartbeat/timer-policy.js";
|
|
|
|
export const QUEUED_RUN_REDRIVE_AFTER_MS = 60_000;
|
|
export const QUEUED_RUN_REDRIVE_MAX_INTERVAL_MS = 15 * 60_000;
|
|
export const QUEUED_RUN_REDRIVE_DELAY_MS = 1_000;
|
|
export const QUEUED_RUN_NOT_DISPATCHED = "queued_run_not_dispatched";
|
|
|
|
const NOT_READY_AGENT_STATUSES = ["paused", "terminated", "pending_approval"];
|
|
const UNDISPATCHED_PAGE_SIZE = 500;
|
|
|
|
export type UndispatchedQueuedRun = {
|
|
runId: string;
|
|
companyId: string;
|
|
agentId: string;
|
|
issueId: string | null;
|
|
createdAt: Date;
|
|
};
|
|
|
|
export type UndispatchedQueuedRunCursor = { at: string; runId: string };
|
|
type PageCursor = UndispatchedQueuedRunCursor;
|
|
|
|
/** One page of undispatched queued runs. Live runs are counted once per agent. */
|
|
export function undispatchedQueuedRunPageQuery(db: Db, companyId: string | undefined, createdAfter: Date | null | undefined,
|
|
after: PageCursor | null, limit: number) {
|
|
const liveRuns = db.select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
|
|
count: sql<number>`count(*)`.as("live_count") }).from(heartbeatRuns)
|
|
.where(and(inArray(heartbeatRuns.status, ["running", "scheduled_retry"]),
|
|
companyId ? eq(heartbeatRuns.companyId, companyId) : undefined))
|
|
.groupBy(heartbeatRuns.companyId, heartbeatRuns.agentId).as("agent_live_runs");
|
|
return db.select({
|
|
runId: heartbeatRuns.id,
|
|
companyId: heartbeatRuns.companyId,
|
|
agentId: heartbeatRuns.agentId,
|
|
issueId: sql<string | null>`coalesce(${heartbeatRuns.issueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId')`,
|
|
createdAt: heartbeatRuns.createdAt,
|
|
cursorAt: sql<string>`to_char(${heartbeatRuns.createdAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`,
|
|
}).from(heartbeatRuns)
|
|
.innerJoin(companies, eq(companies.id, heartbeatRuns.companyId))
|
|
.innerJoin(agents, and(eq(agents.id, heartbeatRuns.agentId), eq(agents.companyId, heartbeatRuns.companyId)))
|
|
.leftJoin(liveRuns, and(eq(liveRuns.companyId, heartbeatRuns.companyId), eq(liveRuns.agentId, heartbeatRuns.agentId)))
|
|
.where(and(
|
|
eq(heartbeatRuns.status, "queued"),
|
|
companyId ? eq(heartbeatRuns.companyId, companyId) : undefined,
|
|
createdAfter ? gte(heartbeatRuns.createdAt, createdAfter) : undefined,
|
|
eq(companies.status, "active"),
|
|
eq(agents.lifecycleState, "ready"),
|
|
notInArray(agents.status, NOT_READY_AGENT_STATUSES),
|
|
after ? sql`(${heartbeatRuns.createdAt}, ${heartbeatRuns.id}) > (${after.at}::timestamptz, ${after.runId}::uuid)` : undefined,
|
|
sql`coalesce(${liveRuns.count}, 0) < ${maxConcurrentRunsSql()}`,
|
|
sql`not exists (select 1 from ${heartbeatRuns} task_live
|
|
where task_live.company_id = ${heartbeatRuns.companyId}
|
|
and task_live.context_snapshot->>'issueId' = coalesce(${heartbeatRuns.issueId}::text, ${heartbeatRuns.contextSnapshot}->>'issueId')
|
|
and task_live.status in ('running', 'scheduled_retry'))`,
|
|
))
|
|
.orderBy(asc(heartbeatRuns.createdAt), asc(heartbeatRuns.id))
|
|
.limit(limit);
|
|
}
|
|
|
|
async function listUndispatchedQueuedRunPage(db: Db, companyId: string | undefined, createdAfter: Date | null | undefined,
|
|
after: PageCursor | null, limit: number): Promise<Array<UndispatchedQueuedRun & { cursorAt: string }>> {
|
|
return undispatchedQueuedRunPageQuery(db, companyId, createdAfter, after, limit);
|
|
}
|
|
|
|
/** Every undispatched queued run, read page by page with no cap; one
|
|
* company's runs when `companyId` is given. `createdAfter` is the worktree
|
|
* execution cutoff: dispatch never starts a run created before it. */
|
|
export async function listUndispatchedQueuedRuns(db: Db,
|
|
options: { companyId?: string; createdAfter?: Date | null; pageSize?: number } = {}):
|
|
Promise<UndispatchedQueuedRun[]> {
|
|
return (await readUndispatchedQueuedRuns(db, options)).runs;
|
|
}
|
|
|
|
/** Reads from `after` until the set ends or `maxRuns` rows were read. `next`
|
|
* is where a later read continues, or null when the set was read to its end. */
|
|
export async function readUndispatchedQueuedRuns(db: Db, options: { companyId?: string; createdAfter?: Date | null;
|
|
pageSize?: number; after?: UndispatchedQueuedRunCursor | null; maxRuns?: number } = {}):
|
|
Promise<{ runs: UndispatchedQueuedRun[]; next: UndispatchedQueuedRunCursor | null }> {
|
|
const pageSize = options.pageSize ?? UNDISPATCHED_PAGE_SIZE;
|
|
const maxRuns = options.maxRuns ?? Number.POSITIVE_INFINITY;
|
|
const runs: UndispatchedQueuedRun[] = [];
|
|
let after: PageCursor | null = options.after ?? null;
|
|
for (;;) {
|
|
const want = Math.min(pageSize, maxRuns - runs.length);
|
|
const page = await listUndispatchedQueuedRunPage(db, options.companyId, options.createdAfter, after, want);
|
|
runs.push(...page.map(({ cursorAt: _cursorAt, ...run }) => run));
|
|
if (page.length < want) return { runs, next: null };
|
|
const last = page[page.length - 1]!;
|
|
after = { at: last.cursorAt, runId: last.runId };
|
|
if (runs.length >= maxRuns) return { runs, next: after };
|
|
}
|
|
}
|
|
|
|
export type QueuedRunRedrivePlan = { companyIds: string[]; nextAt: number | null };
|
|
|
|
/** Re-drive deadlines for undispatched queued runs. `refresh` replaces the
|
|
* tracked runs of the companies a dispatch pass just read (or of every company
|
|
* after an instance-wide pass) and keeps the others, so a company-scoped pass
|
|
* never reads another company's queue. */
|
|
export function createQueuedRunRedriveSchedule(now: () => number = Date.now) {
|
|
const tracked = new Map<string, { run: UndispatchedQueuedRun; count: number; dueAt: number }>();
|
|
return {
|
|
refresh(scope: "all" | ReadonlySet<string>, runs: readonly UndispatchedQueuedRun[]): QueuedRunRedrivePlan {
|
|
const current = now();
|
|
const live = new Set(runs.map(run => run.runId));
|
|
for (const [runId, entry] of tracked) {
|
|
if ((scope === "all" || scope.has(entry.run.companyId)) && !live.has(runId)) tracked.delete(runId);
|
|
}
|
|
for (const run of runs) {
|
|
const prior = tracked.get(run.runId);
|
|
tracked.set(run.runId, prior ? { ...prior, run }
|
|
: { run, count: 0, dueAt: run.createdAt.getTime() + QUEUED_RUN_REDRIVE_AFTER_MS });
|
|
}
|
|
const companyIds = new Set<string>();
|
|
let nextAt: number | null = null;
|
|
for (const [runId, entry] of tracked) {
|
|
let dueAt = entry.dueAt;
|
|
if (entry.dueAt <= current) {
|
|
companyIds.add(entry.run.companyId);
|
|
tracked.set(runId, { ...entry, count: entry.count + 1,
|
|
dueAt: current + Math.min(QUEUED_RUN_REDRIVE_AFTER_MS * 2 ** entry.count, QUEUED_RUN_REDRIVE_MAX_INTERVAL_MS) });
|
|
dueAt = current + QUEUED_RUN_REDRIVE_DELAY_MS;
|
|
}
|
|
nextAt = nextAt === null ? dueAt : Math.min(nextAt, dueAt);
|
|
}
|
|
return { companyIds: [...companyIds], nextAt };
|
|
},
|
|
};
|
|
}
|
|
|
|
/** Whether this runtime dispatches queued runs at all, and from which
|
|
* creation time, read the way dispatch reads them: a worktree runtime starts
|
|
* nothing until worktree execution is armed, and then only runs created after
|
|
* its cutoff. */
|
|
export async function readQueuedRunExecutionWindow(db: Db, runtimeEnv: Record<string, string | undefined> = process.env):
|
|
Promise<{ dispatches: boolean; createdAfter: Date | null }> {
|
|
if (!isTruthyRuntimeEnvValue(runtimeEnv.PAPERCLIP_IN_WORKTREE)) return { dispatches: true, createdAfter: null };
|
|
const activation = resolveWorktreeRunExecutionActivation(await instanceSettingsService(db).getExperimental(),
|
|
runtimeEnv.PAPERCLIP_INSTANCE_ID?.trim() || null);
|
|
const cutoff = activation.armed ? new Date(activation.cutoff) : null;
|
|
return cutoff && !Number.isNaN(cutoff.getTime()) ? { dispatches: true, createdAfter: cutoff }
|
|
: { dispatches: false, createdAfter: null };
|
|
}
|