Files
PaperClipAI/server/src/__tests__/automatic-run-brake.test.ts
T
DottaandClaude Fable 5.2 689f3b190e 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>
2026-11-13 21:20:09 -06:00

442 lines
30 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { eq, inArray, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { agentWakeupRequests, agents, automaticRunBrakes, companies, createDb, heartbeatRuns } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import {
AUTOMATIC_RUN_BRAKE, automaticRunOutcomeRules, automaticWorkStatusText, classifyAutomaticRunOutcome, createAutomaticRunBrake,
isAutomaticRun,
} from "../services/recovery/automatic-run-brake.js";
import { taskAutomaticAttempts } from "../services/recovery/task-automatic-attempts.js";
const support = await getEmbeddedPostgresTestSupport();
const suite = support.supported ? describe : describe.skip;
const MINUTE = 60_000;
type Run = typeof heartbeatRuns.$inferSelect;
suite("automatic-run brake", () => {
let db!: ReturnType<typeof createDb>;
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase("paperclip-automatic-run-brake-");
db = createDb(temporary.connectionString);
}, 60_000);
afterEach(async () => {
await db.execute(sql`truncate table automatic_run_brakes, agent_wakeup_requests, heartbeat_runs, agents, companies cascade`);
}, 120_000);
afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); }, 120_000);
async function seedCompany() {
const companyId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Brake", issuePrefix: `B${companyId.replaceAll("-", "").slice(0, 6)}`,
requireBoardApprovalForNewAgents: false });
const agentIds: string[] = [];
for (let index = 0; index < 2; index += 1) {
const agentId = randomUUID();
await db.insert(agents).values({ id: agentId, companyId, name: `Worker ${index}`, role: "engineer", status: "idle",
adapterType: "codex_local", adapterConfig: {}, runtimeConfig: { heartbeat: { maxConcurrentRuns: 1 } }, permissions: {} });
agentIds.push(agentId);
}
return { companyId, agentIds };
}
async function insertRuns(companyId: string, agentId: string, count: number, values: (index: number) => Partial<typeof heartbeatRuns.$inferInsert>) {
if (count === 0) return [] as Run[];
return db.insert(heartbeatRuns).values(Array.from({ length: count }, (_, index) => ({ companyId, agentId,
invocationSource: "automation", triggerDetail: "system", runtimeMode: "legacy",
contextSnapshot: { wakeReason: "transient_failure_retry", issueId: randomUUID() }, ...values(index) }))).returning();
}
const ago = (ms: number) => new Date(Date.now() - ms);
function failedBeforeStarting(companyId: string, agentId: string, count: number, errorCode = "environment_provider_unavailable") {
return insertRuns(companyId, agentId, count, index => ({ status: "failed", errorCode, executionStage: "preparing",
createdAt: ago(4 * MINUTE + index), startedAt: ago(3 * MINUTE + index), finishedAt: ago(MINUTE - index * 100),
resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } }));
}
function interruptedWhileWorking(companyId: string, agentId: string, count: number) {
const codes = ["controller_lease_lost", "server_shutdown_interrupted", "process_lost", "native_session_interrupted"];
return insertRuns(companyId, agentId, count, index => ({ status: index % 2 ? "failed" : "interrupted", errorCode: codes[index % codes.length],
executionStage: "dispatching", lastOutputAt: ago(40_000), createdAt: ago(20 * MINUTE), startedAt: ago(19 * MINUTE),
finishedAt: ago(30_000 - index * 500), contextSnapshot: { wakeReason: "issue_assigned", issueId: randomUUID() } }));
}
function healthy(companyId: string, agentId: string, count: number, status: "succeeded" | "failed" = "succeeded") {
return insertRuns(companyId, agentId, count, index => ({ status, errorCode: status === "failed" ? "adapter_failed" : null,
executionStage: "dispatching", lastOutputAt: ago(10_000), createdAt: ago(5 * MINUTE), startedAt: ago(4 * MINUTE),
finishedAt: ago(5_000 - index * 10) }));
}
function queuedAutomatic(companyId: string, agentId: string, count: number) {
return insertRuns(companyId, agentId, count, index => ({ status: "queued", createdAt: ago(30_000 - index),
contextSnapshot: { wakeReason: "issue_continuation_needed", previousRunId: randomUUID(), issueId: randomUUID() } }));
}
async function forgetRuns(ids: string[]) {
await db.update(heartbeatRuns).set({ createdAt: sql`created_at - interval '1 hour'`, startedAt: sql`started_at - interval '1 hour'`,
finishedAt: sql`finished_at - interval '1 hour'` }).where(inArray(heartbeatRuns.id, ids));
}
async function ageBrake(companyId: string, ms: number) {
const shift = `${ms} milliseconds`;
await db.update(automaticRunBrakes).set({
stateChangedAt: sql`state_changed_at - ${shift}::interval`, openedAt: sql`opened_at - ${shift}::interval`,
nextProbeAt: sql`next_probe_at - ${shift}::interval`, nextCreationAt: sql`next_creation_at - ${shift}::interval`,
releaseWindowStartedAt: sql`release_window_started_at - ${shift}::interval`,
}).where(eq(automaticRunBrakes.companyId, companyId));
}
const brakeRow = async (companyId: string) => (await db.select().from(automaticRunBrakes).where(eq(automaticRunBrakes.companyId, companyId)))[0];
async function openBrake(companyId: string, agentId: string, brake = createAutomaticRunBrake()) {
const failures = await failedBeforeStarting(companyId, agentId, 20);
expect((await brake.refresh(db, companyId)).state).toBe("open");
return failures;
}
async function heldCount(brake: ReturnType<typeof createAutomaticRunBrake>, runs: Run[], options: { personOrigin?: boolean } = {}) {
let started = 0;
for (const run of runs) if (!await brake.holdAutomaticRunStart(db, run, options)) started += 1;
return started;
}
function countingDb() {
let queries = 0;
const counted = new Set(["select", "insert", "update", "delete", "execute"]);
const proxy = new Proxy(db, {
get(target, property, receiver) {
const value = Reflect.get(target, property, receiver);
if (typeof value !== "function") return value;
return counted.has(String(property)) ? (...args: unknown[]) => { queries += 1; return value.apply(target, args); } : value.bind(target);
},
});
return { db: proxy as typeof db, queries: () => queries };
}
it("classifies automatic runs and outcomes with the shared person and restart rules", async () => {
const rules = await automaticRunOutcomeRules();
expect(isAutomaticRun({ id: "a", companyId: "c", contextSnapshot: { wakeReason: "issue_continuation_needed" } })).toBe(true);
expect(isAutomaticRun({ id: "a", companyId: "c", scheduledRetryReason: "transient_failure" })).toBe(true);
expect(isAutomaticRun({ id: "a", companyId: "c", contextSnapshot: { wakeReason: "task_retry", previousRunId: "x" } })).toBe(false);
expect(isAutomaticRun({ id: "a", companyId: "c", contextSnapshot: { wakeReason: "issue_assigned" } })).toBe(false);
const base = { status: "failed", runtimeMode: "legacy", startedAt: new Date(), hasOutput: false, providerWorkStarted: null };
expect(classifyAutomaticRunOutcome({ ...base, errorCode: "environment_provider_unavailable", executionStage: "preparing" }, rules)).toBe("failed_before_starting");
expect(classifyAutomaticRunOutcome({ ...base, errorCode: "controller_lease_lost", executionStage: "dispatching" }, rules)).toBe("neutral");
expect(classifyAutomaticRunOutcome({ ...base, errorCode: "process_lost", executionStage: "preparing" }, rules)).toBe("neutral");
expect(classifyAutomaticRunOutcome({ ...base, errorCode: "budget_hard_stop", executionStage: "preparing" }, rules)).toBe("healthy");
expect(classifyAutomaticRunOutcome({ ...base, errorCode: "adapter_failed", executionStage: "dispatching" }, rules)).toBe("healthy");
expect(classifyAutomaticRunOutcome({ ...base, errorCode: "adapter_failed", executionStage: null, providerWorkStarted: "false" }, rules)).toBe("failed_before_starting");
expect(classifyAutomaticRunOutcome({ ...base, status: "running", errorCode: null, executionStage: "preparing" }, rules)).toBe("neutral");
expect(classifyAutomaticRunOutcome({ ...base, status: "cancelled", errorCode: "environment_provider_unavailable", executionStage: "preparing" }, rules)).toBe("neutral");
const preDispatch = { version: 1, providerWorkStarted: false };
for (const runtimeMode of ["legacy", "native"]) {
const shape = { ...base, runtimeMode, executionStage: runtimeMode === "legacy" ? "preparing" : null,
providerWorkStarted: runtimeMode === "legacy" ? "false" : null, nativePreDispatchFailure: runtimeMode === "native" ? preDispatch : undefined };
for (const errorCode of ["environment_provider_unavailable", "setup_failed", "adapter_failed"]) {
expect(classifyAutomaticRunOutcome({ ...shape, errorCode }, rules)).toBe("failed_before_starting");
}
for (const errorCode of ["controller_lease_lost", "process_lost", "native_session_interrupted", "server_shutdown_interrupted"]) {
expect(classifyAutomaticRunOutcome({ ...shape, errorCode }, rules)).toBe("neutral");
}
const working = { ...base, runtimeMode, executionStage: runtimeMode === "legacy" ? "dispatching" : null, hasOutput: true };
expect(classifyAutomaticRunOutcome({ ...working, errorCode: "adapter_failed" }, rules)).toBe("healthy");
expect(classifyAutomaticRunOutcome({ ...working, errorCode: "environment_provider_unavailable" }, rules)).toBe("failed_before_starting");
}
});
it("opens on native runs that failed before dispatch", async () => {
const { companyId, agentIds: [agentId] } = await seedCompany();
await insertRuns(companyId, agentId!, 20, index => ({ runtimeMode: "native", status: "failed",
errorCode: index % 2 ? "adapter_failed" : "setup_failed", createdAt: ago(4 * MINUTE), startedAt: ago(3 * MINUTE),
finishedAt: ago(MINUTE - index * 100), nativePhase: "terminal_failure",
resultJson: { nativePreDispatchFailure: { version: 1, providerWorkStarted: false }, failureCause: index % 2 ? "40P01" : "adapter_reported_error" } }));
expect((await createAutomaticRunBrake().refresh(db, companyId))).toMatchObject({ state: "open",
reason: { recentAutomaticRuns: 20, failedBeforeStarting: 20, trigger: "failed_before_starting" } });
}, 60_000);
it("sees failures that finished in the window behind more than 500 newer runs", async () => {
const { companyId, agentIds: [agentId, otherAgent] } = await seedCompany();
const failures = await failedBeforeStarting(companyId, agentId!, 20, "setup_failed");
await db.update(heartbeatRuns).set({ createdAt: sql`now() - interval '90 minutes'`, startedAt: sql`now() - interval '3 minutes'` })
.where(inArray(heartbeatRuns.id, failures.map(run => run.id)));
await queuedAutomatic(companyId, otherAgent!, 600);
await insertRuns(companyId, otherAgent!, 50, () => ({ status: "succeeded", createdAt: ago(MINUTE), contextSnapshot: { wakeReason: "issue_assigned" } }));
expect((await createAutomaticRunBrake().refresh(db, companyId)).state).toBe("open");
}, 120_000);
it("opens when automatic runs fail before starting, holds all but one probe, and never holds a person's work", async () => {
const { companyId, agentIds: [agentId, otherAgent] } = await seedCompany();
const brake = createAutomaticRunBrake();
await failedBeforeStarting(companyId, agentId!, 20);
const snapshot = await brake.refresh(db, companyId);
expect(snapshot).toMatchObject({ state: "open", reason: { recentAutomaticRuns: 20, failedBeforeStarting: 20 } });
expect(automaticWorkStatusText(snapshot)).toMatch(/^Automatic work is paused for this company since .* because the last 5 automatic runs could not get a sandbox/);
expect(automaticWorkStatusText(snapshot)).not.toMatch(/brake|probe|_/);
const queued = [...await queuedAutomatic(companyId, agentId!, 25), ...await queuedAutomatic(companyId, otherAgent!, 25)];
const attemptsBefore = await Promise.all(queued.map(run => taskAutomaticAttempts(db, companyId, String(run.contextSnapshot!.issueId), new Date())));
expect(await heldCount(brake, queued, { personOrigin: false })).toBe(1);
expect(await heldCount(createAutomaticRunBrake(), queued, { personOrigin: false })).toBe(0);
const after = await db.select().from(heartbeatRuns).where(inArray(heartbeatRuns.id, queued.map(run => run.id)));
expect(after.every(run => run.status === "queued" && run.errorCode === null)).toBe(true);
const attemptsAfter = await Promise.all(queued.map(run => taskAutomaticAttempts(db, companyId, String(run.contextSnapshot!.issueId), new Date())));
expect(attemptsAfter.map(attempts => attempts.all.length)).toEqual(attemptsBefore.map(attempts => attempts.all.length));
const [retry] = await insertRuns(companyId, agentId!, 1, () => ({ status: "queued", contextSnapshot: { wakeReason: "task_retry", previousRunId: queued[0]!.id } }));
const [assignment] = await insertRuns(companyId, agentId!, 1, () => ({ status: "queued", contextSnapshot: { wakeReason: "issue_assigned" } }));
const [joinedByPerson] = await insertRuns(companyId, agentId!, 1, () => ({ status: "queued",
contextSnapshot: { wakeReason: "issue_continuation_needed", previousRunId: randomUUID() } }));
await db.insert(agentWakeupRequests).values({ companyId, agentId: agentId!, source: "on_demand", triggerDetail: "manual",
reason: "issue_commented", status: "queued", requestedByActorType: "user", requestedByActorId: "board", runId: joinedByPerson!.id });
const [continuationOfPersonRetry] = await insertRuns(companyId, agentId!, 1, () => ({ status: "queued",
contextSnapshot: { wakeReason: "transient_failure_retry", previousRunId: retry!.id } }));
for (const run of [retry!, assignment!, joinedByPerson!, continuationOfPersonRetry!]) {
expect(await brake.holdAutomaticRunStart(db, run)).toBe(false);
}
expect(await brake.holdAutomaticRunStart(db, queued[3]!, { personOrigin: true })).toBe(false);
}, 60_000);
it("stays closed for mixed outcomes, person-owned failures and task failures after the agent started", async () => {
const { companyId, agentIds: [agentId] } = await seedCompany();
const brake = createAutomaticRunBrake();
expect((await brake.refresh(db, companyId)).state).toBe("closed");
expect(await brakeRow(companyId)).toBeUndefined();
await failedBeforeStarting(companyId, agentId!, 8, "setup_failed");
await healthy(companyId, agentId!, 4, "failed");
expect((await brake.refresh(db, companyId)).state).toBe("closed");
await insertRuns(companyId, agentId!, 30, index => ({ status: "failed", errorCode: index % 2 ? "budget_hard_stop" : "claude_auth_required",
executionStage: "preparing", createdAt: ago(3 * MINUTE), startedAt: ago(2 * MINUTE), finishedAt: ago(MINUTE),
resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } }));
await healthy(companyId, agentId!, 30, "failed");
expect((await brake.refresh(db, companyId)).state).toBe("closed");
expect(await brakeRow(companyId)).toBeUndefined();
}, 60_000);
it("ignores failures older than the window", async () => {
const { companyId, agentIds: [agentId] } = await seedCompany();
const failures = await failedBeforeStarting(companyId, agentId!, 40);
await db.update(heartbeatRuns).set({ finishedAt: sql`now() - interval '11 minutes'` }).where(inArray(heartbeatRuns.id, failures.map(run => run.id)));
expect((await createAutomaticRunBrake().refresh(db, companyId)).state).toBe("closed");
}, 60_000);
it("stays closed through a release swap that interrupts working runs, and opens when their continuations cannot get a sandbox", async () => {
const { companyId, agentIds: [agentId, otherAgent] } = await seedCompany();
const brake = createAutomaticRunBrake();
await interruptedWhileWorking(companyId, agentId!, 40);
expect((await brake.refresh(db, companyId)).state).toBe("closed");
const continuations = [...await queuedAutomatic(companyId, agentId!, 20), ...await queuedAutomatic(companyId, otherAgent!, 20)];
expect(await heldCount(createAutomaticRunBrake(), continuations)).toBe(40);
expect((await brake.reserveCreation(db, companyId, { issueId: randomUUID(), sourceRunId: randomUUID() })).heldUntil).toBeNull();
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "environment_provider_unavailable", executionStage: "preparing",
startedAt: sql`now() - interval '20 seconds'`, finishedAt: sql`now() - interval '5 seconds'`,
resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } })
.where(inArray(heartbeatRuns.id, continuations.map(run => run.id)));
expect((await brake.refresh(db, companyId)).state).toBe("open");
}, 60_000);
it("opens on five sandbox refusals in a row, below the run count", async () => {
const { companyId, agentIds: [agentId] } = await seedCompany();
const brake = createAutomaticRunBrake();
await failedBeforeStarting(companyId, agentId!, 4);
expect((await brake.refresh(db, companyId)).state).toBe("closed");
await failedBeforeStarting(companyId, agentId!, 1);
expect((await brake.refresh(db, companyId)).state).toBe("open");
}, 60_000);
it("waits out a failed probe, then releases at a doubling rate after two probes reach the agent, and closes", async () => {
const { companyId, agentIds: [agentId, otherAgent] } = await seedCompany();
const failures = await openBrake(companyId, agentId!);
await forgetRuns(failures.map(run => run.id));
const queued = [...await queuedAutomatic(companyId, agentId!, 30), ...await queuedAutomatic(companyId, otherAgent!, 30)];
const probe = async () => {
const brake = createAutomaticRunBrake();
for (const run of queued) if (!await brake.holdAutomaticRunStart(db, run, { personOrigin: false })) return run;
return null;
};
const first = await probe();
expect(first).not.toBeNull();
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "environment_provider_unavailable", executionStage: "preparing",
startedAt: sql`now()`, finishedAt: sql`now()`, resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } })
.where(eq(heartbeatRuns.id, first!.id));
queued.splice(queued.indexOf(first!), 1);
expect(await probe()).toBeNull();
expect((await brakeRow(companyId))).toMatchObject({ state: "open", probeSuccesses: 0, probeRunId: null });
await ageBrake(companyId, AUTOMATIC_RUN_BRAKE.probeIntervalMs);
for (let success = 0; success < AUTOMATIC_RUN_BRAKE.probeSuccessesToRelease; success += 1) {
const run = await probe();
expect(run).not.toBeNull();
await db.update(heartbeatRuns).set({ status: "running", startedAt: sql`now()`, executionStage: "dispatching" })
.where(eq(heartbeatRuns.id, run!.id));
queued.splice(queued.indexOf(run!), 1);
await createAutomaticRunBrake().refresh(db, companyId);
}
expect(await brakeRow(companyId)).toMatchObject({ state: "open", probeSuccesses: 2 });
await ageBrake(companyId, AUTOMATIC_RUN_BRAKE.minOpenMs);
expect((await createAutomaticRunBrake().refresh(db, companyId)).state).toBe("half_open");
const startedPerWindow: number[] = [];
for (let step = 0; step < AUTOMATIC_RUN_BRAKE.releaseSteps; step += 1) {
const startedNow = await heldCount(createAutomaticRunBrake(), queued, { personOrigin: false })
+ await heldCount(createAutomaticRunBrake(), queued, { personOrigin: false });
startedPerWindow.push(startedNow);
await ageBrake(companyId, AUTOMATIC_RUN_BRAKE.releaseIntervalMs);
}
expect(startedPerWindow).toEqual([2, 4, 8, 16, 32, 64]);
expect((await createAutomaticRunBrake().refresh(db, companyId)).state).toBe("closed");
expect(await heldCount(createAutomaticRunBrake(), queued, { personOrigin: false })).toBe(queued.length);
}, 120_000);
it("stays open when runs that started fine are followed by newer failures before starting", async () => {
const { companyId, agentIds: [agentId] } = await seedCompany();
const failures = await openBrake(companyId, agentId!);
await forgetRuns(failures.map(run => run.id));
await insertRuns(companyId, agentId!, 2, () => ({ status: "running", executionStage: "dispatching", lastOutputAt: ago(80_000),
startedAt: ago(90_000), createdAt: ago(100_000) }));
await failedBeforeStarting(companyId, agentId!, 10);
await ageBrake(companyId, AUTOMATIC_RUN_BRAKE.minOpenMs);
expect((await createAutomaticRunBrake().refresh(db, companyId)).state).toBe("open");
}, 60_000);
it("reopens from a gradual release when runs fail before starting again", async () => {
const { companyId, agentIds: [agentId] } = await seedCompany();
const failures = await openBrake(companyId, agentId!);
await forgetRuns(failures.map(run => run.id));
const recovered = await healthy(companyId, agentId!, 2);
await ageBrake(companyId, AUTOMATIC_RUN_BRAKE.minOpenMs);
expect((await createAutomaticRunBrake().refresh(db, companyId)).state).toBe("half_open");
await forgetRuns(recovered.map(run => run.id));
const again = await failedBeforeStarting(companyId, agentId!, 5);
await db.update(heartbeatRuns).set({ finishedAt: sql`now()` }).where(inArray(heartbeatRuns.id, again.map(run => run.id)));
expect((await createAutomaticRunBrake().refresh(db, companyId)).state).toBe("open");
}, 60_000);
it("frees the probe slot when the probe is cancelled, deleted or never starts", async () => {
const { companyId, agentIds: [agentId, otherAgent] } = await seedCompany();
await openBrake(companyId, agentId!);
const queued = [...await queuedAutomatic(companyId, agentId!, 3), ...await queuedAutomatic(companyId, otherAgent!, 3)];
const brake = createAutomaticRunBrake();
expect(await brake.holdAutomaticRunStart(db, queued[0]!, { personOrigin: false })).toBe(false);
expect(await heldCount(createAutomaticRunBrake(), queued.slice(1), { personOrigin: false })).toBe(0);
await ageBrake(companyId, AUTOMATIC_RUN_BRAKE.probeIntervalMs);
expect(await createAutomaticRunBrake().holdAutomaticRunStart(db, queued[3]!, { personOrigin: false })).toBe(false);
expect((await brakeRow(companyId))?.probeRunId).toBe(queued[3]!.id);
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: sql`now()` }).where(eq(heartbeatRuns.id, queued[3]!.id));
await createAutomaticRunBrake().refresh(db, companyId);
expect((await brakeRow(companyId))?.probeRunId).toBeNull();
await ageBrake(companyId, AUTOMATIC_RUN_BRAKE.probeIntervalMs);
expect(await createAutomaticRunBrake().holdAutomaticRunStart(db, queued[4]!, { personOrigin: false })).toBe(false);
await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, queued[4]!.id));
await createAutomaticRunBrake().refresh(db, companyId);
expect((await brakeRow(companyId))?.probeRunId).toBeNull();
}, 60_000);
it("lets another run take the probe when the reserved probe never starts within the claim bound", async () => {
const { companyId, agentIds: [agentId, otherAgent] } = await seedCompany();
await openBrake(companyId, agentId!);
const [first] = await queuedAutomatic(companyId, agentId!, 1);
const [second] = await queuedAutomatic(companyId, otherAgent!, 1);
expect(await createAutomaticRunBrake().holdAutomaticRunStart(db, first!, { personOrigin: false })).toBe(false);
expect(await createAutomaticRunBrake().holdAutomaticRunStart(db, second!, { personOrigin: false })).toBe(true);
await ageBrake(companyId, AUTOMATIC_RUN_BRAKE.probeClaimBoundMs + 1_000);
expect(await createAutomaticRunBrake().holdAutomaticRunStart(db, second!, { personOrigin: false })).toBe(false);
expect((await brakeRow(companyId))?.probeRunId).toBe(second!.id);
await db.update(heartbeatRuns).set({ status: "running", startedAt: sql`now()` }).where(eq(heartbeatRuns.id, second!.id));
await ageBrake(companyId, AUTOMATIC_RUN_BRAKE.probeClaimBoundMs + 1_000);
expect(await createAutomaticRunBrake().holdAutomaticRunStart(db, first!, { personOrigin: false })).toBe(true);
}, 60_000);
it("closes by itself when no automatic run started or finished for the quiet bound, even with runs waiting", async () => {
const { companyId, agentIds: [agentId] } = await seedCompany();
const failures = await openBrake(companyId, agentId!);
await ageBrake(companyId, AUTOMATIC_RUN_BRAKE.quietCloseMs - MINUTE);
expect((await createAutomaticRunBrake().refresh(db, companyId)).state).toBe("open");
await forgetRuns(failures.map(run => run.id));
await queuedAutomatic(companyId, agentId!, 5);
await ageBrake(companyId, 2 * MINUTE);
expect((await createAutomaticRunBrake().refresh(db, companyId))).toMatchObject({ state: "closed", reason: { trigger: "no_automatic_work" } });
}, 60_000);
it("lets two servers agree on the state and start one probe between them", async () => {
const { companyId, agentIds: [agentId, otherAgent] } = await seedCompany();
await failedBeforeStarting(companyId, agentId!, 20);
const [left, right] = [createAutomaticRunBrake(), createAutomaticRunBrake()];
const [leftState, rightState] = await Promise.all([left.refresh(db, companyId), right.refresh(db, companyId)]);
expect([leftState.state, rightState.state]).toEqual(["open", "open"]);
expect(leftState.stateChangedAt?.getTime()).toBe(rightState.stateChangedAt?.getTime());
const queued = [...await queuedAutomatic(companyId, agentId!, 25), ...await queuedAutomatic(companyId, otherAgent!, 25)];
const results = await Promise.all(queued.map((run, index) => (index % 2 ? left : right).holdAutomaticRunStart(db, run, { personOrigin: false })));
expect(results.filter(held => !held)).toHaveLength(1);
}, 60_000);
it("allows one new automatic run a minute while open and no automatic run is starting, across servers", async () => {
const { companyId, agentIds: [agentId] } = await seedCompany();
await openBrake(companyId, agentId!);
const work = { issueId: randomUUID(), sourceRunId: randomUUID() };
const [left, right] = [createAutomaticRunBrake(), createAutomaticRunBrake()];
const decisions = await Promise.all([left, right, left, right].map(async brake => (await brake.reserveCreation(db, companyId, work)).heldUntil));
expect(decisions.filter(held => held === null)).toHaveLength(1);
const later = decisions.find(Boolean)!;
expect(later.getTime()).toBeGreaterThan(Date.now() + 50_000);
await queuedAutomatic(companyId, agentId!, 3);
await ageBrake(companyId, AUTOMATIC_RUN_BRAKE.creationIntervalMs);
expect((await createAutomaticRunBrake().reserveCreation(db, companyId, work)).heldUntil).toBeNull();
await insertRuns(companyId, agentId!, 1, () => ({ status: "running", executionStage: "preparing", startedAt: ago(20_000) }));
await ageBrake(companyId, AUTOMATIC_RUN_BRAKE.creationIntervalMs);
expect((await createAutomaticRunBrake().reserveCreation(db, companyId, work)).heldUntil).not.toBeNull();
}, 60_000);
it("keeps a pass over hundreds of held runs at a bounded number of queries", async () => {
const { companyId, agentIds: [agentId, otherAgent] } = await seedCompany();
await openBrake(companyId, agentId!);
const queued = [...await queuedAutomatic(companyId, agentId!, 125), ...await queuedAutomatic(companyId, otherAgent!, 125)];
const counting = countingDb();
const brake = createAutomaticRunBrake();
let started = 0;
for (let pass = 0; pass < 100; pass += 1) {
for (const run of queued) {
if (await brake.holdAutomaticRunStart(counting.db, run, { personOrigin: false })) continue;
started += 1;
await db.update(heartbeatRuns).set({ status: "running", startedAt: sql`now()` }).where(eq(heartbeatRuns.id, run.id));
}
}
expect(started).toBe(1);
expect(counting.queries()).toBeLessThanOrEqual(6);
const fallback = countingDb();
const second = createAutomaticRunBrake();
for (let pass = 0; pass < 100; pass += 1) for (const run of queued) await second.holdAutomaticRunStart(fallback.db, run);
expect(fallback.queries()).toBeLessThanOrEqual(queued.length + 5);
}, 120_000);
it("reads as closed and logs once when its run rules cannot load", async () => {
const { companyId, agentIds: [agentId] } = await seedCompany();
await failedBeforeStarting(companyId, agentId!, 20);
const loadRules = vi.fn(async () => { throw new Error("module failed to load"); });
const brake = createAutomaticRunBrake({ loadRules });
const queued = await queuedAutomatic(companyId, agentId!, 3);
expect((await brake.refresh(db, companyId)).state).toBe("closed");
expect((await brake.reserveCreation(db, companyId, { issueId: randomUUID(), sourceRunId: randomUUID() })).heldUntil).toBeNull();
expect(await heldCount(brake, queued)).toBe(3);
expect(await brakeRow(companyId)).toBeUndefined();
}, 60_000);
it("keeps its in-process memory bounded across many companies and runs", async () => {
const brake = createAutomaticRunBrake();
const { companyId, agentIds: [agentId] } = await seedCompany();
for (let index = 0; index < AUTOMATIC_RUN_BRAKE.maxCompanies + 100; index += 1) await brake.read(db, randomUUID());
await openBrake(companyId, agentId!, brake);
for (let index = 0; index < AUTOMATIC_RUN_BRAKE.maxRuns + 200; index += 1) {
await brake.holdAutomaticRunStart(db, { id: randomUUID(), companyId, contextSnapshot: { wakeReason: "issue_continuation_needed" } });
}
expect(brake.cacheSizes()).toEqual({ companies: AUTOMATIC_RUN_BRAKE.maxCompanies, runs: AUTOMATIC_RUN_BRAKE.maxRuns });
}, 180_000);
});