diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 12e7848e60a..77562d0644d 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -598,6 +598,21 @@ The **Retry now** action returns `waiting` with the saved retry schedule while cleanup holds ownership. Its controls show the wait without claiming that a run started, and another click can check the gate again. +For legacy local runs, physical cleanup and cost settlement have separate receipts. +The owning controller can record verified process cleanup while usage is incomplete. +The accounting worker then records an honest lower bound or an unpriced charge; +missing usage does not prove zero cost. The run status and saved retry intent stay +unchanged. A later usage receipt can still reconcile the same charge. + +If the controller stops before it saves the cleanup receipt, an authorized board +member can retry that run through the existing company-scoped cost-accounting +Retry endpoint. It checks the saved controller and child identities, local +ownership, and environment cleanup before it records physical closure. A live +process, an unknown identity, a foreign host, or pending cleanup keeps the hold. +A repeated request or a lost HTTP response must not add a second charge. This +action settles accounting; it does not start a provider turn or authorize task +replay. + A human comment may supersede a retry only while it remains `scheduled_retry`. Queued and running retries retain their execution and receive the comment through normal wake coalescing. Supersession rechecks the scheduled status atomically with diff --git a/server/src/routes/costs.ts b/server/src/routes/costs.ts index 4c5ff6d7479..f43ae6e1a0a 100644 --- a/server/src/routes/costs.ts +++ b/server/src/routes/costs.ts @@ -108,7 +108,7 @@ export function costRoutes( const actor = costReaderActor(req, companyId); if (!(await assertCompanyCostReadAllowed(req, res, companyId))) return; if (actor.readOnly) throw forbidden("Viewers cannot retry cost recording"); - res.json(await accountingIntegrityService(db, budgetHooks).retry(companyId, req.body.runId, actor.userId)); + res.json(await accountingIntegrityService(db, budgetHooks, heartbeat.recoverLegacyAccountingReceipt).retry(companyId, req.body.runId, actor.userId)); }); router.get("/companies/:companyId/costs/subscriptions", async (req, res) => { @@ -437,7 +437,7 @@ export function costRoutes( res.json(await agents.getById(agentId)); }); - const integrity = accountingIntegrityService(db, budgetHooks); + const integrity = accountingIntegrityService(db, budgetHooks, heartbeat.recoverLegacyAccountingReceipt); const billing = billingReconciliationService(db, budgetHooks); // Operational accounting evidence and repairs are board-only. These payloads // can contain company-wide billing identifiers even for an agent's own run. diff --git a/server/src/services/accounting-integrity.ts b/server/src/services/accounting-integrity.ts index cc54a4e5a9f..0ef03391b6f 100644 --- a/server/src/services/accounting-integrity.ts +++ b/server/src/services/accounting-integrity.ts @@ -6,6 +6,7 @@ import { receiptFingerprint } from "./receipt-fingerprint.js"; import { withAccountingReadSnapshot, withOperationAccountingTransaction } from "./accounting-transaction.js"; import { logActivity } from "./activity-log.js"; import { accountRunCost } from "./run-cost-accounting.js"; +import { recoverLegacyProcessSettlement } from "./heartbeat/legacy-process-settlement.js"; import type { BudgetServiceHooks } from "./budgets.js"; /** Independent aggregation: deliberately does not reuse writer projections. */ @@ -57,7 +58,8 @@ async function inspect(tx: Db, companyId: string): Promise return { companyId, findings, fingerprint: receiptFingerprint({ companyId, findings }), checkedAt: new Date().toISOString() }; } -export function accountingIntegrityService(db: Db, hooks: BudgetServiceHooks = {}) { +export function accountingIntegrityService(db: Db, hooks: BudgetServiceHooks = {}, + recoverLegacyReceipt = (companyId: string, runId: string) => recoverLegacyProcessSettlement(db, companyId, runId)) { return { inspect: (companyId: string) => withAccountingReadSnapshot(db, companyId, tx => inspect(tx, companyId)), repair: (companyId: string, fingerprint: string, reason: string, actorId: string) => withOperationAccountingTransaction(db, companyId, async (tx, publications) => { @@ -74,7 +76,10 @@ export function accountingIntegrityService(db: Db, hooks: BudgetServiceHooks = { const [run] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId))); if (!run) throw notFound("Accounting run not found"); await logActivity(db, { companyId, actorType: "user", actorId, action: "accounting.retry_requested", entityType: "heartbeat_run", entityId: runId }); - try { return { accounted: await accountRunCost(db, runId, hooks) }; } + try { + await recoverLegacyReceipt(companyId, runId); + return { accounted: await accountRunCost(db, runId, hooks) }; + } catch (error) { await db.update(heartbeatRuns).set({ accountingLastAttemptAt: new Date(), accountingAttemptCount: sql`${heartbeatRuns.accountingAttemptCount} + 1`, accountingLastError: error instanceof Error ? error.message.slice(0,1000) : "Accounting retry failed", diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 65578e0ac47..d1c6a1e1c94 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -40,7 +40,7 @@ import { promptInjectionPreventionService } from "./prompt-injection-prevention. import { createHeartbeatAgentStatus } from "./heartbeat/agent-status.js"; import { heartbeatExternalProvider, nativeRuntimeHasInstructionFilesystem } from "./heartbeat/external-provider.js"; import { pendingCaseHandoffForRun, recordCaseHandoffExecutionReleased, recordLegacyCaseHandoffCleanupIntent, recordLegacyCaseHandoffCleanupVerified } from "./heartbeat/case-handoff-lifecycle.js"; -import { recordLegacyPreparationSettlement, recordLegacyProcessSettlement } from "./heartbeat/legacy-process-settlement.js"; +import { recordLegacyPreparationSettlement, recordLegacyProcessSettlement, recoverLegacyProcessSettlement } from "./heartbeat/legacy-process-settlement.js"; import { hasStoppedLocalProcessTree, legacyAdapterNeedsLocalProcessSettlement } from "./heartbeat/process-settlement.js"; import { dotRunnerBroker } from "./dot-runner-broker.js"; import { withRunExecutionTiming, measureRunPhase, measureWorkspaceSyncPhase, isWorkspaceSyncDetailPhase } from "./execution-preparation-timing.js"; @@ -1015,6 +1015,10 @@ export function heartbeatService( const budgetHooks = { cancelWorkForScope: cancelBudgetScopeWork, }; + const recoverLegacyAccountingReceipt = (companyId: string, runId: string) => + recoverLegacyProcessSettlement(db, companyId, runId, id => + !activeRunExecutions.has(id) && !runningProcesses.has(id) && !adapterExecutionControls.has(id) + && !processRunCancellationSettlements.has(id) && !failedProcessRunCancellations.has(id)); const reconcileCostAccounting = createCostAccountingReconciler(db, budgetHooks, async () => { const outcomes = await Promise.allSettled([ decisionModelService(db, { budgetHooks }).recoverInterrupted(), @@ -4424,6 +4428,7 @@ export function heartbeatService( } return { + recoverLegacyAccountingReceipt, stopInvocationsForAgents, waitForRunExecutionDrain: async ( runId: string, diff --git a/server/src/services/heartbeat/legacy-process-settlement.test.ts b/server/src/services/heartbeat/legacy-process-settlement.test.ts index 9c2d9ff334b..a843e629932 100644 --- a/server/src/services/heartbeat/legacy-process-settlement.test.ts +++ b/server/src/services/heartbeat/legacy-process-settlement.test.ts @@ -2,8 +2,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import type { Db } from "@paperclipai/db"; import { legacyControllerBootId, legacyControllerClaim } from "../legacy-controller-lease.js"; import { legacySourceProcessSettled, recordLegacyProcessSettlement, type LegacyProcessSettlementSource } from "./legacy-process-settlement.js"; -const { pendingCleanup } = vi.hoisted(() => ({ pendingCleanup: vi.fn() })); +const { pendingCleanup, notifyAccounting } = vi.hoisted(() => ({ pendingCleanup: vi.fn(), notifyAccounting: vi.fn() })); vi.mock("../execution-blocker.js", () => ({ hasPendingRunCleanup: pendingCleanup })); +vi.mock("../delivery-work-notifications.js", () => ({ DELIVERY_QUEUES: { accounting: "accounting" }, notifyDeliveryWork: notifyAccounting })); const startedAt = new Date("2099-01-01T00:00:00Z"), finishedAt = new Date("2099-01-01T00:00:01Z"); function source() { return { id: "run", companyId: "company", agentId: "agent", runtimeMode: "legacy", status: "failed", @@ -23,7 +24,7 @@ function database(row: LegacyProcessSettlementSource | null, failure?: Error) { return { db, update }; } describe("host-owned legacy process settlement", () => { - beforeEach(() => { pendingCleanup.mockReset(); pendingCleanup.mockResolvedValue(false); }); + beforeEach(() => { pendingCleanup.mockReset(); pendingCleanup.mockResolvedValue(false); notifyAccounting.mockReset(); }); it("binds every receipt field to the exact retained local process identity", () => { const run = source(); expect(legacySourceProcessSettled(run)).toBe(true); for (const [key, value] of Object.entries(run.legacyProcessSettlement!)) { @@ -58,6 +59,13 @@ describe("host-owned legacy process settlement", () => { expect(held.update).not.toHaveBeenCalled(); expect(await recordLegacyProcessSettlement(database(null).db, run, () => true)).toBe(false); }); + it("does not publish after the normal work-intent await loses the current owner", async () => { + const run = source(), saved = database(run); let owned = true; + notifyAccounting.mockImplementation(async () => { owned = false; }); + expect(await recordLegacyProcessSettlement(saved.db, run, () => owned)).toBe(false); + expect(notifyAccounting).toHaveBeenCalledOnce(); + expect(saved.update).not.toHaveBeenCalled(); + }); it("clears a prior receipt on the normal legacy claim", () => { expect(legacyControllerClaim("legacy")).toMatchObject({ legacyProcessSettlement: null }); }); diff --git a/server/src/services/heartbeat/legacy-process-settlement.ts b/server/src/services/heartbeat/legacy-process-settlement.ts index 0c1e155f13c..b400f454b91 100644 --- a/server/src/services/heartbeat/legacy-process-settlement.ts +++ b/server/src/services/heartbeat/legacy-process-settlement.ts @@ -1,7 +1,10 @@ -import { and, eq, inArray, isNull, sql } from "drizzle-orm"; -import { heartbeatRuns, type Db } from "@paperclipai/db"; +import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm"; +import { environmentLeases, heartbeatRuns, type Db } from "@paperclipai/db"; import { hasPendingRunCleanup } from "../execution-blocker.js"; -import { legacyControllerBootId } from "../legacy-controller-lease.js"; +import { finishedLegacyControllerOwnerStamp, legacyControllerBootId } from "../legacy-controller-lease.js"; +import { currentProcessProbe, proveOwnerGone } from "../owner-proof.js"; +import { proveRunProcessGone } from "../run-process-owner.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "../delivery-work-notifications.js"; const schema = "paperclip.legacy-process-settlement.v1"; const statuses = ["failed", "timed_out", "interrupted"]; @@ -81,10 +84,11 @@ export async function recordLegacyProcessSettlement(db: Db, observed: LegacyProc eq(heartbeatRuns.processPid, observed.processPid!), eq(heartbeatRuns.processGroupId, observed.processGroupId!), eq(heartbeatRuns.processStartedAt, observed.processStartedAt!), isNull(heartbeatRuns.nativeIssueId), isNull(heartbeatRuns.nativeSessionId), isNull(heartbeatRuns.executionControlDeadlineAt), - eq(heartbeatRuns.costAccountingPending, false), sql`NOT COALESCE(${heartbeatRuns.resultJson} ?| ARRAY['startupCancellation','cancellation','executionCancellation','nativeCancellation'], false)`, )).for("update"); if (!current || !canCommit() || await hasPendingRunCleanup(tx, current.companyId, current.id) || !canCommit()) return false; + await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, current.companyId); + if (!canCommit()) return false; const updated = await tx.update(heartbeatRuns).set({ legacyProcessSettlement: receipt(current) }) .where(and(eq(heartbeatRuns.id, current.id), eq(heartbeatRuns.companyId, current.companyId))) .returning({ id: heartbeatRuns.id }); @@ -122,3 +126,65 @@ export async function recordLegacyPreparationSettlement(db: Db, observed: Legacy return updated.length === 1; }); } + +export async function recoverLegacyProcessSettlement(db: Db, companyId: string, runId: string, + currentBootIdle?: (runId: string) => boolean): Promise { + const readLeases = (tx: Db, lock = false) => { + const query = tx.select().from(environmentLeases).where(and( + eq(environmentLeases.companyId, companyId), eq(environmentLeases.heartbeatRunId, runId), + )).orderBy(asc(environmentLeases.id)); + return lock ? query.for('update', { skipLocked: true }) : query; + }; + const [observed] = await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId), + eq(heartbeatRuns.runtimeMode, 'legacy'), eq(heartbeatRuns.costAccountingPending, true), + isNull(heartbeatRuns.costAccountedAt), + sql`${heartbeatRuns.usageJson}->>'accountingReceiptReady' = 'false'`, + )).limit(1); + if (!observed || !observed.costAccountingPending || observed.costAccountedAt + || observed.usageJson?.accountingReceiptReady !== false || observed.usageJson?.accountingCaptureFailed === true + || observed.usageJson?.accountingProviderWorkStarted === false + || (observed.resultJson?.executionRecovery as Record | undefined)?.providerWorkStarted === false + || !identityIsComplete(observed) || observed.nativeIssueId || observed.nativeSessionId + || observed.executionControlDeadlineAt + || observed.scheduledRetryAt && observed.scheduledRetryAt > observed.finishedAt! + || ['startupCancellation','cancellation','executionCancellation','nativeCancellation'] + .some(key => observed.resultJson && Object.hasOwn(observed.resultJson, key))) return false; + if (matchesReceipt(observed.legacyProcessSettlement, receipt(observed))) return true; + if (observed.legacyProcessSettlement !== null) return false; + const leases = await readLeases(db); + if (leases.length === 0 || leases.some(lease => lease.provider !== 'local' || lease.providerLeaseId !== null + || lease.metadata?.driver !== 'local' || !lease.releasedAt + || !['released','expired','failed'].includes(lease.status))) return false; + const owner = finishedLegacyControllerOwnerStamp(observed); + if (!owner?.processStartedAt) return false; + const probe = { ...currentProcessProbe(), readOnly: true }; + if (probe.processSpace === 'unknown' || observed.processHostHash !== probe.processSpace + || owner.processSpace !== probe.processSpace) return false; + const sameBoot = observed.controllerBootId === legacyControllerBootId; + const locallyIdle = () => currentBootIdle ? currentBootIdle(runId) : !sameBoot; + if (!locallyIdle()) return false; + const controller = await proveOwnerGone(owner, probe); + if (!(controller.verdict === 'gone' + || sameBoot && controller.verdict === 'alive' && controller.reason === 'current_process' + && locallyIdle())) return false; + const child = await proveRunProcessGone(observed, 'legacy_accounting_receipt', probe); + if (child?.verdict !== 'gone') return false; + return db.transaction(async transaction => { + const tx = transaction as unknown as Db; + const [current] = await tx.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId), + )).for('update'); + if (!current || JSON.stringify(current) !== JSON.stringify(observed) + || JSON.stringify(await readLeases(tx, true)) !== JSON.stringify(leases) + || !locallyIdle() + || await hasPendingRunCleanup(tx, companyId, runId) + || !locallyIdle()) return false; + await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, companyId); + if (!locallyIdle()) return false; + const updated = await tx.update(heartbeatRuns).set({ legacyProcessSettlement: receipt(current) }) + .where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId))) + .returning({ id: heartbeatRuns.id }); + return updated.length === 1; + }); +} diff --git a/server/src/services/hot-restart.ts b/server/src/services/hot-restart.ts index 1d8e7adfb0f..f19a8232043 100644 --- a/server/src/services/hot-restart.ts +++ b/server/src/services/hot-restart.ts @@ -1,7 +1,7 @@ import { execFile } from "node:child_process"; import fs from "node:fs/promises"; import path from "node:path"; -import { readLinuxProcessStartedAt, type LinuxProcessStartOptions } from "../vendor/paperclip-runner/index.js"; +import type { LinuxProcessStartOptions } from "../vendor/paperclip-runner/index.js"; import { resolvePaperclipHomeDir, resolvePaperclipInstanceId, @@ -186,6 +186,7 @@ export async function readProcessStartedAt( const runCommand = options.runCommand ?? runProcessCommand; if (platform === "linux") { + const { readLinuxProcessStartedAt } = await import("../vendor/paperclip-runner/index.js"); return readLinuxProcessStartedAt(pid, options.linuxProcessStart); } diff --git a/server/src/services/run-cost-accounting.test.ts b/server/src/services/run-cost-accounting.test.ts index 29800c24559..f6b19147456 100644 --- a/server/src/services/run-cost-accounting.test.ts +++ b/server/src/services/run-cost-accounting.test.ts @@ -1,25 +1,44 @@ import { randomUUID } from "node:crypto"; +import { databaseWorkPending, reconcileDatabaseWork } from "@paperclipai/db/work-signals"; import { promises as fs } from "node:fs"; import os from "node:os"; import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { runChildProcess } from "../adapters/utils.js"; +import { currentControllerProcessStamp, currentProcessStartedAtMs, type ControllerProcess } from "./controller-process-identity.js"; +import { currentProcessProbe } from "./owner-proof.js"; +import { proveRunProcessGone } from "./run-process-owner.js"; import { and, eq, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; -import { agents, budgetEvaluationWork, budgetPolicies, companies, costEvents, costAdjustments, createDb, heartbeatRuns, projects, promptInjectionInvocations, runUsageReceipts, type Db } from "@paperclipai/db"; +import { agents, applyPendingMigrations, closeRegisteredClients, environmentLeases, budgetReservations, budgetEvaluationWork, budgetPolicies, companies, costEvents, costAdjustments, createDb, heartbeatRuns, projects, promptInjectionInvocations, runUsageReceipts, type Db } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "../__tests__/helpers/external-test-database.js"; import { accountRunCost, createCostAccountingReconciler, readCostAccountingWork } from "./run-cost-accounting.js"; import { createRunUsageRecorder, persistUsageReceipt, type UsageReceiptEnvelope } from "./usage-receipts.js"; import * as usageReceipts from "./usage-receipts.js"; +import * as budgetTracing from "./budget-tracing.js"; import { billingReconciliationService } from "./billing-reconciliation.js"; import { accountingIntegrityService } from "./accounting-integrity.js"; +import { legacyControllerBootId } from "./legacy-controller-lease.js"; +import { recordLegacyProcessSettlement } from "./heartbeat/legacy-process-settlement.js"; +import { DELIVERY_QUEUES, subscribeDeliveryWork } from "./delivery-work-notifications.js"; -const support = await getEmbeddedPostgresTestSupport(); +const external = resolveExternalTestDatabaseUrl("PAPERCLIP_ACCOUNTING_TEST_DATABASE_URL"); +if (external && process.env.PAPERCLIP_TEST_POSTGRES_ADMIN_URL?.trim()) await getEmbeddedPostgresTestSupport(); +const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); (support.supported ? describe : describe.skip)("run cost accounting work", () => { let database: Awaited>; let db: Db; let directory: string; + let fixtureCompanySequence = 0; beforeAll(async () => { - database = await startEmbeddedPostgresTestDatabase("run-cost-work-"); - db = createDb(database.connectionString); + if (external) { + await applyPendingMigrations(external); + database = { connectionString: external, cleanup: () => closeRegisteredClients(external, { scope: "database" }) }; + } else { + database = await startEmbeddedPostgresTestDatabase("run-cost-work-"); + } + db = createDb(database.connectionString, external ? { maxConnections: 2 } : undefined); directory = await fs.mkdtemp(path.join(os.tmpdir(), "run-cost-work-")); }, 60_000); afterEach(async () => { await db.transaction(async tx => { @@ -30,7 +49,7 @@ const support = await getEmbeddedPostgresTestSupport(); async function seed(change: Partial = {}) { const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(); - await db.insert(companies).values({ id: companyId, name: "Accounting", issuePrefix: "ACCT" }); + await db.insert(companies).values({ id: companyId, name: "Accounting", issuePrefix: `ACCT${++fixtureCompanySequence}` }); await db.insert(agents).values({ id: agentId, companyId, name: "Accounting", role: "engineer", status: "idle", adapterType: "process" }); await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", status: "succeeded", costAccountingPending: true, finishedAt: new Date(), @@ -46,6 +65,272 @@ const support = await getEmbeddedPostgresTestSupport(); pricingProvenance: { source: "provider_reported", version: "test" } } }; } + async function stoppedLegacy() { + const sourceId = randomUUID(), processStartedAt = new Date(Date.now() - 1000), finishedAt = new Date(); + const owner = await seed({ runtimeMode: "legacy", status: "failed", errorCode: "codex_harness_crash", + controllerBootId: legacyControllerBootId, controllerLeaseExpiresAt: null, + processPid: 42, processGroupId: 42, processStartedAt, finishedAt, + usageJson: { accountingReceiptSourceId: sourceId, accountingReceiptSequence: 1, accountingReceiptReady: false, + provider: "openai", model: "test", billingType: "metered_api", costStatus: "unpriced" } }); + await db.update(agents).set({ adapterType: "codex_local" }).where(eq(agents.id, owner.agentId)); + await db.insert(budgetReservations).values({ companyId: owner.companyId, agentId: owner.agentId, + runId: owner.runId, amountCents: "0", state: "held", providerStartedAt: processStartedAt }); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, owner.runId)); + const proof = { schema: "paperclip.legacy-process-settlement.v1", runId: run.id, + companyId: run.companyId, agentId: run.agentId, runtimeMode: "legacy", targetKind: "local", + controllerBootId: run.controllerBootId, processPid: run.processPid, processGroupId: run.processGroupId, + processStartedAt: processStartedAt.toISOString(), finishedAt: finishedAt.toISOString(), status: "failed" }; + return { ...owner, sourceId, run, proof }; + } + + it("normal legacy accounting joins the host-owned process receipt before settling unknown crash usage", async () => { + const owner = await stoppedLegacy(); + expect(await accountRunCost(db, owner.runId)).toBe(false); + expect(await readCostAccountingWork(db, Date.now(), directory)).toEqual({ pending: false, nextRunAt: null }); + const wake = vi.fn(), unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.accounting, wake); + try { + expect(await recordLegacyProcessSettlement(db, owner.run, () => true)).toBe(true); + expect(wake).toHaveBeenCalledOnce(); + const [pending] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, owner.runId)); + expect(pending.costAccountingPending).toBe(true); + expect(pending.usageJson).toMatchObject({ accountingReceiptReady: false }); + expect(pending.legacyProcessSettlement).toEqual(owner.proof); + } finally { unsubscribe(); } + expect((await readCostAccountingWork(db, Date.now(), directory)).pending).toBe(true); + await createCostAccountingReconciler(db)(); + const [settled] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, owner.runId)); + expect(settled).toMatchObject({ status: "failed", errorCode: "codex_harness_crash", costAccountingPending: false, + costAccountedAt: expect.any(Date), usageJson: { accountingReceiptReady: false, accountingReceiptUnavailable: true } }); + expect(settled.usageJson?.accountingProviderWorkStarted).toBeUndefined(); + expect(settled.usageJson?.accountingClosureTimedOut).toBeUndefined(); + const [hold] = await db.select().from(budgetReservations).where(eq(budgetReservations.runId, owner.runId)); + expect(hold).toMatchObject({ state: "settled", settledAt: expect.any(Date) }); + const charges = await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, owner.runId)); + expect(charges).toHaveLength(1); expect(charges[0].costStatus).toBe("unpriced"); + const late = { ...receipt(owner, owner.sourceId, 2, 0.02), + receipt: { ...receipt(owner, owner.sourceId, 2, 0.02).receipt, provider: "openai", biller: "openai" } }; + await persistUsageReceipt(db, late); await persistUsageReceipt(db, late); + await createCostAccountingReconciler(db)(); + expect(await accountRunCost(db, owner.runId)).toBe(false); + const final = await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, owner.runId)); + expect(final).toHaveLength(2); + expect(final.reduce((sum, row) => sum + row.costCents, 0)).toBeCloseTo(2); + expect(final.filter(row => row.idempotencyKey === `heartbeat:${owner.runId}:late:${late.id}`)).toHaveLength(1); + const [after] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, owner.runId)); + expect(after.costAccountingPending).toBe(false); + + const rollbackOwner = await stoppedLegacy(); + const rollbackWake = vi.fn(), stopWatching = subscribeDeliveryWork(db, DELIVERY_QUEUES.accounting, rollbackWake); + try { + await expect(db.transaction(async tx => { + expect(await recordLegacyProcessSettlement(tx as unknown as Db, rollbackOwner.run, () => true)).toBe(true); + expect(rollbackWake).not.toHaveBeenCalled(); + throw new Error("controlled producer rollback"); + })).rejects.toThrow("controlled producer rollback"); + expect(rollbackWake).toHaveBeenCalledTimes(1); + expect(databaseWorkPending(db, DELIVERY_QUEUES.accounting)).toBe(true); + const [unpublished] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, rollbackOwner.runId)); + expect(unpublished.legacyProcessSettlement).toBeNull(); + expect(unpublished.costAccountingPending).toBe(true); + expect((await readCostAccountingWork(db, Date.now(), directory)).pending).toBe(false); + expect(rollbackWake).toHaveBeenCalledTimes(1); + await reconcileDatabaseWork(db, DELIVERY_QUEUES.accounting); + expect(databaseWorkPending(db, DELIVERY_QUEUES.accounting)).toBe(false); + expect(rollbackWake).toHaveBeenCalledTimes(2); + const beforeCommitWakeCount = rollbackWake.mock.calls.length; + expect(await recordLegacyProcessSettlement(db, rollbackOwner.run, () => true)).toBe(true); + expect(rollbackWake).toHaveBeenCalledTimes(beforeCommitWakeCount + 1); + } finally { stopWatching(); } + expect((await readCostAccountingWork(db, Date.now(), directory)).pending).toBe(true); + await createCostAccountingReconciler(db)(); + const [recovered] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, rollbackOwner.runId)); + expect(recovered.costAccountingPending).toBe(false); + }); + + it.skipIf(process.platform === "win32")("normal accounting Retry reconstructs an uncommitted legacy receipt after its real controller and child exited", async () => { + const identityModule = new URL('./controller-process-identity.ts', import.meta.url).href; + const loader = fileURLToPath(import.meta.resolve('tsx/esm')); + async function joinedIdentity() { + const command = `console.error("accounting-identity:program-entered"); const identity = await import(${JSON.stringify(identityModule)}); console.error("accounting-identity:module-imported"); await identity.currentProcessStartedAtMs(); console.error("accounting-identity:birth-read"); console.log(JSON.stringify(identity.currentControllerProcessStamp()));`; + let groupId: number | null = null; + let observedStderrChars = 0; + const result = await runChildProcess(randomUUID(), process.execPath, + ['--import', loader, '--input-type=module', '-e', command], { + cwd: process.cwd(), env: { NODE_OPTIONS: process.env.NODE_OPTIONS ?? '', PATH: process.env.PATH ?? '' }, + timeoutSec: 5, graceSec: 1, onLog: async (stream, chunk) => { + if (stream === "stderr" && observedStderrChars < 8192) { + const observed = chunk.slice(0, 8192 - observedStderrChars); + observedStderrChars += observed.length; + process.stderr.write(observed); + } + }, + onSpawn: async meta => { groupId = meta.processGroupId ?? null; }, + }); + expect(result.exitCode, JSON.stringify({ exitCode: result.exitCode, signal: result.signal, timedOut: result.timedOut, pid: result.pid, startedAt: result.startedAt, stdoutTail: result.stdout.slice(-8192), stderrTail: result.stderr.slice(-8192) })).toBe(0); + const identity = JSON.parse(result.stdout.trim()) as ControllerProcess; + expect(identity.processStartedAt).not.toBeNull(); + expect(Number.isSafeInteger(groupId) && groupId! > 1).toBe(true); + return { ...identity, groupId }; + } + const controller = await joinedIdentity(), child = await joinedIdentity(); + const owner = await stoppedLegacy(); + await db.update(heartbeatRuns).set({ controllerBootId: controller.bootId, controllerProcess: controller, + processPid: child.pid, processGroupId: child.groupId, processStartedAt: new Date(child.processStartedAt!), + processHostHash: child.hostHash, legacyProcessSettlement: null }) + .where(eq(heartbeatRuns.id, owner.runId)); + await db.insert(environmentLeases).values({ companyId: owner.companyId, heartbeatRunId: owner.runId, + provider: 'local', providerLeaseId: null, status: 'failed', leasePolicy: 'ephemeral', + releasedAt: new Date(), metadata: { driver: 'local' } }); + const [base] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, owner.runId)); + await currentProcessStartedAtMs(); + const liveController = currentControllerProcessStamp(); + const reused = await proveRunProcessGone(base, 'legacy-accounting-reuse-component', { + ...currentProcessProbe(), controllerInstance: undefined, + pidExists: () => true, processGroupExists: () => false, + readStartedAt: async () => new Date(Date.parse(child.processStartedAt!) + 2000), + }); + expect(reused).toEqual({ verdict: 'gone', reason: 'pid_reused' }); + for (const change of [ + { processHostHash: 'unknown-foreign-process-space' }, + { status: 'cancelled' }, + { controllerLeaseExpiresAt: new Date(Date.now() + 60_000) }, + { executionControlDeadlineAt: new Date() }, + { resultJson: { executionCancellation: { state: 'requested' } } }, + { controllerBootId: liveController.bootId, controllerProcess: liveController }, + ]) { + await db.update(heartbeatRuns).set({ ...base, ...change }).where(eq(heartbeatRuns.id, owner.runId)); + expect(await accountingIntegrityService(db).retry(owner.companyId, owner.runId, 'board')).toEqual({ accounted: false }); + const [held] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, owner.runId)); + expect(held.legacyProcessSettlement).toBeNull(); expect(held.costAccountingPending).toBe(true); + } + await db.update(heartbeatRuns).set(base).where(eq(heartbeatRuns.id, owner.runId)); + await db.update(environmentLeases).set({ status: 'active', releasedAt: null }) + .where(eq(environmentLeases.heartbeatRunId, owner.runId)); + expect(await accountingIntegrityService(db).retry(owner.companyId, owner.runId, 'board')).toEqual({ accounted: false }); + await db.update(environmentLeases).set({ status: 'failed', releasedAt: new Date() }) + .where(eq(environmentLeases.heartbeatRunId, owner.runId)); + await db.update(environmentLeases).set({ cleanupStatus: 'failed' }) + .where(eq(environmentLeases.heartbeatRunId, owner.runId)); + expect(await accountingIntegrityService(db).retry(owner.companyId, owner.runId, 'board')).toEqual({ accounted: false }); + await db.update(environmentLeases).set({ cleanupStatus: null }) + .where(eq(environmentLeases.heartbeatRunId, owner.runId)); + let leaseLocked!: () => void, releaseLease!: () => void; + const locked = new Promise(resolve => { leaseLocked = resolve; }); + const release = new Promise(resolve => { releaseLease = resolve; }); + const holder = db.transaction(async tx => { + await tx.select().from(environmentLeases).where(eq(environmentLeases.heartbeatRunId, owner.runId)).for('update'); + leaseLocked(); await release; + }); + await locked; + try { + expect(await accountingIntegrityService(db).retry(owner.companyId, owner.runId, 'board')).toEqual({ accounted: false }); + } finally { releaseLease(); await holder; } + const precommitLost = new Proxy(db, { get(target, property) { + if (property === 'transaction') return async (callback: Parameters[0], options?: Parameters[1]) => + target.transaction(async tx => { + await callback(tx); + throw new Error('controlled closure publication rollback'); + }, options); + const value = Reflect.get(target, property); + return typeof value === 'function' ? value.bind(target) : value; + } }) as Db; + await expect(accountingIntegrityService(precommitLost).retry(owner.companyId, owner.runId, 'board')) + .rejects.toThrow('controlled closure publication rollback'); + expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, owner.runId))).toEqual([]); + const [uncommitted] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, owner.runId)); + expect(uncommitted.legacyProcessSettlement).toBeNull(); + expect(uncommitted.costAccountingPending).toBe(true); + let lostReply = false; + const replyLost = new Proxy(db, { get(target, property) { + if (property === 'transaction') return async (...args: Parameters) => { + const result = await target.transaction(...args); + if (!lostReply) { lostReply = true; throw new Error('controlled committed reply loss'); } + return result; + }; + const value = Reflect.get(target, property); + return typeof value === 'function' ? value.bind(target) : value; + } }) as Db; + await expect(accountingIntegrityService(replyLost).retry(owner.companyId, owner.runId, 'board')) + .rejects.toThrow('controlled committed reply loss'); + const result = await accountingIntegrityService(db).retry(owner.companyId, owner.runId, 'board'); + expect(result.accounted).toBe(true); + const [settled] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, owner.runId)); + expect(settled.legacyProcessSettlement).toMatchObject({ controllerBootId: controller.bootId, + processPid: child.pid, processGroupId: child.groupId, schema: 'paperclip.legacy-process-settlement.v1' }); + expect(settled.usageJson).toMatchObject({ accountingReceiptReady: false, accountingReceiptUnavailable: true }); + expect(await accountingIntegrityService(db).retry(owner.companyId, owner.runId, 'board')).toEqual({ accounted: false }); + expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, owner.runId))).toHaveLength(1); + }); + + it("keeps missing malformed foreign live and controlled legacy closure evidence pending", async () => { + const owner = await stoppedLegacy(); + for (const bad of [null, {}, [], { ...owner.proof, extra: true }, { ...owner.proof, processPid: "42" }, + ...Object.keys(owner.proof).map(key => ({ ...owner.proof, [key]: "foreign" }))]) { + await db.update(heartbeatRuns).set({ legacyProcessSettlement: sql`${JSON.stringify(bad)}::jsonb` }).where(eq(heartbeatRuns.id, owner.runId)); + expect(await accountRunCost(db, owner.runId)).toBe(false); + expect((await readCostAccountingWork(db, Date.now(), directory)).pending).toBe(false); + } + for (const changed of [{ status: "running" }, { controllerLeaseExpiresAt: new Date(Date.now() + 1000) }, + { controllerBootId: randomUUID() }, { processPid: 43 }, { processGroupId: 43 }, + { processStartedAt: new Date(0) }, { processPid: null, processGroupId: null, processStartedAt: null }, + { runtimeMode: "native" }, { executionControlDeadlineAt: new Date() }, + { resultJson: { executionCancellation: { state: "requested" } } }]) { + await db.update(heartbeatRuns).set({ ...owner.run, legacyProcessSettlement: owner.proof, ...changed }) + .where(eq(heartbeatRuns.id, owner.runId)); + expect(await accountRunCost(db, owner.runId)).toBe(false); + } + expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, owner.runId))).toEqual([]); + }); + + it("preserves observed spend as a lower bound when the stopped legacy provider lost its final receipt", async () => { + const owner = await stoppedLegacy(); + await db.update(heartbeatRuns).set({ legacyProcessSettlement: owner.proof, + usageJson: { ...owner.run.usageJson, costUsd: 0.01, inputTokens: 5, outputTokens: 2, + budgetExposure: { sourceId: owner.sourceId, sequence: 1, costCents: "2.0000000" } } }) + .where(eq(heartbeatRuns.id, owner.runId)); + expect(await accountRunCost(db, owner.runId)).toBe(true); + const [charge] = await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, owner.runId)); + expect(charge).toMatchObject({ costCents: 2, inputTokens: 5, outputTokens: 2, costStatus: "estimated" }); + expect(charge.pricingProvenance?.evidence).toContain("lower bound"); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, owner.runId)); + expect(run.usageJson).toMatchObject({ accountingReceiptReady: false, accountingReceiptUnavailable: true }); + }); + + it("preserves included subscription cost policy while legacy usage remains explicitly incomplete", async () => { + const owner = await stoppedLegacy(); + await db.update(heartbeatRuns).set({ legacyProcessSettlement: owner.proof, + usageJson: { ...owner.run.usageJson, billingType: 'subscription_included', costUsd: null } }) + .where(eq(heartbeatRuns.id, owner.runId)); + expect(await accountRunCost(db, owner.runId)).toBe(true); + const [charge] = await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, owner.runId)); + expect(charge).toMatchObject({ billingType: 'subscription_included', costStatus: 'reported', costCents: 0 }); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, owner.runId)); + expect(run.usageJson).toMatchObject({ accountingReceiptReady: false, accountingReceiptUnavailable: true }); + }); + + it("revalidates exact legacy process receipt and claim after the accounting spool pre-read", async () => { + const owner = await stoppedLegacy(); + await db.update(heartbeatRuns).set({ legacyProcessSettlement: owner.proof }).where(eq(heartbeatRuns.id, owner.runId)); + let changed = false; + const replacementClaim = randomUUID(); + const observed = new Proxy(db, { get(target, property) { + if (property === "transaction") return async (...args: Parameters) => { + if (!changed) { changed = true; await db.update(heartbeatRuns).set({ + controllerBootId: replacementClaim, legacyProcessSettlement: { ...owner.proof, controllerBootId: replacementClaim }, + }).where(eq(heartbeatRuns.id, owner.runId)); } + return target.transaction(...args); + }; + const value = Reflect.get(target, property); + return typeof value === "function" ? value.bind(target) : value; + } }) as Db; + const race = await Promise.allSettled([accountRunCost(observed, owner.runId)]); + if (race[0].status === 'fulfilled') expect(race[0].value).toBe(false); + else expect(race[0].reason.message).toContain('closure changed'); + expect(await db.select().from(costEvents).where(eq(costEvents.heartbeatRunId, owner.runId))).toEqual([]); + const [pending] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, owner.runId)); + expect(pending.costAccountingPending).toBe(true); + }); + it("returns from settled or running calls without opening an accounting transaction", async () => { const { runId } = await seed({ costAccountingPending: false }); const transaction = vi.fn(db.transaction.bind(db)); @@ -76,22 +361,67 @@ const support = await getEmbeddedPostgresTestSupport(); const owner = await seed(); const [policy] = await db.insert(budgetPolicies).values({ companyId: owner.companyId, scopeType: "company", scopeId: owner.companyId, windowKind: "calendar_month_utc", amount: 100 }).returning(); + const began = performance.now(); + const observations: Record[] = []; + let droppedObservations = 0; + const observe = (event: string, detail: Record = {}) => { + if (observations.length < 128) observations.push({ event, elapsedMs: performance.now() - began, ...detail }); + else droppedObservations++; + }; + const previousDebug = db.$client.options.debug; + db.$client.options.debug = (connection, query, parameters, types) => { + const verb = query.trim().split(/\s+/, 1)[0]?.toLowerCase(); + observe("driver-query-built", { connection, operation: verb && ["select", "insert", "update", "delete", "begin", "commit", "rollback", "savepoint", "release"].includes(verb) ? verb : "other" }); + if (typeof previousDebug === "function") previousDebug(connection, query, parameters, types); + }; + const originalBudgetSpan = budgetTracing.withBudgetSpan; + const spanObserver = vi.spyOn(budgetTracing, "withBudgetSpan").mockImplementation( + (name: Parameters[0], work: () => Promise, attributes?: Parameters[2]) => { + observe("operation-entered", { name }); + const result = originalBudgetSpan(name, work, attributes); + void result.then(() => { observe("operation-fulfilled", { name }); }, () => { observe("operation-rejected", { name }); }); + return result; + }); let release!: () => void, locked!: () => void; const gate = new Promise(resolve => { release = resolve; }); const acquired = new Promise(resolve => { locked = resolve; }); - const holder = db.transaction(async tx => { - await tx.select({ id: companies.id }).from(companies).where(eq(companies.id, owner.companyId)).for("no key update"); - await tx.select({ id: agents.id }).from(agents).where(eq(agents.id, owner.agentId)).for("no key update"); - await tx.select({ id: budgetPolicies.id }).from(budgetPolicies).where(eq(budgetPolicies.id, policy.id)).for("update"); - locked(); - await gate; - }); - await acquired; - const settle = accountRunCost(db, owner.runId); let timer: ReturnType | undefined; + let holder: Promise | undefined; + let settle: Promise | undefined; try { - expect(await Promise.race([settle, new Promise(resolve => { timer = setTimeout(() => resolve("blocked"), 1500); })])).toBe(true); - } finally { if (timer) clearTimeout(timer); release(); await holder; await settle; } + observe("holder-requested"); + holder = db.transaction(async tx => { + observe("holder-transaction-entered"); + await tx.select({ id: companies.id }).from(companies).where(eq(companies.id, owner.companyId)).for("no key update"); + observe("holder-company-lock-acquired"); + await tx.select({ id: agents.id }).from(agents).where(eq(agents.id, owner.agentId)).for("no key update"); + observe("holder-agent-lock-acquired"); + await tx.select({ id: budgetPolicies.id }).from(budgetPolicies).where(eq(budgetPolicies.id, policy.id)).for("update"); + observe("holder-policy-lock-acquired"); + locked(); + await gate; + observe("holder-gate-released"); + }); + await acquired; + observe("settlement-requested"); + settle = accountRunCost(db, owner.runId); + const raceResult = await Promise.race([settle, new Promise(resolve => { timer = setTimeout(() => resolve("blocked"), 1500); })]); + observe("original-race-result", { result: raceResult }); + expect(raceResult).toBe(true); + observe("original-race-assertion-passed"); + } finally { + if (timer) clearTimeout(timer); + release(); + try { + if (holder) { await holder; observe("holder-transaction-fulfilled"); } + if (settle) { await settle; observe("settlement-promise-fulfilled"); } + } finally { + db.$client.options.debug = previousDebug; + spanObserver.mockRestore(); + console.error("accounting-held-writer-observation " + JSON.stringify({ observations, droppedObservations, + scope: "query-build-and-operation-completion; no query-result/SQL-wait proof; no SQL or parameters logged" })); + } + } }); it("settles another run of the same company and agent while one run is locked", async () => { diff --git a/server/src/services/run-cost-accounting.ts b/server/src/services/run-cost-accounting.ts index 3965daeb6a8..bbd5f090b10 100644 --- a/server/src/services/run-cost-accounting.ts +++ b/server/src/services/run-cost-accounting.ts @@ -42,6 +42,15 @@ async function readAccountingClosure(db: Db, runId: string) { coordinatorId: nativeRunFinalizations.runId, resultId: nativeRunFinalizations.resultId, phase: nativeRunFinalizations.phase, providerWorkNeverStarted: sql`(${nativeProviderWorkNeverStarted}) is true`, processPid: heartbeatRuns.processPid, processGroupId: heartbeatRuns.processGroupId, + legacyClosure: sql`case when ${heartbeatRuns.runtimeMode} = 'legacy' then + jsonb_build_object('receipt', ${heartbeatRuns.legacyProcessSettlement}, + 'runId', ${heartbeatRuns.id}, 'companyId', ${heartbeatRuns.companyId}, 'agentId', ${heartbeatRuns.agentId}, + 'controllerBootId', ${heartbeatRuns.controllerBootId}, 'controllerLeaseExpiresAt', ${heartbeatRuns.controllerLeaseExpiresAt}, + 'processPid', ${heartbeatRuns.processPid}, 'processGroupId', ${heartbeatRuns.processGroupId}, + 'processStartedAt', ${heartbeatRuns.processStartedAt}, 'finishedAt', ${heartbeatRuns.finishedAt}, + 'status', ${heartbeatRuns.status}, 'scheduledRetryAt', ${heartbeatRuns.scheduledRetryAt}, + 'nativeIssueId', ${heartbeatRuns.nativeIssueId}, 'nativeSessionId', ${heartbeatRuns.nativeSessionId}, + 'executionControlDeadlineAt', ${heartbeatRuns.executionControlDeadlineAt}, 'result', ${heartbeatRuns.resultJson}) else null end`, }).from(heartbeatRuns).leftJoin(nativeRunFinalizations, and( eq(nativeRunFinalizations.runId, heartbeatRuns.id), eq(nativeRunFinalizations.companyId, heartbeatRuns.companyId), )).where(eq(heartbeatRuns.id, runId)); @@ -101,6 +110,26 @@ const closedNativeReceiptSource = sql`${heartbeatRuns.runtimeMode} = 'native' order by process_event.seq desc limit 1) = 'native.local_process_stopped') or (${heartbeatRuns.status} in ('failed', 'cancelled', 'timed_out', 'interrupted') and ${remoteExecutionTerminated}))`; +const closedLegacyReceiptSource = sql`${heartbeatRuns.runtimeMode} = 'legacy' + and ${heartbeatRuns.status} in ('failed', 'timed_out', 'interrupted') + and ${heartbeatRuns.finishedAt} is not null + and (${heartbeatRuns.scheduledRetryAt} is null or ${heartbeatRuns.scheduledRetryAt} <= ${heartbeatRuns.finishedAt}) + and ${heartbeatRuns.controllerBootId} is not null and length(${heartbeatRuns.controllerBootId}::text) > 0 + and ${heartbeatRuns.controllerLeaseExpiresAt} is null + and ${heartbeatRuns.processPid} > 1 and ${heartbeatRuns.processGroupId} > 1 + and ${heartbeatRuns.processStartedAt} is not null + and ${heartbeatRuns.nativeIssueId} is null and ${heartbeatRuns.nativeSessionId} is null + and ${heartbeatRuns.executionControlDeadlineAt} is null + and not coalesce(${heartbeatRuns.resultJson} ?| array['startupCancellation','cancellation','executionCancellation','nativeCancellation'], false) + and ${heartbeatRuns.legacyProcessSettlement} = jsonb_build_object( + 'schema', 'paperclip.legacy-process-settlement.v1', 'runId', ${heartbeatRuns.id}::text, + 'companyId', ${heartbeatRuns.companyId}::text, 'agentId', ${heartbeatRuns.agentId}::text, + 'runtimeMode', 'legacy', 'targetKind', 'local', 'controllerBootId', ${heartbeatRuns.controllerBootId}, + 'processPid', ${heartbeatRuns.processPid}, 'processGroupId', ${heartbeatRuns.processGroupId}, + 'processStartedAt', to_char(${heartbeatRuns.processStartedAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'), + 'finishedAt', to_char(${heartbeatRuns.finishedAt} at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'), + 'status', ${heartbeatRuns.status})`; + /** A native run whose provider never started has nothing to account: recovery * settled, not one usage receipt was ever journaled for the run (a provider * turn journals one as soon as it starts), and its local process either never @@ -173,8 +202,8 @@ async function captureFailureSettles(db: Db, runId: string): Promise { return row?.due === true; } -async function readNativeReceiptClosure(db: Db, runId: string) { - const [row] = await db.select({ closed: sql`${closedNativeReceiptSource}`, +async function readProviderReceiptClosure(db: Db, runId: string) { + const [row] = await db.select({ closed: sql`(${closedNativeReceiptSource}) or (${closedLegacyReceiptSource})`, timedOut: sql`${closureEvidenceTimedOut()}`, neverStarted: sql`${nativeProviderWorkNeverStarted}` }).from(heartbeatRuns) .where(eq(heartbeatRuns.id, runId)); if (row?.neverStarted === true) return "no_provider_work" as const; @@ -285,7 +314,7 @@ export async function accountRunCost(db: Db, runId: string, hooks: BudgetService const captureFailed = object(run.usageJson).accountingCaptureFailed === true; if (captureFailed && !await captureFailureSettles(tx, run.id)) return false; const providerWorkNeverStarted = !captureFailed && run.runtimeMode === "native" && object(run.usageJson).accountingReceiptReady === false - && await readNativeReceiptClosure(tx, run.id) === "no_provider_work"; + && await readProviderReceiptClosure(tx, run.id) === "no_provider_work"; const preProviderFailure = !captureFailed && (object(object(run.resultJson).executionRecovery).providerWorkStarted === false || object(run.usageJson).accountingProviderWorkStarted === false || providerWorkNeverStarted); // A failed native turn is not necessarily the end of this heartbeat: the @@ -295,15 +324,9 @@ export async function accountRunCost(db: Db, runId: string, hooks: BudgetService const [coordinator] = await tx.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, run.id)); if (coordinator && !coordinator.resultId && coordinator.phase !== "terminal_failure") return false; } - // A stop can mark the run terminal before the provider's shutdown receipt - // arrives. Keep the debt pending instead of acknowledging an invented zero - // and permanently discarding that late receipt. Once native recovery has - // given up and the provider process is verified stopped, no producer can - // deliver it: settle the known part as unpriced usage. A later receipt - // still posts through late-receipt reconciliation. const receiptUnavailable = !preProviderFailure && (captureFailed || object(run.usageJson).accountingReceiptReady === false); const receiptClosure = captureFailed ? "timed_out" as const - : receiptUnavailable ? await readNativeReceiptClosure(tx, run.id) : null; + : receiptUnavailable ? await readProviderReceiptClosure(tx, run.id) : null; if (receiptUnavailable && !receiptClosure) return false; const closureTimedOut = receiptClosure === "timed_out"; if (!preProviderFailure) await ensureRuntimeAccountingBaseline(tx, run.companyId, run.agentId); @@ -458,7 +481,7 @@ function actionableRunAccounting(at: Date = new Date()) { and ${heartbeatRuns.runtimeMode} = 'native' and ${nativeRunFinalizations.resultId} is null and ${nativeRunFinalizations.phase} <> 'terminal_failure'))`, sql`(${heartbeatRuns.usageJson}->>'accountingReceiptReady' is distinct from 'false' or ${heartbeatRuns.resultJson}->'executionRecovery'->>'providerWorkStarted' = 'false' or ${heartbeatRuns.usageJson}->>'accountingProviderWorkStarted' = 'false' - or (${closedNativeReceiptSource}) or (${closureEvidenceTimedOut(at)}) or (${nativeProviderWorkNeverStarted}))`, + or (${closedNativeReceiptSource}) or (${closedLegacyReceiptSource}) or (${closureEvidenceTimedOut(at)}) or (${nativeProviderWorkNeverStarted}))`, )), )), );