Files
PaperClipAI/tests/runner-e2e/scheduled-finalization.ts
T
DottaandPaperclip b6e690044a feat(evals): allow reviewed bounded provisional accounting (#17365)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product E2E campaigns include model, setup, storage and
observability costs.
> - Some billing windows close after the tests and reports finish.
> - Requiring settled receipts for retained storage can block a good
campaign for weeks.
> - A reservation alone does not prove that a pending charge has an
upper bound.
> - This change permits provisional completion only with reviewed
evidence for the exact cost configuration.
> - Reports preserve unknown amounts and holds until later
reconciliation.

## Linked Issues or Issue Description

Refs: #17360, #17354

**What existing behavior does this improve?**

The Product E2E scheduled accounting gate and its retained cost reports.

**Current behavior**

Every pending receipt fails finalization. A completed test can wait
through the retained-storage billing window. The journal has dollar
reservations but no explicit qualification of their bounds.

**Proposed behavior**

Permit provisional completion when all pending charges have reviewed
full-lifecycle bounds, no requests remain in flight, no receipts
conflict, and known costs plus held amounts fit the campaign limit. Keep
all existing holds and receipt-finality rules. Missing evidence still
fails.

**Reason and benefit**

An operator can distinguish delayed but bounded billing from unbounded
or missing costs. The campaign can finish without claiming that its
invoice is settled.

**Breaking changes**

The journal accepts optional bound metadata and an invalidation record.
New reports add an optional bounded-pending count. Current readers
retain old journals and reports without granting them bounds. Older code
must not read new bound-bearing journals. The existing daily/weekly
enable gates and budget amounts stay unchanged.

**Additional context**

This implements the operator-approved provisional-cost policy for the
existing eval harness. It does not change product budgets or the
agent-eval roadmap. A targeted GitHub search found no duplicate open PR.

## What Changed

- Accounting owns a narrow evidence contract: a reviewed audit hash,
exact configuration hash and full-lifecycle scope.
- Gateway reservations retain that evidence before dispatch. Changed
limits or rates fail before dispatch. Unexpected routing, model identity
or excessive usage invalidates a bound durably.
- Operating allowances can carry separately reviewed bounds for each
cost component, including its full storage lifetime. No existing
allowance becomes qualified by default.
- Reports and Braintrust experiment metadata distinguish provisional
accounting, complete receipts, blocked accounting and unavailable
evidence. Public output omits private audit hashes.
- Scheduled finalization allows qualified provisional costs and
explicitly rejects spending overruns, including overruns with complete
receipts.
- Add regressions for legacy data, restarts, late reconciliation,
conflicts, malformed evidence, routing uncertainty and exceeded limits.
Document the evidence and migration boundaries.

## Verification

- Full offline eval-support suite: 4,062 Vitest tests passed, two
existing tests skipped; 137 Node tests passed.
- `pnpm test:e2e:runner:typecheck`: passed.
- `git diff --check`: passed.
- Read the retained hosted qualification journal with the new policy.
All six legacy pending charges remain unqualified. Known cost
`$0.421245200`, held `$19.327680000`, and committed `$19.748925200`
remain unchanged. The journal's SHA-256 is unchanged. The original
failed workflow remains failed.
- No paid models, network provider calls, receipt imports or reservation
releases were used for this verification.
- Rebased onto master `4d90634f74`; 142 targeted tests and typecheck
passed.
- Review reproduced a lost OpenAI input-total limit check when cache
details were missing (1 failed, 47 passed). Fix
`5fef9ba7c149951a51eae468614a4b89f0b3d6db` preserves unpriced provider
usage bounds. Then 178 focused tests, full offline support and typecheck
passed.
- Current-head hosted CI passed:
https://github.com/paperclipai/paperclip/actions/runs/40020746585
(attempt 2). Typecheck, build, all general/Runner/serialized tests and
browser gates are green.
- CI attempt 1 hit a PostgreSQL deadlock in unchanged chat-test cleanup;
its skipped flag restoration caused a second assertion failure. One
failed-jobs-only retry passed. Original failure evidence is preserved in
attempt 1. No paid eval campaign was rerun.
- Greptile reviewed exact head
`5fef9ba7c149951a51eae468614a4b89f0b3d6db` at 5/5; its one finding is
fixed and resolved. The optional Paperclip review is paused and supplied
no assessment.

## Risks

- Evidence hashes bind an audit to a configuration; they do not prove
the audit is true. Operators must review real provider limits, all price
tiers, full resource lifetimes and enforceable infrastructure limits
before configuring bounds.
- Provisional completion is not invoice settlement. Later billing can
reveal overruns, which must be reconciled and inspected. The ledger
cannot stop external billing.
- Existing pilot journals, configured allowances and price cards have no
new bound approval. This PR alone does not qualify or enable recurring
paid work.
- The gateway cannot qualify a canceled Braintrust request without route
confirmation. It preserves that unknown hold.
- No new dependency, secret, repository variable, workflow, schedule or
cloud resource changes.

## Model Used

OpenAI Codex, GPT-6 family. The exact deployment ID and context-window
size are not exposed in this session. Used reasoning, repository tools
and code execution. No paid evaluation model calls were made for this
change.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [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>
2026-10-23 13:57:57 -07:00

124 lines
8.8 KiB
TypeScript

import { usdToUnits } from "../../packages/shared/src/money.js";
import { evalAccountingStatus } from "./operations-report.js";
import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { evalBraintrustConfig } from "./braintrust.js";
import { openExperimentIngestion } from "./experiment-ingestion.js";
import { collectScheduledIngestion } from "./ingestion-usage.js";
import { importBraintrustExperiment, type BraintrustExperimentReceipt } from "./braintrust-experiment.js";
import { verifyBraintrustIndexing } from "./braintrust-indexing.js";
import { feedbackReviewTemplate, validateCampaignFeedbackReview, type CampaignFeedbackReview } from "./feedback-dispositions.js";
import { expectedFixtureFeedback } from "./feedback-persistence.js";
import { feedbackReview, summarizeCampaignFeedback, type FeedbackEvidence } from "./feedback.js";
import type { EvalOperationsManifest } from "./operations.js";
import type { RunnerE2ECampaign, RunnerE2EResult } from "./types.js";
export function reviewScheduledFeedback(campaign: RunnerE2ECampaign,
evidence: Array<{ result: RunnerE2EResult; feedback: FeedbackEvidence | null }>, now: string): CampaignFeedbackReview {
const synthetic = new Set<string>();
for (const { result, feedback } of evidence) {
if (result.suiteId !== "feedback-persistence" || !feedback || result.feedback?.collection !== "complete"
|| result.feedback.invocationCollection !== "complete") continue;
const marker = result.matcherResults?.find(row => row.matcher.kind === "message_exact")?.matcher;
const nonce = marker?.kind === "message_exact" ? /^PAPERCLIP_E2E_OK_([a-z0-9]+-[1-9][0-9]*)$/.exec(marker.expected)?.[1] : undefined;
if (!nonce) continue;
const checks = ["complete-retained-evidence", "one-of-each", "complaint-body-and-attribution", "complaint-completed-tool",
"suggestion-body-and-attribution", "suggestion-completed-tool", "only-expected-submissions"];
if (!checks.every(id => result.matcherResults?.some(row => row.matcher.kind === "json_path"
&& row.matcher.path === `feedbackPersistence.${id}` && row.passed))) continue;
const bodies = expectedFixtureFeedback(nonce);
if (feedback.entries.length !== 2 || !["complaint", "suggestion"].every(kind => feedback.entries.filter(entry =>
entry.kind === kind && entry.body === bodies[kind as keyof typeof bodies]).length === 1)) continue;
for (const group of feedbackReview(feedback.entries)) synthetic.add(group.fingerprint);
}
const template = feedbackReviewTemplate(campaign);
const review: CampaignFeedbackReview = { ...template, version: 1, reviewedAt: now, reviewedBy: "agent",
decisions: template.decisions.map(row => ({ fingerprint: row.fingerprint,
disposition: synthetic.has(row.fingerprint) ? "unsupported" : "needs_investigation" })) };
validateCampaignFeedbackReview(campaign, review);
return review;
}
export function scheduledCampaignFindings(campaign: RunnerE2ECampaign): string[] {
const findings: string[] = [];
if (campaign.failed || campaign.results.length !== campaign.expected.length || campaign.accounting?.missingAttempts) findings.push("product_or_missing_attempt");
if (campaign.accounting?.attempts.some(row => row.cleanup !== "passed")) findings.push("cleanup_failure");
const operations = campaign.operations;
if (!operations || operations.status === "unavailable") findings.push("accounting_unavailable");
else {
if (evalAccountingStatus(operations) === "blocked") findings.push("accounting_incomplete");
if (usdToUnits(operations.committedUsd) > usdToUnits(operations.limitUsd)) findings.push("accounting_over_budget");
}
const feedback = summarizeCampaignFeedback(campaign.accounting?.attempts ?? campaign.results);
if (feedback.incomplete || feedback.failedSubmissions || feedback.unknownSubmissions) findings.push("feedback_collection_incomplete");
if (!campaign.feedbackReview || campaign.feedbackReview.decisions.some(row => ["actionable", "needs_investigation"].includes(row.disposition))) findings.push("feedback_needs_review");
if (campaign.results.some(row => row.tracing?.status !== "accepted" || row.tracing.nativeConfiguration !== "configured"
|| row.tracing.finalization?.status !== "accepted")) findings.push("trace_export_incomplete");
return findings;
}
export async function finalizeScheduledCampaign(env: NodeJS.ProcessEnv) {
if (!env.PAPERCLIP_E2E_OPERATIONS_MANIFEST || !env.GITHUB_WORKSPACE) throw new Error("Missing scheduled campaign manifest");
const manifest = JSON.parse(await readFile(env.PAPERCLIP_E2E_OPERATIONS_MANIFEST, "utf8")) as EvalOperationsManifest;
const directory = path.dirname(env.PAPERCLIP_E2E_OPERATIONS_MANIFEST);
const root = path.join(env.GITHUB_WORKSPACE, "tests/runner-e2e/results", manifest.limits.campaignId);
const campaign = JSON.parse(await readFile(path.join(root, "campaign.json"), "utf8")) as RunnerE2ECampaign;
const originals: RunnerE2EResult[] = [], evidence: Array<{ result: RunnerE2EResult; feedback: FeedbackEvidence | null }> = [];
for (const selected of campaign.results) {
if (selected.attempt < 1) continue;
if (!manifest.executionIds.includes(selected.executionId) || selected.attempt !== 1) throw new Error("Unexpected scheduled attempt");
const resultPath = path.join(root, ...selected.executionId.split("."), "attempt-1");
const result = JSON.parse(await readFile(path.join(resultPath, "result.json"), "utf8")) as RunnerE2EResult;
originals.push(result);
let feedback: FeedbackEvidence | null = null;
try { feedback = JSON.parse(await readFile(path.join(resultPath, "snapshots/agent-feedback.json"), "utf8")); } catch {}
evidence.push({ result, feedback });
}
campaign.feedbackReview = reviewScheduledFeedback(campaign, evidence, new Date().toISOString());
await writeFile(path.join(directory, "feedback-review.json"), `${JSON.stringify(campaign.feedbackReview, null, 2)}\n`, { mode: 0o600 });
const findings = scheduledCampaignFindings(campaign);
const config = evalBraintrustConfig(env);
let experiment: BraintrustExperimentReceipt | undefined;
let ingestion: Awaited<ReturnType<typeof openExperimentIngestion>> | undefined;
try {
if (!config) throw new Error("Missing Braintrust export configuration");
if (config.projectId !== manifest.projectId || campaign.campaignId !== manifest.limits.campaignId) throw new Error("Scheduled ingestion identity mismatch");
ingestion = await openExperimentIngestion({ projectId: config.projectId, campaignId: manifest.limits.campaignId,
receiptPath: `${manifest.ledgerPath}.experiment-ingestion.jsonl`, deadlineAt: Date.now() + 60_000 });
await importBraintrustExperiment(config, campaign, originals, async receipt => {
await writeFile(path.join(directory, "experiment-receipt.json"), `${JSON.stringify(receipt, null, 2)}\n`, { mode: 0o600 });
experiment = receipt;
}, ingestion.transport);
} catch { findings.push("experiment_import_incomplete"); }
finally {
try { await ingestion?.close(); }
catch { findings.push("experiment_ingestion_accounting_incomplete"); }
}
try {
if (!config) throw new Error("Missing Braintrust ingestion configuration");
const usage = await collectScheduledIngestion({ ledgerPath: manifest.ledgerPath, campaignId: manifest.limits.campaignId,
projectId: config.projectId, executionIds: manifest.executionIds });
await writeFile(path.join(directory, "ingestion-usage.json"), `${JSON.stringify(usage, null, 2)}\n`, { mode: 0o600 });
if (usage.status !== "complete") findings.push("ingestion_accounting_incomplete");
} catch { findings.push("ingestion_accounting_unavailable"); }
let indexing = "unavailable";
try {
if (!config) throw new Error("Missing Braintrust query configuration");
const receipt = await verifyBraintrustIndexing(config, campaign, originals, experiment);
indexing = receipt.status;
await writeFile(path.join(directory, "indexing-receipt.json"), `${JSON.stringify(receipt, null, 2)}\n`, { mode: 0o600 });
} catch {}
if (indexing !== "verified") findings.push("trace_or_experiment_indexing_incomplete");
await writeFile(path.join(directory, "findings.json"), `${JSON.stringify({ version: 1, findings,
nativeIndexVerification: indexing, invoiceReconciliation: "pending",
accountingStatus: campaign.operations ? evalAccountingStatus(campaign.operations) : "unavailable",
feedbackReviewMethod: "Only exact synthetic fixture bodies with all corroborating graders are automatically dismissed; all other feedback requires review" }, null, 2)}\n`, { mode: 0o600 });
for (const finding of findings) console.error(`::error title=Eval operations::${finding}`);
return findings;
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
if ((await finalizeScheduledCampaign(process.env)).length) process.exitCode = 1;
}