mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 09:05:15 +01:00
fix(recovery): pause automatic recovery runs while a company's runs fail before starting (#21443)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Automatic recovery continues interrupted and failed tasks without a person, with a per-task limit of 6 automatic attempts per hour > - There is no company-level limit. When the sandbox provider refuses to create sandboxes, every task fails the same way, and recovery keeps creating new runs for each task > - On a hosted instance, one hour of a provider outage made 510 automatic runs, 587 failures and 0 successes across 289 tasks. No task had more than 4 runs, so the per-task limit did not engage. Each start asked a refusing provider for a sandbox and used server memory, which made the outage longer > - Recovery must still continue every task by itself. The answer is to wait while the infrastructure fails, not to give the task to a person > - This pull request adds a company-scoped pause for automatic work: it opens when recent automatic runs fail before the agent starts, the recovery passes stop creating new automatic runs while it is open, and it closes by itself when runs start normally again > - The benefit is that an infrastructure outage no longer multiplies itself through recovery, and recovery resumes with no person acting ## Linked Issues or Issue Description **What happened?** During a sandbox provider outage, automatic recovery created hundreds of new runs per hour across hundreds of tasks. All of them failed before the agent did any work. The per-task limit did not engage because no single task reached it. **Expected behavior** When most recent automatic runs of a company fail before they start, recovery waits instead of creating more runs. It tries again at a small rate. It resumes at full rate when runs start normally again. A person's work is never held. **Steps to reproduce** 1. Make the sandbox provider refuse lease creation (HTTP 503) for a company with many assigned tasks. 2. Let recovery continue the failed tasks. 3. Count automatic runs created per hour: it grows with the number of tasks, and every run fails at sandbox creation. Refs #21394 (continuation classification this change will reuse when it lands), #21433 (start-pass rewrite that the start hook will build on). ## What Changed - New table `automatic_run_brakes` (one row per company, cascade delete with the company; migration `0480`). Migration `0481` builds `heartbeat_runs_company_finished_idx (company_id, finished_at desc) where finished_at is not null` concurrently, so the signal reads the runs that finished in the window directly. It stores the state (closed, open, half_open), the reason with the window numbers, and the compare-and-set fields that two servers share. A company with no row is closed. - New module `server/src/services/recovery/automatic-run-brake.ts`: - Signal: on the database clock, the automatic runs of the company that finished in the last 10 minutes (and since the last state change), newest 500 by finish time, plus up to 200 running runs. A run counts as a failure only when it ended in its own start phase: no provider work (`executionRecovery.providerWorkStarted = false` or the native `nativePreDispatchFailure` record), a legacy run still preparing, or a transient setup code. A run interrupted by a server stop, restart or lease loss is neutral, so a release swap does not open the pause. A run that succeeded, or ended for a person-owned or task reason, counts as healthy. - Opens at 12 or more counted runs with 80% or more failures, or on 5 sandbox refusals (`environment_provider_unavailable`) in a row. - Each outcome counts once, at its own time: a finished run at its finish time, a running run that got past setup at its start time. Read time never orders evidence. - Closes in two steps: open moves to half_open after at least 2 minutes when the newest 2 counted runs are healthy or the newest one succeeded; half_open releases at a doubling rate per minute (2, 4, 8, 16, 32, 64) and then closes. It reopens from half_open if the signal trips again. It closes by itself after 15 minutes with no automatic activity. - Reads are one indexed query per company, cached for 5 seconds in a bounded in-process map (256 companies). Each state change writes one structured log line (`automatic_run_brake.opened|half_open|closed|reopened`) with the numbers. - It also contains the start gate `holdAutomaticRunStart` (one probe at a time, at most one new probe per 60 s, release budget per window by compare-and-set, no I/O while the cached "held until" time has not passed, person origin taken as an argument with a cached fallback). This pull request does not call it from the start pass; see Risks. - Recovery passes defer creating runs while the pause is open. The gate is only where a run is created: - `deliverReconciledExecutions`: after the agent-room check and right before the wake, the delivery asks for a creation slot; when the pause holds it, the continuation stays pending. The held backlog (`continueHeldExecutions`) is not gated: recording a pending continuation creates no run and costs nothing, and its delivery passes this gate once. - Assigned-work sweep `act()`: after the process rate limit and before it claims a continuation, it asks for a creation slot; when held, it returns `deferred_rate_limit` with the next try time, so nothing is written to the per-task attempt ledger. New assignments with no earlier run are not deferred. - A reserved slot is given back (compare-and-set on its own timestamp) when no run is created: the wake is refused or throws, the task is capped, the claim changed, or the task went back to review. The give-back is conditional in SQL on no run for that task having been created since the reservation, so a wake that commits its run and then throws keeps the slot. - The sweep's overdue saved-work recovery path returns before the slot is asked for: it starts a recovery attempt, not a run, and is never held. - Person work is never deferred. The gate is called only at the delivery (`agentHasRoom`) and the sweep (`act()`), and each call passes the task and the run it continues. While the pause is open, the gate does not hold the record when any of these is true; it holds only when none is. With no task or no source run it does not hold (fails open). | Shape | How it is recognised | | --- | --- | | A Retry or "move forward" waiting for the task (`deferred_issue_execution`, `queued` or `claimed`, no run yet) | an unstarted wake request from a user for the task | | A Retry folded (`coalesced`) into the continuation, or a Retry while the delivery is pending | a wake request from a user for the task, requested after the source run finished (any status) | | A person's message or a new assignment by a person after the last run | the same: a wake request from a user for the task after the source run finished | | A held task selected because a person pressed Retry (the refused Retry run) | a run for the task created after the source run finished whose wake is a person reason (`task_retry`, chat message), or that has `taskRetryRequestId` or `explicitUserContinuation` | | A continuation of a person's Retry (any depth) | the source run's chain reaches a person's run (`listPersonOriginSourceRunIds`, the dispatch rule) | | A Retry during pending delivery that becomes the continuation itself (`deliverContinuationAsRun`) | not gated: that run is created by the person's own wake, never by these passes | | The held backlog's saved-input path | not gated: recording or releasing a held continuation creates no run here | - To prevent a deadlock, a pass may still create one automatic run per minute per company when no automatic run of the company started in the last 2 minutes, however many runs wait (compare-and-set, shared by servers). - `GET /api/companies/:id/assigned-work-invariant` now returns `automaticWork` with the state, the time it paused, the window numbers and a plain sentence, for example "Automatic work is paused for this company since T because 47 of 50 recent automatic runs failed before starting." - `listPersonOriginSourceRunIds` in `heartbeat/queued-run-line.ts` is now exported, unchanged, so the gate uses the same person-origin rule as dispatch. - The outcome rules (person-owned codes, restart codes, transient setup codes, native pre-dispatch record) come from their owning modules through one memoised dynamic import. A static import of `heartbeat/retries.ts` made a module cycle at server start. ### What the pause consumes, and how waste is bounded | Token | Taken | Given back or bounded | | --- | --- | --- | | Creation slot (one per minute per company while open) | right before the run is created, after every other check | released only when no run for the task was committed after the reservation | | Probe slot (start gate) | when the start gate lets one automatic run through | another run may take it when the reserved run has not started within 10 seconds (claim declined, agent paused or full) or was cancelled, deleted or finished | | Gradual-release start (start gate) | one per run the start gate lets through | a declined claim spends one start of that window; the window ends within 60 seconds and the next one doubles | | Probe success count | once per probe run, by compare-and-set on its id | a probe run counts once; cancelled or deleted probes count as neither success nor failure | ### When the pause opens, stays open and closes | State | Leaves when | Bound | | --- | --- | --- | | closed | opens when, in the last 10 minutes since the last change, 12 or more counted automatic runs finished and 80% or more failed before starting, or the newest 5 counted runs were sandbox refusals | none needed | | open | moves to half_open when it has been open 2 minutes or more and the newest 2 counted runs are healthy, or the newest one succeeded | evidence arrives at least once a minute: when no automatic run started in the last 2 minutes, a pass may create one per minute | | open | closes when no automatic run started or finished for 15 minutes (queued runs do not count) | 15 minutes after the last activity | | open | stays open only while new automatic runs keep failing before starting | each new try is spaced by the existing passes and by one creation per minute when nothing starts | | half_open | closes after 6 release minutes (2, 4, 8, 16, 32, 64) | 6 minutes | | half_open | reopens when the signal trips again, counted only since half_open began | none needed | Restart-class endings (server stop, restart, lease loss, process loss, interrupted native session) are neutral in every state, so a release swap does not open the pause. ## Verification - `npx vitest run src/__tests__/automatic-run-brake.test.ts` (14 tests, pass): classification; opens on 20 failures before start; 50 queued automatic runs give exactly one probe and no failure or attempt; a person's Retry, a new assignment, a run a person joined and the continuation of a person's Retry are not held; mixed and person-owned outcomes stay closed; old data is ignored; 40 working runs interrupted by a restart stay closed, then the same continuations failing at sandbox acquisition open it; 5 refusals in a row open it; failed probe waits for the interval, two probes past setup move to half_open, the release gives exactly 2, 4, 8, 16, 32, 64 starts per window and then closes; reopen from half_open; probe slot frees after cancel, delete or no start; quiet close after 15 minutes; two instances on one database agree and start one probe; one creation per minute while open across servers; 250 held runs over 100 passes use at most 5 queries (at most 255 with the person-origin fallback, one per run, once); caches stay at 256 companies and 1024 runs. - `npx vitest run src/__tests__/automatic-run-brake-recovery-passes.test.ts` (pass; one test per person shape above at the delivery and the sweep, with the pause open and no creation slot, plus a control that still holds a continuation no person asked for): includes "no pause record: every pass behaves as before", "the waiting run cannot start: a pass continues a task on another agent, then the pause closes", "one held task spends one creation slot", and "a person's Retry or message is never paused at the delivery, the sweep or the held backlog".: sweep, delivery and held backlog create nothing while open, write no attempts, and continue by themselves after recovery; the sweep still continues one task a minute when nothing automatic waits. With the three deferral lines removed, all 4 fail (red), and they pass with them (green). - The pause reads as closed and logs once when its run rules cannot load (test in `automatic-run-brake.test.ts`). - `npx vitest run src/__tests__/automatic-run-brake-import.test.ts`: the module loads after the heartbeat service, in the server's import order. - `npx tsc --noEmit -p server/tsconfig.json`: clean. - `pnpm verify`: see the comment below for the result. CI supplies the full suite. ## Risks - This pull request does not hold starts. Already queued runs and `transient_failure_retry` runs still start while the pause is open; they act as the natural tries. The start gate goes in as a follow-up on top of #21433, at a point before that pass counts a claim attempt and reads the full run row, so a held run costs no attempt and no read. - The sweep reuses the `deferred_rate_limit` outcome for a deferral, to keep its outcome type unchanged while #21394 edits that file. - The automatic-run predicate is built from master exports (`RECOVERY_WAKE_REASONS`, retry markers). It will switch to `isAutomaticContinuationRun` when #21394 lands. - Migration `0480` adds one small table. - Migration `0481` (`0481_heartbeat_runs_company_finished_index.sql`) runs `CREATE INDEX CONCURRENTLY IF NOT EXISTS` as a top-level statement: it is listed in `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS` in `packages/db/src/client.ts`, like 0470 and 0476, and the runner drops and rebuilds an invalid index after an interrupted build. The index is declared in the Drizzle schema, so `pnpm db:generate` reports no changes, and `pnpm --filter @paperclipai/db check:migrations` passes. On a large `heartbeat_runs` table the build is online (no write lock) but takes time proportional to the table. After it exists, it is one more index on a hot table: each run that finishes writes one more index entry. - No user-visible text changes outside the operator report. ## Model Used - Claude Fable 5.2 (Anthropic), via Claude Code with tool use (shell, file edits, tests). ## 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 Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
6826800425
commit
689f3b190e
19 files changed
+2471
-20
No files matched your search
@@ -39,6 +39,8 @@ import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js";
|
||||
import { readSystemRecovery } from "./system-recovery-state.js";
|
||||
import { isReattachPhaseActive } from "./heartbeat/run-admission.js";
|
||||
import { provenGoneLegacyControllerBootId } from "./legacy-controller-lease.js";
|
||||
import { reserveAutomaticRunCreation } from "./recovery/automatic-run-brake.js";
|
||||
import { recordContinuationDeliveryAttempt } from "./recovery/continuation-delivery-attempt.js";
|
||||
import { continueFreshInTransaction, continueHeldExecutions, freshContinuationCheckDue, recordFreshContinuationCheck,
|
||||
settleCoalescedFreshContinuationHolds } from "./fresh-continuation-fallback.js";
|
||||
import { alias } from "drizzle-orm/pg-core";
|
||||
@@ -395,6 +397,7 @@ export async function deliverReconciledExecutions(
|
||||
] : [
|
||||
sql`${pastBound} desc`,
|
||||
sql`${overdueTurn} asc nulls last`,
|
||||
sql`${attemptedAt} asc nulls first`,
|
||||
sql`${sourceRun.finishedAt} desc nulls last`,
|
||||
sql`${issueRecoveryActions.updatedAt} asc`,
|
||||
];
|
||||
@@ -445,21 +448,14 @@ export async function deliverReconciledExecutions(
|
||||
] : [
|
||||
sql`${candidates.pastBound} desc`,
|
||||
sql`${candidates.heldAt} asc nulls last`,
|
||||
sql`${candidates.attemptedAt} asc nulls first`,
|
||||
sql`${candidates.sourceFinishedAt} desc nulls last`,
|
||||
sql`${candidates.actionUpdatedAt} asc`,
|
||||
]))
|
||||
.limit(25);
|
||||
return rows.map(row => row.action);
|
||||
};
|
||||
const deferRefusedContinuation = (action: typeof issueRecoveryActions.$inferSelect) => db.update(issueRecoveryActions)
|
||||
.set({ evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify(
|
||||
{ continuationDeliveryAttemptedAt: new Date().toISOString() })}::jsonb` })
|
||||
.where(and(
|
||||
eq(issueRecoveryActions.companyId, action.companyId),
|
||||
eq(issueRecoveryActions.id, action.id),
|
||||
eq(issueRecoveryActions.status, "resolved"),
|
||||
sql`${issueRecoveryActions.evidence}->>'continuationDelivery' = 'pending'`,
|
||||
));
|
||||
const deferRefusedContinuation = (action: typeof issueRecoveryActions.$inferSelect) => recordContinuationDeliveryAttempt(db, action);
|
||||
const agentHasRoom = async (action: typeof issueRecoveryActions.$inferSelect, agentId: string, kind: ContinuationClass) => {
|
||||
if ((admittedByCompany.get(action.companyId) ?? 0) >= companyLimit) return false;
|
||||
// A few at a time per agent, fresh or not: the rest waits here, durably,
|
||||
@@ -553,6 +549,8 @@ export async function deliverReconciledExecutions(
|
||||
seenAgents.add(action.returnOwnerAgentId);
|
||||
continue;
|
||||
}
|
||||
const slot = await reserveAutomaticRunCreation(db, action.companyId, { issueId: task.id, sourceRunId: decision.runId });
|
||||
if (slot.heldUntil) { await deferRefusedContinuation(action); continue; }
|
||||
const run = await wake(action.returnOwnerAgentId, {
|
||||
source: "automation",
|
||||
triggerDetail: "system",
|
||||
@@ -573,9 +571,10 @@ export async function deliverReconciledExecutions(
|
||||
...((action.evidence.freshContinuation as { isolation?: unknown } | undefined)?.isolation === "fresh_isolated_workspace"
|
||||
? { freshContinuationIsolation: action.id } : {}),
|
||||
},
|
||||
});
|
||||
}).catch(async error => { await slot.release(); throw error; });
|
||||
seenAgents.add(action.returnOwnerAgentId);
|
||||
if (!run) {
|
||||
await slot.release();
|
||||
await deferRefusedContinuation(action);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -35,7 +35,8 @@ import { HELD_RECOVERY_WAKE_KEYS, queuedRecoveryRunsOf } from "../recovery-queue
|
||||
import { listPersonOriginSourceRunIds } from "../heartbeat/queued-run-line.js";
|
||||
import { aliasedRun, queuedRunStalledSql } from "./stalled-queued-run-sql.js";
|
||||
import { attributeBlock, BLOCK_ATTRIBUTION_WINDOW_MS, blockedStatusDetailsSql } from "../interruption-block-release.js";
|
||||
import { ASSIGNED_WORK_CONTINUED_ACTION, taskAutomaticAttempts } from "./task-automatic-attempts.js";
|
||||
import { ASSIGNED_WORK_CONTINUED_ACTION, PAUSED_FOR_AUTOMATIC_WORK, taskAutomaticAttempts } from "./task-automatic-attempts.js";
|
||||
import { automaticRunCreationHeldUntil, readAutomaticWorkStatus, reserveAutomaticRunCreation } from "./automatic-run-brake.js";
|
||||
import { isReattachPhaseActive, reattachPhaseRecheckAt } from "../heartbeat/run-admission.js";
|
||||
import { ensureFreshContinuation, type FreshContinuationResult } from "../fresh-continuation-fallback.js";
|
||||
import { canContinueRecoveryRunAutomatically } from "../continuation-cause.js";
|
||||
@@ -627,6 +628,9 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
|
||||
if (repairTimes.length >= ASSIGNED_WORK_REPAIRS_PER_MINUTE) {
|
||||
return { verdict, outcome: "deferred_rate_limit", retryAt: new Date(repairTimes[0] + 60_000 + Math.floor(Math.random() * 5_000)) };
|
||||
}
|
||||
const heldUntil = facts.latestRun
|
||||
? await automaticRunCreationHeldUntil(db, issue.companyId, { issueId: issue.id, sourceRunId: facts.latestRun.id }) : null;
|
||||
if (heldUntil) return { verdict, outcome: "deferred_rate_limit", retryAt: heldUntil };
|
||||
const claimed = await claimContinuation(issue, at);
|
||||
if (claimed.kind !== "claimed") return { verdict, outcome: claimed.kind === "capped" ? "deferred_cap" : claimed.kind === "changed" ? "changed" : "deferred_rate_limit",
|
||||
retryAt: claimed.kind === "changed" ? null : claimed.retryAt };
|
||||
@@ -648,6 +652,15 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
|
||||
await settleContinuationActivity(claimed, claimed.reason, "not_started", { waitingUntil: fresh.retryAt.toISOString() });
|
||||
return { verdict: claimed.verdict, outcome: fresh.kind === "backoff" ? "deferred_cap" : "waiting_on_recovery", retryAt: fresh.retryAt };
|
||||
}
|
||||
const slot = facts.latestRun
|
||||
? await reserveAutomaticRunCreation(db, issue.companyId, { issueId: issue.id, sourceRunId: facts.latestRun.id }) : null;
|
||||
if (slot?.heldUntil) {
|
||||
if (claimed.restoredTo) await revertRestoredBlock(issue, claimed);
|
||||
await settleContinuationActivity(claimed, claimed.reason, "not_started",
|
||||
{ waitingUntil: slot.heldUntil.toISOString(), [PAUSED_FOR_AUTOMATIC_WORK]: "true" });
|
||||
return { verdict: claimed.verdict, outcome: "deferred_rate_limit", retryAt: slot.heldUntil };
|
||||
}
|
||||
const release = async () => { if (slot && !slot.heldUntil) await slot.release(); };
|
||||
const run = await deps.enqueueWakeup(issue.assigneeAgentId!, {
|
||||
source: facts.latestRun ? "automation" : "assignment", triggerDetail: "system",
|
||||
reason: facts.latestRun ? "issue_continuation_needed" : "issue_assigned",
|
||||
@@ -663,6 +676,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
|
||||
// A refused continuation stays a violation; the claim spaces the next try.
|
||||
// A block lifted for it is put back, so the task never sits unblocked
|
||||
// with nothing pending.
|
||||
if (!run) await release();
|
||||
if (!run && claimed.restoredTo) await revertRestoredBlock(issue, claimed);
|
||||
await settleContinuationActivity(claimed, claimed.reason, run ? "queued" : "not_started",
|
||||
fresh?.kind === "person_owned" ? { waitingFor: fresh.reason } : {});
|
||||
@@ -680,12 +694,19 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
|
||||
}
|
||||
|
||||
async function replaceStalledRun(issue: IssueRow, claimed: Claimed, runId: string): Promise<AssignedWorkCheck> {
|
||||
const slot = await reserveAutomaticRunCreation(db, issue.companyId, { issueId: issue.id, sourceRunId: runId });
|
||||
if (slot.heldUntil) {
|
||||
await settleContinuationActivity(claimed, claimed.reason, "not_started",
|
||||
{ waitingUntil: slot.heldUntil.toISOString(), [PAUSED_FOR_AUTOMATIC_WORK]: "true" });
|
||||
return { verdict: claimed.verdict, outcome: "deferred_rate_limit", retryAt: slot.heldUntil };
|
||||
}
|
||||
const cancelled = !claimed.stalledFence ? false : await deps.cancelStalledQueuedRun!({ companyId: issue.companyId, runId,
|
||||
...claimed.stalledFence }).catch(error => {
|
||||
logger.warn({ err: error, companyId: issue.companyId, issueId: issue.id, runId }, "assigned-work sweep could not cancel a stalled queued run");
|
||||
return false;
|
||||
});
|
||||
if (!cancelled) {
|
||||
await slot.release();
|
||||
await db.delete(activityLog).where(eq(activityLog.id, claimed.activityId));
|
||||
return { verdict: claimed.verdict, outcome: "changed", retryAt: null };
|
||||
}
|
||||
@@ -699,6 +720,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
|
||||
logger.warn({ err: error, companyId: issue.companyId, issueId: issue.id }, "assigned-work replacement for a stalled run was not admitted");
|
||||
return null;
|
||||
});
|
||||
if (!run) await slot.release();
|
||||
await settleContinuationActivity(claimed, claimed.reason, run ? "queued" : "not_started");
|
||||
return { verdict: claimed.verdict, outcome: run ? "replaced_stalled_run" : "enqueue_refused", retryAt: claimed.nextCheckAt };
|
||||
}
|
||||
@@ -942,7 +964,7 @@ export function assignedWorkSweep(db: Db, deps: AssignedWorkDeps) {
|
||||
const queuedByAgent = new Map(queuedRows.map(row => [row.agentId, Number(row.queuedRuns)]));
|
||||
const slotRows = stalledRows.map(row => ({ agentName: row.agentName, stalledRuns: Number(row.stalledRuns),
|
||||
queuedRuns: queuedByAgent.get(row.agentId) ?? 0 }));
|
||||
return { ...summary, agentsWithStalledSlots: slotRows };
|
||||
return { ...summary, agentsWithStalledSlots: slotRows, automaticWork: await readAutomaticWorkStatus(db, companyId) };
|
||||
}
|
||||
|
||||
return { checkIssue, listSuspects, report, loadFacts, flushPassLog: passLog.flush };
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { automaticRunBrakes, type Db } from "@paperclipai/db";
|
||||
import { logger } from "../../middleware/logger.js";
|
||||
import { PERSON_WAKE_REASONS, RECOVERY_WAKE_REASONS } from "../heartbeat/queued-run-dispatch-order.js";
|
||||
import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE } from "../environment-provider-unavailable-error.js";
|
||||
|
||||
export const AUTOMATIC_RUN_BRAKE = {
|
||||
windowMs: 10 * 60_000,
|
||||
startProgressMs: 2 * 60_000,
|
||||
minCounted: 12,
|
||||
failureShare: 0.8,
|
||||
consecutiveProviderRefusals: 5,
|
||||
minOpenMs: 2 * 60_000,
|
||||
quietCloseMs: 15 * 60_000,
|
||||
probeIntervalMs: 60_000,
|
||||
probeClaimBoundMs: 10_000,
|
||||
probeRunningBoundMs: 10 * 60_000,
|
||||
probeSuccessesToRelease: 2,
|
||||
releaseIntervalMs: 60_000,
|
||||
releaseInitialRate: 2,
|
||||
releaseSteps: 6,
|
||||
creationIntervalMs: 60_000,
|
||||
cacheTtlMs: 5_000,
|
||||
maxCompanies: 256,
|
||||
maxRuns: 1_024,
|
||||
rowLimit: 500,
|
||||
runningLimit: 200,
|
||||
} as const;
|
||||
|
||||
export type AutomaticRunBrakeState = "closed" | "open" | "half_open";
|
||||
|
||||
export type AutomaticRunFacts = {
|
||||
id: string;
|
||||
companyId: string;
|
||||
retryOfRunId?: string | null;
|
||||
scheduledRetryReason?: string | null;
|
||||
contextSnapshot?: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
const EXTRA_AUTOMATIC_WAKE_REASONS: ReadonlySet<string> = new Set(["issue_assignment_recovery", "transient_failure_retry"]);
|
||||
|
||||
export function isAutomaticRun(run: AutomaticRunFacts): boolean {
|
||||
const context = run.contextSnapshot ?? {};
|
||||
const reason = typeof context.wakeReason === "string" ? context.wakeReason : null;
|
||||
if (context.explicitUserContinuation || context.taskRetryRequestId || (reason && PERSON_WAKE_REASONS.has(reason))) return false;
|
||||
return Boolean(run.retryOfRunId || run.scheduledRetryReason || context.previousRunId || context.retryReason
|
||||
|| context.freshContinuationIsolation
|
||||
|| (reason && (RECOVERY_WAKE_REASONS.has(reason) || EXTRA_AUTOMATIC_WAKE_REASONS.has(reason))));
|
||||
}
|
||||
|
||||
export type AutomaticRunOutcome = "failed_before_starting" | "healthy" | "neutral";
|
||||
|
||||
export type AutomaticRunOutcomeFacts = {
|
||||
status: string;
|
||||
errorCode: string | null;
|
||||
runtimeMode: string | null;
|
||||
executionStage: string | null;
|
||||
startedAt: Date | null;
|
||||
hasOutput: boolean;
|
||||
providerWorkStarted: string | null;
|
||||
nativePreDispatchFailure?: unknown;
|
||||
};
|
||||
|
||||
export type AutomaticRunOutcomeRules = {
|
||||
isPersonOwnedFailureCode: (code: string | null) => boolean;
|
||||
restartCodes: readonly string[];
|
||||
isTransientSetupCode: (code: string | null) => boolean;
|
||||
hasNativePreDispatchFailureRecord: (resultJson: unknown) => boolean;
|
||||
listPersonOriginSourceRunIds: (db: Db, companyId: string, runIds: string[]) => Promise<string[]>;
|
||||
};
|
||||
|
||||
let outcomeRules: Promise<AutomaticRunOutcomeRules> | null = null;
|
||||
|
||||
export function automaticRunOutcomeRules(): Promise<AutomaticRunOutcomeRules> {
|
||||
outcomeRules ??= Promise.all([import("../fresh-continuation-fallback.js"), import("../heartbeat/retries.js"),
|
||||
import("../heartbeat/run-failure-cause.js"), import("../heartbeat/queued-run-line.js")])
|
||||
.then(([fallback, retries, failureCause, queuedRunLine]) => ({
|
||||
isPersonOwnedFailureCode: fallback.isPersonOwnedFailureCode,
|
||||
restartCodes: fallback.BACKLOG_CONTINUATION_SOURCE_CODES,
|
||||
isTransientSetupCode: retries.isTransientWorkspacePreparationCode,
|
||||
hasNativePreDispatchFailureRecord: failureCause.hasNativePreDispatchFailureRecord,
|
||||
listPersonOriginSourceRunIds: queuedRunLine.listPersonOriginSourceRunIds,
|
||||
}))
|
||||
.catch(error => { outcomeRules = null; throw error; });
|
||||
return outcomeRules;
|
||||
}
|
||||
|
||||
export function classifyAutomaticRunOutcome(run: AutomaticRunOutcomeFacts, rules: AutomaticRunOutcomeRules): AutomaticRunOutcome {
|
||||
if (run.status === "running") return run.executionStage === "dispatching" || run.hasOutput ? "healthy" : "neutral";
|
||||
if (!run.startedAt || run.status === "cancelled" || !["succeeded", "failed", "timed_out", "interrupted"].includes(run.status)) return "neutral";
|
||||
if (run.status === "succeeded" || rules.isPersonOwnedFailureCode(run.errorCode)) return "healthy";
|
||||
if (run.errorCode && rules.restartCodes.includes(run.errorCode)) return "neutral";
|
||||
const startPhase = run.providerWorkStarted === "false" || rules.isTransientSetupCode(run.errorCode)
|
||||
|| rules.hasNativePreDispatchFailureRecord({ nativePreDispatchFailure: run.nativePreDispatchFailure })
|
||||
|| (run.runtimeMode === "legacy" && run.executionStage === "preparing");
|
||||
return startPhase ? "failed_before_starting" : "healthy";
|
||||
}
|
||||
|
||||
type BrakeRow = typeof automaticRunBrakes.$inferSelect;
|
||||
|
||||
type SignalRow = {
|
||||
db_now: string | Date;
|
||||
id: string;
|
||||
status: string;
|
||||
error_code: string | null;
|
||||
runtime_mode: string | null;
|
||||
execution_stage: string | null;
|
||||
started_at: string | Date | null;
|
||||
finished_at: string | Date | null;
|
||||
created_at: string | Date;
|
||||
has_output: boolean;
|
||||
provider_work_started: string | null;
|
||||
native_pre_dispatch: unknown;
|
||||
retry_of_run_id: string | null;
|
||||
scheduled_retry_reason: string | null;
|
||||
context: Record<string, unknown> | null;
|
||||
};
|
||||
|
||||
type Evidence = {
|
||||
counted: number;
|
||||
failedBeforeStarting: number;
|
||||
healthy: number;
|
||||
providerRefusalStreak: boolean;
|
||||
recoveredSince: boolean;
|
||||
lastStartAt: number | null;
|
||||
lastActivityAt: number | null;
|
||||
};
|
||||
|
||||
export type AutomaticRunBrakeSnapshot = {
|
||||
companyId: string;
|
||||
state: AutomaticRunBrakeState;
|
||||
pausedSince: Date | null;
|
||||
stateChangedAt: Date | null;
|
||||
reason: Record<string, unknown>;
|
||||
nextProbeAt: Date | null;
|
||||
nextCreationAt: Date | null;
|
||||
probeRunId: string | null;
|
||||
probeSuccesses: number;
|
||||
dbNow: Date;
|
||||
evidence: Evidence;
|
||||
};
|
||||
|
||||
const toDate = (value: string | Date | null | undefined) => value == null ? null : value instanceof Date ? value : new Date(value);
|
||||
|
||||
function boundedMap<K, V>(max: number) {
|
||||
const map = new Map<K, V>();
|
||||
return {
|
||||
get(key: K) {
|
||||
const value = map.get(key);
|
||||
if (value !== undefined) { map.delete(key); map.set(key, value); }
|
||||
return value;
|
||||
},
|
||||
set(key: K, value: V) {
|
||||
map.delete(key);
|
||||
map.set(key, value);
|
||||
while (map.size > max) map.delete(map.keys().next().value as K);
|
||||
},
|
||||
delete(key: K) { map.delete(key); },
|
||||
clear() { map.clear(); },
|
||||
get size() { return map.size; },
|
||||
};
|
||||
}
|
||||
|
||||
function rampStep(stateChangedAt: Date, now: Date) {
|
||||
return Math.max(0, Math.floor((now.getTime() - stateChangedAt.getTime()) / AUTOMATIC_RUN_BRAKE.releaseIntervalMs));
|
||||
}
|
||||
|
||||
const outcomeFacts = (row: SignalRow): AutomaticRunOutcomeFacts => ({ status: row.status, errorCode: row.error_code,
|
||||
runtimeMode: row.runtime_mode, executionStage: row.execution_stage, startedAt: toDate(row.started_at), hasOutput: row.has_output,
|
||||
providerWorkStarted: row.provider_work_started, nativePreDispatchFailure: row.native_pre_dispatch });
|
||||
|
||||
const latest = (values: Array<number | null | undefined>) => {
|
||||
const known = values.filter((value): value is number => typeof value === "number");
|
||||
return known.length ? Math.max(...known) : null;
|
||||
};
|
||||
|
||||
function evaluate(rows: SignalRow[], state: AutomaticRunBrakeState, lower: number, now: Date, rules: AutomaticRunOutcomeRules): Evidence {
|
||||
const automatic = rows.filter(row => isAutomaticRun({ id: row.id, companyId: "", retryOfRunId: row.retry_of_run_id,
|
||||
scheduledRetryReason: row.scheduled_retry_reason, contextSnapshot: row.context }));
|
||||
const outcomes = automatic.flatMap(row => {
|
||||
const finishedAt = toDate(row.finished_at);
|
||||
if (row.status !== "running" && (!finishedAt || finishedAt.getTime() < lower)) return [];
|
||||
const startedAt = toDate(row.started_at);
|
||||
if (row.status === "running" && (!startedAt || startedAt.getTime() < lower)) return [];
|
||||
const outcome = classifyAutomaticRunOutcome(outcomeFacts(row), rules);
|
||||
return outcome === "neutral" ? [] : [{ outcome, row, at: (finishedAt ?? startedAt!).getTime() }];
|
||||
}).sort((left, right) => right.at - left.at);
|
||||
const failedBeforeStarting = outcomes.filter(entry => entry.outcome === "failed_before_starting").length;
|
||||
const streak = outcomes.slice(0, AUTOMATIC_RUN_BRAKE.consecutiveProviderRefusals);
|
||||
const lastStartAt = latest(automatic.map(row => toDate(row.started_at)?.getTime()));
|
||||
const lastActivityAt = latest([lastStartAt, ...automatic.map(row => toDate(row.finished_at)?.getTime())]);
|
||||
return {
|
||||
counted: outcomes.length,
|
||||
failedBeforeStarting,
|
||||
healthy: outcomes.length - failedBeforeStarting,
|
||||
providerRefusalStreak: streak.length === AUTOMATIC_RUN_BRAKE.consecutiveProviderRefusals
|
||||
&& streak.every(entry => entry.row.error_code === ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE),
|
||||
recoveredSince: state === "open" && outcomes.length > 0 && (outcomes[0]!.row.status === "succeeded"
|
||||
|| (outcomes.length >= AUTOMATIC_RUN_BRAKE.probeSuccessesToRelease
|
||||
&& outcomes.slice(0, AUTOMATIC_RUN_BRAKE.probeSuccessesToRelease).every(entry => entry.outcome === "healthy"))),
|
||||
lastStartAt,
|
||||
lastActivityAt,
|
||||
};
|
||||
}
|
||||
|
||||
function trips(evidence: Evidence) {
|
||||
return evidence.providerRefusalStreak || (evidence.counted >= AUTOMATIC_RUN_BRAKE.minCounted
|
||||
&& evidence.failedBeforeStarting / evidence.counted >= AUTOMATIC_RUN_BRAKE.failureShare);
|
||||
}
|
||||
|
||||
export type AutomaticWork = { issueId: string; sourceRunId: string | null };
|
||||
|
||||
export type AutomaticRunCreationSlot = { heldUntil: Date } | { heldUntil: null; release: () => Promise<void> };
|
||||
|
||||
const NO_RESERVATION = async () => undefined;
|
||||
|
||||
type CacheEntry = { snapshot: AutomaticRunBrakeSnapshot; readAt: number; skewMs: number; heldUntil: number };
|
||||
|
||||
export function createAutomaticRunBrake(options: { loadRules?: () => Promise<AutomaticRunOutcomeRules> } = {}) {
|
||||
const loadRules = options.loadRules ?? automaticRunOutcomeRules;
|
||||
const companies = boundedMap<string, CacheEntry>(AUTOMATIC_RUN_BRAKE.maxCompanies);
|
||||
const personOrigin = boundedMap<string, boolean>(AUTOMATIC_RUN_BRAKE.maxRuns);
|
||||
let rulesFailureLogged = false;
|
||||
|
||||
async function rulesOrNull() {
|
||||
try {
|
||||
return await loadRules();
|
||||
} catch (error) {
|
||||
if (!rulesFailureLogged) {
|
||||
rulesFailureLogged = true;
|
||||
logger.error({ err: error, event: "automatic_run_brake.rules_unavailable" },
|
||||
"Automatic work pause could not load its run rules; automatic work is not paused");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function readRow(db: Db, companyId: string): Promise<BrakeRow | null> {
|
||||
const [row] = await db.select().from(automaticRunBrakes).where(eq(automaticRunBrakes.companyId, companyId));
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
async function readSignal(db: Db, companyId: string, row: BrakeRow | null) {
|
||||
const state = row?.state ?? "closed";
|
||||
const changedAt = row?.stateChangedAt ?? null;
|
||||
const lower = state === "open"
|
||||
? sql`coalesce(${changedAt?.toISOString() ?? null}::timestamptz, now() - ${`${AUTOMATIC_RUN_BRAKE.windowMs} milliseconds`}::interval)`
|
||||
: sql`greatest(now() - ${`${AUTOMATIC_RUN_BRAKE.windowMs} milliseconds`}::interval, ${changedAt?.toISOString() ?? null}::timestamptz)`;
|
||||
const columns = sql`r.id, r.status, r.error_code, r.runtime_mode, r.execution_stage, r.started_at, r.finished_at, r.created_at,
|
||||
r.last_output_at is not null as has_output, r.result_json #>> '{executionRecovery,providerWorkStarted}' as provider_work_started,
|
||||
r.result_json -> 'nativePreDispatchFailure' as native_pre_dispatch, r.retry_of_run_id, r.scheduled_retry_reason,
|
||||
jsonb_build_object('wakeReason', r.context_snapshot->'wakeReason', 'previousRunId', r.context_snapshot->'previousRunId',
|
||||
'retryReason', r.context_snapshot->'retryReason', 'freshContinuationIsolation', r.context_snapshot->'freshContinuationIsolation',
|
||||
'explicitUserContinuation', r.context_snapshot->'explicitUserContinuation',
|
||||
'taskRetryRequestId', r.context_snapshot->'taskRetryRequestId') as context`;
|
||||
const rows = [...await db.execute<SignalRow & { lower_at: string | Date }>(sql`
|
||||
with clock as (select now() as db_now, ${lower} as lower_at)
|
||||
select clock.db_now, clock.lower_at, runs.* from clock left join lateral (
|
||||
(select ${columns} from heartbeat_runs r
|
||||
where r.company_id = ${companyId} and r.finished_at is not null and r.finished_at >= clock.lower_at
|
||||
order by r.finished_at desc limit ${AUTOMATIC_RUN_BRAKE.rowLimit})
|
||||
union all
|
||||
(select ${columns} from heartbeat_runs r
|
||||
where r.company_id = ${companyId} and r.status = 'running'
|
||||
order by r.started_at desc nulls last limit ${AUTOMATIC_RUN_BRAKE.runningLimit})
|
||||
) runs on true`)];
|
||||
return { rows: rows.filter(row => row.id), now: toDate(rows[0]!.db_now)!, lower: toDate(rows[0]!.lower_at)!.getTime() };
|
||||
}
|
||||
|
||||
async function transition(db: Db, companyId: string, row: BrakeRow | null, to: AutomaticRunBrakeState,
|
||||
reason: Record<string, unknown>): Promise<BrakeRow | null> {
|
||||
const from = row?.state ?? "closed";
|
||||
const values = {
|
||||
state: to,
|
||||
reason,
|
||||
stateChangedAt: sql`date_trunc('milliseconds', now())`,
|
||||
openedAt: to === "open" ? (from === "half_open" && row?.openedAt ? row.openedAt : sql`date_trunc('milliseconds', now())`) : to === "closed" ? null : row?.openedAt ?? null,
|
||||
nextProbeAt: null,
|
||||
probeRunId: null,
|
||||
probeSuccesses: 0,
|
||||
releaseWindowStartedAt: null,
|
||||
releaseWindowStarts: 0,
|
||||
nextCreationAt: null,
|
||||
updatedAt: sql`now()`,
|
||||
};
|
||||
const expectedChangedAt = row?.stateChangedAt?.toISOString() ?? null;
|
||||
const [updated] = await db.insert(automaticRunBrakes).values({ companyId, ...values })
|
||||
.onConflictDoUpdate({
|
||||
target: automaticRunBrakes.companyId,
|
||||
set: values,
|
||||
setWhere: sql`${automaticRunBrakes.state} = ${from}
|
||||
and date_trunc('milliseconds', ${automaticRunBrakes.stateChangedAt}) is not distinct from ${expectedChangedAt}::timestamptz`,
|
||||
}).returning();
|
||||
if (!updated) return readRow(db, companyId);
|
||||
const event = to === "open" ? (from === "half_open" ? "reopened" : "opened") : to;
|
||||
logger[to === "open" ? "warn" : "info"]({ event: `automatic_run_brake.${event}`, companyId, from, to, ...reason },
|
||||
to === "open" ? "Automatic work paused for a company while its runs fail before starting"
|
||||
: to === "half_open" ? "Automatic work for a company is resuming gradually" : "Automatic work for a company is running normally again");
|
||||
return updated;
|
||||
}
|
||||
|
||||
async function settleProbe(db: Db, row: BrakeRow, rows: SignalRow[], rules: AutomaticRunOutcomeRules): Promise<BrakeRow> {
|
||||
if (row.state !== "open" || !row.probeRunId) return row;
|
||||
const known = rows.find(candidate => candidate.id === row.probeRunId);
|
||||
const [probe] = known ? [known] : [...await db.execute<SignalRow>(sql`
|
||||
select r.id, r.status, r.error_code, r.runtime_mode, r.execution_stage, r.started_at, r.finished_at, r.created_at,
|
||||
r.last_output_at is not null as has_output, r.result_json #>> '{executionRecovery,providerWorkStarted}' as provider_work_started,
|
||||
r.result_json -> 'nativePreDispatchFailure' as native_pre_dispatch
|
||||
from heartbeat_runs r where r.company_id = ${row.companyId} and r.id = ${row.probeRunId}`)];
|
||||
if (probe && (probe.status === "queued" || probe.status === "scheduled_retry")) return row;
|
||||
const outcome = probe ? classifyAutomaticRunOutcome(outcomeFacts(probe), rules) : "neutral";
|
||||
if (probe?.status === "running" && outcome === "neutral") return row;
|
||||
const completed = probe?.status === "succeeded";
|
||||
const successes = outcome === "healthy" ? row.probeSuccesses + (completed ? AUTOMATIC_RUN_BRAKE.probeSuccessesToRelease : 1)
|
||||
: outcome === "failed_before_starting" ? 0 : row.probeSuccesses;
|
||||
const [updated] = await db.update(automaticRunBrakes).set({
|
||||
probeRunId: null, probeSuccesses: successes, updatedAt: sql`now()`,
|
||||
...(outcome === "healthy" ? { nextProbeAt: sql`now()` } : {}),
|
||||
}).where(sql`${automaticRunBrakes.companyId} = ${row.companyId} and ${automaticRunBrakes.state} = 'open'
|
||||
and ${automaticRunBrakes.probeRunId} = ${row.probeRunId}`).returning();
|
||||
return updated ?? (await readRow(db, row.companyId)) ?? row;
|
||||
}
|
||||
|
||||
async function refresh(db: Db, companyId: string): Promise<CacheEntry> {
|
||||
const rules = await rulesOrNull();
|
||||
if (!rules) {
|
||||
const now = new Date();
|
||||
const entry: CacheEntry = { readAt: now.getTime(), skewMs: 0, heldUntil: 0, snapshot: { companyId, state: "closed", pausedSince: null,
|
||||
stateChangedAt: null, reason: {}, nextProbeAt: null, nextCreationAt: null, probeRunId: null, probeSuccesses: 0, dbNow: now,
|
||||
evidence: { counted: 0, failedBeforeStarting: 0, healthy: 0, providerRefusalStreak: false, recoveredSince: false,
|
||||
lastStartAt: null, lastActivityAt: null } } };
|
||||
companies.set(companyId, entry);
|
||||
return entry;
|
||||
}
|
||||
let row = await readRow(db, companyId);
|
||||
let signal = await readSignal(db, companyId, row);
|
||||
if (row) row = await settleProbe(db, row, signal.rows, rules);
|
||||
let state: AutomaticRunBrakeState = row?.state ?? "closed";
|
||||
let evidence = evaluate(signal.rows, state, signal.lower, signal.now, rules);
|
||||
const numbers = { windowMinutes: AUTOMATIC_RUN_BRAKE.windowMs / 60_000, recentAutomaticRuns: evidence.counted,
|
||||
failedBeforeStarting: evidence.failedBeforeStarting, healthy: evidence.healthy };
|
||||
const changedAt = row?.stateChangedAt?.getTime() ?? 0;
|
||||
const elapsed = signal.now.getTime() - changedAt;
|
||||
let target: { to: AutomaticRunBrakeState; reason: Record<string, unknown> } | null = null;
|
||||
if (state === "closed" && trips(evidence)) {
|
||||
target = { to: "open", reason: { ...numbers, trigger: evidence.providerRefusalStreak ? "sandbox_refusals" : "failed_before_starting" } };
|
||||
} else if (state === "half_open" && trips(evidence)) {
|
||||
target = { to: "open", reason: { ...numbers, trigger: evidence.providerRefusalStreak ? "sandbox_refusals" : "failed_before_starting" } };
|
||||
} else if (state === "half_open" && rampStep(row!.stateChangedAt, signal.now) >= AUTOMATIC_RUN_BRAKE.releaseSteps) {
|
||||
target = { to: "closed", reason: { ...numbers, trigger: "released" } };
|
||||
} else if (state === "open" && elapsed >= AUTOMATIC_RUN_BRAKE.minOpenMs
|
||||
&& (evidence.recoveredSince || (row?.probeSuccesses ?? 0) >= AUTOMATIC_RUN_BRAKE.probeSuccessesToRelease)) {
|
||||
target = { to: "half_open", reason: { ...numbers, trigger: "runs_starting_again" } };
|
||||
} else if (state === "open" && elapsed >= AUTOMATIC_RUN_BRAKE.quietCloseMs
|
||||
&& (evidence.lastActivityAt ?? 0) < signal.now.getTime() - AUTOMATIC_RUN_BRAKE.quietCloseMs) {
|
||||
target = { to: "closed", reason: { ...numbers, trigger: "no_automatic_work" } };
|
||||
}
|
||||
if (target) {
|
||||
row = await transition(db, companyId, row, target.to, target.reason);
|
||||
state = row?.state ?? "closed";
|
||||
if (state !== "closed") {
|
||||
signal = await readSignal(db, companyId, row);
|
||||
evidence = evaluate(signal.rows, state, signal.lower, signal.now, rules);
|
||||
}
|
||||
}
|
||||
const snapshot: AutomaticRunBrakeSnapshot = {
|
||||
companyId, state, pausedSince: row?.openedAt ?? null, stateChangedAt: row?.stateChangedAt ?? null,
|
||||
reason: row?.reason ?? {}, nextProbeAt: row?.nextProbeAt ?? null, nextCreationAt: row?.nextCreationAt ?? null,
|
||||
probeRunId: row?.probeRunId ?? null, probeSuccesses: row?.probeSuccesses ?? 0, dbNow: signal.now, evidence,
|
||||
};
|
||||
const readAt = Date.now();
|
||||
const entry = { snapshot, readAt, skewMs: signal.now.getTime() - readAt, heldUntil: companies.get(companyId)?.heldUntil ?? 0 };
|
||||
companies.set(companyId, entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
async function current(db: Db, companyId: string): Promise<CacheEntry> {
|
||||
const entry = companies.get(companyId);
|
||||
if (entry && Date.now() - entry.readAt < AUTOMATIC_RUN_BRAKE.cacheTtlMs) return entry;
|
||||
return refresh(db, companyId);
|
||||
}
|
||||
|
||||
async function read(db: Db, companyId: string): Promise<AutomaticRunBrakeSnapshot> {
|
||||
return (await current(db, companyId)).snapshot;
|
||||
}
|
||||
|
||||
async function isPersonWork(db: Db, companyId: string, work: AutomaticWork) {
|
||||
if (!work.sourceRunId) return true;
|
||||
const personReasons = sql.join([...PERSON_WAKE_REASONS].map(reason => sql`${reason}`), sql`, `);
|
||||
const [asked] = [...await db.execute<{ asked: boolean }>(sql`
|
||||
with source as (select max(coalesce(r.finished_at, r.created_at)) as finished_at from heartbeat_runs r
|
||||
where r.company_id = ${companyId} and r.id = ${work.sourceRunId}::uuid)
|
||||
select exists (select 1 from agent_wakeup_requests w, source
|
||||
where w.company_id = ${companyId} and w.requested_by_actor_type = 'user' and w.payload->>'issueId' = ${work.issueId}
|
||||
and ((w.run_id is null and w.status in ('queued', 'deferred_issue_execution', 'claimed'))
|
||||
or w.requested_at > coalesce(source.finished_at, '-infinity'::timestamptz)))
|
||||
or exists (select 1 from heartbeat_runs h, source
|
||||
where h.company_id = ${companyId} and h.context_snapshot->>'issueId' = ${work.issueId}
|
||||
and h.created_at > coalesce(source.finished_at, '-infinity'::timestamptz)
|
||||
and (h.context_snapshot->>'wakeReason' in (${personReasons}) or h.context_snapshot ? 'taskRetryRequestId'
|
||||
or jsonb_typeof(h.context_snapshot->'explicitUserContinuation') = 'object')) as asked`)];
|
||||
if (asked?.asked) return true;
|
||||
const rules = await rulesOrNull();
|
||||
return !rules || (await rules.listPersonOriginSourceRunIds(db, companyId, [work.sourceRunId])).includes(work.sourceRunId);
|
||||
}
|
||||
|
||||
async function creationHeldUntil(db: Db, companyId: string, work: AutomaticWork): Promise<Date | null> {
|
||||
const entry = await current(db, companyId);
|
||||
if (entry.snapshot.state !== "open") return null;
|
||||
const now = Date.now();
|
||||
const lastStartAt = entry.snapshot.evidence.lastStartAt;
|
||||
const startHold = lastStartAt !== null && lastStartAt - entry.skewMs > now - AUTOMATIC_RUN_BRAKE.startProgressMs
|
||||
? now + AUTOMATIC_RUN_BRAKE.creationIntervalMs : 0;
|
||||
const slotHold = entry.snapshot.nextCreationAt ? entry.snapshot.nextCreationAt.getTime() - entry.skewMs : 0;
|
||||
const until = Math.max(startHold, slotHold);
|
||||
if (until <= now) return null;
|
||||
return await isPersonWork(db, companyId, work) ? null : new Date(until);
|
||||
}
|
||||
|
||||
async function reserveCreation(db: Db, companyId: string, work: AutomaticWork): Promise<AutomaticRunCreationSlot> {
|
||||
const entry = await current(db, companyId);
|
||||
if (entry.snapshot.state !== "open") return { heldUntil: null, release: NO_RESERVATION };
|
||||
if (await isPersonWork(db, companyId, work)) return { heldUntil: null, release: NO_RESERVATION };
|
||||
const recheck = new Date(Date.now() + AUTOMATIC_RUN_BRAKE.creationIntervalMs);
|
||||
const lastStartAt = entry.snapshot.evidence.lastStartAt;
|
||||
if (lastStartAt !== null && lastStartAt - entry.skewMs > Date.now() - AUTOMATIC_RUN_BRAKE.startProgressMs) return { heldUntil: recheck };
|
||||
const [seeded] = await db.update(automaticRunBrakes).set({
|
||||
nextCreationAt: sql`date_trunc('milliseconds', now()) + ${`${AUTOMATIC_RUN_BRAKE.creationIntervalMs} milliseconds`}::interval`,
|
||||
updatedAt: sql`now()`,
|
||||
}).where(sql`${automaticRunBrakes.companyId} = ${companyId} and ${automaticRunBrakes.state} = 'open'
|
||||
and (${automaticRunBrakes.nextCreationAt} is null or ${automaticRunBrakes.nextCreationAt} <= now())`)
|
||||
.returning({ nextCreationAt: automaticRunBrakes.nextCreationAt });
|
||||
if (seeded?.nextCreationAt) {
|
||||
const token = seeded.nextCreationAt.toISOString();
|
||||
entry.snapshot = { ...entry.snapshot, nextCreationAt: seeded.nextCreationAt };
|
||||
return { heldUntil: null, release: async () => {
|
||||
await db.update(automaticRunBrakes).set({ nextCreationAt: null, updatedAt: sql`now()` })
|
||||
.where(sql`${automaticRunBrakes.companyId} = ${companyId} and ${automaticRunBrakes.nextCreationAt} = ${token}::timestamptz
|
||||
and not exists (select 1 from heartbeat_runs r where r.company_id = ${companyId}
|
||||
and r.context_snapshot->>'issueId' = ${work.issueId}
|
||||
and r.created_at >= ${token}::timestamptz - ${`${AUTOMATIC_RUN_BRAKE.creationIntervalMs} milliseconds`}::interval)`);
|
||||
companies.delete(companyId);
|
||||
} };
|
||||
}
|
||||
const row = await readRow(db, companyId);
|
||||
if (row?.state !== "open") { companies.delete(companyId); return { heldUntil: null, release: NO_RESERVATION }; }
|
||||
const at = row.nextCreationAt ? row.nextCreationAt.getTime() - entry.skewMs : recheck.getTime();
|
||||
return { heldUntil: new Date(Math.max(Date.now(), at)) };
|
||||
}
|
||||
|
||||
async function isPersonOrigin(db: Db, run: AutomaticRunFacts) {
|
||||
const known = personOrigin.get(run.id);
|
||||
if (known !== undefined) return known;
|
||||
const rules = await rulesOrNull();
|
||||
if (!rules) return true;
|
||||
const origin = (await rules.listPersonOriginSourceRunIds(db, run.companyId, [run.id])).includes(run.id);
|
||||
personOrigin.set(run.id, origin);
|
||||
return origin;
|
||||
}
|
||||
|
||||
async function grantProbe(db: Db, entry: CacheEntry, run: AutomaticRunFacts) {
|
||||
const [granted] = await db.update(automaticRunBrakes).set({
|
||||
probeRunId: run.id, updatedAt: sql`now()`,
|
||||
nextProbeAt: sql`now() + ${`${AUTOMATIC_RUN_BRAKE.probeIntervalMs} milliseconds`}::interval`,
|
||||
}).where(sql`${automaticRunBrakes.companyId} = ${run.companyId} and ${automaticRunBrakes.state} = 'open'
|
||||
and (((${automaticRunBrakes.nextProbeAt} is null or ${automaticRunBrakes.nextProbeAt} <= now())
|
||||
and (${automaticRunBrakes.probeRunId} is null or not exists (select 1 from heartbeat_runs p
|
||||
where p.company_id = ${automaticRunBrakes.companyId} and p.id = ${automaticRunBrakes.probeRunId} and p.status = 'running'
|
||||
and p.started_at > now() - ${`${AUTOMATIC_RUN_BRAKE.probeRunningBoundMs} milliseconds`}::interval)))
|
||||
or (${automaticRunBrakes.probeRunId} is not null
|
||||
and ${automaticRunBrakes.nextProbeAt} <= now() + ${`${AUTOMATIC_RUN_BRAKE.probeIntervalMs - AUTOMATIC_RUN_BRAKE.probeClaimBoundMs} milliseconds`}::interval
|
||||
and not exists (select 1 from heartbeat_runs p where p.company_id = ${automaticRunBrakes.companyId}
|
||||
and p.id = ${automaticRunBrakes.probeRunId} and p.started_at is not null)))`)
|
||||
.returning({ nextProbeAt: automaticRunBrakes.nextProbeAt });
|
||||
const now = Date.now();
|
||||
if (granted) {
|
||||
entry.heldUntil = now + AUTOMATIC_RUN_BRAKE.probeClaimBoundMs;
|
||||
entry.snapshot = { ...entry.snapshot, probeRunId: run.id, nextProbeAt: granted.nextProbeAt };
|
||||
return true;
|
||||
}
|
||||
const nextProbeAt = entry.snapshot.nextProbeAt ? entry.snapshot.nextProbeAt.getTime() - entry.skewMs : 0;
|
||||
entry.heldUntil = Math.max(now + AUTOMATIC_RUN_BRAKE.cacheTtlMs, nextProbeAt);
|
||||
return false;
|
||||
}
|
||||
|
||||
async function grantRelease(db: Db, entry: CacheEntry, companyId: string) {
|
||||
const [granted] = [...await db.execute<{ starts: number; window_ends_at: string | Date }>(sql`
|
||||
with ramp as (
|
||||
select b.company_id, b.state_changed_at + floor(extract(epoch from now() - b.state_changed_at) * 1000
|
||||
/ ${AUTOMATIC_RUN_BRAKE.releaseIntervalMs}) * ${`${AUTOMATIC_RUN_BRAKE.releaseIntervalMs} milliseconds`}::interval as window_start,
|
||||
${AUTOMATIC_RUN_BRAKE.releaseInitialRate} * power(2, floor(extract(epoch from now() - b.state_changed_at) * 1000
|
||||
/ ${AUTOMATIC_RUN_BRAKE.releaseIntervalMs}))::int as rate
|
||||
from automatic_run_brakes b where b.company_id = ${companyId} and b.state = 'half_open'
|
||||
)
|
||||
update automatic_run_brakes b set
|
||||
release_window_starts = case when b.release_window_started_at = ramp.window_start then b.release_window_starts + 1 else 1 end,
|
||||
release_window_started_at = ramp.window_start, updated_at = now()
|
||||
from ramp
|
||||
where b.company_id = ramp.company_id and b.state = 'half_open'
|
||||
and (b.release_window_started_at is distinct from ramp.window_start or b.release_window_starts < ramp.rate)
|
||||
returning b.release_window_starts as starts, ramp.window_start + ${`${AUTOMATIC_RUN_BRAKE.releaseIntervalMs} milliseconds`}::interval as window_ends_at`)];
|
||||
if (granted) return true;
|
||||
const step = rampStep(entry.snapshot.stateChangedAt ?? entry.snapshot.dbNow, new Date(Date.now() + entry.skewMs));
|
||||
const windowEnds = (entry.snapshot.stateChangedAt?.getTime() ?? 0) + (step + 1) * AUTOMATIC_RUN_BRAKE.releaseIntervalMs;
|
||||
entry.heldUntil = Math.max(Date.now() + 1_000, windowEnds - entry.skewMs);
|
||||
return false;
|
||||
}
|
||||
|
||||
async function holdAutomaticRunStart(db: Db, run: AutomaticRunFacts, options: { personOrigin?: boolean } = {}): Promise<boolean> {
|
||||
if (!isAutomaticRun(run)) return false;
|
||||
const cached = companies.get(run.companyId);
|
||||
if (cached && cached.snapshot.state === "closed" && Date.now() - cached.readAt < AUTOMATIC_RUN_BRAKE.cacheTtlMs) return false;
|
||||
if (options.personOrigin ?? await isPersonOrigin(db, run)) return false;
|
||||
if (cached && cached.heldUntil > Date.now()) return true;
|
||||
const entry = await current(db, run.companyId);
|
||||
if (entry.snapshot.state === "closed") return false;
|
||||
if (entry.heldUntil > Date.now()) return true;
|
||||
const allowed = entry.snapshot.state === "open" ? await grantProbe(db, entry, run) : await grantRelease(db, entry, run.companyId);
|
||||
return !allowed;
|
||||
}
|
||||
|
||||
return {
|
||||
read,
|
||||
refresh: async (db: Db, companyId: string) => (await refresh(db, companyId)).snapshot,
|
||||
creationHeldUntil,
|
||||
reserveCreation,
|
||||
holdAutomaticRunStart,
|
||||
cacheSizes: () => ({ companies: companies.size, runs: personOrigin.size }),
|
||||
reset: () => { companies.clear(); personOrigin.clear(); },
|
||||
};
|
||||
}
|
||||
|
||||
export const automaticRunBrake = createAutomaticRunBrake();
|
||||
|
||||
export function automaticRunCreationHeldUntil(db: Db, companyId: string, work: AutomaticWork) {
|
||||
return automaticRunBrake.creationHeldUntil(db, companyId, work);
|
||||
}
|
||||
|
||||
export function reserveAutomaticRunCreation(db: Db, companyId: string, work: AutomaticWork) {
|
||||
return automaticRunBrake.reserveCreation(db, companyId, work);
|
||||
}
|
||||
|
||||
export function automaticWorkStatusText(snapshot: AutomaticRunBrakeSnapshot) {
|
||||
if (snapshot.state === "closed") return "Automatic work is running normally.";
|
||||
const since = (snapshot.pausedSince ?? snapshot.stateChangedAt)?.toISOString() ?? "recently";
|
||||
if (snapshot.state === "half_open") return `Automatic work is resuming gradually since ${snapshot.stateChangedAt?.toISOString() ?? since} because recent runs started normally again.`;
|
||||
const reason = snapshot.reason as { trigger?: string; recentAutomaticRuns?: number; failedBeforeStarting?: number };
|
||||
const because = reason.trigger === "sandbox_refusals"
|
||||
? `the last ${AUTOMATIC_RUN_BRAKE.consecutiveProviderRefusals} automatic runs could not get a sandbox`
|
||||
: `${reason.failedBeforeStarting ?? 0} of ${reason.recentAutomaticRuns ?? 0} recent automatic runs failed before starting`;
|
||||
const next = snapshot.nextProbeAt ?? snapshot.nextCreationAt;
|
||||
return `Automatic work is paused for this company since ${since} because ${because}${next ? `; next try at ${next.toISOString()}` : ""}.`;
|
||||
}
|
||||
|
||||
export async function readAutomaticWorkStatus(db: Db, companyId: string) {
|
||||
const snapshot = await automaticRunBrake.read(db, companyId);
|
||||
return {
|
||||
state: snapshot.state,
|
||||
pausedSince: snapshot.pausedSince,
|
||||
nextTryAt: snapshot.state === "open" ? snapshot.nextProbeAt ?? snapshot.nextCreationAt : null,
|
||||
recentAutomaticRuns: snapshot.evidence.counted,
|
||||
failedBeforeStarting: snapshot.evidence.failedBeforeStarting,
|
||||
summary: automaticWorkStatusText(snapshot),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { issueRecoveryActions, type Db } from "@paperclipai/db";
|
||||
|
||||
/** Records a delivery attempt for a pending continuation, so the next pass tries the records not yet tried first. */
|
||||
export function recordContinuationDeliveryAttempt(db: Db, action: Pick<typeof issueRecoveryActions.$inferSelect, "companyId" | "id">) {
|
||||
return db.update(issueRecoveryActions)
|
||||
.set({ evidence: sql`${issueRecoveryActions.evidence} || ${JSON.stringify(
|
||||
{ continuationDeliveryAttemptedAt: new Date().toISOString() })}::jsonb` })
|
||||
.where(and(
|
||||
eq(issueRecoveryActions.companyId, action.companyId),
|
||||
eq(issueRecoveryActions.id, action.id),
|
||||
eq(issueRecoveryActions.status, "resolved"),
|
||||
sql`${issueRecoveryActions.evidence}->>'continuationDelivery' = 'pending'`,
|
||||
));
|
||||
}
|
||||
@@ -4,13 +4,15 @@ import { ASSIGNED_WORK_CONTINUED_ACTION, AUTOMATIC_RETRY_REASONS, SCHEDULER_TRAN
|
||||
import { CONTINUATION_CAP, CONTINUATION_CAP_WINDOW_MS } from "./assigned-work-invariant.js";
|
||||
|
||||
export { ASSIGNED_WORK_CONTINUED_ACTION, SCHEDULER_TRANSIENT_RETRY_REASON };
|
||||
export const PAUSED_FOR_AUTOMATIC_WORK = "pausedForAutomaticWork";
|
||||
|
||||
export async function taskAutomaticAttempts(db: Db, companyId: string, issueId: string, at: Date) {
|
||||
const since = new Date(at.getTime() - CONTINUATION_CAP_WINDOW_MS);
|
||||
const [continuations, transientRetries] = await Promise.all([
|
||||
db.select({ createdAt: activityLog.createdAt, outcome: sql<string | null>`${activityLog.details}->>'outcome'` }).from(activityLog).where(and(
|
||||
eq(activityLog.companyId, companyId), eq(activityLog.entityType, "issue"), eq(activityLog.entityId, issueId),
|
||||
eq(activityLog.action, ASSIGNED_WORK_CONTINUED_ACTION), gte(activityLog.createdAt, since)))
|
||||
eq(activityLog.action, ASSIGNED_WORK_CONTINUED_ACTION), gte(activityLog.createdAt, since),
|
||||
sql`coalesce(${activityLog.details}->>${PAUSED_FOR_AUTOMATIC_WORK}, '') <> 'true'`))
|
||||
.orderBy(desc(activityLog.createdAt)).limit(64),
|
||||
db.select({ createdAt: heartbeatRuns.createdAt }).from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.companyId, companyId), sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${issueId}`,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { activityLog, heartbeatRuns, issueRecoveryActions, issues } from "@paperclipai/db";
|
||||
import { activityLog, automaticRunBrakes, heartbeatRuns, issueRecoveryActions, issues } from "@paperclipai/db";
|
||||
import { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js";
|
||||
import { registerIssueRecoveryWork } from "./recovery/work.js";
|
||||
import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
|
||||
@@ -11,6 +11,7 @@ import { heartbeatService } from "./heartbeat.js";
|
||||
import { deliverReconciledExecutions } from "./execution-recovery-resolution.js";
|
||||
import { assignedWorkSweep, ASSIGNED_WORK_CONTINUED_ACTION } from "./recovery/assigned-work-sweep.js";
|
||||
import { SAVED_WORK_RECOVERY_START_BOUND_MS } from "./recovery/assigned-work-invariant.js";
|
||||
import { automaticRunBrake } from "./recovery/automatic-run-brake.js";
|
||||
import { action, connectionString, db, failedRemotePreparation, useWorkspaceRecoveryFixture } from "./__tests__/workspace-recovery-fixture.js";
|
||||
|
||||
const targets = vi.hoisted(() => new Map<string, AdapterSandboxExecutionTarget>());
|
||||
@@ -90,6 +91,17 @@ describe("a saved-work recovery the queue has not reached", () => {
|
||||
expect(successor).toBeDefined();
|
||||
}, 90_000);
|
||||
|
||||
it("starts the overdue recovery while automatic work is paused, without using the pause's creation slot", async () => {
|
||||
const f = await stagingShape(45 * 60_000);
|
||||
await db.insert(automaticRunBrakes).values({ companyId: f.companyId, state: "open", openedAt: new Date() });
|
||||
automaticRunBrake.reset();
|
||||
expect(await f.sweep.checkIssue({ companyId: f.companyId, issueId: f.issueId }))
|
||||
.toMatchObject({ verdict: { reason: "saved_work_recovery_overdue" }, outcome: "started_saved_work_recovery" });
|
||||
expect((await db.select().from(automaticRunBrakes).where(eq(automaticRunBrakes.companyId, f.companyId)))[0])
|
||||
.toMatchObject({ state: "open", nextCreationAt: null });
|
||||
automaticRunBrake.reset();
|
||||
});
|
||||
|
||||
it("counts a recovery the queue has time to start as the task's pending path, and looks again when its bound ends", async () => {
|
||||
let clock = Date.now();
|
||||
const f = await stagingShape(2 * 60_000, { now: () => new Date(clock) });
|
||||
|
||||
Reference in new issue
Block a user