Files
PaperClipAI/tests/runner-e2e/chat-catalog-testops-streaming.mjs
T
DottaandPaperclip 0fd82e386e feat(evals): stream completed chat catalog results to TestOps (#18647)
## Thinking Path

> - Paperclip lets people manage AI agents and inspect their work.
> - The chat catalog uses real Product E2E cases and reports their
original grades to TestOps.
> - The current report matrix waits for every selected worker.
> - A large selection can hide completed results for hours.
> - Each case can use the existing private reader and safe exporter
after its own worker ends.
> - This PR gives each case a separate upload and readback job, then
verifies final coverage without another upload.
> - People can inspect completed cases while the rest of the selection
runs.

## Linked Issues or Issue Description

Refs #18542, #18625.

**What existing behavior does this improve?**

The existing chat catalog reports results to TestOps only after all
selected workers finish.

**Current behavior**

One slow case holds back the report and upload jobs for all other cases.

**Proposed behavior**

Each finished case gets its own protected reader, safe projection,
upload and backend verification. The final job checks the whole
selection through read-only requests. It does not upload results again.

**Reason and benefit**

A person can inspect a completed grade and its safe evidence receipts
while other cases run. This changes future runs. It does not change an
in-flight run.

## What Changed

- Add one same-commit reusable workflow with separate worker,
private-reader and TestOps-upload jobs. Each job uses only its own
protected environment. Callers pass empty named secret placeholders and
do not inherit secrets.
- Reuse the original exporter and grade checks. Freeze each case's three
Allure JSON files once. Allow known sibling results during per-case
readback. Keep final exact selection coverage.
- Submit each bundle at most once. Reconcile uncertain responses by
readback. Retain only closed publication, failure and upload-intent
receipts. A rerun attempt still fails the existing attempt-one admission
guard.
- Preserve failed original grades, failed cleanup and missing evidence.
No missing original can become a passing result.
- Keep external-input cases in the serial lane. Small native-only
selections allow two cases at once. Small mixed selections allow one
native and one external case. Larger selections retain eight native
cases and one external case.
- Add source, privacy and failure controls to the existing unit roster.
Document the reporting flow and runner-group admission requirement.
- Fix an existing corruption-test fixture that could write the same byte
back to a random IV. Read and flip one bit instead. Keep the storage
rejection and unpublished-plaintext assertions unchanged.

## Verification

- 152 focused Node controls pass across the shared client, API,
selection, CLI and streaming tests. The retained parent controls show
the missing multipart and partial-readback behavior, plus the small
external-selection error before its fix.
- The focused workflow security control passes. Actionlint passes for
both workflows. Changed JavaScript files pass syntax checks. Git diff
checks pass.
- Local controls use synthetic data and mocked HTTP. They make no
provider call and do not start an app, database or native build.
- Previous head `b51406df` passed PR CI (48 jobs pass and one is
skipped). The review-driven test-only successor `0c65cc21` then failed
one unchanged snapshot-storage corruption test, plus the final CI
summary. The latest head includes its narrow fixture repair. Its first
CI attempt separately hit runner shutdown/lost-communication failures,
two setup/timeouts and a heartbeat-cancel cleanup HTTP 500/lock timeout;
those observations are retained without claiming their underlying cause.
One same-head failed-and-cancelled-only recovery now passes at
`bf9c3e8f`: 48 jobs pass and one is skipped, including required `ci /
verify` and `ci / e2e`. All 31 already-passing jobs retained their
original execution records; all 15 recovered leaves and both dependent
summaries passed. The first attempt remains recorded; the recovery does
not establish the underlying causes of those failures. A small AWS run
after delivery must prove that one case and both attachments are visible
before another original case ends. That live proof is pending; local
controls do not prove vendor ingestion or environment-secret resolution.
- Retained earlier fixture-calibration failures remain recorded. The
final integrated Node control run is green. A deterministic Node
crypto/filesystem control also reproduces the no-op corruption mutation
with a valid IV byte equal to `X`, then passes after flipping that byte.
This control uses no app or database. The failing CI byte was not
captured, so the exact historical byte remains unknown.

## Risks

- The called workflow needs its exact master ref in the existing
selected-workflow runner group. No IAM role change is needed.
- Environment-only secrets must resolve in the called jobs. The caller
passes no actual model or reporting key. The small live proof must
confirm this behavior.
- TestOps does not document an idempotency key for this upload route. An
uncertain write is never resent automatically. If readback cannot verify
it, the workflow fails with retained closed receipts.
- The existing job run can already be marked finished by the selection
watch. The live proof must record its actual stage and prove subsequent
uploads are accepted. This PR does not reopen, stop or close that job
run.
- Backend ingestion does not prove that an already-open TestOps page
refreshes automatically.
- The corruption-test repair changes no production storage or
cryptography. New-head AWS CI must qualify the existing database-backed
owner test.
- Each case adds short protected reader and upload jobs. The app source,
original case clocks, graders, model, budgets, raw-evidence privacy
boundary and zero eval retries stay unchanged. The versioned stream
concurrency group serializes new streaming runs; an old immutable batch
run can continue in its original group.

## Model Used

OpenAI `gpt-6.1-sol`, with tool use and code execution. The session does
not expose a context-window size. Independent source peers used the same
model family.

## 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-11-02 14:18:00 -06:00

135 lines
9.5 KiB
JavaScript

import { lstat, readFile, readdir, realpath } from 'node:fs/promises';
import path from 'node:path';
import { hash, validateSelection, reject } from './chat-completion-testops-contract.mjs';
import { readPilotExport, exportPilotAllure } from './chat-completion-testops-results.mjs';
import { inspectPilotCaseUpload, verifyPilotCaseUpload } from './chat-completion-testops-api.mjs';
export function caseSelection(selection, context, executionId) {
if (context.catalog !== 'full') reject('stream_scope');
const authorized = validateSelection(selection, context, selection.allureJobRunId);
const row = authorized.find(value => value.executionId === executionId);
if (!row) reject('stream_scope');
return { ...selection, cases: [row] };
}
const identity = (selection, context, executionId, selectionSha256) => {
if (!/^[a-f0-9]{64}$/.test(selectionSha256)) reject('stream_binding');
const scoped = caseSelection(selection, context, executionId), row = scoped.cases[0];
return { schema: 'paperclip.chat-catalog-testops-case-bundle/v1', ...context,
projectId: 1, planId: selection.planId, jobId: selection.jobId, launchId: selection.launchId,
allureJobRunId: selection.allureJobRunId, executionId, caseId: row.caseId,
fullSelectionSha256: selectionSha256, fullSelectionCount: selection.cases.length };
};
async function filesAt(root, wanted) {
if (await realpath(root) !== path.resolve(root)) reject('stream_bundle');
const names = (await readdir(root)).sort();
if (names.length !== 3 || names.some(name => !/^[a-f0-9-]{36}-(?:attachment|result)\.json$/.test(name))
|| names.filter(name => name.endsWith('-result.json')).length !== 1) reject('stream_bundle');
const files = []; let total = 0;
for (const name of names) {
const file = path.join(root, name), before = await lstat(file);
if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1 || before.size > 12 * 1024 * 1024) reject('stream_bundle');
const bytes = await readFile(file), after = await lstat(file); total += bytes.length;
if (total > 32 * 1024 * 1024 || before.ino !== after.ino || before.dev !== after.dev || before.size !== bytes.length
|| before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) reject('stream_bundle');
files.push({ name, bytes, sha256: hash(bytes) });
}
const metadata = files.map(file => ({ name: file.name, bytes: file.bytes.length, sha256: file.sha256 }));
if (wanted && JSON.stringify(metadata) !== JSON.stringify(wanted)) reject('stream_bundle');
return { files, metadata };
}
// The existing exporter owns grades and the public allowlist. Materialize once;
// preserve these exact UUID-bearing bytes through every later readback.
export async function prepareCaseBundle(root, output, context, selection, executionId, selectionSha256) {
const bound = identity(selection, context, executionId, selectionSha256);
const scoped = caseSelection(selection, context, executionId);
const exported = await exportPilotAllure(root, output, context, scoped);
const { metadata: files } = await filesAt(output);
const prepared = { ...bound,
projectionBindingSha256: hash(await readFile(path.join(root, 'binding.json'))), exported, files };
return { ...prepared, payloadSha256: hash(JSON.stringify(prepared)) };
}
export async function readCaseBundle(root, output, prepared, context, selection, executionId, selectionSha256) {
const expected = identity(selection, context, executionId, selectionSha256);
if (!prepared || Object.entries(expected).some(([key, value]) => prepared[key] !== value)) reject('stream_binding');
const { payloadSha256, ...unsigned } = prepared;
if (!/^[a-f0-9]{64}$/.test(payloadSha256) || hash(JSON.stringify(unsigned)) !== payloadSha256) reject('stream_bundle');
const scoped = caseSelection(selection, context, executionId);
const validated = await readPilotExport(root, context, scoped), original = validated.campaign.results[0];
if (hash(await readFile(path.join(root, 'binding.json'))) !== prepared.projectionBindingSha256
|| !Array.isArray(prepared.exported) || prepared.exported.length !== 1
|| prepared.exported[0].caseId !== expected.caseId || prepared.exported[0].executionId !== executionId
|| prepared.exported[0].status !== (original.status === 'passed' && original.cleanup === 'passed' ? 'passed' : 'failed')
|| prepared.exported[0].cleanup !== original.cleanup) reject('stream_binding');
return filesAt(output, prepared.files);
}
export async function publishCaseBundle(api, root, output, prepared, context, selection, executionId, selectionSha256, markOnce, options) {
const { files } = await readCaseBundle(root, output, prepared, context, selection, executionId, selectionSha256);
const before = await inspectPilotCaseUpload(api, selection, context, executionId, options);
let response, uncertain = null;
if (!before.present) {
// Once markers are retained before this call. An uncertain reply is reconciled
// by GET only. Neither this function nor the finalizer repeats the POST.
await markOnce({ executionId, caseId: prepared.caseId, payloadSha256: prepared.payloadSha256 });
const body = new FormData();
for (const file of files) body.append('file', new Blob([file.bytes], { type: 'application/json' }), file.name);
try { response = await api(`/api/jobrun/${selection.allureJobRunId}/upload`, 'POST', body); }
catch (error) { uncertain = { kind: ['testops_api_http', 'testops_response_invalid', 'testops_response_too_large'].includes(error?.code)
? error.code : 'transport_or_response_failure', httpStatus: Number.isInteger(error?.status) ? error.status : null }; }
}
let verification;
try { verification = await verifyPilotCaseUpload(api, selection, context, executionId, prepared.exported, options); }
catch (error) {
if (uncertain) { const stopped = new Error('chat_completion_testops_stream_upload_uncertain'); stopped.uploadFailure = uncertain; throw stopped; }
throw error;
}
const after = await api(`/api/jobrun/${selection.allureJobRunId}`);
if (after.id !== Number(selection.allureJobRunId) || after.job?.id !== selection.jobId || after.launchId !== selection.launchId
|| after.url !== `https://github.com/paperclipai/paperclip/actions/runs/${context.runId}` || !['in_progress', 'finished'].includes(after.stage)) reject('jobrun_mismatch');
return { ...identity(selection, context, executionId, selectionSha256), schema: 'paperclip.chat-catalog-testops-case-publication/v1',
payloadSha256: prepared.payloadSha256, projectionBindingSha256: prepared.projectionBindingSha256, exported: prepared.exported[0],
uploadSent: !before.present, uncertainUpload: uncertain, jobRunStageBefore: before.jobRunStage, jobRunStageAfter: after.stage,
responseFilesCount: Number.isSafeInteger(response?.filesCount) && response.filesCount >= 0 ? response.filesCount : null,
verification: verification.verification, results: verification.results };
}
// The finalizer authenticates the already-emitted bytes and their original
// grades. It never calls the random-UUID exporter or the upload endpoint.
export async function publicationSet(bundlesRoot, publicationsRoot, context, selection, selectionSha256) {
const rows = validateSelection(selection, context, selection.allureJobRunId);
const roots = [bundlesRoot, publicationsRoot];
for (const [index, root] of roots.entries()) {
if (await realpath(root) !== path.resolve(root)) reject('stream_publications');
const prefix = `chat-catalog-case-${index === 0 ? 'bundle' : 'publication'}-${context.runId}-1-`;
const names = await readdir(root);
if (names.length !== rows.length || names.some(name => !rows.some((_, i) => name === `${prefix}${i}`))) reject('stream_publications');
}
const exported = [];
for (const [index, row] of rows.entries()) {
const bundle = path.join(bundlesRoot, `chat-catalog-case-bundle-${context.runId}-1-${index}`);
const publication = path.join(publicationsRoot, `chat-catalog-case-publication-${context.runId}-1-${index}`);
for (const directory of [bundle, publication]) {
const stat = await lstat(directory);
if (!stat.isDirectory() || stat.isSymbolicLink()) reject('stream_publications');
}
const read = async (directory, name) => {
const stat = await lstat(path.join(directory, name));
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 65_536) reject('stream_publications');
return JSON.parse(await readFile(path.join(directory, name), 'utf8'));
};
const prepared = await read(bundle, 'prepared.json');
await readCaseBundle(path.join(bundle, 'projection'), path.join(bundle, 'allure'), prepared, context, selection, row.executionId, selectionSha256);
const value = await read(publication, 'publication.json');
const expected = { ...identity(selection, context, row.executionId, selectionSha256), schema: 'paperclip.chat-catalog-testops-case-publication/v1' };
if (Object.entries(expected).some(([key, wanted]) => value[key] !== wanted)
|| value.payloadSha256 !== prepared.payloadSha256 || value.projectionBindingSha256 !== prepared.projectionBindingSha256
|| JSON.stringify(value.exported) !== JSON.stringify(prepared.exported[0]) || value.verification !== 'VERIFIED'
|| !Array.isArray(value.results) || value.results.length !== 1 || value.results[0].caseId !== row.caseId
|| value.results[0].executionId !== row.executionId || value.results[0].attachmentsVerified !== true) reject('stream_publications');
exported.push(value.exported);
}
return exported;
}