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

@@ -1,3 +1,4 @@
import { beginIdleTrackedWork } from "./task-admission.js";
import { hasStopOnlyCleanup, prepareSandboxStopAndRetain, readStopOnlyCleanup, settleStopOnlyCleanup, stopOnlyCleanupKey } from "./sandbox-stop-and-retain.js";
import { readEnvironmentCreationCleanupError } from "@paperclipai/plugin-sdk";
import { preserveEnvironmentSyncOutErrorDiagnostic } from "./environment-sync-out-error.js";
@@ -1327,6 +1328,16 @@ function createSandboxEnvironmentDriver(
// write, so a flushed row and a synchronous row are indistinguishable to the
// sweep.
const deferredOrphanCleanups: DeferredOrphanCleanupRecord[] = [];
// Keep the token through queue splices, failed flushes and buffer overflow.
// Release only when the database durably owns cleanup of this exact orphan.
const orphanIdleWork = new Map<string, () => void>();
const orphanIdleKey = (record: DeferredOrphanCleanupRecord) => JSON.stringify([
record.companyId, record.provider, record.providerLeaseId ?? record,
]);
const trackOrphanIdleWork = (record: DeferredOrphanCleanupRecord) => {
const key = orphanIdleKey(record);
if (!orphanIdleWork.has(key)) orphanIdleWork.set(key, beginIdleTrackedWork());
};
const DEFERRED_ORPHAN_CLEANUP_FAILURE_REASON = "acquire_rejected_teardown_failed";
// The in-process buffer alone loses an orphan on a restart. So the driver also
@@ -1345,6 +1356,7 @@ function createSandboxEnvironmentDriver(
// Add one orphan record to the in-process buffer. Report `false` only when the
// buffer is full, so the caller keeps the error log as the last durable handle.
const enqueueDeferredOrphanCleanup = (record: DeferredOrphanCleanupRecord): boolean => {
trackOrphanIdleWork(record);
// Dedup by the provider lease id, so a repeated failure for the same orphan
// never buffers it twice. Each acquire mints a unique provider lease id, so
// two distinct orphans never collide. Skip the dedup for a null lease id,
@@ -1406,6 +1418,9 @@ function createSandboxEnvironmentDriver(
// leaves the spooled copy for a later flush, which re-inserts a duplicate
// the idempotent teardown handles. This order never loses the orphan.
await orphanCleanupSpool.remove(record);
const idleKey = orphanIdleKey(record);
orphanIdleWork.get(idleKey)?.();
orphanIdleWork.delete(idleKey);
recovered += 1;
} catch {
// The database is still down. Re-queue the record for a later flush,
@@ -1544,6 +1559,7 @@ function createSandboxEnvironmentDriver(
cause: unknown,
cleanupWriteError: unknown,
): Promise<never> => {
trackOrphanIdleWork(record);
const persisted = await orphanCleanupSpool.append(record);
const buffered = enqueueDeferredOrphanCleanup(record);
logger.error(
+5 -55
View File
@@ -677,6 +677,7 @@ import {
} from "./effective-run-config-fingerprints.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import { serverVersion } from "../version.js";
import { computeTaskDrain, applyTaskDrain, startTaskDrain, stopTaskDrain, readTaskDrain } from "./task-admission.js";
const MAX_LIVE_LOG_CHUNK_BYTES = 8 * 1024;
@@ -1352,61 +1353,8 @@ const nativeSessionResumeDispatchTimers = new Map<
string,
ReturnType<typeof setTimeout>
>();
// Task drain: an operator-controlled hold on new run admission, so a caller
// can wait for active work to finish before it stops the process. The state
// lives in process memory only — a process restart clears it — and it sits at
// module scope like activeRunExecutions above, so both the pure
// resolveHeartbeatSchedulingSuppression() check and every heartbeatService()
// instance see the same drain.
let taskDrainState: { startedAt: Date; expiresAt: Date | null } | null = null;
function readTaskDrain(
now: Date,
): { startedAt: Date; expiresAt: Date | null } | null {
if (
taskDrainState &&
taskDrainState.expiresAt !== null &&
taskDrainState.expiresAt.getTime() <= now.getTime()
) {
taskDrainState = null;
}
return taskDrainState;
}
/** Compute the drain a start call would apply, without changing state. */
export function computeTaskDrain(opts: { ttlMs?: number | null } = {}): {
startedAt: Date;
expiresAt: Date | null;
} {
const startedAt = new Date();
const ttlMs = opts.ttlMs ?? null;
const expiresAt =
ttlMs === null ? null : new Date(startedAt.getTime() + ttlMs);
return { startedAt, expiresAt };
}
/** Assign the given drain as the current task-drain state. */
export function applyTaskDrain(drain: {
startedAt: Date;
expiresAt: Date | null;
}): void {
taskDrainState = drain;
}
export function startTaskDrain(opts: { ttlMs?: number | null } = {}): {
startedAt: Date;
expiresAt: Date | null;
} {
const drain = computeTaskDrain(opts);
applyTaskDrain(drain);
return drain;
}
export function stopTaskDrain(): { wasActive: boolean } {
const wasActive = readTaskDrain(new Date()) !== null;
taskDrainState = null;
return { wasActive };
}
// Shared with HTTP admission so an idle hold fences work before inspection.
export { computeTaskDrain, applyTaskDrain, startTaskDrain, stopTaskDrain } from "./task-admission.js";
/**
* Report the task-drain state for this process only. `activeRuns` and
@@ -1421,11 +1369,13 @@ export function getTaskDrainStatus(): {
activeRuns: number;
pendingWakes: number;
quiescent: boolean;
ownerId?: string;
} {
const state = readTaskDrain(new Date());
const activeRuns = activeRunExecutionPromises.size;
const pendingWakes = activeWakeupPromises.size;
return {
...(state?.ownerId ? { ownerId: state.ownerId } : {}),
draining: state !== null,
startedAt: state?.startedAt ?? null,
expiresAt: state?.expiresAt ?? null,
+43
View File
@@ -0,0 +1,43 @@
import { promises as fs } from "node:fs";
import path from "node:path";
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
import { idleWorkSnapshot } from "./task-admission.js";
export type IdleLocalWork = "none" | "present" | "unknown";
const spoolDirectories = new Set<string>();
export function registerIdleSpoolDirectory(directory: string): void { spoolDirectories.add(path.resolve(directory)); }
export const idleAccountingSpoolPath = () => path.join(resolvePaperclipInstanceRoot(), "accounting-receipts");
export const idleOrphanSpoolPath = () => process.env.SANDBOX_ORPHAN_CLEANUP_SPOOL_DIR ??
path.join(resolvePaperclipInstanceRoot(), "data", "sandbox-orphan-cleanup");
let startupComplete = false;
let ingressTracked = false;
let scheduledBackups = false;
export function markIdleIngressTracked() { ingressTracked = true; }
export function markIdleStartupComplete(options: { scheduledBackups: boolean }) {
scheduledBackups = options.scheduledBackups;
startupComplete = true;
}
/** Any entry, including malformed JSON, a temp file or a failed probe, is
* evidence to retain. Recovery readers intentionally skip some such files;
* they cannot certify that stopping the process is safe. */
export async function inspectIdleSpool(directory: string): Promise<IdleLocalWork> {
try {
const info = await fs.lstat(directory);
if (!info.isDirectory() || info.isSymbolicLink()) return "unknown";
const dir = await fs.opendir(directory);
try { return (await dir.read()) === null ? "none" : "present"; }
finally { await dir.close(); }
} catch (error) {
return (error as NodeJS.ErrnoException).code === "ENOENT" ? "none" : "unknown";
}
}
export async function readIdleLocalWork(): Promise<IdleLocalWork> {
if (!startupComplete || !ingressTracked) return "unknown";
if (scheduledBackups || idleWorkSnapshot().active !== 0) return "present";
const directories = new Set([...spoolDirectories, idleAccountingSpoolPath(), idleOrphanSpoolPath()]);
const results = await Promise.all([...directories].map(inspectIdleSpool));
if (results.includes("unknown")) return "unknown";
return results.includes("present") ? "present" : "none";
}
+125
View File
@@ -0,0 +1,125 @@
import { idleWorkSnapshot } from "./task-admission.js";
import { readIdleLocalWork, type IdleLocalWork } from "./idle-local-work.js";
import type { Db } from "@paperclipai/db";
import { sql } from "drizzle-orm";
export interface IdleSleepDrainStatus {
ownerId?: string;
draining: boolean;
startedAt: Date | null;
expiresAt: Date | null;
activeRuns: number;
pendingWakes: number;
}
export interface IdleSleepSafety {
version: 1;
backgroundWork: "none" | "present" | "unknown";
}
// These are deliberately conservative. Completed agent runs and workspace
// operations are history, not reasons to keep an otherwise idle instance up.
// Other background features remain awake until their work and inbound events
// have a durable wake path. In particular, an empty in-memory run set is not
// evidence that a restarted process has no persisted work to recover.
const WORK_CHECKS = [
`SELECT 1 FROM agents WHERE status = 'running' OR
(status NOT IN ('terminated', 'paused', 'pending_approval') AND
runtime_config->'heartbeat'->>'enabled' = 'true' AND
COALESCE((runtime_config->'heartbeat'->>'intervalSec')::numeric, 0) > 0)`,
`SELECT 1 FROM heartbeat_runs WHERE
status NOT IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted')
OR scheduled_retry_at IS NOT NULL OR cost_accounting_pending`,
`SELECT 1 FROM agent_instruction_working_copies WHERE
state NOT IN ('saved', 'unchanged', 'resolved', 'unavailable', 'conflict')
OR process_stopped_at IS NULL OR next_attempt_at IS NOT NULL
OR receipt ? 'baseline' OR receipt->>'cleanupPending' = 'true'`,
`SELECT 1 FROM budget_reservations WHERE state NOT IN ('settled', 'released')`,
// Persistent machine credentials can receive work without a human opening
// the instance. They need an ingress wake contract before we can sleep.
`SELECT 1 FROM agent_api_keys WHERE revoked_at IS NULL`,
`SELECT 1 FROM board_api_keys WHERE revoked_at IS NULL
AND (expires_at IS NULL OR expires_at > now())`,
`SELECT 1 FROM agent_wakeup_requests WHERE
status NOT IN ('completed', 'failed', 'cancelled', 'skipped', 'timed_out')`,
`SELECT 1 FROM issues WHERE status NOT IN ('done', 'cancelled')`,
// A completed issue can still need its first watchdog review, including a
// retry after immediate evaluation failed before creating a review/run.
`SELECT 1 FROM issue_watchdogs WHERE status <> 'disabled'`,
`SELECT 1 FROM workspace_operations WHERE status NOT IN ('succeeded', 'failed', 'cancelled')`,
`SELECT 1 FROM environment_leases WHERE status NOT IN ('released', 'expired')`,
`SELECT 1 FROM routines WHERE status NOT IN ('paused', 'archived')`,
`SELECT 1 FROM routine_runs WHERE status NOT IN ('completed', 'failed', 'skipped', 'cancelled')`,
`SELECT 1 FROM plugin_jobs WHERE status <> 'paused'`,
`SELECT 1 FROM plugin_job_runs WHERE status NOT IN ('succeeded', 'failed', 'cancelled')`,
`SELECT 1 FROM plugin_webhook_deliveries WHERE status NOT IN ('succeeded', 'failed')`,
`SELECT 1 FROM tool_connections WHERE status <> 'archived'`,
`SELECT 1 FROM issue_recovery_actions WHERE status NOT IN ('resolved', 'cancelled')`,
`SELECT 1 FROM status_cards WHERE archived_at IS NULL`,
`SELECT 1 FROM external_objects WHERE NOT is_terminal OR next_refresh_at IS NOT NULL`,
// These less common work sources fail closed on any retained state. Their
// terminal-state exceptions can be added with tests for the owning service.
...[
"chat_endpoints", "chat_deliveries", "chat_publications", "chat_actions",
"chat_completion_deliveries", "connection_event_deliveries",
"connection_intent_deliveries", "tool_action_requests", "tool_action_deliveries",
"issue_question_response_deliveries", "workspace_runtime_services",
"execution_workspace_runtime_leases", "pipeline_automation_executions",
"native_run_finalizations", "company_transfer_runs", "decisions", "decision_effect_executions",
"decision_archive_notification_outbox", "browser_use_sessions", "browser_use_runs",
"browser_use_browsers", "environment_custom_image_setup_sessions", "feedback_exports",
"adapter_auth_sessions", "company_secret_proposals", "execution_workspaces",
"mcp_oauth_grants", "mcp_mutation_receipts", "mcp_event_subscriptions",
"mcp_event_deliveries", "mcp_attachment_uploads", "dot_agent_bindings",
"dot_runner_assignments", "dot_runner_operations", "dot_mailbox_items",
].map((table) => `SELECT 1 FROM ${table}`),
] as const;
function sameQuietHold(before: IdleSleepDrainStatus, after: IdleSleepDrainStatus, now: number): boolean {
return before.ownerId === after.ownerId && before.draining && after.draining && before.activeRuns === 0 && before.pendingWakes === 0
&& after.activeRuns === 0 && after.pendingWakes === 0
&& before.startedAt !== null && after.startedAt?.getTime() === before.startedAt.getTime()
&& (after.expiresAt === null || after.expiresAt.getTime() > now);
}
/** Inventory persisted work after the task-drain admission hold lands.
* Only a caller holding the exact idle owner may receive an empty report.
*/
export async function readIdleSleepSafety(
db: Db,
getDrainStatus: () => IdleSleepDrainStatus,
now: () => number = Date.now,
ownerId?: string,
inspectLocalWork: () => Promise<IdleLocalWork> = readIdleLocalWork,
): Promise<IdleSleepSafety> {
const unknown: IdleSleepSafety = { version: 1, backgroundWork: "unknown" };
const before = getDrainStatus();
const localBefore = idleWorkSnapshot();
if (!sameQuietHold(before, before, now())) return unknown;
try {
const blocked = await db.transaction(async (tx) => {
await tx.execute(sql`SET LOCAL statement_timeout = '5s'`);
const checks = WORK_CHECKS.map((query) => sql`EXISTS (${sql.raw(query)})`);
// Version labels and manifest declarations do not prove arbitrary worker
// code has no background activity. No plugin approvals are supported.
checks.push(sql`EXISTS (SELECT 1 FROM plugins WHERE status <> 'disabled')`);
const rows = await tx.execute<{ blocked: boolean }>(sql`SELECT ${sql.join(checks, sql` OR `)} AS blocked`);
return rows.length === 1 && typeof rows[0]?.blocked === "boolean" ? rows[0].blocked : undefined;
}, { isolationLevel: "repeatable read", accessMode: "read only" });
if (blocked === undefined || !sameQuietHold(before, getDrainStatus(), now())) return unknown;
if (blocked) return { version: 1, backgroundWork: "present" };
if (!ownerId || ownerId !== before.ownerId || before.expiresAt === null || localBefore.active !== 0) return unknown;
const local = await inspectLocalWork();
const after = getDrainStatus();
const localAfter = idleWorkSnapshot();
if (!sameQuietHold(before, after, now()) || localAfter.active !== 0 ||
localBefore.generation !== localAfter.generation) return unknown;
return { version: 1, backgroundWork: local };
} catch {
// Missing migrations, unknown state, malformed configuration, timeouts and
// database failures never authorize stopping the application. Do not leak
// SQL, configuration or tenant data through this control response.
return unknown;
}
}
@@ -1,7 +1,7 @@
import { promises as fs } from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
import { idleOrphanSpoolPath, registerIdleSpoolDirectory } from "./idle-local-work.js";
/**
* One orphan pending-cleanup record. The acquire builds it when the conditional
@@ -72,13 +72,6 @@ const RECORD_FILE_SUFFIX = ".json";
// without a torn write.
let tempFileCounter = 0;
function resolveDefaultSpoolDir(): string {
return (
process.env.SANDBOX_ORPHAN_CLEANUP_SPOOL_DIR ??
path.resolve(resolvePaperclipInstanceRoot(), "data", "sandbox-orphan-cleanup")
);
}
// Build the stable file name for one record. Key on the provider lease id, the
// value the teardown needs, so a repeated append for the same orphan reuses the
// same file. A null provider lease id carries no identity, so fall back to a
@@ -147,7 +140,8 @@ async function writeFileDurable(absPath: string, data: string): Promise<void> {
* directory for a test.
*/
export function createSandboxOrphanCleanupSpool(spoolDir?: string): SandboxOrphanCleanupSpool {
const dir = spoolDir ?? resolveDefaultSpoolDir();
const dir = spoolDir ?? idleOrphanSpoolPath();
registerIdleSpoolDirectory(dir);
return {
async append(record) {
+50
View File
@@ -0,0 +1,50 @@
import { randomUUID } from "node:crypto";
export type TaskDrainState = { startedAt: Date; expiresAt: Date | null; ownerId?: string };
let taskDrainState: TaskDrainState | null = null;
export function readTaskDrain(now: Date): TaskDrainState | null {
if (taskDrainState?.expiresAt && taskDrainState.expiresAt.getTime() <= now.getTime()) taskDrainState = null;
return taskDrainState;
}
export function computeTaskDrain(opts: { ttlMs?: number | null; purpose?: "idle" } = {}): TaskDrainState {
const startedAt = new Date();
return { startedAt, expiresAt: opts.ttlMs == null ? null : new Date(startedAt.getTime() + opts.ttlMs),
...(opts.purpose === "idle" ? { ownerId: randomUUID() } : {}) };
}
export function applyTaskDrain(drain: TaskDrainState): void { taskDrainState = drain; }
export function startTaskDrain(opts: { ttlMs?: number | null; purpose?: "idle" } = {}): TaskDrainState {
const drain = computeTaskDrain(opts);
applyTaskDrain(drain);
return drain;
}
export function stopTaskDrain(): { wasActive: boolean } {
const wasActive = readTaskDrain(new Date()) !== null;
taskDrainState = null;
return { wasActive };
}
export function isIdleTaskDrainActive(): boolean { return Boolean(readTaskDrain(new Date())?.ownerId); }
// Tokens count work until its actual promise settles, including after HTTP
// disconnects and after a cleanup batch has been removed from its input queue.
// The generation also catches work which starts AND finishes during a scan.
let generation = 0;
let active = 0;
export function beginIdleTrackedWork(): () => void {
generation++;
active++;
let finished = false;
return () => {
if (finished) return;
finished = true;
active--;
generation++;
};
}
export function trackIdleWork<T>(work: Promise<T>): Promise<T> {
const finish = beginIdleTrackedWork();
return work.finally(finish);
}
export function idleWorkSnapshot() { return { generation, active }; }
+14 -6
View File
@@ -1,3 +1,4 @@
import { beginIdleTrackedWork } from "./task-admission.js";
import { priceAnthropicReceipt } from "./anthropic-pricing.js";
import { priceCodexReceipt } from "./codex-pricing.js";
import { randomUUID } from "node:crypto";
@@ -8,7 +9,7 @@ import { and, eq, isNull, sql } from "drizzle-orm";
import { heartbeatRuns, runUsageReceipts, type Db } from "@paperclipai/db";
import type { AdapterExecutionResult, AdapterUsageCheckpoint } from "@paperclipai/adapter-utils";
import { pricingProvenanceSchema, usdToUnits } from "@paperclipai/shared";
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
import { idleAccountingSpoolPath, registerIdleSpoolDirectory } from "./idle-local-work.js";
import { conflict, notFound } from "../errors.js";
import { logger } from "../middleware/logger.js";
import { receiptFingerprint } from "./receipt-fingerprint.js";
@@ -37,9 +38,10 @@ const envelopeSchema = z.object({
adapterType: z.string().max(100), receipt: checkpointSchema,
});
export type UsageReceiptEnvelope = z.infer<typeof envelopeSchema>;
export const usageReceiptSpoolPath = () => path.join(resolvePaperclipInstanceRoot(), "accounting-receipts");
export const usageReceiptSpoolPath = idleAccountingSpoolPath;
export async function spoolUsageReceipt(envelope: UsageReceiptEnvelope, directory = usageReceiptSpoolPath()) {
registerIdleSpoolDirectory(directory);
const parsed = envelopeSchema.parse(envelope);
await ensureDurableDirectory(directory);
const target = path.join(directory, `${parsed.id}.json`);
@@ -185,6 +187,7 @@ export async function recoverPendingRunUsageReceipts(db: Db, input: { companyId:
}
export async function createRunUsageRecorder(db: Db, input: { companyId: string; runId: string; adapterType: string }, directory = usageReceiptSpoolPath()) {
registerIdleSpoolDirectory(directory);
const sourceId = randomUUID();
// Verify durable storage before starting paid work, including a directory
// sync. The database binding fences checkpoints from replaced controllers.
@@ -211,26 +214,31 @@ export async function createRunUsageRecorder(db: Db, input: { companyId: string;
}
let chain = Promise.resolve();
let captureFailed = bound[0].usageJson?.accountingCaptureFailed === true;
let finishFailedCapture: (() => void) | undefined;
async function persistFailure() {
if (!captureFailed) return;
await withAccountingTransaction(db, input.companyId, async tx => {
await tx.update(heartbeatRuns).set({
const persisted = await withAccountingTransaction(db, input.companyId, async tx => {
const rows = await tx.update(heartbeatRuns).set({
costAccountingPending: true, accountingLastError: "usage_capture_failed",
usageJson: sql`coalesce(${heartbeatRuns.usageJson}, '{}'::jsonb) || '{"accountingCaptureFailed":true,"accountingReceiptReady":false}'::jsonb`,
}).where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId),
isNull(heartbeatRuns.costAccountedAt), sql`${heartbeatRuns.usageJson}->>'accountingReceiptSourceId' = ${sourceId}`));
isNull(heartbeatRuns.costAccountedAt), sql`${heartbeatRuns.usageJson}->>'accountingReceiptSourceId' = ${sourceId}`)).returning({ id: heartbeatRuns.id });
return rows.length === 1;
});
if (persisted) { finishFailedCapture?.(); finishFailedCapture = undefined; }
}
function enqueue(action: () => Promise<AdapterUsageCheckpoint>) {
const finishQueuedCapture = beginIdleTrackedWork();
const result = chain.then(action).catch(async error => {
captureFailed = true;
finishFailedCapture ??= beginIdleTrackedWork();
// Persist before exposing rejection: the adapter's flush may throw before
// complete(), and failure finalization must not settle an older receipt.
try { await persistFailure(); }
catch (failure) { logger.error({ err: failure, runId: input.runId }, "Usage capture failure fence requires retry before finalization"); }
throw error;
});
chain = result.then(() => undefined, () => undefined);
chain = result.then(() => undefined, () => undefined).finally(finishQueuedCapture);
return result;
}
async function capture(raw: AdapterUsageCheckpoint) {