Repository navigation
ci: preserve timing evidence from interrupted Python shards #6318
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a7cae58
ci: retain incremental pytest timing evidence across interruption
loopx-agent c5cf3fb
docs: explain CI timing readback and measurement limits
loopx-agent ac2e2ba
Merge remote-tracking branch 'origin/main' into codex/python-ci-criti…
loopx-agent b3dfe66
fix(ci): keep interrupted pytest observations usable
loopx-agent 735ee23
Merge remote-tracking branch 'origin/main' into codex/python-ci-criti…
loopx-agent 9795f25
fix(ci): frame timing records alongside quiet pytest progress
loopx-agent c93b704
fix(ci): read timing observations across GitHub log chunks
loopx-agent File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| """Stream pytest-owned timings from the controller, including interrupted runs. | ||
|
|
||
| This is a CI observation adapter, not a splitter, timing cache or test gate. | ||
| Load explicitly with ``-p scripts.ci.pytest_timing``. No configuration or test | ||
| selection changes; node ids and phase/outcome values come from pytest itself. | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import hashlib | ||
| import math | ||
| import time | ||
|
|
||
| import pytest | ||
| from _pytest.subtests import SubtestReport | ||
|
|
||
|
|
||
| PREFIX = "LOOPX_PYTEST_TIMING " | ||
|
|
||
|
|
||
| def pytest_configure(config): | ||
| # xdist sends TestReports to the controller. Worker output would duplicate | ||
| # reports and can be lost when a worker is killed. | ||
| if not hasattr(config, "workerinput"): | ||
| config.pluginmanager.register(TimingObserver(config), "loopx-ci-timing-observer") | ||
|
|
||
|
|
||
| class TimingObserver: | ||
| def __init__(self, config): | ||
| self.config = config | ||
| self.started = time.perf_counter() | ||
| self.collection = None | ||
|
|
||
| def emit(self, **row): | ||
| row["elapsed_seconds"] = round(time.perf_counter() - self.started, 6) | ||
| line = PREFIX + json.dumps(row, ensure_ascii=True, allow_nan=False, separators=(",", ":")) | ||
| reporter = self.config.pluginmanager.get_plugin("terminalreporter") | ||
| if reporter is not None: | ||
| reporter.ensure_newline() | ||
| # Quiet progress writes directly to the terminal writer without | ||
| # currentfspath, so ensure_newline alone cannot end that line. | ||
| if reporter._tw.width_of_current_line: | ||
| reporter._tw.line() | ||
| reporter.write_line(line) | ||
| reporter._tw.flush() | ||
|
|
||
| @pytest.hookimpl(trylast=True) | ||
| def pytest_sessionstart(self, session): | ||
| self.emit(event="start", version=1) | ||
|
|
||
| def record_collection(self, ids): | ||
| if self.collection is None: | ||
| self.collection = tuple(ids) | ||
| self.emit(event="collection", selected=len(ids)) | ||
| elif self.collection != tuple(ids): | ||
| # xdist owns rejecting different worker collections. Preserve the | ||
| # observation without changing that decision or claiming coverage. | ||
| self.emit(event="collection_mismatch") | ||
|
|
||
| @pytest.hookimpl(optionalhook=True) | ||
| def pytest_xdist_node_collection_finished(self, node, ids): | ||
| self.record_collection(ids) | ||
|
|
||
| def pytest_collection_finish(self, session): | ||
| if not getattr(self.config.option, "numprocesses", None): | ||
| self.record_collection([item.nodeid for item in session.items]) | ||
|
|
||
| def pytest_runtest_logreport(self, report): | ||
| # A subtest is nested within its collected item's call phase. Its | ||
| # duration is already included there; it is not another selected item | ||
| # or another call phase. Keep pytest's own subtest result reporting. | ||
| if isinstance(report, SubtestReport): | ||
| return | ||
| duration = report.duration | ||
| # Parameter payloads can be huge or trigger hosted secret masking, | ||
| # corrupting JSON. Hash full identity; display only the parent name. | ||
| self.emit(event="phase", test_id=hashlib.sha256( | ||
| report.nodeid.encode("utf-8", errors="surrogatepass")).hexdigest(), | ||
| display_nodeid=report.nodeid.partition("[")[0][:256], phase=report.when, | ||
| outcome=report.outcome, | ||
| seconds=duration if math.isfinite(duration) and duration >= 0 else None) | ||
|
|
||
| @pytest.hookimpl(trylast=True) | ||
| def pytest_sessionfinish(self, session, exitstatus): | ||
| self.emit(event="end", exit_code=int(session.exitstatus)) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| /** Read CI timing observations; never supplies a test gate or reusable cache. */ | ||
| import { readFileSync, statSync } from "node:fs"; | ||
| import { pathToFileURL } from "node:url"; | ||
|
|
||
| const prefix = "LOOPX_PYTEST_TIMING "; | ||
| type Phase = "setup" | "call" | "teardown"; // pytest TestReport vocabulary, local adapter | ||
| type Outcome = "passed" | "failed" | "skipped"; | ||
| type Observation = { seconds: number | null; outcome: Outcome }; | ||
| type Case = { display_nodeid: string } & Partial<Record<Phase, Observation>>; | ||
|
|
||
| function finite(value: unknown): value is number { | ||
| return typeof value === "number" && Number.isFinite(value) && value >= 0; | ||
| } | ||
|
|
||
| export function summarizeTimingLog(log: string) { | ||
| const cases = new Map<string, Case>(); | ||
| let started = false, ended = false; | ||
| let selected: number | null = null, exitCode: number | null = null; | ||
| let elapsed = 0, records = 0; | ||
| for (const original of log.split(/\r?\n/)) { | ||
| const line = original.replace(/^\uFEFF/, "").replace(/\x1b\[[0-9;]*m/g, "") | ||
| .replace(/^\d{4}-\d{2}-\d{2}T\S+Z\s+/, ""); | ||
| if (!line.startsWith(prefix)) continue; | ||
| if (++records > 200_000) throw new Error("Timing log exceeds the observation limit."); | ||
| const row = JSON.parse(line.slice(prefix.length)); | ||
| if (!row || Array.isArray(row) || typeof row !== "object" || | ||
| !finite(row.elapsed_seconds) || row.elapsed_seconds < elapsed || ended) { | ||
| throw new Error("Invalid timing record order or elapsed duration."); | ||
| } | ||
| elapsed = row.elapsed_seconds; | ||
| if (row.event === "start") { | ||
| if (started || records !== 1 || row.version !== 1) throw new Error("Invalid timing start."); | ||
| started = true; | ||
| } else if (!started) { | ||
| throw new Error("Timing record has no start."); | ||
| } else if (row.event === "collection") { | ||
| if (selected !== null || cases.size || !Number.isSafeInteger(row.selected) || row.selected < 0) { | ||
| throw new Error("Invalid selected collection count."); | ||
| } | ||
| selected = row.selected; | ||
| } else if (row.event === "phase") { | ||
| if (selected === null || typeof row.test_id !== "string" || !/^[a-f0-9]{64}$/.test(row.test_id) || | ||
| typeof row.display_nodeid !== "string" || !row.display_nodeid || | ||
| row.display_nodeid.length > 512 || !["setup", "call", "teardown"].includes(row.phase) || | ||
| !["passed", "failed", "skipped"].includes(row.outcome) || | ||
| (row.seconds !== null && !finite(row.seconds))) throw new Error("Invalid pytest phase."); | ||
| const phase = row.phase as Phase; | ||
| const entry: Case = cases.get(row.test_id) ?? { display_nodeid: row.display_nodeid }; | ||
| if (entry.display_nodeid !== row.display_nodeid || entry[phase] || (phase !== "setup" && !entry.setup) || | ||
| (phase === "call" && entry.setup?.outcome !== "passed") || entry.teardown) { | ||
| throw new Error("Duplicate or out-of-order pytest phase."); | ||
| } | ||
| entry[phase] = { seconds: row.seconds, outcome: row.outcome as Outcome }; | ||
| cases.set(row.test_id, entry); | ||
| if (cases.size > selected) throw new Error("Reported cases exceed the selected collection."); | ||
| } else if (row.event === "end") { | ||
| if (!Number.isInteger(row.exit_code) || row.exit_code < 0 || row.exit_code > 5) { | ||
| throw new Error("Invalid pytest exit code."); | ||
| } | ||
| exitCode = row.exit_code; | ||
| ended = true; | ||
| } else { | ||
| throw new Error(`Unusable timing event: ${String(row.event)}`); | ||
| } | ||
| } | ||
| if (!started) throw new Error("No CI timing observations found; this is not a zero-cost run."); | ||
| let measured = 0, invalid = 0, finished = 0; | ||
| const phaseSeconds = { setup: 0, call: 0, teardown: 0 }; | ||
| const longest = []; | ||
| for (const [testId, entry] of cases) { | ||
| let seconds = 0; | ||
| for (const phase of ["setup", "call", "teardown"] as const) { | ||
| const value = entry[phase]?.seconds; | ||
| if (value === null) invalid++; | ||
| else if (value !== undefined) { seconds += value; phaseSeconds[phase] += value; } | ||
| } | ||
| measured += seconds; | ||
| const caseFinished = !!(entry.teardown && (entry.call || entry.setup?.outcome !== "passed")); | ||
| if (caseFinished) finished++; | ||
| longest.push({ test_id: testId, display_nodeid: entry.display_nodeid, | ||
| measured_seconds: seconds, finished: caseFinished }); | ||
| } | ||
| longest.sort((a, b) => b.measured_seconds - a.measured_seconds || a.test_id.localeCompare(b.test_id)); | ||
| return { | ||
| execution_complete: ended && (exitCode === 0 || exitCode === 1) && | ||
| selected !== null && selected > 0 && finished === selected && invalid === 0, | ||
| pytest_exit_code: exitCode, | ||
| selected_cases: selected, | ||
| observed_cases: cases.size, | ||
| finished_cases: finished, | ||
| invalid_duration_count: invalid, | ||
| observed_elapsed_seconds: elapsed, | ||
| measured_worker_seconds: measured, | ||
| phase_seconds: phaseSeconds, | ||
| longest_cases: longest.slice(0, 25), | ||
| }; | ||
| } | ||
|
|
||
| if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { | ||
| try { | ||
| if (process.argv.length !== 3) throw new Error("Usage: node scripts/ci/pytest_timing.ts JOB_LOG"); | ||
| if (statSync(process.argv[2]).size > 32 * 1024 * 1024) throw new Error("Job log exceeds 32 MiB."); | ||
| process.stdout.write(JSON.stringify(summarizeTimingLog(readFileSync(process.argv[2], "utf8")), null, 2) + "\n"); | ||
| } catch (error) { | ||
| process.stderr.write(`${error instanceof Error ? error.message : error}\n`); | ||
| process.exitCode = 1; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.