GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — t3code/.github/scripts/thread-transfer-report.cjs at collin/main · collissimo/t3code Expand file tree/ Copy paththread-transfer-report.cjsMore file actions 602 lines (558 loc) · 20.5 KB / Copy paththread-transfer-report.cjsFile metadata and controls602 lines (558 loc) · 20.5 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 const fs = require("node:fs"); const path = require("node:path"); const ARTIFACT_NAME = "thread-transfer-results"; const RESULT_FILE = "thread-transfer-result.json"; const SCENARIOS_FILE = "thread-transfer-scenarios.json"; const COMMENT_MARKER = "<!-- t3-thread-transfer-report -->"; const PROVIDERS = ["codex", "claudeAgent"]; const OBSERVED_KEYS = [ "totalWireBytes", "threadSnapshotWireBytes", "threadSnapshotDecodedBytes", "measuredTurnWebSocketWireBytes", "measuredTurnWebSocketDecodedBytes", "measuredTurnWebSocketMessages", ]; const CEILING_KEYS = [ "totalWireBytes", "threadSnapshotWireBytes", "measuredTurnWebSocketWireBytes", "measuredTurnWebSocketDecodedBytes", "measuredTurnWebSocketMessages", ]; const SCENARIO_KEYS = [ "id", "historyTurns", "historyCommandToolsPerTurn", "historyMcpResultBytes", "measuredCommandTools", "measuredMcpResultBytes", ]; const SCENARIO_ROW_KEYS = ["phase", "metric", "unit", "observed", "ceiling"]; // These labels come from the PR and reach a comment the bot posts: no markup, links or mentions. // GitHub still links plain text such as `GH-26`, so they are rendered as code spans. const SCENARIO_LABEL = /^[A-Za-z0-9][A-Za-z0-9 ,-]{0,79}$/; const MAX_SCENARIO_ROWS = 100; function resultShaMarker(sha) { return `<!-- t3-thread-transfer-result-sha:${sha} -->`; } function assertObject(value, label) { if (value === null || typeof value !== "object" || Array.isArray(value)) { throw new Error(`${label} must be an object`); } } function assertExactKeys(value, expected, label) { assertObject(value, label); const actual = Object.keys(value).sort(); const wanted = [...expected].sort(); if (actual.length !== wanted.length || actual.some((key, index) => key !== wanted[index])) { throw new Error(`${label} has unexpected fields`); } } function assertMetric(value, label) { if (!Number.isSafeInteger(value) || value < 0 || value > 1_000_000_000) { throw new Error(`${label} must be a non-negative safe integer below 1,000,000,000`); } } function validateResult(value) { assertExactKeys(value, ["schemaVersion", "scenario", "providers"], "result"); if (value.schemaVersion !== 1) { throw new Error("result.schemaVersion must be 1"); } assertExactKeys(value.scenario, SCENARIO_KEYS, "result.scenario"); if (!["thread-transfer-v1", "thread-transfer-v2"].includes(value.scenario.id)) { throw new Error("result.scenario.id is not supported"); } for (const key of SCENARIO_KEYS.slice(1)) { assertMetric(value.scenario[key], `result.scenario.${key}`); } assertExactKeys(value.providers, PROVIDERS, "result.providers"); for (const provider of PROVIDERS) { const entry = value.providers[provider]; assertExactKeys(entry, ["observed", "ceiling"], `result.providers.${provider}`); assertExactKeys(entry.observed, OBSERVED_KEYS, `result.providers.${provider}.observed`); assertExactKeys(entry.ceiling, CEILING_KEYS, `result.providers.${provider}.ceiling`); for (const key of OBSERVED_KEYS) { assertMetric(entry.observed[key], `result.providers.${provider}.observed.${key}`); } for (const key of CEILING_KEYS) { assertMetric(entry.ceiling[key], `result.providers.${provider}.ceiling.${key}`); } } return value; } function validateScenarios(value) { assertExactKeys(value, ["schemaVersion", "providers"], "scenarios"); if (value.schemaVersion !== 1) { throw new Error("scenarios.schemaVersion must be 1"); } assertExactKeys(value.providers, PROVIDERS, "scenarios.providers"); for (const provider of PROVIDERS) { const rows = value.providers[provider]; if (!Array.isArray(rows) || rows.length > MAX_SCENARIO_ROWS) { throw new Error( `scenarios.providers.${provider} must list at most ${MAX_SCENARIO_ROWS} rows`, ); } const seen = new Set(); for (const [index, row] of rows.entries()) { const label = `scenarios.providers.${provider}[${index}]`; assertExactKeys(row, SCENARIO_ROW_KEYS, label); for (const key of ["phase", "metric"]) { if (typeof row[key] !== "string" || !SCENARIO_LABEL.test(row[key])) { throw new Error(`${label}.${key} must be a short plain label`); } } if (row.unit !== "bytes" && row.unit !== "count") { throw new Error(`${label}.unit must be bytes or count`); } assertMetric(row.observed, `${label}.observed`); assertMetric(row.ceiling, `${label}.ceiling`); const key = scenarioKey(row); if (seen.has(key)) throw new Error(`${label} repeats an earlier row`); seen.add(key); } } return value; } function scenarioKey(row) { return `${row.phase}|${row.metric}`; } function readArtifactFile(directory, name, validate) { if (!directory) return undefined; const file = path.join(directory, name); if (!fs.existsSync(file)) return undefined; const stat = fs.lstatSync(file); if (!stat.isFile() || stat.size > 64 * 1_024) { throw new Error(`${name} must be a regular file smaller than 64 KiB`); } return validate(JSON.parse(fs.readFileSync(file, "utf8"))); } function readResult(directory) { return readArtifactFile(directory, RESULT_FILE, validateResult); } // Older runs upload only the result file, so a run without scenarios is still a valid run. function readScenarios(directory) { return readArtifactFile(directory, SCENARIOS_FILE, validateScenarios); } function formatBytes(bytes) { if (bytes < 1_024) return `${bytes} B`; if (bytes >= 1_024 * 1_024) return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB`; return `${(bytes / 1_024).toFixed(1)} KiB`; } function formatValue(value, kind) { return kind === "bytes" ? formatBytes(value) : value.toLocaleString("en-US"); } function formatImpact(current, baseline, kind) { if (baseline === undefined) return "—"; const delta = current - baseline; const prefix = delta > 0 ? "+" : delta < 0 ? "−" : ""; const magnitude = formatValue(Math.abs(delta), kind); const percent = baseline === 0 ? "" : ` (${prefix}${Math.abs((delta / baseline) * 100).toFixed(1)}%)`; return `${prefix}${magnitude}${percent}`; } function sameScenario(left, right) { return SCENARIO_KEYS.every((key) => left[key] === right[key]); } const METRICS = [ { key: "totalWireBytes", label: "Total thread wire", kind: "bytes" }, { key: "threadSnapshotWireBytes", label: "Thread snapshot wire", kind: "bytes" }, { key: "measuredTurnWebSocketWireBytes", label: "Live turn WebSocket wire", kind: "bytes", }, { key: "measuredTurnWebSocketDecodedBytes", label: "Live turn WebSocket decoded", kind: "bytes", }, { key: "measuredTurnWebSocketMessages", label: "Live turn messages", kind: "messages" }, ]; function providerLabel(provider) { return provider === "codex" ? "Codex" : "Claude"; } /** * The scenario rows of a run against the same rows on `main`. Rows that fail or differ from * `main` are listed in the open; the full table is collapsed below them. */ function renderScenarios(current, baseline, ceilingChanges) { if (!current) return { lines: [], failed: false }; const header = [ "| Provider | Scenario | Metric | Main baseline | This PR | Impact | PR ceiling | |", "| --- | --- | --- | ---: | ---: | ---: | ---: | --- |", ]; const all = []; const notable = []; let failed = false; let withoutBaseline = 0; for (const provider of PROVIDERS) { const baselineRows = new Map( (baseline?.providers[provider] ?? []).map((row) => [scenarioKey(row), row]), ); for (const row of current.providers[provider]) { const before = baselineRows.get(scenarioKey(row)); const beforeObserved = before?.unit === row.unit ? before.observed : undefined; const pass = row.observed <= row.ceiling; failed ||= !pass; if (beforeObserved === undefined) withoutBaseline += 1; const line = `| ${providerLabel(provider)} | \`${row.phase}\` | \`${row.metric}\` | ${beforeObserved === undefined ? "—" : formatValue(beforeObserved, row.unit)} | ${formatValue(row.observed, row.unit)} | ${formatImpact(row.observed, beforeObserved, row.unit)} | ${formatValue(row.ceiling, row.unit)} | ${pass ? "✅" : "❌"} |`; all.push(line); if (!pass || (beforeObserved !== undefined && beforeObserved !== row.observed)) { notable.push(line); } if (beforeObserved !== undefined && before.ceiling !== row.ceiling) { ceilingChanges.push( `- ${providerLabel(provider)} \`${row.phase}\` \`${row.metric}\`: ${formatValue(before.ceiling, row.unit)} → ${formatValue(row.ceiling, row.unit)}`, ); } } } const compared = all.length - withoutBaseline; const summary = !baseline ? `No \`main\` baseline exists yet for these ${all.length} scenario measurements.` : [ notable.length > 0 ? `${notable.length} of ${all.length} scenario measurements changed or failed.` : `${compared === all.length ? "All " : ""}${compared} scenario measurements match \`main\`.`, ...(withoutBaseline > 0 ? [`${withoutBaseline} have no \`main\` baseline.`] : []), ].join(" "); return { failed, lines: [ "### Other scenarios", "", summary, ...(notable.length > 0 ? ["", ...header, ...notable] : []), "", "<details>", `<summary>All ${all.length} scenario measurements</summary>`, "", ...header, ...all, "", "</details>", "", ], }; } function renderComment(input) { const current = input.current; const baseline = input.baseline; const comparable = baseline !== undefined && sameScenario(current.scenario, baseline.scenario); const rows = []; const ceilingChanges = []; let failed = false; for (const provider of PROVIDERS) { for (const metric of METRICS) { const observed = current.providers[provider].observed[metric.key]; const ceiling = current.providers[provider].ceiling[metric.key]; const baselineObserved = comparable ? baseline.providers[provider].observed[metric.key] : undefined; const pass = observed <= ceiling; failed ||= !pass; rows.push( `| ${providerLabel(provider)} | ${metric.label} | ${baselineObserved === undefined ? "—" : formatValue(baselineObserved, metric.kind)} | ${formatValue(observed, metric.kind)} | ${formatImpact(observed, baselineObserved, metric.kind)} | ${formatValue(ceiling, metric.kind)} | ${pass ? "✅" : "❌"} |`, ); if (comparable && baseline.providers[provider].ceiling[metric.key] !== ceiling) { ceilingChanges.push( `- ${providerLabel(provider)} ${metric.label}: ${formatValue(baseline.providers[provider].ceiling[metric.key], metric.kind)} → ${formatValue(ceiling, metric.kind)}`, ); } } } const scenarios = renderScenarios( input.currentScenarios, input.baselineScenarios, ceilingChanges, ); failed ||= scenarios.failed; const baselineLink = input.baselineRun ? `[\`${input.baselineRun.sha.slice(0, 7)}\`](${input.baselineRun.url})` : "unavailable"; const currentLink = `[\`${input.currentRun.sha.slice(0, 7)}\`](${input.currentRun.url})`; const notices = []; if (!baseline) { notices.push( "> ℹ️ No successful `main` baseline artifact is available yet. This run establishes the initial measurement.", ); } else if (!comparable) { notices.push( "> ⚠️ The thread fixture changed, so impact percentages are not directly comparable to the `main` baseline.", ); } else if (!input.baselineRun.matchesBase) { notices.push( "> ℹ️ The exact PR base did not have a successful artifact. Baseline uses the latest successful `main` measurement shown below.", ); } if (ceilingChanges.length > 0) { notices.push( `> ⚠️ **This PR changes transfer ceilings:**\n>\n${ceilingChanges.map((line) => `> ${line}`).join("\n")}`, ); } return [ COMMENT_MARKER, resultShaMarker(input.currentRun.sha), "## Thread transfer impact", "", failed ? "❌ One or more thread transfer ceilings were exceeded." : "✅ Thread transfer remains within every enforced ceiling.", ...(notices.length > 0 ? ["", ...notices] : []), "", "| Provider | Metric | Main baseline | This PR | Impact | PR ceiling | |", "| --- | --- | ---: | ---: | ---: | ---: | --- |", ...rows, "", ...scenarios.lines, `Baseline: ${baselineLink} · PR result: ${currentLink} · Source CI: ${input.currentRun.conclusion}`, "", "<details>", "<summary>Scenario and decoded snapshot size</summary>", "", `${current.scenario.historyTurns} historical turns, ${current.scenario.historyCommandToolsPerTurn} command tools per turn, ${formatBytes(current.scenario.historyMcpResultBytes)} retained MCP result per historical turn, and a ${formatBytes(current.scenario.measuredMcpResultBytes)} retained result in the measured turn.`, "", ...PROVIDERS.map( (provider) => `- ${providerLabel(provider)} decoded thread snapshot: ${formatBytes(current.providers[provider].observed.threadSnapshotDecodedBytes)}`, ), "", "</details>", "", "_Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed._", ].join("\n"); } async function artifactsForRun(github, owner, repo, runId) { return github.paginate(github.rest.actions.listWorkflowRunArtifacts, { owner, repo, run_id: runId, per_page: 100, }); } function findResultArtifact(artifacts) { return artifacts.find((artifact) => artifact.name === ARTIFACT_NAME && !artifact.expired); } async function resolve({ github, context, core }) { const source = context.payload.workflow_run; const { owner, repo } = context.repo; if (source.event !== "pull_request") { core.setOutput("publish", "false"); return; } let pullNumber = source.pull_requests?.[0]?.number; if (!pullNumber) { let associated; try { associated = await github.paginate(github.rest.repos.listPullRequestsAssociatedWithCommit, { owner, repo, commit_sha: source.head_sha, per_page: 100, }); } catch (error) { // A force-pushed or deleted PR head can disappear before this workflow runs. if ( error.status === 422 && error.response?.data?.message === `No commit found for SHA: ${source.head_sha}` ) { core.info(`Skipping CI result for unavailable commit ${source.head_sha}.`); core.setOutput("publish", "false"); return; } throw error; } const matchingPulls = associated.filter( (pull) => pull.state === "open" && pull.head.sha === source.head_sha && pull.head.ref === source.head_branch, ); if (matchingPulls.length !== 1) { core.info( `Expected one open pull request for ${source.head_repository?.full_name ?? "unknown repository"}:${source.head_branch ?? "unknown branch"} at ${source.head_sha}; found ${matchingPulls.length}.`, ); core.setOutput("publish", "false"); return; } pullNumber = matchingPulls[0].number; } if (!pullNumber) { core.info("No open pull request is associated with the completed CI run."); core.setOutput("publish", "false"); return; } const { data: pull } = await github.rest.pulls.get({ owner, repo, pull_number: pullNumber }); if (pull.head.sha !== source.head_sha) { core.info(`Skipping stale CI result ${source.head_sha}; PR head is ${pull.head.sha}.`); core.setOutput("publish", "false"); return; } const sourceArtifacts = await artifactsForRun(github, owner, repo, source.id); const sourceArtifact = findResultArtifact(sourceArtifacts); // Successful server tests require this artifact; its absence means CI skipped them. if (!sourceArtifact && source.conclusion === "success") { core.info("CI skipped the server tests for this change; nothing to report."); core.setOutput("publish", "false"); return; } // One page each for the exact base and the newest runs; paging through // every successful main run costs up to ten requests to keep 20. const listRuns = async (filters) => { const { data } = await github.rest.actions.listWorkflowRuns({ owner, repo, workflow_id: source.workflow_id, branch: pull.base.ref, event: "push", status: "success", per_page: 20, ...filters, }); return data.workflow_runs; }; const [baseRuns, recentRuns] = await Promise.all([ listRuns({ head_sha: pull.base.sha }), listRuns({}), ]); const orderedRuns = [ ...baseRuns, ...recentRuns.filter((run) => run.head_sha !== pull.base.sha), ].slice(0, 20); let baselineRun; for (const run of orderedRuns) { const artifacts = await artifactsForRun(github, owner, repo, run.id); if (findResultArtifact(artifacts)) { baselineRun = run; break; } } core.setOutput("publish", "true"); core.setOutput("pull_number", String(pullNumber)); core.setOutput("pr_artifact", sourceArtifact ? "true" : "false"); core.setOutput("pr_run_id", String(source.id)); core.setOutput("pr_sha", source.head_sha); core.setOutput("pr_conclusion", source.conclusion ?? "unknown"); core.setOutput("baseline_artifact", baselineRun ? "true" : "false"); core.setOutput("baseline_run_id", baselineRun ? String(baselineRun.id) : ""); core.setOutput("baseline_sha", baselineRun?.head_sha ?? ""); core.setOutput( "baseline_matches_base", baselineRun?.head_sha === pull.base.sha ? "true" : "false", ); } async function upsertComment(github, context, pullNumber, body, options = {}) { const { owner, repo } = context.repo; const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number: pullNumber, per_page: 100, }); const existing = comments.find( (comment) => comment.user?.login === "github-actions[bot]" && comment.body?.includes(COMMENT_MARKER), ); if ( options.preserveResultSha && existing?.body?.includes(resultShaMarker(options.preserveResultSha)) ) { return; } if (existing) { await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body }); } else { await github.rest.issues.createComment({ owner, repo, issue_number: pullNumber, body }); } } async function upsertCommentForCurrentHead( github, context, core, pullNumber, expectedSha, body, options, ) { const { owner, repo } = context.repo; const { data: pull } = await github.rest.pulls.get({ owner, repo, pull_number: pullNumber, }); if (pull.head.sha !== expectedSha) { core.info(`Skipping stale CI result ${expectedSha}; PR head is ${pull.head.sha}.`); return false; } await upsertComment(github, context, pullNumber, body, options); return true; } async function publish({ github, context, core }) { const pullNumber = Number(process.env.PR_NUMBER); if (!Number.isSafeInteger(pullNumber) || pullNumber <= 0) { throw new Error("PR_NUMBER is invalid"); } const current = readResult(process.env.PR_RESULT_DIR); const currentRun = { sha: process.env.PR_SHA, conclusion: process.env.PR_CONCLUSION, url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.PR_RUN_ID}`, }; if (!current) { await upsertCommentForCurrentHead( github, context, core, pullNumber, currentRun.sha, [ COMMENT_MARKER, "## Thread transfer impact", "", `⚠️ The latest [CI run](${currentRun.url}) did not produce a thread transfer result for \`${currentRun.sha.slice(0, 7)}\`.`, "", "_This comment will update automatically after the next completed run._", ].join("\n"), { preserveResultSha: currentRun.sha }, ); return; } const baseline = readResult(process.env.BASELINE_RESULT_DIR); const baselineRun = baseline ? { sha: process.env.BASELINE_SHA, matchesBase: process.env.BASELINE_MATCHES_BASE === "true", url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.BASELINE_RUN_ID}`, } : undefined; const body = renderComment({ current, baseline, currentScenarios: readScenarios(process.env.PR_RESULT_DIR), baselineScenarios: readScenarios(process.env.BASELINE_RESULT_DIR), currentRun, baselineRun, }); const published = await upsertCommentForCurrentHead( github, context, core, pullNumber, currentRun.sha, body, ); if (published) { core.info(`Updated thread transfer report on PR #${pullNumber}.`); } } module.exports = { publish, readResult, renderComment, resolve, upsertCommentForCurrentHead, validateResult, validateScenarios, }; |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |