Files
DottaandPaperclip 53732c811b fix(evals): classify latency from observation bounds (#16829)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Product E2E probes measure when acknowledgements and replies become
visible.
> - A poll gives a time interval for an event.
> - The first positive poll can occur after a target that the event
could still meet.
> - This pull request compares the full interval with a strict or
inclusive target.
> - Reports retain the raw observations and the original verdict when
the timing verdict changes.

## Linked Issues or Issue Description

**What happened?**

A historical acknowledgement was absent at 1901 ms and first present at
2427 ms. A report marked the 2000 ms target as failed. The interval
crosses that target, so the available evidence cannot give a pass or
fail verdict.

**Expected behavior**

Return pass when the full interval meets the target. Return fail when
the full interval rules out the target. Return inconclusive for overlap,
invalid evidence, or insufficient evidence. Respect strict and inclusive
targets and open and closed endpoints.

**Steps to reproduce**

Run the deterministic timing tests. Use the acknowledgement interval
`(1901, 2427] ms` with `<= 2000 ms`. Compare the late reply interval
`(52965, 53334] ms` with `<= 30000 ms`. The first is inconclusive. The
second fails.

**Paperclip version or commit**

The source includes master at
`14afc12124017d4ec30d0f4bfd6892f8ce475d21`.

Related PR:
[#13710](https://github.com/paperclipai/paperclip/pull/13710) changed
chat latency and session reuse. This change corrects probe evidence and
report verdicts.

## What Changed

- Add a shared interval classifier with explicit endpoint and target
operators.
- Start observation before dispatch. Use a monotonic clock. Bound
asynchronous reads by request start and completion.
- Measure the first visible response separately from message creation
and final settlement. Share browser reads with an optional
acknowledgement probe.
- Keep raw bounds, clock resolution, message metadata, failed reads, and
original verdicts in retained report evidence.
- Add deterministic coverage for threshold equality, missing data,
edited messages, asynchronous reads, teardown, report correction, and a
finite-domain oracle.
- Bound observer shutdown to one second across pending and final reads.
Retain timeout counts. Ignore late completions and start no more reads
after shutdown.
- Document the timing contract in the existing Product E2E guide.
- Keep current startup reuse evidence after the master merge. Update
four stale test expectations for qualified Copilot admission. Keep the
explicit suite and provider restrictions.

## Verification

- Current head: `c42e87e6d3b4b347e7cb176f56819c1d0abe106d`.
- Passed: `pnpm test:e2e:runner:unit` (3,287 Vitest tests and 128 native
completion tests; two explicit skips).
- Passed: `pnpm test:e2e:runner:typecheck`, `pnpm -r typecheck`, `pnpm
build`, `pnpm check:token-gates`, and `git diff origin/master --check`.
- Passed: [exact-head
CI](https://github.com/paperclipai/paperclip/actions/runs/39607140418),
including both required checks (`ci / verify` and `ci / e2e`), all
general and serialized test jobs, all eight browser shards, build,
canary dry run, and the clean public npm-install smoke.
- Greptile reviewed the complete current diff and returned [5/5 with no
actionable
issues](https://github.com/paperclipai/paperclip/pull/16829#issuecomment-6266704814).
All review threads are resolved.
- The redundant local `pnpm test:run` was stopped after the exact-head
CI test jobs passed. It did not produce a complete local verdict; the
full repository test evidence is the CI run above.
- The [earlier broad
run](https://github.com/paperclipai/paperclip/actions/runs/39249282597)
failed on the old head. Its full test command timed out after 15
minutes. Five E2E support failures came from ambient `NODE_PATH` and a
missing historical Git object. Current master supplies the
closed-environment launcher and retained source fixture. The full
support suite passes with these fixes.
- After the current master merge, four stale Copilot assertions and the
nested unit launcher failed. Copilot is now qualified. Those assertions
now require no qualification override and retain the rejected
suite/provider cases. The full documented unit command passes.
- The first local typecheck after the merge used stale generated package
declarations and failed. The typechecks pass after `pnpm build`.
- These checks use synthetic timing evidence. They make no live provider
calls and claim no new live latency measurement.

## Risks

- The browser diagnostic depends on the existing message and receipt DOM
markers. Controlled tests cover visibility, receipt separation,
concurrent reads, and teardown.
- Corrected timing verdicts can become inconclusive. The report keeps
the original verdict and does not change the overall workflow grade.
- This change adds no database migration or product surface.

## Model Used

- OpenAI GPT-6 Codex. Model family: GPT-6. This session does not expose
a more specific model ID or context window size. The agent used
reasoning, shell tools, code inspection, and deterministic tests. The
earlier implementation session did not retain its exact model ID.

## 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-21 08:31:22 -05:00

293 lines
9.7 KiB
TypeScript

import { isIncompleteFirstTaskResult } from "./case-outcome.js";
import { classifyLatency } from "./latency-timing.js";
import { summarizeStartupReuse } from "../../packages/adapter-utils/src/startup-reuse.js";
import { validateRetainedRunnerResult } from "./result-validation.js";
import {
discoverReportCatalog,
parseReportExecutionId,
type ReportExecution,
} from "./report-catalog.js";
import { runnerMatrix, runnerSuites } from "./catalog.js";
import {
aggregateCampaignBilling,
summarizeExecutionBilling,
} from "./billing.js";
import { resolveRunnerE2ESource } from "./source.js";
import type {
RunnerE2ECampaign,
RunnerE2EHistoryCampaign,
RunnerE2EHistoryIndex,
RunnerE2EResult,
} from "./types.js";
export function canonicalExecutionId(id: string) {
if (runnerMatrix.some((execution) => execution.id === id)) return id;
const coreId = `core-compatibility.${id}`;
return runnerMatrix.some((execution) => execution.id === coreId)
? coreId
: id;
}
export function upgradeRunnerResult(result: RunnerE2EResult): RunnerE2EResult {
validateRetainedRunnerResult(result);
if (result.latencyProbes) result = { ...result, latencyProbes: result.latencyProbes.map(probe => {
const corrected = classifyLatency(probe, probe.target);
return probe.verdict === corrected.verdict ? corrected
: { ...corrected, recordedVerdict: probe.recordedVerdict ?? probe.verdict };
}) };
result = { ...result, startupReuse: result.startupReuse ?? (result.runIds ?? []).map(runId => ({
runId, ...summarizeStartupReuse([]),
})) };
const executionId = canonicalExecutionId(result.executionId);
const execution = runnerMatrix.find(
(candidate) => candidate.id === executionId,
);
if (!execution)
return {
...result,
executionId,
suiteId: result.suiteId ?? parseReportExecutionId(executionId).suiteId,
};
return {
...result,
executionId,
suiteId: result.suiteId ?? execution.suite.id,
suiteDefinitionHash:
result.suiteDefinitionHash ?? execution.suiteDefinitionHash,
...(result.schema === "paperclip.runner-e2e.result/v1"
? {
source: result.source ?? {
sha: null,
ref: null,
workflowRunUrl: null,
},
}
: {}),
};
}
export function buildRunnerCampaign(input: {
campaignId: string;
generatedAt: string;
expected: readonly string[];
results: readonly RunnerE2EResult[];
eventName?: string | null;
catalog?: readonly ReportExecution[];
}): RunnerE2ECampaign {
const expected = input.expected.map(canonicalExecutionId);
const results = input.results.map((result) => ({
...upgradeRunnerResult(result),
billing: result.billing ?? summarizeExecutionBilling(result),
}));
const knownCatalog = input.catalog ?? runnerMatrix;
const catalog = discoverReportCatalog({
catalog: knownCatalog,
expected,
results,
});
const discoveredSuites = [
...new Map(
catalog.map((execution) => [execution.suite.id, execution.suite]),
).values(),
];
const resultSource = results.find((result) => result.source)?.source;
const source = {
...resolveRunnerE2ESource(resultSource),
eventName: input.eventName ?? process.env.GITHUB_EVENT_NAME ?? null,
};
const suites = discoveredSuites
.map((suite) => {
const suiteExpected = expected.filter((id) =>
id.startsWith(`${suite.id}.`),
);
if (suiteExpected.length === 0) return null;
const suiteResults = results.filter(
(result) =>
expected.includes(result.executionId) &&
result.executionId.startsWith(`${suite.id}.`),
);
const passed = suiteResults.filter(
(result) => result.status === "passed" && result.cleanup === "passed",
).length;
const executed = suiteResults.filter(
(result) => result.attempt > 0,
).length;
return {
suiteId: suite.id,
suiteDefinitionHash:
suiteResults[0]?.suiteDefinitionHash ??
catalog.find((execution) => execution.suite.id === suite.id)!
.suiteDefinitionHash,
expected: suite.expectedMatrixSize,
selected: suiteExpected.length,
executed,
passed,
failed: suiteExpected.length - passed - suiteResults.filter(r => isIncompleteFirstTaskResult(r)).length,
incomplete: suiteResults.filter(r => isIncompleteFirstTaskResult(r)).length,
retries: suiteResults.reduce(
(total, result) => total + Math.max(0, result.attempt - 1),
0,
),
cleanupPassed: suiteResults.every(
(result) => result.cleanup === "passed",
),
complete:
suiteExpected.length === suite.expectedMatrixSize &&
knownCatalog.filter((execution) => execution.suite.id === suite.id)
.length === suiteExpected.length &&
knownCatalog
.filter((execution) => execution.suite.id === suite.id)
.every(
(execution) =>
suiteExpected.includes(execution.id) &&
suiteResults.every(
(result) =>
result.suiteDefinitionHash ===
execution.suiteDefinitionHash,
),
),
durationMs: suiteResults.reduce(
(total, result) => total + result.durationMs,
0,
),
billing: aggregateCampaignBilling(suiteResults),
};
})
.filter((suite): suite is NonNullable<typeof suite> => Boolean(suite));
const passed = results.filter(
(result) => result.status === "passed" && result.cleanup === "passed",
).length;
const rankingSnapshots = [
...new Map(
results.flatMap((result) =>
result.rankingSnapshot
? [
[
result.rankingSnapshot.snapshotId,
{
snapshotId: result.rankingSnapshot.snapshotId,
capturedAt: result.rankingSnapshot.capturedAt,
sourceUrl: result.rankingSnapshot.sourceUrl,
},
] as const,
]
: [],
),
).values(),
];
return {
schema: "paperclip.runner-e2e.campaign/v2",
campaignId: input.campaignId,
generatedAt: input.generatedAt,
source,
expected,
complete:
suites.length === runnerSuites.length &&
suites.every((suite) => suite.complete),
selected: expected.length,
executed: results.filter((result) => result.attempt > 0).length,
passed,
failed: expected.length - passed - results.filter(r => isIncompleteFirstTaskResult(r)).length,
incomplete: results.filter(r => isIncompleteFirstTaskResult(r)).length,
retries: results.reduce(
(total, result) => total + Math.max(0, result.attempt - 1),
0,
),
cleanupPassed: results.every((result) => result.cleanup === "passed"),
rankingSnapshots,
billing: aggregateCampaignBilling(results),
suites,
results,
};
}
export function campaignHistoryRecord(
campaign: RunnerE2ECampaign,
publicBaseUrl: string,
): RunnerE2EHistoryCampaign {
const publicUrl = `${publicBaseUrl.replace(/\/$/, "")}/campaigns/${encodeURIComponent(campaign.campaignId)}/`;
return {
campaignId: campaign.campaignId,
generatedAt: campaign.generatedAt,
source: campaign.source,
complete: campaign.complete,
selected: campaign.selected,
executed: campaign.executed,
passed: campaign.passed,
failed: campaign.failed,
incomplete: campaign.incomplete ?? 0,
retries: campaign.retries,
cleanupPassed: campaign.cleanupPassed,
publicUrl,
billing: campaign.billing,
suites: campaign.suites,
executions: campaign.results.map((result) => ({
executionId: result.executionId,
suiteId: result.suiteId ?? "core-compatibility",
profileId: result.profileId,
environmentId: result.environmentId,
caseId: result.caseId,
provider: result.provider,
model: result.model,
status: isIncompleteFirstTaskResult(result) ? "incomplete" : result.status,
durationMs: result.durationMs,
attempt: result.attempt,
cleanup: result.cleanup,
billing: result.billing ?? summarizeExecutionBilling(result),
})),
};
}
export function emptyRunnerHistory(): RunnerE2EHistoryIndex {
return {
schema: "paperclip.runner-e2e.history/v1",
updatedAt: new Date(0).toISOString(),
latestCampaignId: null,
latestGreenCampaignId: null,
latestBySuite: {},
latestGreenBySuite: {},
campaigns: [],
};
}
export function mergeRunnerHistory(
current: RunnerE2EHistoryIndex | null | undefined,
campaign: RunnerE2EHistoryCampaign,
): RunnerE2EHistoryIndex {
const base =
current?.schema === "paperclip.runner-e2e.history/v1"
? current
: emptyRunnerHistory();
const campaigns = [
campaign,
...base.campaigns.filter(
(candidate) => candidate.campaignId !== campaign.campaignId,
),
].sort(
(left, right) =>
Date.parse(right.generatedAt) - Date.parse(left.generatedAt),
);
const latestBySuite: Record<string, string> = {};
const latestGreenBySuite: Record<string, string> = {};
for (const candidate of campaigns) {
for (const suite of candidate.suites) {
latestBySuite[suite.suiteId] ??= candidate.campaignId;
if (suite.complete && suite.failed === 0 && (suite.incomplete ?? 0) === 0) {
latestGreenBySuite[suite.suiteId] ??= candidate.campaignId;
}
}
}
return {
schema: "paperclip.runner-e2e.history/v1",
updatedAt: new Date().toISOString(),
latestCampaignId: campaigns[0]?.campaignId ?? null,
latestGreenCampaignId:
campaigns.find(
(candidate) => candidate.complete && candidate.failed === 0 && (candidate.incomplete ?? 0) === 0,
)?.campaignId ?? null,
latestBySuite,
latestGreenBySuite,
campaigns,
};
}