Merge current mainline while preserving accepted-plan waits

Retain provider-capacity retry handling alongside the server-authorized plan wait check.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-06 11:47:19 -05:00
commit 824d0790d9
33 files changed
+901 -69

No files matched your search

+32
View File
@@ -247,6 +247,38 @@ public identity, and the existing unique singleton-key index makes concurrent
or later attempts to replace it fail closed. The server loads the row before
constructing URL-dependent runtime services on every boot.
### Unclaimed Cloud warm standby
`PAPERCLIP_CLOUD_WARM_STANDBY=1` is an opt-in control-plane marker for an
unclaimed warm application. It requires Cloud configuration, a stack identity,
and runtime identity verification keys. After restoring the durable identity,
startup checks once for company data. Existing companies or a persisted claim
keep the application fully active. A failed database check fails startup.
An empty unclaimed application keeps its HTTP server and sandbox plugins ready,
but skips recurring database work: chat/email delivery, plugin jobs, browser
cleanup, feedback export, import cleanup, execution reconciliation, heartbeat
schedules, and automatic backups. Startup migrations, plugin installation, and
other one-time preparation still run. Normal anonymous health probes return
`warmStandby: true` without SQL or session lookups. This is application liveness,
not a current database connectivity check. Other API requests and WebSocket upgrades return 503 until
the signed claim succeeds. Page and asset requests serve only the static UI
router, bypassing session, bearer-key, tenant, and other dynamic handlers.
The existing signed claim on `GET /api/health` writes the identity durably before
normal requests and polling resume. No polling discovers claims and no process
restart is required. Timers resume on their next normal tick; request-driven
work can proceed immediately. Claim failure leaves standby intact. A restart
restores the claim even if provider environment alignment has not completed.
Deleting a claimed workspace's last company never puts it back into standby.
Deploy support before enabling the marker. Validate idle database transactions
and health probes, claim/bootstrap latency, recurring work after claim, and a
restart with stale provider variables on an isolated warm application first.
Rollback by setting the marker to `0` and restarting. No schema changes are
required. This mechanism does not sleep claimed workspaces or replace a durable
scheduler for their background work.
## Resource membership tables
Paperclip stores current-user sidebar membership state in:
+4
View File
@@ -197,6 +197,10 @@ the task shows **Model unavailable**, the provider's account restriction, and
guidance to choose a supported model or clear the task's model override before
retrying. The run retains this reason even when the runner saves a generic
failure result.
When a committed Codex terminal reports `serverOverloaded`, the task displays
the model capacity error and **Model at capacity** on its scheduled retry card.
Automatic retries wait one and two minutes, then stop. Use
**Tasks → Model capacity retry** in Storybook to inspect the waiting state.
Claude Code uses model-specific effort levels; Haiku has no effort slider.
Grok uses its adapter's reasoning levels, including for its default model.
Kimi shows effort only when its agent uses the CLI engine, including with its
+10
View File
@@ -1934,3 +1934,13 @@ per-turn snapshot participates in session compatibility, so subsequent turns
remove stale instructions after edits or access revocation. See
[Connection instructions](connections/CONNECTION-INSTRUCTIONS.md) for contracts,
UI conventions, custom adapter integration, and initial memory templates.
### Native provider capacity retry
Committed, run-bound Codex `serverOverloaded` terminal failures display the model
capacity error directly and schedule at most two automatic retries, after one
and two minutes. Retries share the execution failure budget, retain task history,
and honor current ownership, review, governance, pause, dependency, budget, and
cleanup gates. Restart or duplicate finalization must not create another
successor. Permanent model/auth incompatibility and usage-limit exhaustion retain
their existing operator recovery requirements.
+22
View File
@@ -469,6 +469,28 @@ Warm sandbox reuse must match the current host Git tip and branch as well as the
file snapshot and saved stamp, including managed nested repositories. A history
or branch mismatch restages the host before the next run begins.
### Native provider model capacity
A committed Codex `turn.failed` event with `codexErrorInfo: serverOverloaded`,
bound to the failed terminal turn and pinned execution identity, surfaces
“Selected model is at capacity. Please try a different model.” directly.
Paperclip preserves the accepted result and task history, then atomically records
a durable automatic retry with its status decision. The first retry waits one
minute; the second waits two minutes. Both spend the existing failure-retry
budget. Exhaustion requires an explicit retry or a model change.
Retries use a fresh provider session and the normal task context, without an
automatic model switch. Consumed wake input and continuation receipts stay on
the failed run; `retryOfRunId` supplies task history without lending the new run
its predecessor's resume authority. Finalization replay and restart reuse the
same successor.
Scheduling preserves pending review authority and respects task holds; promotion,
claim, and dispatch recheck ownership, dependencies, governance, pause, budget,
and execution locks. Claim also waits for the predecessor's provider execution,
workspace finalization, and environment cleanup to settle. Model incompatibility,
usage-limit exhaustion, unknown failures, and unbound diagnostic text do not
qualify as capacity failures.
### Workspace scan failures before provider startup
Repository discovery distinguishes an ordinary folder from a failed Git read.
@@ -1,7 +1,9 @@
import { createCloudWarmStandby } from "../services/cloud-warm-standby.js";
import { cloudWarmStandbyMiddleware } from "../middleware/cloud-warm-standby.js";
import { generateKeyPairSync, sign } from "node:crypto";
import express from "express";
import request from "supertest";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { createDb, instanceSettings } from "@paperclipai/db";
import {
applyCloudRuntimeIdentityAssertion,
@@ -106,6 +108,7 @@ describeEmbeddedPostgres("Cloud runtime identity", () => {
});
afterEach(() => {
vi.restoreAllMocks();
for (const key of [
"PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN",
"PAPERCLIP_CLOUD_STACK_ID",
@@ -183,6 +186,39 @@ describeEmbeddedPostgres("Cloud runtime identity", () => {
});
});
it("keeps probes idle until a verified durable claim and stays active across restart", async () => {
const env = { ...process.env, PAPERCLIP_CLOUD_WARM_STANDBY: "1" };
const isStandby = await createCloudWarmStandby(db, env);
const execute = vi.spyOn(db, "execute");
const health = healthRoutes(db, {
deploymentMode: "authenticated", deploymentExposure: "public",
authReady: true, companyDeletionEnabled: false, isWarmStandby: isStandby,
});
const app = express();
app.use(cloudRuntimeIdentityMiddleware(db));
app.use(cloudWarmStandbyMiddleware(isStandby, health));
app.use("/api/health", health);
expect((await request(app).get("/api/health")).body.warmStandby).toBe(true);
expect(execute).not.toHaveBeenCalled();
const requestTime = Math.floor(Date.now() / 1000);
const invalid = await request(app).get("/api/health").set("x-paperclip-cloud-runtime-identity", assertion({
claims: { sub: "another-stack", iat: requestTime, exp: requestTime + 300 },
}));
expect(invalid.status).toBe(401);
expect(isStandby()).toBe(true);
const signed = assertion({ claims: { iat: requestTime, exp: requestTime + 300 } });
const claimed = await request(app).get("/api/health").set("x-paperclip-cloud-runtime-identity", signed);
expect(claimed.status).toBe(200);
expect(claimed.body.warmStandby).toBeUndefined();
expect(isStandby()).toBe(false);
expect(execute).toHaveBeenCalledOnce();
expect((await request(app).get("/api/health").set("x-paperclip-cloud-runtime-identity", signed)).status).toBe(200);
resetCloudRuntimeIdentityForTests();
process.env.PAPERCLIP_PUBLIC_URL = POOL_ORIGIN;
await initializeCloudRuntimeIdentity(db);
expect((await createCloudWarmStandby(db, env))()).toBe(false);
});
it("restores the canonical identity before consumers read stale startup variables", async () => {
await applyCloudRuntimeIdentityAssertion({ db, compactJws: assertion(), now: NOW });
resetCloudRuntimeIdentityForTests();
@@ -0,0 +1,127 @@
import { createServer, request as httpRequest } from "node:http";
import express from "express";
import request from "supertest";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
import { cloudWarmStandbyMiddleware, cloudWarmStandbyServerOptions } from "../middleware/cloud-warm-standby.js";
import { healthRoutes } from "../routes/health.js";
import { emailChannelService } from "../services/email-channels.js";
import { createPluginJobScheduler } from "../services/plugin-job-scheduler.js";
const healthOptions = {
deploymentMode: "authenticated" as const,
deploymentExposure: "public" as const,
authReady: true,
companyDeletionEnabled: false,
runtimeEnv: { PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "test-token" },
};
afterEach(() => vi.useRealTimers());
describe("unclaimed Cloud background work", () => {
it("keeps probes and tenant requests out of SQL and auth until claim", async () => {
let standby = true;
const execute = vi.fn().mockResolvedValue([]);
const db = { execute } as unknown as Db;
const health = healthRoutes(db, { ...healthOptions, isWarmStandby: () => standby });
const app = express();
const auth = vi.fn((_req, _res, next) => next());
const ui = express.Router();
ui.get("/", (_req, res) => res.type("html").send("ready"));
ui.get("/assets/app.js", (_req, res) => res.type("js").send("ready"));
app.use(cloudWarmStandbyMiddleware(() => standby, health, ui));
app.use(auth);
app.use("/api/health", health);
app.get("/api/companies", (_req, res) => res.json([]));
for (let i = 0; i < 3; i++) {
const probe = await request(app).get("/api/health").set("authorization", "Bearer ignored-in-standby");
expect(probe.status).toBe(200);
expect(probe.body.warmStandby).toBe(true);
expect(probe.body.serverInfo).toBeUndefined();
}
expect((await request(app).head("/api/health")).status).toBe(200);
expect((await request(app).get("/api/companies")).status).toBe(503);
expect((await request(app).post("/api/health/dev-server/restart")).status).toBe(503);
for (const path of ["/", "/assets/app.js"]) {
const page = await request(app).get(path)
.set("authorization", "Bearer test-bearer")
.set("x-paperclip-cloud-tenant-token", "test-tenant")
.set("cookie", "paperclip.session_token=test-session");
expect(page.status).toBe(200);
}
expect((await request(app).post("/mcp/gateways/gw_test")).status).toBe(503);
expect((await request(app).get("/unknown-dynamic-handler")).status).toBe(503);
expect(auth).not.toHaveBeenCalled();
expect(execute).not.toHaveBeenCalled();
standby = false;
expect((await request(app).get("/api/companies")).status).toBe(200);
const claimed = await request(app).get("/api/health");
expect(claimed.status).toBe(200);
expect(claimed.body.warmStandby).toBeUndefined();
expect(execute).toHaveBeenCalledOnce();
execute.mockRejectedValueOnce(new Error("offline"));
expect((await request(app).get("/api/health")).status).toBe(503);
});
it("rejects every WebSocket upgrade before auth and admits upgrades after claim", async () => {
let standby = true;
const app = express();
const health = healthRoutes({} as Db, { ...healthOptions, isWarmStandby: () => standby });
const authenticate = vi.fn();
app.use(cloudWarmStandbyMiddleware(() => standby, health));
const server = createServer(cloudWarmStandbyServerOptions(() => standby), app);
server.on("upgrade", (_req, socket) => {
authenticate();
socket.end("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n");
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address() as { port: number };
const upgrade = (path: string) => new Promise<number>((resolve, reject) => {
const req = httpRequest({
host: "127.0.0.1", port: address.port, path,
headers: { connection: "Upgrade", upgrade: "websocket", authorization: "Bearer test-bearer" },
});
req.on("response", (res) => { res.resume(); resolve(res.statusCode!); });
req.on("upgrade", (res, socket) => { socket.destroy(); resolve(res.statusCode!); });
req.on("error", reject);
req.end();
});
try {
for (const path of ["/api/companies/company/events/ws?token=anything", "/api/health", "/prp", "/"]) {
expect(await upgrade(path)).toBe(503);
}
expect(authenticate).not.toHaveBeenCalled();
standby = false;
expect(await upgrade("/api/companies/company/events/ws?token=anything")).toBe(101);
expect(authenticate).toHaveBeenCalledOnce();
} finally {
await new Promise<void>((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
}
});
it("email and plugin timers leave SQL idle, then resume without restarting", async () => {
vi.useFakeTimers();
let enabled = false;
const select = vi.fn(() => { throw new Error("SQL probe"); });
const db = { select } as unknown as Db;
const email = emailChannelService(db, { heartbeat: { wakeup: vi.fn() }, isBackgroundWorkEnabled: () => enabled });
const scheduler = createPluginJobScheduler({
db,
jobStore: {} as never,
workerManager: {} as never,
tickIntervalMs: 1000,
isBackgroundWorkEnabled: () => enabled,
});
try {
email.start();
scheduler.start();
await vi.advanceTimersByTimeAsync(10 * 60_000);
expect(select).not.toHaveBeenCalled();
enabled = true;
await vi.advanceTimersByTimeAsync(1000);
expect(select.mock.calls.length).toBeGreaterThanOrEqual(2);
} finally {
scheduler.stop();
await email.shutdown();
}
});
});
@@ -14310,7 +14310,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
await commitNativeStatusDecision({ db, companyId: fixture.companyId, issueId: fixture.issueId, runId: fixture.runId,
assessmentId: coordinator!.assessmentId!, priorStatus: issue!.status, priorStatusVersion: issue!.statusVersion,
priorDecisionId: issue!.lastStatusDecisionId,
decision: { policyVersion: "phase6-v8", statusAction: "in_progress", toStatus: "in_progress",
decision: { policyVersion: "phase6-v9", statusAction: "in_progress", toStatus: "in_progress",
reasonCode: "board_response_waiting", unblockDescriptor: null, effects: [] },
requireBoardResponseWaitSource: source!.source, requireBoardResponseWaitOrigin: origin!,
});
@@ -14934,7 +14934,7 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
priorStatusVersion: issue!.statusVersion,
priorDecisionId: issue!.lastStatusDecisionId,
decision: {
policyVersion: "phase6-v8",
policyVersion: "phase6-v9",
statusAction: reasonCode === "prior_status_preserved_no_live_path" ? "preserve" : "in_progress",
toStatus: "in_progress",
reasonCode,
+42 -24
View File
@@ -1,3 +1,5 @@
import { cloudWarmStandbyMiddleware } from "./middleware/cloud-warm-standby.js";
import type { CloudWarmStandby } from "./services/cloud-warm-standby.js";
import { browserUseRoutes } from "./routes/browser-use.js";
import { browserUseService } from "./services/browser-use.js";
import { slackToolRoutes } from "./routes/slack-tools.js";
@@ -461,6 +463,7 @@ export function createManagedBundledPluginWorkerRecovery(input: {
export async function createApp(
db: Db,
opts: {
cloudWarmStandby?: CloudWarmStandby;
uiMode: UiMode;
serverPort: number;
storageService: StorageService;
@@ -505,7 +508,17 @@ export async function createApp(
},
) {
const app = express();
const staticUi = express.Router();
app.locals.paperclipDb = db;
const isWarmStandby = opts.cloudWarmStandby ?? (() => false);
const health = healthRoutes(db, {
deploymentMode: opts.deploymentMode,
deploymentExposure: opts.deploymentExposure,
authReady: opts.authReady,
companyDeletionEnabled: opts.companyDeletionEnabled,
databaseBackupHealth: opts.databaseBackupHealth,
isWarmStandby,
});
const captureRawBody = (
req: express.Request,
_res: express.Response,
@@ -558,6 +571,9 @@ export async function createApp(
}),
);
app.use(cloudRuntimeIdentityMiddleware(db));
// A signed claim above commits identity before any normal request can seed
// company data. Unclaimed probes bypass session resolution as well as SQL.
app.use(cloudWarmStandbyMiddleware(isWarmStandby, health, staticUi));
// Connection-intent tools carry their own short-lived, run-bound bearer and
// must be reachable by remote adapters that intentionally do not receive an
// agent API key. Every request revalidates the active heartbeat row.
@@ -595,7 +611,12 @@ export async function createApp(
// Provider-authenticated ingress is intentionally outside the board
// mutation guard. The Chat SDK adapter verifies the provider signature
// before Paperclip persists or acts on any event.
const emailChannels = emailChannelService(db, { heartbeat: connectionIntentHeartbeat, storage: opts.storageService, publicBaseUrl: opts.chatWebhookPublicBaseUrl ?? opts.authPublicBaseUrl });
const emailChannels = emailChannelService(db, {
isBackgroundWorkEnabled: () => !isWarmStandby(),
heartbeat: connectionIntentHeartbeat,
storage: opts.storageService,
publicBaseUrl: opts.chatWebhookPublicBaseUrl ?? opts.authPublicBaseUrl,
});
app.use(emailWebhookRoutes(emailChannels));
app.use(chatWebhookRoutes(chatChannels));
// The instance validates single-use registration state and its trusted
@@ -642,16 +663,7 @@ export async function createApp(
const agentAvatars = agentAvatarRoutes();
api.use(agentAvatars.router);
api.use(boardMutationGuard());
api.use(
"/health",
healthRoutes(db, {
deploymentMode: opts.deploymentMode,
deploymentExposure: opts.deploymentExposure,
authReady: opts.authReady,
companyDeletionEnabled: opts.companyDeletionEnabled,
databaseBackupHealth: opts.databaseBackupHealth,
}),
);
api.use("/health", health);
api.use(openApiRoutes());
api.use("/cloud", cloudRoutes());
api.use("/companies", companyRoutes(db, opts.storageService));
@@ -810,6 +822,7 @@ export async function createApp(
const jobStore = pluginJobStore(db);
const lifecycle = pluginLifecycleManager(db, { workerManager });
const scheduler = createPluginJobScheduler({
isBackgroundWorkEnabled: () => !isWarmStandby(),
db,
jobStore,
workerManager,
@@ -982,7 +995,7 @@ export async function createApp(
if (uiDist) {
// Hashed asset files (Vite emits them under /assets/<name>.<hash>.<ext>)
// never change once built, so they can be cached aggressively.
app.use(
staticUi.use(
"/assets",
express.static(path.join(uiDist, "assets"), {
maxAge: "1y",
@@ -990,14 +1003,14 @@ export async function createApp(
}),
);
// Serve root/index through the same runtime HTML transform as SPA routes.
app.get(["/", "/index.html"], (_req, res) => {
staticUi.get(["/", "/index.html"], (_req, res) => {
res.type("html").set("Cache-Control", "no-cache").send(readBrandedStaticIndexHtml(uiDist));
});
// Non-hashed static files (favicon.ico, manifest, robots.txt, etc.):
// short cache so operators who swap them out see the new version
// reasonably fast, with must-revalidate overrides for index.html and
// sw.js (see staticUiCacheControl for why those two).
app.use(
staticUi.use(
express.static(uiDist, {
maxAge: "1h",
setHeaders(res, filePath) {
@@ -1014,7 +1027,7 @@ export async function createApp(
// with a MIME-type error, and cache that broken response. Return 404
// instead. The index.html response itself is no-cache so a subsequent
// deploy's updated asset hashes are picked up on next load.
app.get(/.*/, (req, res) => {
staticUi.get(/.*/, (req, res) => {
if (req.path.startsWith("/assets/")) {
res.status(404).end();
return;
@@ -1106,9 +1119,9 @@ export async function createApp(
const renderViteHtml = viteHtmlRenderer;
if (fs.existsSync(publicUiRoot)) {
app.use(express.static(publicUiRoot, { index: false }));
staticUi.use(express.static(publicUiRoot, { index: false }));
}
app.get(/.*/, async (req, res, next) => {
staticUi.get(/.*/, async (req, res, next) => {
if (!shouldServeViteDevHtml(req)) {
next();
return;
@@ -1120,9 +1133,10 @@ export async function createApp(
next(err);
}
});
app.use(vite.middlewares);
staticUi.use(vite.middlewares);
}
app.use(staticUi);
app.use(errorHandler);
jobCoordinator.start();
@@ -1137,7 +1151,7 @@ export async function createApp(
}
};
const flushPendingFeedbackExports = async () => {
if (feedbackExportShuttingDown) return;
if (feedbackExportShuttingDown || isWarmStandby()) return;
try {
await opts.feedbackExportService?.flushPendingFeedbackTraces();
} catch (err) {
@@ -1186,24 +1200,25 @@ export async function createApp(
});
const unsubscribeChatPublicationSignals = subscribeAllCompanyLiveEvents(
(event) => {
if (isChatPublicationCommitSignal(event))
if (!isWarmStandby() && isChatPublicationCommitSignal(event))
chatReconciliation.notifyPublications();
},
);
let chatPublicationTimer: ReturnType<typeof setInterval> | null = setInterval(
() => {
chatReconciliation.reconcile();
if (!isWarmStandby()) chatReconciliation.reconcile();
},
CHAT_PUBLICATION_FLUSH_INTERVAL_MS,
);
chatPublicationTimer.unref?.();
chatReconciliation.reconcile();
if (!isWarmStandby()) chatReconciliation.reconcile();
// Abandoned chunked-import spool sweep: hourly (plus once at startup),
// deleting spool dirs whose transfer saw no activity for 24h and cancelling
// their still-open ledger runs. Same setInterval + unref + shutdown-clear
// shape as the feedback export flush above.
const importTransferSpoolRoot = resolveDefaultImportTransferSpoolRoot();
const sweepImportTransferSpools = () => {
if (isWarmStandby()) return;
sweepAbandonedImportTransferSpools(db, importTransferSpoolRoot)
.then((result) => {
if (result.swept > 0) {
@@ -1217,9 +1232,12 @@ export async function createApp(
);
});
};
const browserUseTimer = setInterval(() => { void browserUse.sweep().catch(() => logger.warn("Browser Use reconciliation failed; retrying.")); }, 3000);
const browserUseTimer = setInterval(() => {
if (isWarmStandby()) return;
void browserUse.sweep().catch(() => logger.warn("Browser Use reconciliation failed; retrying."));
}, 3000);
browserUseTimer.unref?.();
void browserUse.sweep().catch(() => logger.warn("Browser Use startup reconciliation failed; retrying."));
if (!isWarmStandby()) void browserUse.sweep().catch(() => logger.warn("Browser Use startup reconciliation failed; retrying."));
let importTransferSweepTimer: ReturnType<typeof setInterval> | null =
setInterval(
sweepImportTransferSpools,
+12 -4
View File
@@ -1,3 +1,5 @@
import { cloudWarmStandbyServerOptions } from "./middleware/cloud-warm-standby.js";
import { createCloudWarmStandby } from "./services/cloud-warm-standby.js";
import { subscribeAllCompanyLiveEvents } from "./services/live-events.js";
import { chatCompletionDeliveryService } from "./services/chat-completion-delivery.js";
/// <reference path="./types/express.d.ts" />
@@ -17,7 +19,7 @@ import { reconcileAbandonedExecutionControl } from "./services/execution-control
import { EXECUTION_RECONCILIATION_INTERVAL_MS } from "./services/execution-control-deadline.js";
import { connectionIntentDeliveryService } from "./services/connection-intent-delivery.js";
import { existsSync, readFileSync, rmSync } from "node:fs";
import { createServer } from "node:http";
import { createServer, type RequestListener } from "node:http";
import { resolve } from "node:path";
import { createInterface } from "node:readline/promises";
import { stdin, stdout } from "node:process";
@@ -652,6 +654,7 @@ async function startServerWithDatabaseTeardown(
// Auth, routes, or child-runtime configuration capture any public URL.
const restoredCloudRuntimeIdentity = await initializeCloudRuntimeIdentity(db as any);
if (restoredCloudRuntimeIdentity) config = loadConfig();
const isWarmStandby = await createCloudWarmStandby(db as any);
if (config.deploymentMode === "local_trusted" && !isLoopbackHost(config.host)) {
throw new Error(
@@ -884,6 +887,7 @@ async function startServerWithDatabaseTeardown(
// self-hosted: createApp falls back to its built-in kubernetes-only default.
const managedPluginAutoInstall = managedConfig?.plugins.autoInstall ?? null;
const app = await createApp(db as any, {
cloudWarmStandby: isWarmStandby,
uiMode,
serverPort: listenPort,
storageService,
@@ -922,7 +926,8 @@ async function startServerWithDatabaseTeardown(
decisionServiceOptions,
managedPluginAutoInstall,
});
const server = createServer(app as unknown as Parameters<typeof createServer>[0]);
// Upgrade admission runs before every WebSocket listener, outside Express.
const server = createServer(cloudWarmStandbyServerOptions(isWarmStandby), app as unknown as RequestListener);
// Increase keep-alive timeouts to safely outlive default idle timeouts
// of common reverse proxies and load balancers (like AWS ALB, Nginx, or Traefik).
@@ -1165,7 +1170,7 @@ async function startServerWithDatabaseTeardown(
["local_ai_login_cleanup", () => localAiLoginService(db).reapExpired()],
] as const;
const sweepExecutionControl = () => {
if (heartbeatSchedulerStopped) return;
if (heartbeatSchedulerStopped || isWarmStandby()) return;
// Independent durable queues must not block one another. Each queue remains
// single-flight; a later sweep observes committed transitions from its peers.
for (const [queue, work] of executionControlSweeps) {
@@ -1180,7 +1185,9 @@ async function startServerWithDatabaseTeardown(
executionControlInterval.unref?.();
sweepExecutionControl();
const startHeartbeatSchedulerInterval = (callback: () => void) => {
heartbeatSchedulerInterval = setInterval(callback, config.heartbeatSchedulerIntervalMs);
heartbeatSchedulerInterval = setInterval(() => {
if (!isWarmStandby()) callback();
}, config.heartbeatSchedulerIntervalMs);
heartbeatSchedulerInterval?.unref?.();
};
const externalObjects = externalObjectService(db as any, {
@@ -1853,6 +1860,7 @@ async function startServerWithDatabaseTeardown(
"Automatic database backups enabled",
);
setInterval(() => {
if (isWarmStandby()) return;
void runServerDatabaseBackup("scheduled").catch(() => {
// runServerDatabaseBackup already logs the failure with context.
});
@@ -0,0 +1,41 @@
import type { ServerOptions } from "node:http";
import { Router, type RequestHandler } from "express";
import type { CloudWarmStandby } from "../services/cloud-warm-standby.js";
/** Mount after signed identity handoff and before session or tenant resolution. */
export function cloudWarmStandbyMiddleware(
isStandby: CloudWarmStandby,
health: RequestHandler,
staticUi: RequestHandler = Router(),
) {
const router = Router();
router.use("/api/health", (req, res, next) => {
if (isStandby() && !req.headers.upgrade && (req.method === "GET" || req.method === "HEAD") && req.path === "/") {
req.actor = { type: "none", source: "none" };
health(req, res, next);
return;
}
next();
});
router.use((req, res, next) => {
if (!isStandby()) return next();
req.actor = { type: "none", source: "none" };
const unavailable = () => res.status(503).json({ error: "workspace_unclaimed" });
if (/^\/api(?:\/|$)/i.test(req.path) || req.headers.upgrade || (req.method !== "GET" && req.method !== "HEAD")) {
unavailable();
return;
}
// Serve only the UI router, never fall through to session, tenant, bearer,
// MCP, or other dynamic handlers, even when the request carries credentials.
staticUi(req, res, (error?: unknown) => {
if (error) next(error);
else unavailable();
});
});
return router;
}
/** Node 24.9+ routes rejected upgrades through the guarded HTTP request path. */
export function cloudWarmStandbyServerOptions(isStandby: CloudWarmStandby): ServerOptions {
return { shouldUpgradeCallback: () => !isStandby() };
}
@@ -191,16 +191,19 @@ describeEmbeddedPostgres("run-dispatch postgres adapter", () => {
});
}
it.each(["executionRunId", "checkoutRunId"] as const)("suppresses delayed native replacement after another run acquires %s", async (lock) => {
it.each([
["executionRunId", "native_safe_replacement"], ["checkoutRunId", "native_safe_replacement"],
["executionRunId", "native_provider_overloaded"], ["checkoutRunId", "native_provider_overloaded"],
] as const)("suppresses delayed retry after another run acquires %s (%s)", async (lock, retryReason) => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
await seedIssue({ companyId, issueId, assigneeAgentId: agentId, status: "in_progress" });
const contextSnapshot = { issueId, wakeReason: "native_safe_replacement", retryReason: "native_safe_replacement", forceFreshSession: true };
const contextSnapshot = { issueId, wakeReason: retryReason, retryReason, forceFreshSession: true };
const replacementId = await seedRun({ companyId, agentId, status: "scheduled_retry", contextSnapshot });
const competingId = await seedRun({ companyId, agentId, status: "running", contextSnapshot: { issueId } });
await db.update(issues).set({ [lock]: competingId }).where(eq(issues.id, issueId));
const adapter = createPostgresRunDispatchAdapter(db);
expect(await adapter.evaluateScheduledRetryGate({ companyId, runId: replacementId, retryReasonOverride: "native_safe_replacement", now: new Date() }))
expect(await adapter.evaluateScheduledRetryGate({ companyId, runId: replacementId, retryReasonOverride: retryReason, now: new Date() }))
.toMatchObject({ allowed: false, errorCode: "issue_execution_lock_changed" });
await db.update(heartbeatRuns).set({ status: "queued" }).where(eq(heartbeatRuns.id, replacementId));
expect(await adapter.cancelStaleQueuedRun({ companyId, runId: replacementId, expectedStatus: "queued", now: new Date() }))
@@ -218,15 +221,15 @@ describeEmbeddedPostgres("run-dispatch postgres adapter", () => {
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, competingId)))[0]?.status).toBe("running");
});
it("does not dispatch a replacement when the task becomes blocked after scheduling", async () => {
it.each(["native_safe_replacement", "native_provider_overloaded"])("does not dispatch %s when the task becomes blocked after scheduling", async retryReason => {
const { companyId, agentId } = await seedCompanyAndAgent();
const issueId = randomUUID();
await seedIssue({ companyId, issueId, assigneeAgentId: agentId, status: "in_progress" });
const contextSnapshot = { issueId, wakeReason: "native_safe_replacement", retryReason: "native_safe_replacement", forceFreshSession: true };
const contextSnapshot = { issueId, wakeReason: retryReason, retryReason: retryReason, forceFreshSession: true };
const replacementId = await seedRun({ companyId, agentId, status: "scheduled_retry", contextSnapshot });
await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, issueId));
const adapter = createPostgresRunDispatchAdapter(db);
expect(await adapter.evaluateScheduledRetryGate({ companyId, runId: replacementId, retryReasonOverride: "native_safe_replacement", now: new Date() }))
expect(await adapter.evaluateScheduledRetryGate({ companyId, runId: replacementId, retryReasonOverride: retryReason, now: new Date() }))
.toMatchObject({ allowed: false, errorCode: "issue_blocked" });
await db.update(heartbeatRuns).set({ status: "queued" }).where(eq(heartbeatRuns.id, replacementId));
expect(await adapter.cancelStaleQueuedRun({ companyId, runId: replacementId, expectedStatus: "queued", now: new Date() }))
@@ -128,7 +128,7 @@ function classifyRetryReasonKind(retryReason: string | null): RetryReasonKind {
if (retryReason === MAX_TURN_CONTINUATION_RETRY_REASON) return "max_turn_continuation";
if (retryReason === ISSUE_DISPOSITION_REPAIR_RETRY_REASON) return "disposition_repair";
if ((retryReason === "ai_connection_busy" || retryReason === "ai_connection_pool_wait")) return "ai_connection_wait";
if (retryReason === "native_safe_replacement") return "native_safe_replacement";
if (retryReason === "native_safe_replacement" || retryReason === "native_provider_overloaded") return "native_safe_replacement";
return "other";
}
+18
View File
@@ -127,6 +127,7 @@ export function healthRoutes(
serverInfo?: ServerInfoSnapshot;
databaseBackupHealth?: InspectDatabaseBackupHealthOptions;
runtimeEnv?: CloudInstanceEnv;
isWarmStandby?: () => boolean;
} = {
deploymentMode: "local_trusted",
deploymentExposure: "private",
@@ -293,6 +294,23 @@ export function healthRoutes(
return;
}
// Startup has already validated the empty database. During warm standby,
// readiness means the HTTP app can accept a signed claim; probing SQL would
// keep the idle database awake. The claim itself still performs durable SQL,
// and claimed instances retain the normal live database check below.
if (opts.isWarmStandby?.()) {
res.json({
status: healthStatus,
deploymentMode: opts.deploymentMode,
deploymentExposure: opts.deploymentExposure,
commit,
warmStandby: true,
...(cloud ? { cloud } : {}),
...(hiddenSettings.length ? { hiddenSettings } : {}),
});
return;
}
try {
await db.execute(sql`SELECT 1`);
} catch (error) {
@@ -0,0 +1,66 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
import * as identity from "./cloud-runtime-identity.js";
import { createCloudWarmStandby } from "./cloud-warm-standby.js";
const env = {
PAPERCLIP_CLOUD_WARM_STANDBY: "1",
PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "test-token",
PAPERCLIP_CLOUD_STACK_ID: "stack-test",
PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS: "test-keys",
};
function database(rows: unknown[] = []) {
const limit = vi.fn().mockResolvedValue(rows);
const select = vi.fn(() => ({ from: () => ({ limit }) }));
return { db: { select } as unknown as Db, select, limit };
}
afterEach(() => vi.restoreAllMocks());
describe("Cloud warm standby", () => {
it.each([
{},
{ ...env, PAPERCLIP_CLOUD_WARM_STANDBY: "0" },
{ ...env, PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: undefined },
{ ...env, PAPERCLIP_CLOUD_STACK_ID: undefined },
{ ...env, PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS: undefined },
])("leaves ordinary or incomplete configurations active without querying", async (config) => {
const { db, select } = database();
expect((await createCloudWarmStandby(db, config))()).toBe(false);
expect(select).not.toHaveBeenCalled();
});
it("protects existing company data even when the marker is set", async () => {
const { db } = database([{ id: "company-test" }]);
expect((await createCloudWarmStandby(db, env))()).toBe(false);
});
it("never mistakes a failed empty-database check for standby", async () => {
const { db, limit } = database();
limit.mockRejectedValue(new Error("database unavailable"));
await expect(createCloudWarmStandby(db, env)).rejects.toThrow("database unavailable");
});
it("checks emptiness once and exits standby monotonically on the matching committed claim", async () => {
const getter = vi.spyOn(identity, "getCloudRuntimeIdentity").mockReturnValue(null);
const { db, select } = database();
const isStandby = await createCloudWarmStandby(db, env);
for (let i = 0; i < 100; i++) expect(isStandby()).toBe(true);
expect(select).toHaveBeenCalledOnce();
const claimed = { stackId: "stack-other" } as identity.CloudRuntimeIdentitySnapshot;
getter.mockReturnValue(claimed);
expect(isStandby()).toBe(true);
getter.mockReturnValue({ ...claimed, stackId: env.PAPERCLIP_CLOUD_STACK_ID });
expect(isStandby()).toBe(false);
getter.mockReturnValue(null);
expect(isStandby()).toBe(false);
expect(select).toHaveBeenCalledOnce();
});
it("starts active after a persisted identity is restored, even with no companies", async () => {
vi.spyOn(identity, "getCloudRuntimeIdentity").mockReturnValue({ stackId: env.PAPERCLIP_CLOUD_STACK_ID } as identity.CloudRuntimeIdentitySnapshot);
const { db, select } = database();
expect((await createCloudWarmStandby(db, env))()).toBe(false);
expect(select).not.toHaveBeenCalled();
});
});
+37
View File
@@ -0,0 +1,37 @@
import { companies, type Db } from "@paperclipai/db";
import { isCloudManagedInstance } from "./cloud-instance.js";
import { getCloudRuntimeIdentity } from "./cloud-runtime-identity.js";
/** In-memory predicate. Calling it never opens a database connection. */
export type CloudWarmStandby = () => boolean;
/**
* Call after initializeCloudRuntimeIdentity and before starting any pollers.
* Only explicitly marked, empty, unclaimed Cloud instances may stand by.
* A signed claim is committed before the identity getter changes, and restores
* on boot even if the provider still carries the old warm-pool environment.
*/
export async function createCloudWarmStandby(
db: Db,
env: NodeJS.ProcessEnv = process.env,
): Promise<CloudWarmStandby> {
const stackId = env.PAPERCLIP_CLOUD_STACK_ID?.trim();
if (
env.PAPERCLIP_CLOUD_WARM_STANDBY !== "1"
|| !isCloudManagedInstance(env)
|| !stackId
|| !env.PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS?.trim()
|| getCloudRuntimeIdentity()
) return () => false;
// Protect existing tenants if an operator accidentally sets the marker.
// Fail startup on a read error; never infer emptiness from an unavailable DB.
const existing = await db.select({ id: companies.id }).from(companies).limit(1);
if (existing.length > 0) return () => false;
let standby = true;
return () => {
if (standby && getCloudRuntimeIdentity()?.stackId === stackId) standby = false;
return standby;
};
}
+3
View File
@@ -74,6 +74,8 @@ export type EmailActor = {
type Endpoint = typeof chatEndpoints.$inferSelect;
type Tx = Parameters<Parameters<Db["transaction"]>[0]>[0];
export interface EmailChannelOptions {
/** Suppress periodic database work while an unclaimed Cloud app stands by. */
isBackgroundWorkEnabled?: () => boolean;
heartbeat: Pick<ReturnType<typeof heartbeatService>, "wakeup">;
storage?: StorageService;
publicBaseUrl?: string;
@@ -2041,6 +2043,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) {
await Promise.all(items.slice(i, i + 4).map(work));
}
async function tick() {
if (options.isBackgroundWorkEnabled?.() === false) return;
if (activeTick) return activeTick;
activeTick = runTick();
try {
+18 -8
View File
@@ -17588,26 +17588,32 @@ export function heartbeatService(
)).for("update") : [];
const ownsIssue = owner?.assigneeAgentId === run.agentId &&
context.wakeReason !== "source_scoped_recovery_action";
if (ownsIssue && run.scheduledRetryReason === "native_safe_replacement" &&
if (ownsIssue && ["native_safe_replacement", "native_provider_overloaded"].includes(run.scheduledRetryReason ?? "") &&
owner.checkoutRunId && owner.checkoutRunId !== run.id) {
return { ownsIssue, blocked: true };
}
if (ownsIssue && owner.executionRunId && owner.executionRunId !== run.id) {
if (run.scheduledRetryReason === "native_provider_overloaded" && owner?.executionRunId &&
owner.executionRunId !== run.id && owner.executionRunId !== run.retryOfRunId) {
return { ownsIssue, blocked: true };
}
const previousRunId = run.scheduledRetryReason === "native_provider_overloaded"
? run.retryOfRunId : ownsIssue ? owner?.executionRunId : null;
if (previousRunId && previousRunId !== run.id) {
const [previous] = await tx.select({ status: heartbeatRuns.status })
.from(heartbeatRuns).where(and(
eq(heartbeatRuns.id, owner.executionRunId),
eq(heartbeatRuns.id, previousRunId),
eq(heartbeatRuns.companyId, run.companyId),
));
// A terminal result can precede workspace/lease cleanup on this or
// another controller. Local absence alone is not a release receipt.
if (!isHeartbeatRunTerminalStatus(previous?.status) ||
liveRunExecutions.has(owner.executionRunId)) {
liveRunExecutions.has(previousRunId)) {
return { ownsIssue, blocked: true };
}
const [pendingLease] = await tx.select({ id: environmentLeases.id })
.from(environmentLeases).where(and(
eq(environmentLeases.companyId, run.companyId),
eq(environmentLeases.heartbeatRunId, owner.executionRunId),
eq(environmentLeases.heartbeatRunId, previousRunId),
or(and(isNull(environmentLeases.releasedAt),
// Warm release deliberately retains the sandbox. Its successful
// receipt settles the old run without destroying the resource.
@@ -17621,7 +17627,7 @@ export function heartbeatService(
phase: nativeRunFinalizations.phase, leaseOwner: nativeRunFinalizations.leaseOwner,
}).from(nativeRunFinalizations).where(and(
eq(nativeRunFinalizations.companyId, run.companyId),
eq(nativeRunFinalizations.runId, owner.executionRunId),
eq(nativeRunFinalizations.runId, previousRunId),
));
if (pendingLease || (finalization && (finalization.leaseOwner ||
!["committed", "applied", "terminal_failure"].includes(finalization.phase)))) {
@@ -17971,6 +17977,10 @@ export function heartbeatService(
updatedAt: claimedAt,
};
if (nativeReviewContext) {
if (run.scheduledRetryReason === "native_provider_overloaded") {
const predecessor = await lockIssueExecutionClaim(tx);
if (predecessor.blocked) return null;
}
return claimQueuedNativeReviewRun(tx, {
run, claimedAt, claimValues,
agentNameKey: normalizeAgentNameKey(agent.name),
@@ -18038,7 +18048,7 @@ export function heartbeatService(
// Mention/context runs can touch an issue, but only the current assignee
// owns the issue execution lock shown as the active run.
eq(issues.assigneeAgentId, claimed.agentId),
claimed.scheduledRetryReason === "native_safe_replacement"
["native_safe_replacement", "native_provider_overloaded"].includes(claimed.scheduledRetryReason ?? "")
? or(
isNull(issues.checkoutRunId),
eq(issues.checkoutRunId, claimed.id),
@@ -22906,7 +22916,7 @@ export function heartbeatService(
if (
!issueId ||
(!isResolvedInteractionContinuationWakeContext(context) &&
run.scheduledRetryReason !== "native_safe_replacement")
!["native_safe_replacement", "native_provider_overloaded"].includes(run.scheduledRetryReason ?? ""))
) {
return { dispatched: true, resultPromise: dispatch(() => {}) };
}
@@ -0,0 +1,69 @@
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { agentWakeupRequests, heartbeatRuns, type Db } from "@paperclipai/db";
import { accountingForScheduledRetry, executionFailureRetryCount } from "../execution-recovery-attempt.js";
import { NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, NATIVE_PROVIDER_OVERLOADED_CODE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js";
/** Called under the finalizer's issue/coordinator locks, in the status-effect transaction. */
export async function materializeNativeProviderCapacityRetry(input: {
tx: Db;
companyId: string;
issueId: string;
runId: string;
agentId: string;
}) {
const [run] = await input.tx.select().from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId),
eq(heartbeatRuns.agentId, input.agentId), eq(heartbeatRuns.nativeIssueId, input.issueId),
)).for("update");
if (!run || run.runtimeMode !== "native") throw new Error("native_capacity_retry_run_binding_mismatch");
// Share the predecessor claim with every other failure-retry lane.
const [existing] = await input.tx.select().from(heartbeatRuns).where(and(
eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.retryOfRunId, run.id),
)).limit(1);
if (existing) return existing.id;
const attempt = executionFailureRetryCount(run) + 1;
if (attempt > NATIVE_PROVIDER_CAPACITY_MAX_RETRIES) throw new Error("native_capacity_retry_exhausted");
const now = new Date();
const dueAt = new Date(now.getTime() + 60_000 * 2 ** (attempt - 1));
const retryId = randomUUID();
const predecessorContext = { ...run.contextSnapshot };
// Resume receipts and delivered wake input belong to the failed run. The
// new turn has ordinary task authority; history comes from retryOfRunId.
// Match the consumed-input boundary used by native safe replacements.
for (const key of [
"explicitUserContinuation", "wakeCommentId", "wakeCommentIds", "commentId",
"commentIds", "latestCommentId", "resumeIntent", "followUpRequested",
"paperclipWake", "paperclipWakeComment", "paperclipTaskMarkdown", "paperclipTaskMarkdownCompact",
"paperclipTaskMarkdownAssignment", "paperclipTaskMarkdownAssignmentCompact", "paperclipTurnContext",
]) delete predecessorContext[key];
const contextSnapshot = {
...predecessorContext,
issueId: input.issueId,
taskId: input.issueId,
forceFreshSession: true,
retryOfRunId: run.id,
retryReason: NATIVE_PROVIDER_OVERLOADED_CODE,
wakeReason: NATIVE_PROVIDER_OVERLOADED_CODE,
scheduledRetryAttempt: attempt,
scheduledRetryAt: dueAt.toISOString(),
executionRetryAccounting: accountingForScheduledRetry(run, NATIVE_PROVIDER_OVERLOADED_CODE, attempt),
};
const [wake] = await input.tx.insert(agentWakeupRequests).values({
companyId: run.companyId, agentId: run.agentId, source: "automation", triggerDetail: "system",
reason: NATIVE_PROVIDER_OVERLOADED_CODE, status: "queued", runId: retryId,
idempotencyKey: `native-capacity:${run.companyId}:${run.id}`,
requestedByActorType: "system", requestedByActorId: "native_finalizer",
payload: contextSnapshot,
}).returning({ id: agentWakeupRequests.id });
await input.tx.insert(heartbeatRuns).values({
id: retryId, companyId: run.companyId, agentId: run.agentId,
invocationSource: "automation", triggerDetail: "system", status: "scheduled_retry",
responsibleUserId: run.responsibleUserId, wakeupRequestId: wake.id,
retryOfRunId: run.id, scheduledRetryReason: NATIVE_PROVIDER_OVERLOADED_CODE,
scheduledRetryAttempt: attempt, scheduledRetryAt: dueAt,
error: NATIVE_PROVIDER_OVERLOADED_MESSAGE, errorCode: NATIVE_PROVIDER_OVERLOADED_CODE,
contextSnapshot,
});
return retryId;
}
@@ -10,7 +10,7 @@ function record(value: unknown): Record<string, unknown> {
}
/** Re-derive authority from immutable run-bound evidence, including after restart. */
export async function readPersistedNativeModelRejection(
export async function readPersistedNativeProviderFailure(
db: Db,
run: typeof heartbeatRuns.$inferSelect,
turnId: string | null,
@@ -20,7 +20,7 @@ export async function readPersistedNativeModelRejection(
terminal.turnTerminalState !== "failed" || terminal.runTerminalState !== "failed") return null;
let execution;
try { execution = parseNativeExecutionInput(record(run.runnerProfileJson).nativeExecutionInput); } catch { return null; }
if (execution.provider.kind !== "codex" || !execution.provider.model ||
if (execution.provider.kind !== "codex" ||
execution.binding.runId !== run.id || execution.binding.companyId !== run.companyId ||
execution.binding.agentId !== run.agentId || execution.binding.issueId !== run.nativeIssueId ||
execution.session.normalizedSessionId !== run.nativeSessionId ||
@@ -43,3 +43,10 @@ export async function readPersistedNativeModelRejection(
observed.observe(parsed.event);
return observed.forTerminal(turnId, terminal);
}
export async function readPersistedNativeModelRejection(
...args: Parameters<typeof readPersistedNativeProviderFailure>
) {
const failure = await readPersistedNativeProviderFailure(...args);
return failure?.errorCode === "native_provider_model_rejected" ? failure : null;
}
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { PrpEvent, PrpTerminalState } from "../../vendor/paperclip-runner/index.js";
import { createNativeProviderFailureObservation, NATIVE_MODEL_REJECTION_DIAGNOSTIC, NATIVE_MODEL_REJECTION_MESSAGE } from "./native-provider-failure.js";
import { createNativeProviderFailureObservation, NATIVE_MODEL_REJECTION_DIAGNOSTIC, NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js";
const model = "test-model";
const response = {
@@ -19,6 +19,19 @@ const terminal: PrpTerminalState = {
const observation = () => createNativeProviderFailureObservation({ kind: "codex", model });
describe("native provider failure observation", () => {
it("surfaces a structured capacity failure without copying arbitrary provider text", () => {
const observed = createNativeProviderFailureObservation({ kind: "codex" });
observed.observe({ ...event, payload: { status: "failed", error: { codexErrorInfo: "serverOverloaded", message: "Private arbitrary response" } } });
expect(observed.forTerminal("turn", terminal)).toEqual({ errorCode: "native_provider_overloaded", errorMessage: NATIVE_PROVIDER_OVERLOADED_MESSAGE, diagnostic: { provider: "codex", category: "server_overloaded" } });
expect(observed.forTerminal("different-turn", terminal)).toBeNull();
expect(observed.forTerminal("turn", { ...terminal, runTerminalState: "succeeded" })).toBeNull();
});
it.each(["usageLimitExceeded", "other", "unauthorized", undefined])("does not retry unrelated provider errors (%s)", (codexErrorInfo) => {
const observed = observation();
observed.observe({ ...event, payload: { status: "failed", error: { codexErrorInfo, message: NATIVE_PROVIDER_OVERLOADED_MESSAGE } } });
expect(observed.forTerminal("turn", terminal)).toBeNull();
});
it("binds the structured rejection to the failed turn and emits no response or model text", () => {
const observed = observation();
observed.observe(event);
@@ -3,6 +3,15 @@ import type { PrpEvent, PrpTerminalState } from "../../vendor/paperclip-runner/i
export const NATIVE_MODEL_REJECTION_MESSAGE =
"The selected model is not supported by the current ChatGPT connection. Choose a supported model or a compatible AI connection.";
export const NATIVE_PROVIDER_OVERLOADED_MESSAGE =
"Selected model is at capacity. Please try a different model.";
export const NATIVE_PROVIDER_OVERLOADED_CODE = "native_provider_overloaded";
export const NATIVE_PROVIDER_CAPACITY_MAX_RETRIES = 2;
export const NATIVE_PROVIDER_OVERLOADED_DIAGNOSTIC = {
provider: "codex",
category: "server_overloaded",
} as const;
export const NATIVE_MODEL_REJECTION_DIAGNOSTIC = {
provider: "codex",
category: "model_auth_incompatible",
@@ -29,13 +38,18 @@ export function readNativeModelRejectionDiagnostic(value: unknown) {
/** Observe only events accepted by the bound control-plane persistence port. */
export function createNativeProviderFailureObservation(provider: { kind: string; model?: string | null }) {
let rejectedTurnId: string | null = null;
let overloadedTurnId: string | null = null;
return {
observe(event: PrpEvent) {
if (provider.kind !== "codex" || !provider.model ||
if (provider.kind !== "codex" ||
event.sourceKind !== "runner" || event.eventType !== "turn.failed" || !event.turnId) return;
const payload = record(event.payload);
const failure = record(payload.error);
if (payload.status !== "failed" || payload.recoverable === true || failure.recoverable === true ||
if (payload.status === "failed" && failure.codexErrorInfo === "serverOverloaded") {
overloadedTurnId = event.turnId;
return;
}
if (!provider.model || payload.status !== "failed" || payload.recoverable === true || failure.recoverable === true ||
typeof failure.message !== "string" || failure.message.length > 4_096) return;
let response: Record<string, unknown>;
try { response = record(JSON.parse(failure.message)); } catch { return; }
@@ -48,8 +62,13 @@ export function createNativeProviderFailureObservation(provider: { kind: string;
rejectedTurnId = event.turnId;
},
forTerminal(turnId: string | null | undefined, terminal: PrpTerminalState) {
if (!rejectedTurnId || turnId !== rejectedTurnId ||
terminal.turnTerminalState !== "failed" || terminal.runTerminalState !== "failed") return null;
if (!turnId || terminal.turnTerminalState !== "failed" || terminal.runTerminalState !== "failed") return null;
if (turnId === overloadedTurnId) return {
errorCode: NATIVE_PROVIDER_OVERLOADED_CODE,
errorMessage: NATIVE_PROVIDER_OVERLOADED_MESSAGE,
diagnostic: { ...NATIVE_PROVIDER_OVERLOADED_DIAGNOSTIC },
};
if (turnId !== rejectedTurnId) return null;
return {
errorCode: "native_provider_model_rejected" as const,
errorMessage: NATIVE_MODEL_REJECTION_MESSAGE,
@@ -0,0 +1,178 @@
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, agentWakeupRequests, companies, completionContracts, createDb, environmentLeases, heartbeatRuns, issueComments, issueRecoveryActions, issues, nativeRunFinalizations, statusDecisionEffects, statusDecisions } from "@paperclipai/db";
import type { ControlPlanePort, NativeExecutionInputV1, PrpEvent, PrpTerminalState } from "@paperclipai/paperclip-runner";
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { CONTROL_PLANE_CONFORMANCE_RESULT } from "../../vendor/paperclip-runner/testing.js";
const provider = vi.hoisted(() => ({ execute: vi.fn() }));
vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../../vendor/paperclip-runner/index.js")>()), executeNativeSession: provider.execute,
}));
import { executePaperclipNativeSession } from "./native-session-executor.js";
import { buildNativeCompletionContract } from "./completion-contracts.js";
import { prepareNativeHeartbeatRun } from "./prepare-native-run.js";
import { finalizeNativeRun } from "./native-run-finalizer.js";
import { readPersistedNativeProviderFailure } from "./native-provider-failure-evidence.js";
import { NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js";
import { heartbeatService } from "../heartbeat.js";
import { createPostgresWakeQueueAdapter } from "../../modules/wake-queue/adapters/postgres.js";
import { createReleaseIssueExecution } from "../../modules/wake-queue/application/use-cases.js";
import { buildExecutionContinuation } from "../execution-continuation.js";
describe("durable native provider capacity retry", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
const companyId = randomUUID(), agentId = randomUUID(), otherAgentId = randomUUID();
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase("native-capacity-retry-");
db = createDb(temporary.connectionString);
await db.insert(companies).values({ id: companyId, name: "Capacity regression", issuePrefix: "CAP" });
await db.insert(agents).values([
{ id: agentId, companyId, name: "Capacity worker", status: "active", adapterType: "paperclip_runner", adapterConfig: { provider: "codex", model: "test-model" } },
{ id: otherAgentId, companyId, name: "New owner", status: "active", adapterType: "paperclip_runner" },
]);
});
afterAll(async () => { await temporary?.cleanup(); });
async function acceptCapacityFailure(runId: string, issueId: string, mutateOwner = false) {
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
const [run] = await db.update(heartbeatRuns).set({ status: "running", runtimeMode: "native", nativeIssueId: issueId, error: null, errorCode: null }).where(eq(heartbeatRuns.id, runId)).returning();
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
const native = await prepareNativeHeartbeatRun({ db, run, issue, environmentLeaseId: randomUUID() });
const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId));
const contractInput = buildNativeCompletionContract(issue, { revision: contract.revision });
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed" });
const execution: NativeExecutionInputV1 = {
schema: "paperclip.native-execution-input.v1", binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId },
provider: { kind: "codex", model: "test-model" },
task: { identifier: issueId, title: issue.title, description: null, prompt: "Continue the task using its history.", workMode: "standard" },
workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null },
session: { normalizedSessionId: native.normalizedSessionId, driverKind: "codex_app_server", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
completionContract: { id: contract.id, sha256: contract.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1", contract: contractInput },
interactionResponses: [], credentialBindings: [],
};
await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, runId));
const event: PrpEvent = {
schema: "paperclip.prp.event.v1", runId, normalizedSessionId: native.normalizedSessionId, turnId: native.turnId,
sourceInstanceId: native.runnerInstanceId, sourceEventId: "overload", sourceSeq: 1, sourceKind: "runner", eventType: "turn.failed", schemaVersion: 1, priority: 0, emittedAt: new Date().toISOString(),
payload: { status: "failed", error: { codexErrorInfo: "serverOverloaded", message: NATIVE_PROVIDER_OVERLOADED_MESSAGE } },
};
const terminal: PrpTerminalState = { schema: "paperclip.prp.terminal.v1", turnTerminalState: "failed", runTerminalState: "failed", reportedWorkDisposition: "needs_review" };
const result = { ...CONTROL_PLANE_CONFORMANCE_RESULT, reportedWorkDisposition: "needs_review" as const,
summary: "I started investigating the task.", completionClaim: { ...CONTROL_PLANE_CONFORMANCE_RESULT.completionClaim, contractRevision: contractInput.revision } };
provider.execute.mockReset().mockImplementation(async (options: { controlPlane: ControlPlanePort }) => {
await options.controlPlane.openRun({ identity: { companyId, issueId, runId, agentId, sessionId: native.normalizedSessionId }, backendKind: "mock", sourceInstanceId: native.runnerInstanceId });
await options.controlPlane.appendEvent(event);
await options.controlPlane.completeRun({ result, terminal, turnId: native.turnId });
return { result, terminal, turnId: native.turnId, normalizedSessionId: native.normalizedSessionId, providerSessionId: "fixture-session", driverKind: "codex_app_server", driverVersion: "fixture", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
});
const unexpected = async () => { throw new Error("Unexpected provider call"); };
const adapter = await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: { descriptor: unexpected, openSession: unexpected } });
expect(adapter).toMatchObject({ errorCode: "native_provider_overloaded", errorMessage: NATIVE_PROVIDER_OVERLOADED_MESSAGE });
const [persisted] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(persisted.errorCode).toBeNull(); // Restart before adapter metadata is saved.
expect(await readPersistedNativeProviderFailure(db, persisted, native.turnId, terminal)).toMatchObject({ errorCode: "native_provider_overloaded" });
expect(await readPersistedNativeProviderFailure(db, { ...persisted, runnerProfileJson: null }, native.turnId, terminal)).toBeNull();
expect(await readPersistedNativeProviderFailure(db, persisted, "different-turn", terminal)).toBeNull();
if (mutateOwner) await db.update(issues).set({ assigneeAgentId: otherAgentId, executionRunId: null }).where(eq(issues.id, issueId));
for (let replay = 0; replay < 2; replay++) await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
expect(provider.execute).toHaveBeenCalledTimes(1);
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]).toMatchObject({ status: "failed", error: NATIVE_PROVIDER_OVERLOADED_MESSAGE, errorCode: "native_provider_overloaded" });
expect(await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId))).toHaveLength(1);
}
it("retries after one and two minutes across restart/replay, then stops", async () => {
const issueId = randomUUID(), originalRunId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId, title: "Capacity task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "capacity-owner" });
await db.insert(heartbeatRuns).values({ id: originalRunId, companyId, agentId, responsibleUserId: "capacity-owner", contextSnapshot: { issueId, wakeCommentId: "original-message" } });
let runId: string = originalRunId;
const unexpected = vi.fn(async () => { throw new Error("Unexpected recovery"); });
const release = createReleaseIssueExecution({
issueLock: createPostgresWakeQueueAdapter(db, { resolveResponsibleUserId: unexpected, getRoutineEnv: unexpected, resolveSessionBeforeForWakeup: unexpected }),
recovery: { escalateStrandedAssignedIssue: unexpected, escalateStrandedRecoveryIssueInPlace: unexpected },
});
for (let failure = 0; failure <= 2; failure++) {
const before = Date.now();
await acceptCapacityFailure(runId, issueId);
const successors = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId)));
if (failure === 2) {
expect(successors).toHaveLength(0);
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "blocked", unblockDescriptor: { action: expect.stringContaining("Automatic retries exhausted") } });
break;
}
expect(successors).toHaveLength(1);
const retry = successors[0];
expect(retry).toMatchObject({ status: "scheduled_retry", scheduledRetryAttempt: failure + 1, scheduledRetryReason: "native_provider_overloaded", error: NATIVE_PROVIDER_OVERLOADED_MESSAGE,
contextSnapshot: { issueId, forceFreshSession: true, executionRetryAccounting: { version: 1, failureRetries: failure + 1, maxTurnContinuations: 0 } } });
expect(retry.contextSnapshot).not.toHaveProperty("wakeCommentId");
expect(retry.scheduledRetryAt!.getTime() - before).toBeGreaterThanOrEqual(60_000 * 2 ** failure);
expect(retry.scheduledRetryAt!.getTime() - Date.now()).toBeLessThanOrEqual(60_000 * 2 ** failure);
const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.runId, retry.id));
expect(wakes).toHaveLength(1);
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId));
expect(await db.select().from(statusDecisionEffects).where(eq(statusDecisionEffects.decisionId, decision.id))).toMatchObject([{ effectKind: "schedule_retry", targetType: "heartbeat_run", targetId: retry.id }]);
expect((await release({ companyId, runId, now: new Date() })).outcome.kind).toBe("released");
expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId))).toHaveLength(0);
const schedulerAfterRestart = heartbeatService(db, { runtimeEnv: {} });
expect(await schedulerAfterRestart.promoteDueScheduledRetries(new Date())).toMatchObject({ promoted: 0 });
expect(await schedulerAfterRestart.promoteDueScheduledRetries(retry.scheduledRetryAt!)).toMatchObject({ promoted: 1, runIds: [retry.id] });
runId = retry.id;
}
expect(unexpected).not.toHaveBeenCalled();
});
it("uses failed-run history without lending a resumed task's consumed continuation receipt", async () => {
const issueId = randomUUID(), runId = randomUUID(), olderRunId = randomUUID(), commentId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId, title: "Resumed capacity task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "capacity-owner" });
await db.insert(issueComments).values({ id: commentId, companyId, issueId, authorUserId: "capacity-owner", authorType: "user", body: "Continue the investigation." });
const consumedContext = { issueId, wakeCommentId: commentId, wakeCommentIds: [commentId],
explicitUserContinuation: { previousRunId: olderRunId, commentId },
previousRunId: olderRunId, resumeIntent: "continue", paperclipTurnContext: "Previously delivered context" };
await db.insert(heartbeatRuns).values([
{ id: olderRunId, companyId, agentId, status: "failed", contextSnapshot: { issueId } },
{ id: runId, companyId, agentId, responsibleUserId: "capacity-owner", contextSnapshot: consumedContext },
]);
await acceptCapacityFailure(runId, issueId);
const [retry] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId));
expect(retry.contextSnapshot).not.toHaveProperty("explicitUserContinuation");
expect(retry.contextSnapshot).not.toHaveProperty("wakeCommentId");
expect(retry.contextSnapshot).not.toHaveProperty("resumeIntent");
expect(retry.contextSnapshot).not.toHaveProperty("paperclipTurnContext");
const continuation = await buildExecutionContinuation({ db, companyId, issueId, agentId,
runId: retry.id, context: retry.contextSnapshot!, summary: null, exposeLowTrustRaw: false });
expect(continuation).toMatchObject({ trigger: { sourceRunId: runId }, objective: "Continue the investigation.",
messages: [expect.objectContaining({ id: commentId, body: "Continue the investigation." })] });
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0].contextSnapshot)
.toEqual(consumedContext);
await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, retry.id));
});
it("does not claim a capacity retry before predecessor cleanup settles", async () => {
const issueId = randomUUID(), runId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId, title: "Cleanup capacity task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "capacity-owner" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "capacity-owner", contextSnapshot: { issueId } });
await acceptCapacityFailure(runId, issueId);
const [retry] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId));
await db.update(issues).set({ executionRunId: null, checkoutRunId: null }).where(eq(issues.id, issueId));
const scheduler = heartbeatService(db, { runtimeEnv: {} });
expect(await scheduler.promoteDueScheduledRetries(retry.scheduledRetryAt!)).toMatchObject({ promoted: 1 });
await db.insert(environmentLeases).values({ companyId, heartbeatRunId: runId, provider: "local", status: "pending_cleanup", cleanupStatus: "failed" });
await scheduler.resumeQueuedRuns();
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, retry.id)))[0].status).toBe("queued");
expect(provider.execute).toHaveBeenCalledTimes(1);
// Do not leave a runnable fixture behind for the next case.
await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, retry.id));
});
it("does not retry or change the task after reassignment", async () => {
const issueId = randomUUID(), runId = randomUUID();
await db.insert(issues).values({ id: issueId, companyId, title: "Reassigned capacity task", status: "in_progress", assigneeAgentId: agentId, responsibleUserId: "capacity-owner" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: "capacity-owner", contextSnapshot: { issueId } });
await acceptCapacityFailure(runId, issueId, true);
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0);
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "in_progress", assigneeAgentId: otherAgentId });
expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId))).filter(wake => wake.payload?.issueId === issueId)).toHaveLength(0);
});
});
@@ -1,6 +1,7 @@
import { isNativePlanWaitResult, readNativePlanWait } from "./native-plan-wait.js";
import { settleSlackConversation } from "../slack-conversation-lifecycle.js";
import { readPersistedNativeModelRejection } from "./native-provider-failure-evidence.js";
import { executionFailureRetryCount } from "../execution-recovery-attempt.js";
import { readPersistedNativeProviderFailure } from "./native-provider-failure-evidence.js";
import { dismissAutomaticCompletionReviews } from "./automatic-completion-reviews.js";
import { getNativeReviewAssignment, readNativeReviewAssignmentContext } from "./native-review-participant.js";
import { conversationNativeDecision, isConversation } from "../agent-conversations.js";
@@ -1264,9 +1265,9 @@ export async function finalizeNativeRun(input: {
issueId: authoritativeIssue.id,
runId: run.id,
}),
assessment.reportedDisposition === "yielded" &&
(terminalState === "failed" || (assessment.reportedDisposition === "yielded" &&
assessment.continuation?.kind === "response_wake" &&
assessment.hasBlockingRemainingWork
assessment.hasBlockingRemainingWork))
? issueTreeControlService(input.db).getActivePauseHoldGate(
run.companyId, authoritativeIssue.id,
)
@@ -1286,16 +1287,19 @@ export async function finalizeNativeRun(input: {
(!planWait || nativeSha256(planWait.result) !== nativeSha256(result))) {
throw new Error("native_plan_wait_authority_lost");
}
const providerModelRejection = await readPersistedNativeModelRejection(
const providerFailure = await readPersistedNativeProviderFailure(
input.db, run, resultRow.turnId, envelope.terminal as PrpTerminalState,
);
const ownsModelRejectionDecision =
const ownsProviderFailureDecision =
(!authoritativeIssue.executionRunId || authoritativeIssue.executionRunId === run.id) &&
(reviewContext ? nativeReview?.interaction.status === "pending"
: authoritativeIssue.assigneeAgentId === run.agentId && !authoritativeIssue.assigneeUserId);
const proposedDecision = resolveNativeFinalizerStatus({
planWaitAuthorized: planWait !== null,
providerModelRejected: providerModelRejection !== null && ownsModelRejectionDecision,
providerModelRejected: providerFailure?.errorCode === "native_provider_model_rejected" && ownsProviderFailureDecision,
providerOverloaded: providerFailure?.errorCode === "native_provider_overloaded" && ownsProviderFailureDecision,
providerFailureSuperseded: providerFailure?.errorCode === "native_provider_overloaded" && !ownsProviderFailureDecision,
failureRetryCount: executionFailureRetryCount(run),
...(reviewContext ? { nativeReviewOutcome: nativeReview
? nativeReview.interaction.status === "pending" ? "pending" as const : "resolved" as const
: "stale" as const } : {}),
@@ -1384,6 +1388,8 @@ export async function finalizeNativeRun(input: {
requireModelRejectionOwner: decision.reasonCode === "native_provider_model_rejected"
? { agentId: run.agentId, reviewContext }
: undefined,
requireProviderFailureOwner: decision.reasonCode?.startsWith("native_provider_overloaded")
? { agentId: run.agentId, reviewContext } : undefined,
requireBoardResponseWaitSource:
decision.reasonCode === "board_response_waiting" || repairBoardResponseWait
? boardResponseWait?.source
@@ -1426,7 +1432,7 @@ export async function finalizeNativeRun(input: {
);
const clearExecutionFailure = input.projectRunStatus && finalizationPhase === "committed" && terminalState === "succeeded";
const finalizationMetadata = {
...(providerModelRejection ? { nativeProviderFailure: providerModelRejection.diagnostic } : {}),
...(providerFailure ? { nativeProviderFailure: providerFailure.diagnostic } : {}),
finalizationPhase,
...(finalizationPhase === "committed" ? { failureCode: null, originalFailureCode: null, nextAttemptAt: null } : {}),
assessmentId: assessmentRow.id,
@@ -1477,11 +1483,11 @@ export async function finalizeNativeRun(input: {
nativePhase: finalizationPhase,
nativePhaseUpdatedAt: now,
...(clearExecutionFailure ? { error: null, errorCode: null } : {}),
...(providerModelRejection ? {
...(providerFailure ? {
// Recovery can finalize before heartbeat saves the adapter result.
// Retain any independently recorded execution/cleanup failure.
error: sql`coalesce(${heartbeatRuns.error}, ${providerModelRejection.errorMessage})`,
errorCode: sql`coalesce(${heartbeatRuns.errorCode}, ${providerModelRejection.errorCode})`,
error: sql`coalesce(${heartbeatRuns.error}, ${providerFailure.errorMessage})`,
errorCode: sql`coalesce(${heartbeatRuns.errorCode}, ${providerFailure.errorCode})`,
} : {}),
resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb)
|| ${JSON.stringify(finalizationMetadata)}::jsonb
@@ -44,6 +44,25 @@ function arbitrate(
}
describe("native status authority", () => {
it("schedules a capacity retry while preserving partial work and review authority", () => {
for (const nativeReviewOutcome of [undefined, "pending"] as const) {
const decision = arbitrate({ terminalState: "failed", providerOverloaded: true, nativeReviewOutcome });
expect(decision).toMatchObject({ statusAction: "preserve", reasonCode: "native_provider_overloaded" });
expect(decision.effects).toContainEqual(expect.objectContaining({ kind: "schedule_retry", cause: "native_provider_overloaded" }));
}
expect(arbitrate({ terminalState: "failed", providerOverloaded: true, failureRetryCount: 2 }))
.toMatchObject({ statusAction: "blocked", reasonCode: "native_provider_overloaded_exhausted", effects: [{ kind: "bind_blocker", owner: "board", action: expect.stringContaining("Automatic retries exhausted") }] });
});
it.each([
{ hasActivePauseHold: true }, { hasUnresolvedIssueBlockers: true },
{ governanceGate: { kind: "approval" as const, id: "approval" } },
{ priorIssueStatus: "blocked" as const }, { priorIssueStatus: "done" as const },
{ workspaceFinalizeStatus: "failed" as const }, { nativeReviewOutcome: "stale" as const },
{ nativeReviewOutcome: "resolved" as const },
])("does not schedule capacity retries through existing authority or cleanup gates (%j)", (gate) => {
const decision = arbitrate({ terminalState: "failed", providerOverloaded: true, ...gate });
expect(decision.effects.some(effect => effect.kind === "schedule_retry")).toBe(false);
});
it.each(["in_progress", "in_review"] as const)("blocks a current worker's proven model rejection without a retry (%s)", (priorIssueStatus) => {
const decision = arbitrate({ priorIssueStatus, terminalState: "failed", providerModelRejected: true });
expect(decision).toMatchObject({ statusAction: "blocked", toStatus: "blocked", reasonCode: "native_provider_model_rejected", unblockDescriptor: { owner: "board" } });
@@ -528,7 +547,7 @@ describe("native status authority", () => {
expect.objectContaining({
statusAction: "blocked",
toStatus: "blocked",
policyVersion: "phase6-v8",
policyVersion: "phase6-v9",
reasonCode: "current_track_blocker_waiting",
unblockDescriptor: {
owner: "board",
@@ -1,7 +1,7 @@
import type { NativeEvidenceAssessment } from "./evidence-classifier.js";
import { NATIVE_MODEL_REJECTION_MESSAGE } from "./native-provider-failure.js";
import { NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, NATIVE_PROVIDER_OVERLOADED_CODE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js";
export const NATIVE_STATUS_ARBITER_POLICY_VERSION = "phase6-v8";
export const NATIVE_STATUS_ARBITER_POLICY_VERSION = "phase6-v9";
export type NativeAuthoritativeIssueStatus =
| "backlog"
@@ -120,6 +120,9 @@ export function arbitrateNativeStatus(input: {
nativeReviewOutcome?: "resolved" | "pending" | "stale";
/** Re-derived from the committed runner terminal and pinned execution identity. */
providerModelRejected?: boolean;
providerOverloaded?: boolean;
providerFailureSuperseded?: boolean;
failureRetryCount?: number;
agentId: string;
priorIssueStatus: NativeAuthoritativeIssueStatus;
}): NativeStatusDecision {
@@ -151,6 +154,11 @@ export function arbitrateNativeStatus(input: {
],
};
}
if (input.providerFailureSuperseded) return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "preserve", toStatus: input.priorIssueStatus,
reasonCode: "provider_failure_authority_superseded", unblockDescriptor: null, effects: [],
};
if (input.providerModelRejected && input.terminalState === "failed" &&
input.nativeReviewOutcome !== "stale" && input.nativeReviewOutcome !== "resolved") {
if (input.nativeReviewOutcome === "pending") {
@@ -176,6 +184,35 @@ export function arbitrateNativeStatus(input: {
effects: [{ kind: "bind_blocker", owner: "board", action: NATIVE_MODEL_REJECTION_MESSAGE }],
};
}
if (input.providerOverloaded && input.terminalState === "failed" &&
input.nativeReviewOutcome !== "stale" && input.nativeReviewOutcome !== "resolved") {
const held = input.governanceGate || input.hasUnresolvedIssueBlockers || input.hasActivePauseHold || input.priorIssueStatus === "blocked";
const exhausted = (input.failureRetryCount ?? 0) >= NATIVE_PROVIDER_CAPACITY_MAX_RETRIES;
if (held || (exhausted && input.nativeReviewOutcome === "pending")) return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "preserve", toStatus: input.priorIssueStatus,
reasonCode: held ? "native_provider_overloaded_held" : "native_provider_overloaded_exhausted",
unblockDescriptor: null, effects: [{ kind: "release_checkout" }],
};
if (exhausted) {
const action = `${NATIVE_PROVIDER_OVERLOADED_MESSAGE} Automatic retries exhausted; retry later or choose a different model.`;
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "blocked", toStatus: "blocked", reasonCode: "native_provider_overloaded_exhausted",
unblockDescriptor: { owner: "board", action },
effects: [{ kind: "bind_blocker", owner: "board", action }],
};
}
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
statusAction: "preserve", toStatus: input.priorIssueStatus,
reasonCode: NATIVE_PROVIDER_OVERLOADED_CODE, unblockDescriptor: null,
effects: [
{ kind: "schedule_retry", cause: NATIVE_PROVIDER_OVERLOADED_CODE, summary: "Retry after model capacity becomes available.", agentId: input.agentId },
...(input.nativeReviewOutcome === "pending" ? [{ kind: "release_checkout" as const }] : []),
],
};
}
if (input.nativeReviewOutcome) {
return {
policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION,
@@ -50,6 +50,8 @@ import {
type ActivityPublication,
} from "../activity-log.js";
import { emitAgentTaskRun } from "../agent-task-run-telemetry.js";
import { materializeNativeProviderCapacityRetry } from "./native-provider-capacity-retry.js";
import { NATIVE_PROVIDER_OVERLOADED_CODE } from "./native-provider-failure.js";
export class NativeStatusRaceError extends Error {
readonly code = "native_status_race" as const;
@@ -789,6 +791,14 @@ async function materializeDecisionEffect(input: {
}
if (effect.kind === "schedule_retry") {
failAt("continuation_materialization", input.failpoint);
if (effect.cause === NATIVE_PROVIDER_OVERLOADED_CODE) {
const retryId = await materializeNativeProviderCapacityRetry({
tx: input.tx as unknown as Db, companyId: input.companyId,
issueId: input.issue.id, runId: input.runId, agentId: effect.agentId,
});
return { effectKind: effect.kind, targetType: "heartbeat_run", targetId: retryId,
payload: { cause: effect.cause, summary: effect.summary } };
}
const wakeId = await enqueueWake({
tx: input.tx,
companyId: input.companyId,
@@ -1539,6 +1549,7 @@ export async function commitNativeStatusDecision(input: {
requireExternalChatResponseWaitAuthorization?: { agentId: string };
requirePlanWaitSource?: NativePlanWaitSource;
requireModelRejectionOwner?: { agentId: string; reviewContext: NativeReviewAssignmentContext | null };
requireProviderFailureOwner?: { agentId: string; reviewContext: NativeReviewAssignmentContext | null };
requireBoardResponseWaitSource?: NativeBoardResponseWaitSource;
requireBoardResponseWaitOrigin?: NativeBoardResponseWaitOrigin;
reviewResponsePresentation?: {
@@ -1554,6 +1565,9 @@ export async function commitNativeStatusDecision(input: {
if (reasonCode === "native_provider_model_rejected" && !input.requireModelRejectionOwner) {
throw new Error("native_model_rejection_owner_required");
}
if (reasonCode.startsWith("native_provider_overloaded") && !input.requireProviderFailureOwner) {
throw new Error("native_provider_failure_owner_required");
}
const publications: ActivityPublication[] = [];
const terminalRunsToEmit: (typeof heartbeatRuns.$inferSelect)[] = [];
const committed = await input.db.transaction(async (tx) => {
@@ -1623,8 +1637,8 @@ export async function commitNativeStatusDecision(input: {
) {
throw new NativeStatusRaceError();
}
if (input.requireModelRejectionOwner) {
const owner = input.requireModelRejectionOwner;
if (input.requireModelRejectionOwner || input.requireProviderFailureOwner) {
const owner = (input.requireProviderFailureOwner ?? input.requireModelRejectionOwner)!;
// A successor can claim execution without changing statusVersion. Keep
// this new blocking authority behind the same locked issue snapshot.
if (issue.executionRunId && issue.executionRunId !== input.runId) throw new NativeStatusRaceError();
@@ -63,6 +63,8 @@ const DEFAULT_MAX_CONCURRENT_JOBS = 10;
* Options for creating a PluginJobScheduler.
*/
export interface PluginJobSchedulerOptions {
/** Suppress periodic database work while an unclaimed Cloud app stands by. */
isBackgroundWorkEnabled?: () => boolean;
/** Drizzle database instance. */
db: Db;
/** Persistence layer for jobs and runs. */
@@ -244,6 +246,7 @@ export function createPluginJobScheduler(
* A single scheduler tick. Queries for due jobs and dispatches them.
*/
async function tick(): Promise<void> {
if (options.isBackgroundWorkEnabled?.() === false) return;
// Prevent overlapping ticks (in case a tick takes longer than the interval)
if (tickInProgress) {
log.debug("skipping tick — previous tick still in progress");
+2
View File
@@ -36,6 +36,8 @@ export type HealthStatus = {
authReady?: boolean;
bootstrapStatus?: "ready" | "bootstrap_pending";
bootstrapInviteActive?: boolean;
/** The unclaimed Cloud app is ready; this response did not probe SQL. */
warmStandby?: boolean;
features?: {
companyDeletionEnabled?: boolean;
};
@@ -128,6 +128,15 @@ describe("IssueScheduledRetryCard", () => {
expect(container.textContent).not.toMatch(/failed|Retry|Attempt|Replaces run/);
expect(getRetryNowButton()).toBeNull();
});
it("surfaces model capacity and the automatic retry without a generic failure", () => {
renderWithProviders(<IssueScheduledRetryCard issueId="issue-1" scheduledRetry={{ ...baseRetry, scheduledRetryAttempt: 1, scheduledRetryReason: "native_provider_overloaded",
error: "Selected model is at capacity. Please try a different model.", errorCode: "native_provider_overloaded" }} />);
expect(container.textContent).toContain("Model at capacity");
expect(container.textContent).toContain("Selected model is at capacity");
expect(container.textContent).toContain("Paperclip will retry automatically");
expect(container.textContent).not.toContain("Native session failed");
});
it("renders nothing when there is no scheduled retry", () => {
renderWithProviders(<IssueScheduledRetryCard issueId="issue-1" scheduledRetry={null} />);
expect(getCard()).toBeNull();
@@ -115,7 +115,7 @@ export function IssueScheduledRetryCard({
) : null}
{scheduledRetry.error ? (
<div className="mt-1 text-xs text-muted-foreground">
Last attempt failed: {scheduledRetry.error}. Paperclip will retry automatically.
Last attempt failed: {scheduledRetry.error}{/[.!?]$/.test(scheduledRetry.error.trim()) ? "" : "."} Paperclip will retry automatically.
</div>
) : null}
{isError ? (
+1
View File
@@ -4,6 +4,7 @@ import { describeRunRetryState, formatRetryReason } from "./runRetryState";
describe("runRetryState", () => {
it("formats internal retry reasons for operators", () => {
expect(formatRetryReason("transient_failure")).toBe("Transient failure");
expect(formatRetryReason("native_provider_overloaded")).toBe("Model at capacity");
expect(formatRetryReason("issue_continuation_needed")).toBe("Continuation needed");
expect(formatRetryReason("max_turns_continuation")).toBe("Max-turn continuation");
expect(formatRetryReason("custom_reason")).toBe("custom reason");
+1
View File
@@ -19,6 +19,7 @@ export type RunRetryStateSummary = {
};
const RETRY_REASON_LABELS: Record<string, string> = {
native_provider_overloaded: "Model at capacity",
ai_connection_pool_wait: "Waiting for pool usage to recover",
transient_failure: "Transient failure",
missing_issue_comment: "Missing task comment",
@@ -0,0 +1,19 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { IssueScheduledRetryCard } from "@/components/IssueScheduledRetryCard";
const meta = {
title: "Tasks/Model capacity retry",
component: IssueScheduledRetryCard,
decorators: [Story => <div className="max-w-2xl"><Story /></div>],
args: {
issueId: "capacity-task",
scheduledRetry: {
runId: "capacity-retry", status: "scheduled_retry", agentId: "capacity-agent", agentName: "Codex",
retryOfRunId: "failed-capacity-run", scheduledRetryAt: new Date(Date.now() + 60_000).toISOString(),
scheduledRetryAttempt: 1, scheduledRetryReason: "native_provider_overloaded", retryExhaustedReason: null,
error: "Selected model is at capacity. Please try a different model.", errorCode: "native_provider_overloaded",
},
},
} satisfies Meta<typeof IssueScheduledRetryCard>;
export default meta;
export const Waiting: StoryObj<typeof meta> = {};