Files
PaperClipAI/scripts/ci-profile/export.mjs
T
DottaandPaperclip 6acec4266e feat(ci): profile full CODEOWNER PR suites in Honeycomb (#16378)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Its PR workflow runs dozens of parallel build and test jobs.
> - Individual job durations do not show the elapsed cost of the whole
suite.
> - Maintainers need one shared timeline to find slow work and repeated
setup.
> - This pull request adds full-suite profiles for selected CI CODEOWNER
PRs.
> - Honeycomb shows each job, step, test file, and supported test on
that timeline.
> - The benefit is evidence for changes that reduce total CI time.

## Linked Issues or Issue Description

**What existing behavior does this improve?**

The main PR workflow has about 48 jobs. Maintainers need to compare
their overlapping work and find which jobs delay completion.

**Current behavior**

GitHub shows job and step durations separately. Test files and tests are
not joined to a full workflow trace.

**Proposed behavior**

A CI CODEOWNER adds `profile-ci` to a PR. The tested code stays on that
PR branch. All main PR lanes run, including lanes normally skipped for
stack position or release notes. A trusted post-run exporter sends one
wall-clock trace to Honeycomb.

**Reason and benefit**

The trace supports decisions about which CI work to speed up or remove.
Ordinary PRs do not export traces. The roadmap and related-PR search
found no duplicate CI profiling work.

## What Changed

- Add label selection and a full-suite override. Verify the PR author,
original actor, and rerun actors against the trusted `.github/**`
CODEOWNERS rule.
- Record Vitest, Playwright, and Node test file/test timings in local
artifacts. Keep ordinary reporter behavior and failing exit codes.
- Add a trusted `workflow_run` exporter. Use actual GitHub timestamps
for all jobs, setup, steps, waiting, and teardown. Mark missing test
data and partial reruns.
- Keep the ingest key out of PR jobs. Store it only in the
`ci-profiling` environment, restricted to `master`. The exporter reads
bounded JSON and never executes artifact code.
- Record expected test invocations outside reporters so a missing
invocation cannot appear complete. Preserve `node --test` on older PR
checkouts. Flush large shard inventories before exit.
- Add security, timing, routing, and real-reporter checks. Document
operation and activation. Protect the exporter with CODEOWNERS.

## Verification

- 509 focused workflow/reporter/shard checks passed. They include
outside authors, outside rerun actors, bots, stale revisions, malicious
ZIP paths, incomplete reports, and partial ingestion failures.
- Final revision `3bf5d9017d` adds multi-file qualification and fixes
short-file step parenting and duplicate Node file-wrapper events.
Greptile reviewed this exact revision at 5/5 with no unresolved threads.
[Main PR CI
run](https://github.com/paperclipai/paperclip/actions/runs/38728040302):
the initial attempt had 54 successful checks, 3 intentional skips, and
one serialized-shard failure from an unchanged workspace-authorization
test exceeding its 15-second timeout. The single failed-shard retry
passed: the final result is 55 successful checks and 3 intentional
skips. The same timeout reproduces locally with profiling disabled; both
assertions pass with a diagnostic 60-second timeout override (about 23
seconds total). No source or CI timeout was changed.
- A dry run against real GitHub attempt 2 of run `38677445871` produced
exactly 3 executed jobs, 40 spans, and 510 seconds, excluding 45
carried-over jobs. The partial trace remains explicitly incomplete; this
validation did not upload data.
- `actionlint` passed for all four changed workflows. `git diff --check`
passed.
- Full Node 24 `pnpm -r typecheck` and `pnpm build` passed. The local
full `pnpm test:run` was stopped after it reported a setup-token timeout
and a distribution-plugin-catalog fixture failure. The 30 setup-token
tests passed on focused rerun. The plugin fixture fails at `rmSync` of a
directory symlink on this macOS/Node 24.11.0 host; the same failure
reproduces with the unchanged base Vitest configuration and unchanged
test/service files (10 other tests pass). The local full test suite is
therefore not claimed green.
- A real root-config Vitest probe passed 13 tests with profiling both
off and on. Multi-file Vitest, Playwright, and Node probes each verify
two distinct filename rows and four correctly parented tests, including
repeated test names across files. Separate passing probes exercise the
full exporter hierarchy `workflow → job → step → filename → tests`.
Intentional failing probes preserve failing exit status.
- Verified all 48 measured jobs in latest-head run `38728040302` used
AWS: one `paperclip-ci-routing-x64` gate and 47
`paperclip-public-pr-x64` jobs. Profiling preserves AWS authorization
and its GitHub-hosted fallback. The separate privileged exporter runs on
`ubuntu-latest` outside the measured suite.
- [Live Honeycomb
baseline](https://ui.honeycomb.io/paperclip/environments/test/datasets/paperclip-ci/trace/oaPMzw8zGwG):
48 jobs, 731 spans, 479 seconds. It matches [GitHub run
38671274294](https://github.com/paperclipai/paperclip/actions/runs/38671274294).
This historical trace has job/step data only; it is not proof of the
future label-triggered test-reporting journey.
- Verified the dedicated Honeycomb key is ingest-only with dataset
creation disabled. Verified the GitHub environment allows only the
`master` branch. No repository-level secret of that name exists. Both
credential values were scanned absent from source and branch history.

After merge, add `profile-ci` to a CI CODEOWNER PR, wait for the entire
PR run and exporter, then follow the run-summary link. Collapse job
children to compare parallel lanes; expand a job to inspect its steps
and tests.

## Risks

- Activation requires merging the trusted workflow definitions to
`master`. This PR continues using the current trusted reusable workflows
until then.
- Selected runs produce many spans and artifacts. Oversized artifacts
fail export instead of truncating data. Missing or cancelled reporters
are marked incomplete.
- GitHub timings have second precision. Node test times use reporter
receipt time. Rust retains job/step timing but lacks per-test wall
timestamps.
- CI CODEOWNERS are individual users in the explicit `.github/**` rule.
Unsupported team rules and identity lookup failures disable profiling.
- An interrupted upload can leave partial data. Retrying uses the same
span IDs, but the Events API does not promise deduplication.

## Model Used

OpenAI Codex, GPT-6 family, with reasoning, code execution, repository
tools, and browser verification. The runtime does not expose the exact
serving model ID or context-window size.

## 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
- [ ] 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-15 06:59:50 -05:00

121 lines
6.9 KiB
JavaScript

import { execFileSync } from "node:child_process";
import { appendFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { buildTrace, traceUrl } from "./trace.mjs";
import { associatedProfilePr, authorizedActors, trustedOwnerIds } from "./authorize.mjs";
const repository = "paperclipai/paperclip";
const repoPath = `/repos/${repository}`;
const maxBytes = 32 * 1024 * 1024;
const gh = (args) => execFileSync("gh", ["api", ...args], { maxBuffer: maxBytes, timeout: 60_000 });
const get = (endpoint) => JSON.parse(gh([endpoint]).toString());
const pages = (endpoint, field) => JSON.parse(gh(["--paginate", "--slurp", endpoint]).toString())
.flatMap((page) => field ? page[field] : page);
export async function sendEvents(events, apiKey, dataset, fetcher = fetch) {
if (!apiKey) throw new Error("HONEYCOMB_CI_API_KEY is not configured");
for (let offset = 0; offset < events.length; offset += 500) {
const batch = events.slice(offset, offset + 500);
const response = await fetcher(`https://api.honeycomb.io/1/batch/${encodeURIComponent(dataset)}`, {
method: "POST", headers: { "X-Honeycomb-Team": apiKey, "Content-Type": "application/json" },
body: JSON.stringify(batch), redirect: "error", signal: AbortSignal.timeout(30_000),
});
if (!response.ok) throw new Error(`Honeycomb export failed (HTTP ${response.status})`);
const results = await response.json();
if (!Array.isArray(results) || results.length !== batch.length || results.some((result) => result.status !== 202)) {
throw new Error("Honeycomb did not accept every span in the batch");
}
}
}
async function main() {
const args = process.argv.slice(2);
const arg = (name) => args.find((value) => value.startsWith(`${name}=`))?.slice(name.length + 1);
const event = process.env.GITHUB_EVENT_PATH ? JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, "utf8")) : null;
const runId = event?.workflow_run?.id ?? arg("--run-id");
const attempt = event?.workflow_run?.run_attempt ?? arg("--attempt");
if (!/^\d+$/.test(String(runId)) || !/^[1-9]\d*$/.test(String(attempt))) {
throw new Error("Provide --run-id and --attempt, or a workflow_run event");
}
const run = get(`${repoPath}/actions/runs/${runId}/attempts/${attempt}`);
if (run.repository?.full_name !== repository || run.event !== "pull_request"
|| run.path !== ".github/workflows/pr.yml" || run.status !== "completed") {
throw new Error("Only completed main PR workflow attempts can be profiled");
}
// GitHub often leaves workflow_run.pull_requests empty for fork PRs. Resolve
// association through the head commit, then validate repo and exact head.
const pulls = pages(`${repoPath}/commits/${run.head_sha}/pulls?per_page=100`);
const historical = args.includes("--historical");
if (historical && process.env.GITHUB_ACTIONS) throw new Error("Historical export is a local-only operation");
const ownerIds = historical ? [] : trustedOwnerIds(get);
if (process.env.GITHUB_ACTIONS) {
const exporterId = process.env.GITHUB_RUN_ID;
const exporterAttempt = process.env.GITHUB_RUN_ATTEMPT;
if (!/^\d+$/.test(exporterId) || !/^[1-9]\d*$/.test(exporterAttempt)) throw new Error("Invalid exporter run identity");
const exporter = get(`${repoPath}/actions/runs/${exporterId}/attempts/${exporterAttempt}`);
if (!authorizedActors(exporter, ownerIds)) {
console.log("Exporter actor is not a CI CODEOWNER; no data exported.");
return;
}
}
const pr = historical ? undefined : associatedProfilePr(run, pulls, ownerIds);
if (!pr && !historical) {
console.log("No CODEOWNERS-authorized profile-ci PR at this revision; no data exported.");
return;
}
const jobs = pages(`${repoPath}/actions/runs/${runId}/attempts/${attempt}/jobs?per_page=100`, "jobs");
const artifacts = pages(`${repoPath}/actions/runs/${runId}/artifacts?per_page=100`, "artifacts")
.filter((artifact) => artifact.name.startsWith(`ci-profile-${attempt}-`));
// The run name snapshots selection at dispatch. A label added while an
// ordinary run finishes must not retroactively select that earlier run.
if (!historical && !run.display_title.startsWith("CI profile · PR #")) {
console.log("This attempt was not selected for profiling; no data exported.");
return;
}
const directory = mkdtempSync(path.join(tmpdir(), "paperclip-ci-export-"));
const records = [];
let bytes = 0;
try {
for (const artifact of artifacts) {
if (artifact.expired || artifact.size_in_bytes > maxBytes) throw new Error("Timing artifact is expired or too large");
const archive = path.join(directory, `${artifact.id}.zip`);
writeFileSync(archive, gh([`${repoPath}/actions/artifacts/${artifact.id}/zip`]));
const decoded = execFileSync("python3", [fileURLToPath(new URL("./read-artifact.py", import.meta.url)), archive], {
encoding: "utf8", maxBuffer: maxBytes, timeout: 30_000,
});
bytes += Buffer.byteLength(decoded);
if (bytes > 128 * 1024 * 1024) throw new Error("Run timing artifacts exceed 128 MiB; refusing to truncate the trace");
for (const line of decoded.trim().split("\n").filter(Boolean)) records.push(JSON.parse(line));
}
} finally {
rmSync(directory, { recursive: true, force: true });
}
const trace = buildTrace(run, jobs, records);
trace.events[0].data["ci.profile_source"] = historical ? "historical" : "label";
const dataset = process.env.HONEYCOMB_CI_DATASET || "paperclip-ci";
const url = traceUrl(process.env.HONEYCOMB_TEAM || "paperclip", process.env.HONEYCOMB_ENVIRONMENT || "test", dataset, trace);
if (arg("--output")) writeFileSync(arg("--output"), JSON.stringify(trace, null, 2));
if (!args.includes("--dry-run")) {
// Publish the completed root only after every child has been accepted.
// A failed partial export must not advertise complete coverage.
await sendEvents(trace.events.slice(1), process.env.HONEYCOMB_CI_API_KEY, dataset);
await sendEvents([trace.events[0]], process.env.HONEYCOMB_CI_API_KEY, dataset);
}
const summary = [
`### CI profile${pr ? ` for PR #${pr.number}` : " (historical job/step baseline)"}`,
"", `[Open the full CI waterfall in Honeycomb](${url})`, "",
`${trace.jobCount} jobs · ${(trace.wallMs / 1000).toFixed(1)} seconds elapsed · ${trace.events.length} spans`,
"", `GitHub run: ${run.html_url}/attempts/${attempt}`, "",
...trace.warnings.map((warning) => `- ${warning}`),
"", "The workflow root measures elapsed time. Parallel job durations must not be summed as elapsed time.", "",
].join("\n");
console.log(summary);
if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary);
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main().catch((error) => { console.error(error.message); process.exitCode = 1; });
}