fix: fence accepted work and cleanup before idle sleep (#15522)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - A host can stop an idle instance to reduce unused compute.
> - Zero active runs do not prove that requests, saved work, or cleanup
are complete.
> - A client can disconnect while its request still writes, and failed
cleanup can remain only in memory or on disk.
> - This pull request holds new admission and checks accepted work,
cleanup, and persisted work under an owned drain.
> - The host gets an empty report only while those checks remain valid.

## Linked Issues or Issue Description

Refs #13413. That companion PR uses the same owned-hold vocabulary for
runtime services. This PR covers HTTP requests, scheduler work,
accounting, cleanup, and the instance work inventory. It does not
include the preview gateway changes.

**What existing behavior does this improve?**

The instance task-drain API reports process counters. It does not prove
that a host can safely stop the instance for idle sleep.

**Current behavior**

A quiet run set can coexist with an unfinished request, cleanup after a
completed run, future work, or a failed accounting write.

**Proposed behavior**

Provide a bounded owned idle hold. Block new ingress, track accepted
handler promises, inspect durable and local work, and return `none` only
when the same hold stays quiet through the checks. Keep normal
deployment drains compatible.

**Reason and benefit**

Hosts can identify eligible idle instances without treating a disconnect
or failed cleanup write as completed work.

## What Changed

- Add `purpose: "idle"`, a bounded TTL, unique owners, and owner-checked
release to task drain. Existing holds cannot be replaced by another API
request.
- Gate HTTP ingress before parsers, auth, webhooks, and MCP. Gate new
WebSocket upgrades. Track async handlers in nested Express routers and
error middleware until they settle, even after the response or client
disconnect.
- Count accepted live-event WebSocket authentication through settlement,
even after disconnects. Count detached built-in agent, managed-home and
runtime-service startup reconciliation after readiness.
- Keep health and control mutations tracked. Count control-request
authentication separately from the read-only report, including
concurrent user/company/membership writes.
- Pause new scheduler admissions during idle holds. Count work already
in flight, including database backups, and reject scans whose work
generation changes. Periodic backups block sleep without a host wake
schedule.
- Inspect accounting and orphan-cleanup spool directories without
skipping temporary or malformed entries. Retain orphan tokens through
queue splices, flush failures, and buffer overflow. Keep failed usage
capture counted until its database failure fence is written.
- Check persisted work across companies in a bounded read-only
transaction. Include deferred agent-file cleanup and saved watchdogs
whose watched issues are complete. Enabled plugins and unsupported
retained work remain blockers.
- Require the exact idle owner and completed startup tracking before
returning an empty report. Keep reports free of tenant details.
- Document the hosting protocol, retry behavior, conservative blockers,
and the remaining external provider-stop race.

## Verification

- Current head: `8d9a599b732c2047b8c671d4799065d7c90a3567`, rebased on
master `941a3fa991aeb97eb1ac390c65b7973b5f6de1ad`. Both heartbeat helper
extractions are preserved. GitHub confirms no merge conflicts.
- Focused heartbeat renderer/run-log, drain, control-auth, admission,
route and PostgreSQL inventory checks: 234 tests passed in 10 suites
after the rebase.
- The POST task-drain contract includes the expected `409` conflict
response. The 84 OpenAPI and instance-settings route tests and server
typecheck passed after that final documentation fix.
- Final accepted-upgrade/startup regression run: 104 tests passed in
five suites, including success and failure after readiness or
disconnect. Final server typecheck also passed.
- `pnpm -r typecheck`: passed.
- `pnpm build`: passed.
- `pnpm install --frozen-lockfile` and the PR diff secret scan passed.
No dependency or lockfile changes are added by this PR.
- The prior verification covered HTTP disconnects and early responses,
async error handlers, concurrent authentication writes, signed
bootstrap, saved watchdogs, backup promises, orphan cleanup, spools and
failed accounting fences. Those tests passed.
- The last full local `pnpm test:run` stopped in the general-server
phase with 16,658 passing tests and five skill/connector fixture
failures caused by an ancestor workspace skill directory. That full
local run preceded this rebase and has not been repeated for the import
conflict. Full current-head CI passed: 53 successful checks and two
conditional skips, with no failures.
- All eight review findings are fixed and their threads resolved,
including accepted upgrade authentication, detached startup writes and
the POST conflict contract. Current-head Apex review is 5/5 with no new
findings; all eight review threads remain resolved.
- No live provider stop or production change was performed.

## Risks

- The hosting controller must use the owned protocol and hold external
admission through its final validation and provider stop. A legacy drain
cannot authorize idle sleep. During an idle hold, new requests receive
503 with `Retry-After: 1`; the host must handle queueing or retry before
enabling this path.
- This is a single-process protocol. An unexpected restart after the
last validation can race an external provider stop. The host must
serialize deploy/wake/sleep operations and bind the validation to the
instance it stops. Multiple replicas need shared fencing.
- Some retained state conservatively prevents sleep, including every
enabled plugin. This PR does not promise that every inactive instance
becomes eligible.
- The HTTP adapter uses Express 5 router layers. Real Express tests
cover nested routes, errors and disconnects. New routes must register
before tracking is installed. Detached work must have durable state or
explicit work tracking.
- Unrecoverable in-memory cleanup debt keeps the instance awake until
reconciliation. This change does not make such debt survive an unplanned
process crash. No schema migration or provider configuration change is
included.

## Model Used

OpenAI GPT-6 via Codex, with reasoning, repository inspection, tool use
and code execution. The exact deployment variant/model ID and context
window are not exposed in this session.

## 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 and contains no internal
Paperclip ticket id or instance-derived details
- [x] I have run focused tests locally and they pass; the full local
fixture limitation and clean full CI result are documented above
- [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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Devin FoleyandPaperclip authored and GitHub committed 2026-10-08 08:35:45 -07:00
1 parent 71af2fbc3b
commit 3367b75ccc
26 files changed
+1304 -124

No files matched your search

@@ -18,6 +18,8 @@ import {
import { routineWebhookUrl } from "../services/routines.js";
import { paperclipCloudConnectorEnrollmentStatus } from "../services/paperclip-cloud-connector-enrollment.js";
import { cloudRuntimeIdentityMiddleware } from "../middleware/cloud-runtime-identity.js";
import { idleAdmissionMiddleware, trackIdleRequestHandlers } from "../middleware/idle-admission.js";
import { idleWorkSnapshot } from "../services/task-admission.js";
import { healthRoutes } from "../routes/health.js";
import {
getEmbeddedPostgresTestSupport,
@@ -186,6 +188,37 @@ describeEmbeddedPostgres("Cloud runtime identity", () => {
});
});
it.each([false, true])("counts exempt bootstrap writes until they settle (failure=%s)", async (fail) => {
let enterWrite!: () => void, finishWrite!: () => void;
const entered = new Promise<void>(resolve => { enterWrite = resolve; });
const pending = new Promise<void>(resolve => { finishWrite = resolve; });
const transaction = db.transaction.bind(db);
vi.spyOn(db, "transaction").mockImplementationOnce(async (...args) => {
enterWrite();
await pending;
if (fail) throw new Error("fixture bootstrap write failed");
return transaction(...args);
});
const app = express();
app.use(idleAdmissionMiddleware);
app.use(cloudRuntimeIdentityMiddleware(db));
app.get("/api/health", (_req, res) => res.sendStatus(204));
trackIdleRequestHandlers(app);
const requestTime = Math.floor(Date.now() / 1000);
const accepted = request(app).get("/api/health")
.set("x-paperclip-cloud-runtime-identity", assertion({ claims: { iat: requestTime, exp: requestTime + 300 } }))
.then(response => response);
try {
await entered;
expect(idleWorkSnapshot().active).toBe(1);
} finally {
finishWrite();
const response = await accepted;
expect(response.status).toBe(fail ? 401 : 204);
}
expect(idleWorkSnapshot().active).toBe(0);
});
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);
@@ -1,3 +1,4 @@
import { idleWorkSnapshot } from "../services/task-admission.js";
import { createHash, randomUUID } from "node:crypto";
import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
import os from "node:os";
@@ -2372,6 +2373,11 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
});
it("buffers the orphan in-process when the durable spool write also fails", async () => {
const idleBefore = idleWorkSnapshot().active;
let releaseFlush!: () => void;
let enteredFlush!: () => void;
const flushGate = new Promise<void>(resolve => { releaseFlush = resolve; });
const flushEntered = new Promise<void>(resolve => { enteredFlush = resolve; });
const { companyId, environment, runId } = await seedEnvironment({
driver: "sandbox",
name: "Foreign-bound Fake Sandbox Cleanup Spool Unwritable",
@@ -2413,7 +2419,8 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
if (databaseDown) {
return Promise.reject(new Error("pending-cleanup write failed; database down"));
}
return real.insertPendingCleanupLease(input);
enteredFlush();
return flushGate.then(() => real.insertPendingCleanupLease(input));
},
};
});
@@ -2454,11 +2461,18 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
"sandbox_orphan_cleanup_write_failed",
);
expect(fallbackLog?.[0]).toMatchObject({ persisted: false, buffered: true });
expect(idleWorkSnapshot().active).toBe(idleBefore + 1);
// The same runtime still keeps the orphan in-process, so a flush after the
// database recovers lands the durable row.
databaseDown = false;
const flushed = await runtime.flushDeferredOrphanCleanups();
const flushing = runtime.flushDeferredOrphanCleanups();
await flushEntered;
// The batch was spliced out of the queue, but the DB does not own it yet.
expect(idleWorkSnapshot().active).toBe(idleBefore + 1);
releaseFlush();
const flushed = await flushing;
expect(idleWorkSnapshot().active).toBe(idleBefore);
expect(flushed).toEqual({ recovered: 1, pending: 0 });
const rows = await db
.select()
@@ -2467,6 +2481,7 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
expect(rows).toHaveLength(1);
expect(rows[0]?.status).toBe("pending_cleanup");
} finally {
releaseFlush();
logSpy.mockRestore();
factorySpy.mockRestore();
destroySpy.mockRestore();
@@ -0,0 +1,76 @@
import { randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { agents, companies, createDb, heartbeatRuns, type Db } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { createRunUsageRecorder } from "../services/usage-receipts.js";
import { idleWorkSnapshot } from "../services/task-admission.js";
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("idle accounting work", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: ReturnType<typeof createDb>;
const directories: string[] = [];
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("idle-accounting-");
db = createDb(database.connectionString);
}, 60_000);
afterEach(async () => {
await db.execute(sql`TRUNCATE companies CASCADE`);
for (const directory of directories.splice(0)) await fs.rm(directory, { force: true, recursive: true });
});
afterAll(async () => { await database?.cleanup(); });
async function recorder() {
const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Accounting idle test", issuePrefix: "ACCT" });
await db.insert(agents).values({ id: agentId, companyId, name: "Test", role: "engineer", status: "idle", adapterType: "process" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", status: "running" });
const directory = await fs.mkdtemp(path.join(os.tmpdir(), "idle-accounting-"));
directories.push(directory);
let offline = false;
const proxy = new Proxy(db, { get(target, property) {
if (property === "transaction" && offline) return () => Promise.reject(new Error("Database unavailable"));
const value = Reflect.get(target, property);
return typeof value === "function" ? value.bind(target) : value;
} }) as Db;
const recorder = await createRunUsageRecorder(proxy, { companyId, runId, adapterType: "process" }, directory);
return { recorder, directory, runId, setOffline: (value: boolean) => { offline = value; } };
}
it("counts queued receipts until capture and accounting writes settle", async () => {
const before = idleWorkSnapshot().active;
const { recorder: usage } = await recorder();
const first = usage.capture({ complete: false, usage: { inputTokens: 1, outputTokens: 1 } });
const second = usage.capture({ complete: true, usage: { inputTokens: 2, outputTokens: 2 } });
expect(idleWorkSnapshot().active).toBe(before + 2);
await Promise.all([first, second]);
await usage.persistFailure();
expect(idleWorkSnapshot().active).toBe(before);
});
it("keeps unpersisted capture failure as a blocker until its failure fence reaches the database", async () => {
const before = idleWorkSnapshot().active;
const { recorder: usage, directory, runId, setOffline } = await recorder();
await fs.rm(directory, { recursive: true });
await fs.writeFile(directory, "unwritable spool");
setOffline(true);
await expect(usage.capture({ complete: true, usage: { inputTokens: 1, outputTokens: 1 } })).rejects.toThrow();
await expect(usage.persistFailure()).rejects.toThrow();
expect(idleWorkSnapshot().active).toBe(before + 1);
setOffline(false);
// A successful query which updates zero rows is not a durable fence.
await db.update(heartbeatRuns).set({ costAccountedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
await usage.persistFailure();
expect(idleWorkSnapshot().active).toBe(before + 1);
await db.update(heartbeatRuns).set({ costAccountedAt: null }).where(eq(heartbeatRuns.id, runId));
await usage.persistFailure();
expect(idleWorkSnapshot().active).toBe(before);
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(run.costAccountingPending).toBe(true);
expect(run.usageJson?.accountingCaptureFailed).toBe(true);
});
});
+103
View File
@@ -0,0 +1,103 @@
import express from "express";
import request from "supertest";
import { request as httpRequest } from "node:http";
import { afterEach, describe, expect, it } from "vitest";
import { idleAdmissionMiddleware, trackIdleRequestHandlers } from "../middleware/idle-admission.js";
import { idleWorkSnapshot, startTaskDrain, stopTaskDrain, readTaskDrain, beginIdleTrackedWork } from "../services/task-admission.js";
function deferred() {
let resolve!: () => void;
const promise = new Promise<void>(done => { resolve = done; });
return { promise, resolve };
}
function app() { const app = express(); app.use(idleAdmissionMiddleware); return app; }
afterEach(() => stopTaskDrain());
describe("idle admission", () => {
it("preserves legacy drains, but blocks all new work during an owned idle hold", async () => {
const server = app();
server.all("/{*path}", (_req, res) => res.sendStatus(204));
trackIdleRequestHandlers(server);
startTaskDrain({ ttlMs: 60_000 });
await request(server).post("/api/issues").expect(204);
startTaskDrain({ purpose: "idle", ttlMs: 60_000 });
for (const path of ["/api/issues", "/api/chat-webhooks/test", "/mcp", "/api/auth/callback"]) {
await request(server).get(path).expect(503).expect("Retry-After", "1");
await request(server).post(path).expect(503);
}
await request(server).get("/api/health").expect(204);
await request(server).get("/api/instance/task-drain/").expect(204);
await request(server).post("/api/instance/task-drain").expect(204);
stopTaskDrain();
await request(server).post("/api/issues").expect(204);
expect(idleWorkSnapshot().active).toBe(0);
});
it("counts a nested async handler after it sends a response", async () => {
const server = app();
const router = express.Router();
const done = deferred();
router.post("/work", async (_req, res) => { res.sendStatus(202); await done.promise; });
server.use("/api", router);
trackIdleRequestHandlers(server);
await request(server).post("/api/work").expect(202);
expect(idleWorkSnapshot().active).toBe(1);
startTaskDrain({ purpose: "idle", ttlMs: 60_000 });
await request(server).post("/api/work").expect(503);
done.resolve();
await new Promise(resolve => setImmediate(resolve));
expect(idleWorkSnapshot().active).toBe(0);
});
it("does not mistake a client disconnect for completed accepted work", async () => {
const server = app();
const entered = deferred(), done = deferred(), closed = deferred();
server.post("/work", async (_req, res) => { res.once("close", closed.resolve); entered.resolve(); await done.promise; /* client has left */ });
trackIdleRequestHandlers(server);
const listener = server.listen(0, "127.0.0.1");
await new Promise<void>(resolve => listener.once("listening", resolve));
const address = listener.address() as { port: number };
const client = httpRequest({ host: "127.0.0.1", port: address.port, path: "/work", method: "POST" });
client.on("error", () => undefined);
client.end();
try {
await entered.promise;
client.destroy();
await closed.promise;
startTaskDrain({ purpose: "idle", ttlMs: 60_000 });
expect(idleWorkSnapshot().active).toBe(1);
done.resolve();
await new Promise(resolve => setImmediate(resolve));
expect(idleWorkSnapshot().active).toBe(0);
} finally {
done.resolve(); client.destroy();
await new Promise<void>(resolve => listener.close(() => resolve()));
}
});
it("settles errors through async Express error middleware", async () => {
const server = app(), done = deferred();
server.get("/work", async () => { throw new Error("test"); });
server.use(async (_err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
res.sendStatus(500); await done.promise;
});
trackIdleRequestHandlers(server);
await request(server).get("/work").expect(500);
expect(idleWorkSnapshot().active).toBe(1);
done.resolve(); await new Promise(resolve => setImmediate(resolve));
expect(idleWorkSnapshot().active).toBe(0);
});
it("uses unique owners even for simultaneous starts and expires the hold", () => {
const first = startTaskDrain({ purpose: "idle", ttlMs: 60_000 });
const second = startTaskDrain({ purpose: "idle", ttlMs: 60_000 });
expect(second.ownerId).not.toBe(first.ownerId);
expect(readTaskDrain(second.expiresAt!)).toBeNull();
});
it("records even work that starts and finishes between observations", () => {
const before = idleWorkSnapshot();
const done = beginIdleTrackedWork(); done(); done();
expect(idleWorkSnapshot()).toEqual({ active: before.active, generation: before.generation + 2 });
});
});
@@ -0,0 +1,51 @@
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { inspectIdleSpool, readIdleLocalWork, markIdleIngressTracked, markIdleStartupComplete, registerIdleSpoolDirectory } from "../services/idle-local-work.js";
let root: string;
beforeEach(async () => { root = await fs.mkdtemp(path.join(os.tmpdir(), "idle-spool-")); });
afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); await fs.rm(root, { recursive: true, force: true }); });
describe("idle cleanup inspection", () => {
it("refuses to authorize sleep until startup and ingress tracking are ready", async () => {
expect(await readIdleLocalWork()).toBe("unknown");
});
it("accepts absent and empty directories", async () => {
expect(await inspectIdleSpool(path.join(root, "absent"))).toBe("none");
expect(await inspectIdleSpool(root)).toBe("none");
});
it.each(["receipt.json", "malformed.json", "partial.tmp", "write.probe", "unexpected"])("retains every spool entry: %s", async name => {
await fs.writeFile(path.join(root, name), "not valid JSON");
expect(await inspectIdleSpool(root)).toBe("present");
await fs.rm(path.join(root, name));
expect(await inspectIdleSpool(root)).toBe("none");
});
it("fails closed on a non-directory, dangling symlink, or read failure", async () => {
const file = path.join(root, "file"), link = path.join(root, "link");
await fs.writeFile(file, "");
await fs.symlink(path.join(root, "missing"), link);
expect(await inspectIdleSpool(file)).toBe("unknown");
expect(await inspectIdleSpool(path.join(file, "nested"))).toBe("unknown");
expect(await inspectIdleSpool(link)).toBe("unknown");
vi.spyOn(fs, "opendir").mockRejectedValue(Object.assign(new Error("private path"), { code: "EACCES" }));
expect(await inspectIdleSpool(root)).toBe("unknown");
});
it("checks custom spool directories as well as the default paths", async () => {
vi.stubEnv("PAPERCLIP_HOME", root);
vi.stubEnv("SANDBOX_ORPHAN_CLEANUP_SPOOL_DIR", path.join(root, "orphans"));
const custom = path.join(root, "custom-accounting");
registerIdleSpoolDirectory(custom);
markIdleIngressTracked(); markIdleStartupComplete({ scheduledBackups: false });
expect(await readIdleLocalWork()).toBe("none");
markIdleStartupComplete({ scheduledBackups: true });
expect(await readIdleLocalWork()).toBe("present");
markIdleStartupComplete({ scheduledBackups: false });
await fs.mkdir(custom);
await fs.writeFile(path.join(custom, "receipt.tmp"), "incomplete");
expect(await readIdleLocalWork()).toBe("present");
await fs.rm(custom, { recursive: true });
expect(await readIdleLocalWork()).toBe("none");
});
});
@@ -0,0 +1,253 @@
import { beginIdleTrackedWork } from "../services/task-admission.js";
import { randomUUID } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
agentInstructionWorkingCopies, agents, agentApiKeys, agentWakeupRequests, companies, companySecretProposals, createDb,
adapterAuthSessions, environments, environmentLeases, executionWorkspaces,
heartbeatRuns, issues, issueWatchdogs, projects, routines, type Db,
} from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { readIdleSleepSafety, type IdleSleepDrainStatus } from "../services/idle-sleep-safety.js";
const now = Date.UTC(2020, 0, 1);
const held = (): IdleSleepDrainStatus => ({
draining: true, startedAt: new Date(now - 1000), expiresAt: new Date(now + 60_000),
activeRuns: 0, pendingWakes: 0,
});
const unknown = { version: 1, backgroundWork: "unknown" };
const present = { version: 1, backgroundWork: "present" };
const none = { version: 1, backgroundWork: "none" };
const ownerId = "d0b833f4-4098-42de-8420-1907f3aa4895";
const owned = () => ({ ...held(), ownerId });
const emptyLocal = async () => "none" as const;
describe("idle sleep safety failure boundaries", () => {
it.each([
{ draining: false }, { activeRuns: 1 }, { pendingWakes: 1 },
{ startedAt: null }, { expiresAt: new Date(now) },
])("does not query durable work without a quiet admission hold: %j", async (change) => {
const transaction = vi.fn();
expect(await readIdleSleepSafety({ transaction } as unknown as Db, () => ({ ...held(), ...change }), () => now))
.toEqual(unknown);
expect(transaction).not.toHaveBeenCalled();
});
it("fails closed when the database is unavailable", async () => {
const db = { transaction: vi.fn().mockRejectedValue(new Error("private connection detail")) } as unknown as Db;
expect(await readIdleSleepSafety(db, held, () => now)).toEqual(unknown);
});
it.each([
{ draining: false }, { startedAt: new Date(now) }, { expiresAt: new Date(now) },
{ activeRuns: 1 }, { pendingWakes: 1 },
])("rejects a report when the hold changes during the durable scan: %j", async (change) => {
const getStatus = vi.fn().mockReturnValueOnce(held()).mockReturnValue({ ...held(), ...change });
const execute = vi.fn().mockResolvedValue([{ blocked: true }]);
const transaction = vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => fn({ execute }));
expect(await readIdleSleepSafety({ transaction } as unknown as Db, getStatus, () => now)).toEqual(unknown);
expect(transaction).toHaveBeenCalledWith(expect.any(Function), { isolationLevel: "repeatable read", accessMode: "read only" });
});
it("reports persisted work when the admission hold remains unchanged", async () => {
const execute = vi.fn().mockResolvedValue([{ blocked: true }]);
const transaction = vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => fn({ execute }));
expect(await readIdleSleepSafety({ transaction } as unknown as Db, held, () => now)).toEqual(present);
});
});
describe("idle sleep admission and local work", () => {
const emptyDb = () => ({ transaction: async (fn: (tx: unknown) => Promise<unknown>) => fn({ execute: async () => [{ blocked: false }] }) }) as unknown as Db;
it("requires the exact current idle owner and a bounded expiry", async () => {
expect(await readIdleSleepSafety(emptyDb(), held, () => now, undefined, emptyLocal)).toEqual(unknown);
expect(await readIdleSleepSafety(emptyDb(), owned, () => now, "old-owner", emptyLocal)).toEqual(unknown);
expect(await readIdleSleepSafety(emptyDb(), () => ({ ...owned(), expiresAt: null }), () => now, ownerId, emptyLocal)).toEqual(unknown);
expect(await readIdleSleepSafety(emptyDb(), owned, () => now, ownerId, emptyLocal)).toEqual(none);
});
it.each(["present", "unknown"] as const)("retains local work reported as %s", async state => {
expect(await readIdleSleepSafety(emptyDb(), owned, () => now, ownerId, async () => state))
.toEqual({ version: 1, backgroundWork: state });
});
it("refuses sleep while accepted work remains in flight", async () => {
const done = beginIdleTrackedWork();
try { expect(await readIdleSleepSafety(emptyDb(), owned, () => now, ownerId, emptyLocal)).toEqual(unknown); }
finally { done(); }
expect(await readIdleSleepSafety(emptyDb(), owned, () => now, ownerId, emptyLocal)).toEqual(none);
});
it("invalidates a scan even when concurrent work finishes before the final check", async () => {
const inspect = async () => { const done = beginIdleTrackedWork(); done(); return "none" as const; };
expect(await readIdleSleepSafety(emptyDb(), owned, () => now, ownerId, inspect)).toEqual(unknown);
});
it("rechecks owner identity after disk inspection, including same-millisecond replacement", async () => {
let status = owned();
const inspect = async () => { status = { ...status, ownerId: "replacement" }; return "none" as const; };
expect(await readIdleSleepSafety(emptyDb(), () => status, () => now, ownerId, inspect)).toEqual(unknown);
});
it("rechecks expiry after disk inspection and hides inspection errors", async () => {
let clock = now;
expect(await readIdleSleepSafety(emptyDb(), owned, () => clock, ownerId, async () => {
clock += 60_000; return "none";
})).toEqual(unknown);
expect(await readIdleSleepSafety(emptyDb(), owned, () => now, ownerId, async () => { throw new Error("private spool path"); })).toEqual(unknown);
});
});
const support = await getEmbeddedPostgresTestSupport();
if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${support.reason}`);
(support.supported ? describe : describe.skip)("idle sleep durable work", () => {
let db: ReturnType<typeof createDb>;
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("idle-sleep-safety-");
db = createDb(database.connectionString);
}, 60_000);
afterEach(async () => { await db.execute(sql`TRUNCATE companies, plugins, environments CASCADE`); });
afterAll(async () => { await database?.cleanup(); });
const read = () => readIdleSleepSafety(db, owned, () => now, ownerId, emptyLocal);
async function seed() {
const companyId = randomUUID();
const agentId = randomUUID();
const runId = randomUUID();
await db.insert(companies).values({ id: companyId, name: "Idle test", issuePrefix: "IDLE" });
await db.insert(agents).values({ id: agentId, companyId, name: "On-demand agent", role: "engineer", status: "idle", adapterType: "process" });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", status: "succeeded" });
return { companyId, agentId, runId };
}
it("keeps saved agent files awake until deferred cleanup completes", async () => {
const { companyId, agentId, runId } = await seed();
await db.insert(agentInstructionWorkingCopies).values({
runId, companyId, agentId, responsibleUserId: "test-user", entryFile: "AGENTS.md",
baseHash: "test-hash", localRoot: "/tmp/idle-copy", executionRoot: "/tmp/idle-copy",
location: "local", state: "saved", processStoppedAt: new Date(now),
receipt: { schema: "paperclip.agent-files.v1", cleanupPending: true },
});
expect(await read()).toEqual(present);
await db.update(agentInstructionWorkingCopies).set({ receipt: { schema: "paperclip.agent-files.v1" } })
.where(eq(agentInstructionWorkingCopies.runId, runId));
expect(await read()).toEqual(none);
});
it("authorizes an empty database and completed history under a quiet owned hold", async () => {
expect(await read()).toEqual(none);
const { companyId } = await seed();
await db.insert(issues).values({ companyId, title: "Finished work", status: "done" });
await db.insert(routines).values({ companyId, title: "Paused schedule", status: "paused" });
await db.insert(environmentLeases).values({ companyId, status: "released" });
expect(await read()).toEqual(none);
});
it("blocks a saved watchdog on a completed issue before its first review starts", async () => {
const { companyId, agentId } = await seed();
const [issue] = await db.insert(issues).values({ companyId, title: "Finished work", status: "done" }).returning();
expect(await read()).toEqual(none);
const [watchdog] = await db.insert(issueWatchdogs).values({
companyId, issueId: issue!.id, watchdogAgentId: agentId, status: "active",
}).returning();
expect(watchdog!.watchdogIssueId).toBeNull();
expect(watchdog!.lastTriggeredAt).toBeNull();
expect(await read()).toEqual(present);
await db.update(issueWatchdogs).set({ status: "disabled" }).where(eq(issueWatchdogs.id, watchdog!.id));
expect(await read()).toEqual(none);
});
it.each([
["queued run", { status: "queued" }],
["orphan running run", { status: "running" }],
["future retry", { scheduledRetryAt: new Date(now + 86_400_000) }],
["unsettled accounting", { costAccountingPending: true }],
] as const)("blocks %s even when process counters are zero", async (_name, change) => {
const { runId } = await seed();
await db.update(heartbeatRuns).set(change).where(eq(heartbeatRuns.id, runId));
expect(await read()).toEqual(present);
});
it("reports an enabled heartbeat timer and permits sleep after it is disabled", async () => {
const { agentId } = await seed();
await db.update(agents).set({ runtimeConfig: { heartbeat: { enabled: true, intervalSec: 86_400 } } }).where(eq(agents.id, agentId));
expect(await read()).toEqual(present);
await db.update(agents).set({ runtimeConfig: { heartbeat: { enabled: false, intervalSec: 86_400 } } }).where(eq(agents.id, agentId));
expect(await read()).toEqual(none);
});
it("blocks a durable deferred wake", async () => {
const { companyId, agentId } = await seed();
await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "assignment", status: "deferred_issue_execution" });
expect(await read()).toEqual(present);
});
it("blocks an active routine without waiting for its next due time", async () => {
const { companyId } = await seed();
await db.insert(routines).values({ companyId, title: "Tomorrow", status: "active" });
expect(await read()).toEqual(present);
});
it("blocks a remote resource pending cleanup", async () => {
const { companyId } = await seed();
await db.insert(environmentLeases).values({ companyId, status: "pending_cleanup" });
expect(await read()).toEqual(present);
});
it("reports a login sandbox awaiting cleanup", async () => {
const { companyId } = await seed();
const [environment] = await db.insert(environments).values({ name: "Login fixture" }).returning();
await db.insert(adapterAuthSessions).values({
companyId, environmentId: environment!.id, adapterType: "codex_local",
startedByUserId: "fixture-user", publicSessionId: "fixture-session", status: "cleanup_pending",
});
expect(await read()).toEqual(present);
});
it("reports a pending secret proposal with future expiry", async () => {
const { companyId, agentId, runId } = await seed();
await db.insert(companySecretProposals).values({
companyId, kind: "secret", proposedName: "Fixture", proposedKey: "FIXTURE",
justification: "Test pending proposal", proposedByAgentId: agentId, originRunId: runId,
expiresAt: new Date(now + 86_400_000),
});
expect(await read()).toEqual(present);
});
it("reports retained execution workspaces that may need delayed cleanup", async () => {
const { companyId } = await seed();
const [project] = await db.insert(projects).values({ companyId, name: "Fixture project" }).returning();
await db.insert(executionWorkspaces).values({
companyId, projectId: project!.id, name: "Fixture workspace", mode: "isolated",
strategyType: "git_worktree", status: "closed", cleanupEligibleAt: new Date(now + 86_400_000),
});
expect(await read()).toEqual(present);
});
it("blocks externally usable agent keys until revoked", async () => {
const { companyId, agentId } = await seed();
const [key] = await db.insert(agentApiKeys).values({ companyId, agentId, name: "Fixture", keyHash: "fixture-not-a-key" }).returning();
expect(await read()).toEqual(present);
await db.update(agentApiKeys).set({ revokedAt: new Date(now) }).where(eq(agentApiKeys.id, key!.id));
expect(await read()).toEqual(none);
});
it("checks every company in the instance", async () => {
await seed();
const otherId = randomUUID();
await db.insert(companies).values({ id: otherId, name: "Other company", issuePrefix: "OTHER" });
await db.insert(issues).values({ companyId: otherId, title: "Pending work", status: "todo" });
expect(await read()).toEqual(present);
});
it("blocks enabled plugins even without declared jobs or webhooks", async () => {
await db.execute(sql`INSERT INTO plugins (plugin_key, package_name, version, manifest_json)
VALUES ('demo.on-demand', 'demo-plugin', '1.0.0', '{}'::jsonb)`);
expect(await read()).toEqual(present);
await db.execute(sql`UPDATE plugins SET status = 'disabled'`);
expect(await read()).toEqual(none);
});
it("fails closed when the installed schema is older than the report", async () => {
await db.execute(sql`ALTER TABLE heartbeat_runs RENAME COLUMN cost_accounting_pending TO hidden_pending`);
try { expect(await read()).toEqual(unknown); }
finally { await db.execute(sql`ALTER TABLE heartbeat_runs RENAME COLUMN hidden_pending TO cost_accounting_pending`); }
});
});
@@ -29,8 +29,10 @@ const mockCompanyService = vi.hoisted(() => ({
}));
const mockLogActivity = vi.hoisted(() => vi.fn());
const mockPublishActivity = vi.hoisted(() => vi.fn());
const mockReadIdleSleepSafety = vi.hoisted(() => vi.fn());
function registerModuleMocks() {
vi.doMock("../services/idle-sleep-safety.js", () => ({ readIdleSleepSafety: mockReadIdleSleepSafety }));
vi.doMock("../services/index.js", () => ({
companyService: () => mockCompanyService,
heartbeatService: () => mockHeartbeatService,
@@ -89,6 +91,7 @@ describe("instance settings routes", () => {
beforeEach(() => {
vi.clearAllMocks();
mockReadIdleSleepSafety.mockReset();
// vi.clearAllMocks() clears recorded calls only; it does not remove a
// mockImplementation a prior test installed. Reinstall the default here
// so a stateful implementation from one test can never leak into the
@@ -960,6 +963,54 @@ describe("instance settings routes", () => {
expect(res.status).toBe(200);
expect(res.body).toEqual(idleStatus);
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
});
it("acquires an owned bounded idle hold and forwards its owner for inspection", async () => {
const ownerId = "d0b833f4-4098-42de-8420-1907f3aa4895";
mockHeartbeatService.computeTaskDrain.mockReturnValue({ ownerId, startedAt: new Date(), expiresAt: new Date(Date.now() + 60_000) });
await request(createApp(adminActor)).post("/api/instance/task-drain").send({ purpose: "idle", ttlMs: 60_000 }).expect(200);
expect(mockHeartbeatService.computeTaskDrain).toHaveBeenCalledWith({ purpose: "idle", ttlMs: 60_000 });
await request(createApp(adminActor)).get(`/api/instance/task-drain?idleSleepSafety=1&ownerId=${ownerId}`).expect(200);
expect(mockReadIdleSleepSafety).toHaveBeenLastCalledWith(mockDb, expect.any(Function), Date.now, ownerId);
});
it.each([{}, { ttlMs: null }, { ttlMs: 1 }, { ttlMs: 300_001 }])("rejects an unbounded or invalid idle TTL: %j", async body => {
await request(createApp(adminActor)).post("/api/instance/task-drain").send({ ...body, purpose: "idle" }).expect(400);
expect(mockHeartbeatService.applyTaskDrain).not.toHaveBeenCalled();
});
it("rejects replacement and ownerless or stale release of an idle hold", async () => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue({ ...idleStatus, draining: true, ownerId: "current-owner" });
const app = createApp(adminActor);
await request(app).post("/api/instance/task-drain").send({}).expect(409);
await request(app).delete("/api/instance/task-drain").expect(409);
await request(app).delete("/api/instance/task-drain?ownerId=previous-owner").expect(409);
expect(mockHeartbeatService.applyTaskDrain).not.toHaveBeenCalled();
expect(mockHeartbeatService.stopTaskDrain).not.toHaveBeenCalled();
await request(app).delete("/api/instance/task-drain?ownerId=current-owner").expect(200);
expect(mockHeartbeatService.stopTaskDrain).toHaveBeenCalledOnce();
});
it("returns the opt-in instance-wide safety report to an instance admin", async () => {
mockHeartbeatService.getTaskDrainStatus.mockReturnValue(idleStatus);
const report = { version: 1, backgroundWork: "unknown" };
mockReadIdleSleepSafety.mockResolvedValue(report);
const res = await request(createApp(adminActor)).get("/api/instance/task-drain?idleSleepSafety=1");
expect(res.status).toBe(200);
expect(res.body).toEqual({ ...idleStatus, idleSleepSafety: report });
expect(mockReadIdleSleepSafety).toHaveBeenCalledWith(mockDb, expect.any(Function), Date.now, undefined);
expect(mockReadIdleSleepSafety.mock.calls[0][1]()).toEqual(idleStatus);
});
it.each([
["company member", nonAdminActor],
["agent", { type: "agent", agentId: "agent-1", companyId: "company-1" }],
["anonymous caller", { type: "none" }],
])("does not expose the instance-wide work report to a %s", async (_name, actor) => {
const res = await request(createApp(actor)).get("/api/instance/task-drain?idleSleepSafety=1");
expect(res.status).toBe(403);
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
});
it("writes an activity record for every company, then applies the same drain values, in one transaction", async () => {
@@ -4,6 +4,8 @@ import type { Duplex } from "node:stream";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { setupLiveEventsWebSocketServer } from "../realtime/live-events-ws.js";
import { logger } from "../middleware/logger.js";
import { idleWorkSnapshot, startTaskDrain, stopTaskDrain } from "../services/task-admission.js";
import { readIdleSleepSafety } from "../services/idle-sleep-safety.js";
vi.mock("../middleware/logger.js", () => ({
logger: {
@@ -67,6 +69,43 @@ describe("setupLiveEventsWebSocketServer", () => {
vi.clearAllMocks();
});
it.each([false, true])("counts accepted upgrade authentication after disconnect (failure=%s)", async (fail) => {
const server = new EventEmitter();
const socket = new FakeUpgradeSocket();
let finishAuth!: () => void;
const pending = new Promise<void>(resolve => { finishAuth = resolve; });
setupLiveEventsWebSocketServer(server as never, {} as never, {
deploymentMode: "authenticated",
resolveCloudActor: async () => {
await pending;
if (fail) throw new Error("fixture authentication write failed");
return { userId: "fixture-user", companyIds: ["company-1"] };
},
});
server.emit("upgrade", createUpgradeRequest(), socket as unknown as Duplex, Buffer.alloc(0));
const hold = startTaskDrain({ purpose: "idle", ttlMs: 60_000 });
const emptyDb = { transaction: async (run: (tx: unknown) => Promise<unknown>) =>
run({ execute: async () => [{ blocked: false }] }) };
const report = () => readIdleSleepSafety(emptyDb as never,
() => ({ ...hold, draining: true, activeRuns: 0, pendingWakes: 0 }), Date.now, hold.ownerId, async () => "none");
try {
socket.destroy();
await flushPromises();
expect(idleWorkSnapshot().active).toBe(1);
expect((await report()).backgroundWork).toBe("unknown");
finishAuth();
await flushPromises();
expect(idleWorkSnapshot().active).toBe(0);
expect((await report()).backgroundWork).toBe("none");
expect(socket.endedChunks).toEqual([]);
} finally {
finishAuth();
await flushPromises();
stopTaskDrain();
server.emit("close");
}
});
it("does not write a rejection response after the raw upgrade socket is already closed", async () => {
const server = new EventEmitter();
setupLiveEventsWebSocketServer(server as never, {} as never, { deploymentMode: "authenticated" });
@@ -1,3 +1,7 @@
import { idleWorkSnapshot } from "../services/task-admission.js";
import { readIdleSleepSafety } from "../services/idle-sleep-safety.js";
import { reconcileBuiltInAgentsOnStartup, reconcileCodexLocalManagedHomesOnStartup, reconcilePersistedRuntimeServicesOnStartup } from "../services/index.js";
import { runDatabaseBackup } from "@paperclipai/db";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -437,6 +441,65 @@ describe("startServer feedback export wiring", () => {
process.env.BETTER_AUTH_SECRET = "test-secret";
});
it.each(([
["built-in agents", reconcileBuiltInAgentsOnStartup],
["managed homes", reconcileCodexLocalManagedHomesOnStartup],
["runtime services", reconcilePersistedRuntimeServicesOnStartup],
] as const).flatMap(([name, reconcile]) => [false, true].map(fail => ({ name, reconcile, fail }))))
("counts detached $name startup writes after readiness (failure=$fail)", async ({ reconcile, fail }) => {
let finishStartup!: () => void;
const pending = new Promise<void>(resolve => { finishStartup = resolve; });
vi.mocked(reconcile).mockImplementationOnce(async () => {
await pending;
if (fail) throw new Error("fixture startup write failed");
return { reconciled: 0, seeded: 0, failed: 0 } as never;
});
const emptyDb = { transaction: async (run: (tx: unknown) => Promise<unknown>) =>
run({ execute: async () => [{ blocked: false }] }) };
const hold = { ownerId: "fixture-owner", draining: true, activeRuns: 0, pendingWakes: 0,
startedAt: new Date(), expiresAt: new Date(Date.now() + 60_000) };
const report = () => readIdleSleepSafety(emptyDb as never, () => hold, Date.now, hold.ownerId, async () => "none");
try {
await startServer();
await new Promise(resolve => setImmediate(resolve));
expect(idleWorkSnapshot().active).toBe(1);
expect((await report()).backgroundWork).toBe("unknown");
finishStartup();
await new Promise(resolve => setImmediate(resolve));
expect(idleWorkSnapshot().active).toBe(0);
expect((await report()).backgroundWork).toBe("none");
} finally {
finishStartup();
await new Promise(resolve => setImmediate(resolve));
}
});
it.each([false, true])("counts an accepted backup until completion, including failure=%s", async fails => {
await startServer();
await new Promise(resolve => setImmediate(resolve));
const before = idleWorkSnapshot().active;
let resolveBackup!: (value: never) => void;
let rejectBackup!: (error: Error) => void;
vi.mocked(runDatabaseBackup).mockImplementationOnce(() => new Promise((resolve, reject) => {
resolveBackup = resolve; rejectBackup = reject;
}));
const options = createAppMock.mock.calls[0]?.[1] as unknown as {
databaseBackupService: { runManualBackup(): Promise<unknown> };
};
const backup = options.databaseBackupService.runManualBackup();
await Promise.resolve();
expect(idleWorkSnapshot().active).toBe(before + 1);
if (fails) {
const rejection = expect(backup).rejects.toThrow("backup failed");
rejectBackup(new Error("backup failed"));
await rejection;
} else {
resolveBackup({ backupFile: "backup.sql.gz", sizeBytes: 1, prunedCount: 0 } as never);
await backup;
}
expect(idleWorkSnapshot().active).toBe(before);
});
it("starts without PAPERCLIP_DECISION_SIGNING_SECRET by generating a persisted key", async () => {
const originalHome = process.env.PAPERCLIP_HOME;
const originalInstanceId = process.env.PAPERCLIP_INSTANCE_ID;