mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 06:50:43 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Task recovery continues interrupted work so that nobody has to press
Retry
> - A run can fail during setup before any provider work starts. For
example, the environment lease is refused because the sandbox snapshot
qualification is stale.
> - Such a run records the generic `setup_failed` code with
`executionRecovery: { kind: "bootstrap", providerWorkStarted: false }`.
Only the named transient setup codes counted as "continues
automatically", so the board escalation kept the task blocked behind a
manual Retry.
> - On staging, two review tasks stayed blocked this way for days, with
no later run.
> - This pull request makes every setup failure that ended before
provider work continue automatically, under the existing per-task
allowance and the company-wide automatic run brake.
> - The benefit is that a task that never started does not need a
person. Tasks already blocked this way continue after deploy.
## Linked Issues or Issue Description
**What happened?**
Two review tasks on staging failed in their first run with
`setup_failed` ("Failed to acquire lease for environment ...
sandbox_snapshot_qualification_required"). No provider work started.
Each task stayed `blocked` with a system-owned failed interruption and
`canRetry: true`. No automatic continuation followed.
**Expected behavior**
A system-owned setup failure before provider work continues
automatically with bounded backoff. The needed-retry rate is 0%.
**Steps to reproduce**
1. A task's first run fails in setup before dispatch with the generic
`setup_failed` code (for example, a refused environment lease).
2. Generic continuation recovery escalates the task to a board-owned
stranded hold and blocks it.
3. The assigned-work sweep leaves the task to the hold owner
(`left_to_hold_owner`), because `continuesAutomatically` accepted only
the named transient setup codes.
## What Changed
- `continuation-cause.ts`: add `isSetupFailureBeforeProviderWork` and
its SQL twin `setupFailureBeforeProviderWorkSql`. Each matches any
`SETUP_FAILURE_CODES` value, including `setup_failed`, when the run
recorded bootstrap with `providerWorkStarted: false`.
`continuesAutomatically` and `continuesAutomaticallySql` use them for
first-run failures.
- `stranded-hold-continuation.ts`: a stranded hold from such a failure
stays eligible for 7 days (`STRANDED_PRE_PROVIDER_SETUP_MAX_AGE_MS`, the
same as the sweep's `STALE_BLOCK_MS`). Other causes keep the 24-hour
window. Tasks blocked before this release are continued after deploy
without a Retry.
- `assigned-work-sweep.ts`: the suspect pre-filter uses the same longer
window for this failure class.
- Repetition stays bounded by existing mechanisms: the per-task
`continuationAllowance` (2, 4, 8, then 15-minute spacing, at most 6 an
hour), the process-wide repair budget, and the company-wide automatic
run brake. The brake already counts `providerWorkStarted=false` failures
as `failed_before_starting`.
## Verification
- New red/green test in
`server/src/__tests__/assigned-work-invariant.test.ts`: "continues a
task blocked by an environment setup failure before any provider work,
including one blocked days ago". It failed before the fix (the task was
not a sweep suspect). It passes after the fix. A task blocked 40 hours
ago is continued once, and the hold resolves as restored. Work that may
have started, or a run without the bootstrap record, stays with the hold
owner. A block older than 7 days is not touched.
- The existing "temporary setup failure" case now uses an 8-day-old
block for its "old" control, because pre-provider setup failures are now
eligible for 7 days.
- `npx vitest run src/__tests__/assigned-work-invariant.test.ts`: 34/34
pass.
- Related suites: fresh-continuation-fallback, run-completion,
task-retry, task-interruption-presentation, retries, dot-runner,
issue-recovery-actions, recovery-observability,
released-writer-escalation, github retry/recovery integration, and
others. 920 tests pass. Locally, `run-completion.test.ts` reports only
an `afterAll` embedded-Postgres teardown timeout. All of its 263 tests
pass.
- `tsc --noEmit` for `server` passes.
## Risks
- A generic `setup_failed` that is really deterministic is now retried
automatically. The per-task allowance (at most 6 an hour, with backoff)
and the company-wide brake bound this. These are the same bounds that
recovery runs failing with `setup_failed` already use. Person-owned
causes have their own codes and are not affected.
- After deploy, blocked tasks from the last 7 days that match this class
are continued. The process-wide repair budget and the brake pace them.
- The stranded notice text for `setup_failed` still mentions Retry. The
sweep continues the task within the settling grace, and its activity
says that no Retry is needed.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, test execution).
## Checklist
- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
161 lines
9.4 KiB
TypeScript
161 lines
9.4 KiB
TypeScript
import { sql, type SQL } from "drizzle-orm";
|
|
import type { heartbeatRuns } from "@paperclipai/db";
|
|
|
|
/**
|
|
* Run failure codes that only a person can resolve (the test for each: did a
|
|
* person fail to do something, or did the system fail to carry it forward? Only
|
|
* the first belongs here; e.g. a lost carry-over of a Retry's authorization,
|
|
* `continuation_user_authorization_missing`, is the system's): they stopped the work, a
|
|
* credential or access they must share, a configuration choice they must make,
|
|
* a budget stop, or a provider usage limit that is waiting as designed. Every
|
|
* other code, including codes that do not exist yet, gets the fallback.
|
|
*/
|
|
export const PERSON_OWNED_FAILURE_CODES = [
|
|
// A person stopped or paused the work.
|
|
"cancelled", "operator_cancelled", "operator_interrupted", "issue_cancelled", "issue_paused", "agent_paused",
|
|
// A credential, secret or access the person must share.
|
|
"configuration_incomplete", "slack_configuration_incomplete", "signing_secret_unconfigured",
|
|
"user_secret_missing", "user_secret_definition_missing", "user_secret_definition_inactive",
|
|
"github_access_denied", "github_app_installation_suspended", "github_repo_outside_app_installations", "github_repo_not_accessible", "github_auth_required", "project_access_denied",
|
|
"permission_denied", "responsible_user_unauthorized", "oauth_access_projection_disabled",
|
|
"acpx_auth_required", "codex_auth_required", "claude_auth_required", "provider_auth_failed", "hermes_gateway_auth_failed",
|
|
// A configuration choice the person must change.
|
|
"native_provider_model_rejected", "provider_tool_definition_invalid", "turn_limit_exhausted",
|
|
// Budget stops.
|
|
"budget_blocked", "budget_hard_stop", "budget_exceeded",
|
|
// Provider usage limits that wait (and resume) as designed.
|
|
"provider_quota", "provider_limit_wait", "native_provider_usage_limit",
|
|
// An approval the person must give.
|
|
"approval_required", "formal_approval_unavailable",
|
|
] as const;
|
|
|
|
export function isPersonOwnedFailureCode(code: string | null | undefined): boolean {
|
|
return typeof code === "string" && (PERSON_OWNED_FAILURE_CODES as readonly string[]).includes(code);
|
|
}
|
|
|
|
export const AUTOMATIC_CONTINUATION_WAKE_REASONS = [
|
|
"issue_continuation_needed", "issue_assignment_recovery", "issue_recovery_action_restored", "transient_failure_retry",
|
|
] as const;
|
|
|
|
export const PERMANENT_FAILURE_CODES = [
|
|
"agent_interaction_delivery_denied", "adapter_engine_unavailable", "agent_not_invokable", "agent_not_found",
|
|
"low_trust_isolation_unavailable", "low_trust_requires_isolated_workspace", "low_trust_boundary_mismatch",
|
|
"low_trust_requires_sandbox_environment", "low_trust_runtime_services_denied",
|
|
] as const;
|
|
|
|
export const RESTART_CLASS_FAILURE_CODES = [
|
|
"native_restart_recovery_blocked", "native_continuation_requires_reconciliation", "native_session_interrupted",
|
|
"native_runner_process_exited", "server_shutdown_interrupted", "process_lost", "controller_lease_lost",
|
|
"execution_finalization_deadline_exceeded", "local_runtime_api_listener_unavailable",
|
|
"runner_remote_process_identity_unavailable", "continuation_user_authorization_missing",
|
|
] as const;
|
|
|
|
const REUSABLE_SANDBOX_RESUME_FAILED = "reusable_sandbox_resume_failed";
|
|
const TRANSIENT_SANDBOX_CAUSES = ["transport_timeout", "transport_closed", "sandbox_state_transition", "provider_rate_limited",
|
|
"provider_unavailable"] as const;
|
|
const EXTERNAL_STOP_UNCONFIRMED_PROVIDERS = ["openai_dot", "muse"] as const;
|
|
const UNFINISHED_RUN_STATUSES = ["failed", "timed_out", "interrupted", "cancelled"];
|
|
|
|
type ClassifiedRun = Pick<typeof heartbeatRuns.$inferSelect, "status" | "errorCode" | "retryOfRunId" | "scheduledRetryReason"
|
|
| "contextSnapshot"> & { error?: string | null; runnerProfileJson?: unknown; resultJson?: unknown };
|
|
|
|
const TRANSIENT_SETUP_FAILURE_CODES = [
|
|
REUSABLE_SANDBOX_RESUME_FAILED, "remote_workspace_prepare_timeout", "environment_provider_unavailable",
|
|
"workspace_git_scan_timeout", "workspace_git_scan_saturated", "repository_catalog_unavailable",
|
|
] as const;
|
|
|
|
export const SETUP_FAILURE_CODES = ["setup_failed", ...TRANSIENT_SETUP_FAILURE_CODES] as const;
|
|
|
|
const object = (value: unknown): Record<string, unknown> =>
|
|
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
|
|
|
export function isSystemOwnedFailureCode(code: string | null | undefined): boolean {
|
|
return typeof code === "string" && code.length > 0 && !isPersonOwnedFailureCode(code)
|
|
&& !(PERMANENT_FAILURE_CODES as readonly string[]).includes(code);
|
|
}
|
|
|
|
export function continuationCauseIsSystemOwned(run: Pick<ClassifiedRun, "status" | "errorCode" | "error" | "runnerProfileJson">): boolean {
|
|
if (!UNFINISHED_RUN_STATUSES.includes(run.status) || !isSystemOwnedFailureCode(run.errorCode)) return false;
|
|
const provider = object(object(object(run.runnerProfileJson).nativeExecutionInput).provider).kind;
|
|
if ((EXTERNAL_STOP_UNCONFIRMED_PROVIDERS as readonly unknown[]).includes(provider)) return false;
|
|
if (run.errorCode !== REUSABLE_SANDBOX_RESUME_FAILED) return true;
|
|
const cause = /\(cause=([a-z_]+)/.exec(run.error ?? "")?.[1];
|
|
return cause !== undefined && (TRANSIENT_SANDBOX_CAUSES as readonly string[]).includes(cause);
|
|
}
|
|
|
|
export function isRecoveryRun(run: Pick<ClassifiedRun, "retryOfRunId" | "scheduledRetryReason" | "contextSnapshot">): boolean {
|
|
const context = object(run.contextSnapshot);
|
|
if (context.explicitUserContinuation || context.wakeReason === "task_retry") return false;
|
|
return Boolean(run.retryOfRunId || run.scheduledRetryReason || context.previousRunId || context.retryReason
|
|
|| context.freshContinuationIsolation
|
|
|| (AUTOMATIC_CONTINUATION_WAKE_REASONS as readonly unknown[]).includes(context.wakeReason));
|
|
}
|
|
|
|
export function canContinueRecoveryRunAutomatically(run: ClassifiedRun): boolean {
|
|
return continuationCauseIsSystemOwned(run) && isRecoveryRun(run);
|
|
}
|
|
|
|
/**
|
|
* A setup failure the run recorded as ending before any provider work started
|
|
* (`executionRecovery` bootstrap, `providerWorkStarted: false`): an environment
|
|
* lease, sandbox qualification, provider or workspace preparation step failed,
|
|
* so the task never began and running it again repeats nothing. The generic
|
|
* `setup_failed` belongs here too; person-owned causes have their own codes
|
|
* and never reach it. Repetition is bounded by the per-task continuation
|
|
* allowance and the company-wide automatic run brake, not by this test.
|
|
*/
|
|
export function isSetupFailureBeforeProviderWork(run: Pick<ClassifiedRun, "errorCode" | "resultJson">): boolean {
|
|
const recovery = object(object(run.resultJson).executionRecovery);
|
|
return (SETUP_FAILURE_CODES as readonly unknown[]).includes(run.errorCode)
|
|
&& recovery.kind === "bootstrap" && recovery.providerWorkStarted === false;
|
|
}
|
|
|
|
function firstRunFailureContinues(run: Pick<ClassifiedRun, "errorCode" | "resultJson">): boolean {
|
|
return isRestartClassFailureCode(run.errorCode) || isSetupFailureBeforeProviderWork(run);
|
|
}
|
|
|
|
export function continuesAutomatically(run: ClassifiedRun): boolean {
|
|
return continuationCauseIsSystemOwned(run) && (isRecoveryRun(run) || firstRunFailureContinues(run));
|
|
}
|
|
|
|
export function isRestartClassFailureCode(code: string | null | undefined): boolean {
|
|
return typeof code === "string" && (RESTART_CLASS_FAILURE_CODES as readonly string[]).includes(code);
|
|
}
|
|
|
|
const list = (values: readonly string[]) => sql.join(values.map(value => sql`${value}`), sql`, `);
|
|
|
|
export function continuationCauseIsSystemOwnedSql(alias: string): SQL {
|
|
const column = (name: string) => sql.raw(`${alias}.${name}`);
|
|
const code = column("error_code");
|
|
return sql`(${column("status")} in (${list(UNFINISHED_RUN_STATUSES)}) and ${code} is not null and ${code} <> ''
|
|
and ${code} not in (${list([...PERSON_OWNED_FAILURE_CODES, ...PERMANENT_FAILURE_CODES])})
|
|
and coalesce(${column("runner_profile_json")}#>>'{nativeExecutionInput,provider,kind}', '') not in (${list(EXTERNAL_STOP_UNCONFIRMED_PROVIDERS)})
|
|
and (${code} <> ${REUSABLE_SANDBOX_RESUME_FAILED}
|
|
or substring(coalesce(${column("error")}, '') from '\\(cause=([a-z_]+)') in (${list(TRANSIENT_SANDBOX_CAUSES)})))`;
|
|
}
|
|
|
|
export function recoveryRunSql(alias: string): SQL {
|
|
const column = (name: string) => sql.raw(`${alias}.${name}`);
|
|
const context = column("context_snapshot");
|
|
return sql`(not coalesce(${context} ? 'explicitUserContinuation', false)
|
|
and coalesce(${context}->>'wakeReason', '') <> 'task_retry'
|
|
and (${column("retry_of_run_id")} is not null or ${column("scheduled_retry_reason")} is not null
|
|
or ${context} ? 'previousRunId' or ${context} ? 'retryReason' or ${context} ? 'freshContinuationIsolation'
|
|
or ${context}->>'wakeReason' in (${list(AUTOMATIC_CONTINUATION_WAKE_REASONS)})))`;
|
|
}
|
|
|
|
/** SQL twin of `isSetupFailureBeforeProviderWork`. */
|
|
export function setupFailureBeforeProviderWorkSql(alias: string): SQL {
|
|
const column = (name: string) => sql.raw(`${alias}.${name}`);
|
|
return sql`(${column("error_code")} in (${list(SETUP_FAILURE_CODES)})
|
|
and ${column("result_json")}#>>'{executionRecovery,kind}' = 'bootstrap'
|
|
and ${column("result_json")}#>>'{executionRecovery,providerWorkStarted}' = 'false')`;
|
|
}
|
|
|
|
export function continuesAutomaticallySql(alias: string): SQL {
|
|
const column = (name: string) => sql.raw(`${alias}.${name}`);
|
|
return sql`(${continuationCauseIsSystemOwnedSql(alias)} and (${recoveryRunSql(alias)}
|
|
or ${column("error_code")} in (${list(RESTART_CLASS_FAILURE_CODES)})
|
|
or ${setupFailureBeforeProviderWorkSql(alias)}))`;
|
|
}
|