diff --git a/.cursor/rules/xprobe.mdc b/.cursor/rules/xprobe.mdc index 99eb747..12b1693 100644 --- a/.cursor/rules/xprobe.mdc +++ b/.cursor/rules/xprobe.mdc @@ -1,8 +1,8 @@ --- -description: Shared xprobe engineering and measurement workflow +description: Shared xprobe engineering and profiling skill alwaysApply: true --- -Follow `AGENTS.md` for repository engineering rules. For latency measurement -tasks, follow `skills/xprobe-measure-latency/SKILL.md`. Do not create a -Cursor-specific measurement workflow or reinterpret the checked-in JSON schemas. +Follow `AGENTS.md` for repository engineering rules. For profiling tasks, +follow `skills/xprobe-perf-profiling/SKILL.md`. Do not create a +Cursor-specific profiling workflow or reinterpret the checked-in JSON schemas. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 317bcc8..6505220 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -135,6 +135,9 @@ jobs: dist/${{ steps.package.outputs.name }}.tar.gz.sha256 dist/${{ steps.package.outputs.name }}.spdx.json generate_release_notes: true + # X.Y.Z-dev.N tags are prereleases and never become latest. + prerelease: ${{ contains(github.ref_name, '-dev.') }} + make_latest: ${{ !contains(github.ref_name, '-dev.') }} - name: Verify public release archive env: GH_TOKEN: ${{ github.token }} @@ -165,12 +168,27 @@ jobs: python-version: "3.12" - name: Verify the public PyPI wheel run: | + # PyPI names X.Y.Z-dev.N as X.Y.Z.devN. version=${GITHUB_REF_NAME#v} + version=${version/-dev./.dev} + # The simple index is cached for minutes after an upload; the + # per-version JSON is fresh on its first request. for attempt in $(seq 1 30); do - if python -m pip download --quiet --no-deps --only-binary :all: \ - --dest public "xprobe==${version}"; then + if curl -fsSL -o release.json "https://pypi.org/pypi/xprobe/${version}/json?attempt=${attempt}"; then break fi - sleep 20 + sleep 10 done - PYTHON=python tests/install/test_wheel.sh public/xprobe-"${version}"-*.whl + read -r url digest < <(python - <<'PY' + import json + files = json.load(open("release.json"))["urls"] + wheel, = [f for f in files if f["packagetype"] == "bdist_wheel"] + print(wheel["url"], wheel["digests"]["sha256"]) + PY + ) + mkdir -p public + curl -fsSL -o "public/${url##*/}" "$url" + # PyPI serves the wheel this run built. + echo "${digest} public/${url##*/}" | sha256sum -c - + echo "${digest} dist/${url##*/}" | sha256sum -c - + PYTHON=python tests/install/test_wheel.sh "public/${url##*/}" diff --git a/.gitlint b/.gitlint new file mode 100644 index 0000000..f98bd9d --- /dev/null +++ b/.gitlint @@ -0,0 +1,16 @@ +# Commit message rules, checked by `just lint-commits`. +[general] +# A one-line commit is fine. +ignore=body-is-missing,body-min-length +regex-style-search=true + +# GitHub cuts titles longer than 72 characters. +[title-max-length] +line-length=72 + +# Emoji conventional commits, e.g. "๐Ÿ› fix: restore target registers". +[title-match-regex] +regex=^\S+ (feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-z0-9-]+\))?!?: \S + +[body-max-line-length] +line-length=80 diff --git a/AGENTS.md b/AGENTS.md index 5bde077..a5d1f3c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,104 +2,97 @@ ## Sources of truth -- Code, tests, and checked-in JSON schemas define implemented behavior. -- `README.md` and `docs/` describe released behavior. Rewrite stale sections in - place when behavior changes; do not append historical caveats or parallel - inventories. -- Treat user reports and external reviews as evidence to investigate, not as - implemented fact. Verify claims about bounds, clocks, filtering, lifecycle, - and errors against code and tests before documenting or changing them. +- Code, tests, and `schemas/` define implemented behavior. +- `README.md` and `docs/` describe current behavior. Rewrite stale sections in + place instead of appending historical version notes, and keep version strings + matched across manifests and docs. +- Write docs, Skills, and comments in plain, direct engineering prose โ€” skip + defensive disclaimers, walls of text, and jargon filler (e.g. "contracts", + "gates", repeating "bounded"). +- Verify bug reports and review claims against code and tests before changing + or documenting anything. -## Boundaries +## Architecture & boundaries -- The public CLI is exactly `doctor`, `discover`, `validate`, and `measure`. -- Keep public contracts in `xprobe/protocol`, deterministic Linux logic in - `xprobe/core`, collection in `xprobe/collector`, matching in - `xprobe/correlator`, export in `xprobe/exporter`, and orchestration in the CLI. -- Do not add a daemon or persistent session service without a concrete workflow - that cannot be expressed by the four bounded commands. +- The public CLI is strictly `doctor`, `discover`, `validate`, and `measure`. + Do not add a daemon or persistent service unless a concrete workflow cannot + be expressed with these four commands. +- Crate layout: public types and JSON schemas in `xprobe/protocol`, + deterministic Linux logic in `xprobe/core`, collection in `xprobe/collector`, + matching in `xprobe/correlator`, export in `xprobe/exporter`, and CLI + orchestration in `xprobe/cli`. - Keep eBPF and CUPTI callback hot paths bounded and free of blocking I/O. -- Resolve architecture-specific syscall names in core. In BPF, filter process - identity and syscall number before reading scalar registers or reserving a - record. Arm multi-link collectors only after every link is attached. +- Resolve arch-specific syscall names in `core`. In BPF, filter PID and syscall + number before reading scalar registers or reserving a record. Arm multi-link + collectors only after every link attaches. - Resolve runtime probes from mapped binary capabilities, not process names. - libbpf USDT attachment requires its support maps even when xprobe does not - read marker arguments. + libbpf USDT attachment needs its support maps even when marker arguments are + not read. -## Failures and safety +## Safety & error handling - Return malformed data, unexpected I/O, command failures, and cleanup failures - as explicit errors. Do not replace them with defaults or partial success. -- Identify a process by PID plus procfs start time and verify it around attach. + explicitly; never substitute defaults or partial success. +- Identify processes by PID plus procfs start time and re-verify around attach. - Every attach and injection path must restore target state on failure and have deterministic cleanup tests. -- `validate` is read-only. `measure` may inject CUPTI only after validation - reports `injection_required`; log the mutation and include a JSON warning. -- Stop CUPTI logically after collection. Do not `dlclose` the injected agent. -- NVTX callback routing must be initialized before the target's first NVTX API - call. Once initialized, keep the CUPTI subscriber mapped and registered; - logical stop disables callback domains instead of unsubscribing it. -- Correlate NVTX IDs as ordered lifecycles. Thread range keys reuse push levels, - and a bounded capture may end with one range open; retain earlier closed - pairs and report only the trailing start as unmatched. -- Never collect pointer-referenced payloads, environments, or GPU buffer data by - default. Named tracepoints retain identity and timestamps unless a versioned - scalar payload is explicitly designed. Never describe temporal correlation - as exact causality. -- Treat sampled hotspot proportions as estimates. Preserve sample loss, stack - truncation, thread coverage, symbol coverage, and native fallback when Python - semantic symbols are unavailable. +- `validate` is read-only. `measure` injects CUPTI only after validation + reports `injection_required`, logs the mutation, and emits a JSON warning. +- Stop CUPTI logically after collection; never `dlclose` the injected agent. +- Initialize NVTX dispatch before the target's first NVTX call. Once + initialized, keep the CUPTI subscriber mapped and registered; logical stop + disables callback domains instead of unsubscribing. +- Correlate NVTX IDs in order: thread range keys reuse push levels, and a + capture may end with one range open โ€” keep earlier closed pairs and report + only the trailing start as unmatched. +- Never read pointer-referenced payloads, environment variables, or GPU buffer + data by default. Named tracepoints record identity and timestamps only unless + a versioned scalar payload is explicitly added. Never label temporal + correlation as exact causality. +- Treat sampled hotspot shares as estimates, and preserve sample loss, stack + truncation, thread/symbol coverage, and native fallback when Python symbols + are unavailable. -## Agent workflow +## Agent Skill -- Follow `skills/xprobe-measure-latency/SKILL.md` for measurement tasks. -- Choose the shortest Skill route supported by the evidence. Existing artifacts - are analyzed offline; known boundaries go straight to bounded measurement; - unknown live work starts with one triage window and continues with its ranked - next spec or a measurement graph. Escalate only from evidence, and do not - guess selectors. `discover` is only for CUDA context holders. -- Read the quality verdict, source coverage, stream identity, and profiler - overhead before interpreting latency. Summed concurrent GPU duration is not - wall time. -- Keep the Skill entry point short and each fact in one place. Field meanings - belong to schemas and flags to `--help`; Skill tests check behavior, links, - and documented flags rather than pinning prose. -- Keep reusable analysis deterministic and bundled with the Skill. Keep model - orchestration in the caller rather than adding CLI commands or a service. +- Use `skills/xprobe-perf-profiling/SKILL.md` for profiling tasks. +- Keep the Skill short and focused on commands, exact JSON/JSONL artifact + shapes, scripting/RSI recipes, and hard runtime limits โ€” not a fixed + investigation procedure. +- Keep reusable analysis deterministic in `analyze_trace.py`; leave + orchestration to the caller rather than adding CLI commands or a service. +- Skill tests check links, CLI flags, and cited schema fields instead of + pinning prose. +- User docs point to skills.sh (`npx skills add itdevwu/xprobe`), which + installs from `master`. To develop or test the Skill, install from the local + checkout or a GitHub tag URL. -## Release discipline +## Releases & git -- Start post-release work on a dedicated feature or fix branch. Rebase pull - requests into `master`; do not create merge commits. -- Build Linux release artifacts on Ubuntu 22.04 and enforce a GLIBC_2.34 ceiling - for the CLI and every shipped Agent ELF. -- A release is complete only after downloading the public archive, checking its - digest, testing installation, and inspecting all shipped ELF compatibility. -- Retry CI only when logs identify a transient infrastructure failure. Preserve - real compiler, test, packaging, and compatibility failures for diagnosis. -- Pin Rust in `rust-toolchain.toml`. Change the pin only in a dedicated change - and rerun lint and tests under the new compiler. +- Start post-release work on a dedicated branch and rebase PRs onto `master` + (no merge commits). +- Use emoji conventional commits, e.g. `๐Ÿ› fix: restore target registers`. +- Build Linux release artifacts on Ubuntu 22.04 with a `GLIBC_2.34` ceiling for + the CLI and every shipped Agent `.so`. Follow `docs/releasing.md` to verify + the public archive, digest, installation, and ELF compatibility before + marking a release complete. +- Change the Rust version in `rust-toolchain.toml` only in a dedicated commit, + then rerun lint and tests. ## Verification -- Run `just` recipes inside the `xprobe-dev` Mamba environment from - `environment.yml`, for example `mamba run -n xprobe-dev just test`. A bare - host shell may lack Clang, Ninja, and autotools. -- Set `PYTORCH_ENV` to an environment created from `environment-pytorch.yml` - for PyTorch live gates and `just test-release-live`. -- Run `just fmt-check`, `just lint`, and `just test` for Rust changes. -- Run `just test-bpf-live` for BPF attachment changes. -- Run `just test-cupti-live` for CUPTI ABI or callback changes. -- Run `just test-nvtx-live` for NVTX callback, filtering, or lifecycle changes. -- Run `just test-injection-live` for injection or agent lifecycle changes. -- Run `just test-multisource-live` for host/GPU orchestration changes. -- Run `just test-agent-contract` for CLI, schema, docs, or Skill changes. -- Test bundled Skill scripts with deterministic fixtures and include them in - `just test-agent-contract`. -- Run `just benchmark-gpu` for callback hot-path changes. -- Run `just benchmark-aggregate` for aggregate inventory hot-path or capacity - changes. -- Run `just benchmark-multiprocess` for concurrent worker orchestration changes. -- Run `just benchmark-pytorch` for PyTorch workflow or framework-overhead - changes. -- Use emoji conventional commits, for example `๐Ÿ› fix: restore target registers`. +- Run `just` inside the `xprobe-dev` Mamba environment from `environment.yml` + (e.g. `mamba run -n xprobe-dev just test`); a bare shell may lack Clang, + Ninja, or autotools. Set `PYTORCH_ENV` (from `environment-pytorch.yml`) for + PyTorch live tests and `just test-release-live`. +- Rust changes: `just fmt-check`, `just lint`, `just test`. +- CLI, schema, docs, or Skill changes: `just test-agent-contract` (includes + deterministic fixture tests for bundled Skill scripts). +- Subsystem live tests (run matching recipe for touched code): `test-bpf-live`, + `test-cupti-live`, `test-nvtx-live`, `test-injection-live`, + `test-multisource-live`, `test-trigger-live`, `test-python-sample-live` (when + adding a CPython minor version, regenerate + `tests/integration/python-layout/expected.json` from its headers). +- Benchmarks (run matching recipe when touching hot paths or orchestration): + `benchmark-gpu`, `benchmark-aggregate`, `benchmark-multiprocess`, + `benchmark-python-sampling`, `benchmark-pytorch`. diff --git a/CLAUDE.md b/CLAUDE.md index cff4b74..63e2d2b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,4 +1,4 @@ @AGENTS.md -For xprobe latency measurement tasks, follow -`skills/xprobe-measure-latency/SKILL.md` as the shared workflow. +For xprobe profiling tasks, follow +`skills/xprobe-perf-profiling/SKILL.md` as the shared skill. diff --git a/CMakeLists.txt b/CMakeLists.txt index 808242c..00110ba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.20) -project(xprobe VERSION 0.6.3 LANGUAGES C) +project(xprobe VERSION 0.7.0 LANGUAGES C) include(CTest) diff --git a/Cargo.lock b/Cargo.lock index eed577a..783bd52 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -99,6 +99,15 @@ version = "2.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "cc" version = "1.3.0" @@ -196,6 +205,35 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "dyn-clone" version = "1.0.20" @@ -302,6 +340,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "glob" version = "0.3.4" @@ -627,6 +675,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shlex" version = "1.3.0" @@ -693,6 +752,12 @@ dependencies = [ "syn 3.0.0", ] +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -705,6 +770,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "vsprintf" version = "2.0.0" @@ -732,7 +803,7 @@ dependencies = [ [[package]] name = "xprobe-cli" -version = "0.6.3" +version = "0.7.0" dependencies = [ "clap", "serde", @@ -746,17 +817,19 @@ dependencies = [ [[package]] name = "xprobe-collector" -version = "0.6.3" +version = "0.7.0" dependencies = [ "libbpf-rs", + "nix", "perf-event-open", "serde_json", + "xprobe-core", "xprobe-protocol", ] [[package]] name = "xprobe-core" -version = "0.6.3" +version = "0.7.0" dependencies = [ "cpp_demangle", "nix", @@ -768,7 +841,7 @@ dependencies = [ [[package]] name = "xprobe-correlator" -version = "0.6.3" +version = "0.7.0" dependencies = [ "regex", "serde_json", @@ -777,15 +850,16 @@ dependencies = [ [[package]] name = "xprobe-exporter" -version = "0.6.3" +version = "0.7.0" dependencies = [ "serde_json", + "sha2", "xprobe-protocol", ] [[package]] name = "xprobe-protocol" -version = "0.6.3" +version = "0.7.0" dependencies = [ "schemars", "serde", diff --git a/Cargo.toml b/Cargo.toml index 260dc63..bd9faf4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ members = [ resolver = "2" [workspace.package] -version = "0.6.3" +version = "0.7.0" edition = "2024" license = "Apache-2.0" repository = "https://github.com/itdevwu/xprobe" @@ -20,13 +20,14 @@ rust-version = "1.85" clap = { version = "4.5", features = ["derive"] } cpp_demangle = "0.4" libbpf-rs = { version = "0.26.2", features = ["vendored"] } -nix = { version = "0.31.3", features = ["process", "ptrace", "signal", "uio"] } +nix = { version = "0.31.3", features = ["process", "ptrace", "signal", "time", "uio"] } object = { version = "0.36", default-features = false, features = ["read", "std"] } perf-event-open = { version = "0.6.3", features = ["linux-4.8"] } regex = "1.11" schemars = "1.0" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" +sha2 = "0.10" xprobe-collector = { path = "xprobe/collector" } xprobe-core = { path = "xprobe/core" } xprobe-correlator = { path = "xprobe/correlator" } diff --git a/README.md b/README.md index d6ab2fa..7f76f01 100644 --- a/README.md +++ b/README.md @@ -1,150 +1,134 @@

xprobe

-

Find out why your CPU, Python, or CUDA process is slow โ€” in two commands.

-

A bounded Linux profiler for AI coding agents and the humans working with them:
- eBPF + perf + NVIDIA CUPTI, one CLI, strict JSON, no daemon.

+

Minimizing friction on the path to RSI.

+

Live Linux CPU, Python, syscall, and CUDA profiling for AI agents โ€” eBPF, perf, and CUPTI to JSON/JSONL.

CI status Latest release Apache-2.0 license - CUDA 12.x and 13.x + CUDA 12.x and 13.x

- xprobe triages a slow PyTorch CUDA process into ranked findings, then measures request to launch 1.14 ms, launch to kernel 99 ยตs, and kernel 1.2 ยตs on CPU and GPU timelines + Live xprobe captures align a GPU idle bubble with Python GIL stacks on CLOCK_MONOTONIC, feed JSONL into an agent script, and verify an RSI optimization loop

-

Real numbers from the v0.6.0 release gate on an RTX 3060: a PyTorch CUDA workload and a request โ†’ launch โ†’ kernel path.

- -## What it does - -Point xprobe at a running process. It watches one bounded window and tells you -where the time went โ€” on-CPU hotspots, threads waiting for a CPU or blocked, -container CPU throttling, hot syscalls, GPU kernels, and GPU clock limits โ€” -ranked by impact, each with a ready next measurement. The second command then -measures that exact latency: a function, a syscall, a CUDA API call, a kernel, -a copy, an NVTX range, or a whole request โ†’ launch โ†’ kernel path from a single -capture. - -- **Built for AI agents.** Ships as an [Agent Skill](skills/xprobe-measure-latency/SKILL.md) - for Claude Code, Codex, and Cursor. Compact JSON with a `good`/`caution` - quality verdict, so an agent can act on results without reading 100 KB of - events. -- **CPU, Python, and GPU in one tool.** Sampled native and CPython stacks, - eBPF uprobes, syscalls, tracepoints, CPython GC, and CUDA 12/13 activity via - CUPTI, correlated with explicit confidence. -- **Bounded by design.** Every capture is limited by samples or duration, - timeout, and capacity; there is no daemon; CUDA injection is disclosed - before it happens; the raw events are always kept for offline re-analysis. -- **Honest about what it knows.** Sampled shares are estimates, temporal - matches are labeled heuristic, and anything a capture cannot answer is listed - as not covered. - -## Install - -Install the version-matched Skill with the open Agent Skills CLI. This is the -only installation action required from the user: +

Illustrative RSI loop: live GPU bubble + Python GIL capture aligned on CLOCK_MONOTONIC, sliced in JSONL, patched, and re-verified.

-```bash -npx skills@1 add \ - https://github.com/itdevwu/xprobe/tree/v0.6.3/skills/xprobe-measure-latency \ - --global -``` +## โšก Why xprobe? + +Traditional profilers are built for human eyes and GUIs: bulky traces, slow exports, heavy overhead, and noise that burns an agent's context window. Recursive self-improvement (RSI) needs the opposite โ€” a live, low-friction sensor that emits compact, script-ready data on one shared timeline and turns profiling into a fast, honest feedback loop. -The installer detects Codex, Claude Code, Cursor, and other compatible agents. -When invoked, the Skill checks for the matching `xprobe` CLI and installs or -repairs it under a writable prefix before profiling. It can then diagnose and -adjust path, permission, NVIDIA, CUDA, or CUPTI problems from live evidence. -Node.js is only needed for Skill installation, not for xprobe itself. +| Capability | `xprobe` | `perf` / `uprobe` | `py-spy` | `nsys` | `torch.profiler` | +| --- | :---: | :---: | :---: | :---: | :---: | +| Live attach to running processes (no launch wrapper) | โœ…1 | โœ… | โœ… | โš ๏ธ | โŒ | +| CPU + CPython GIL + syscall + CUDA on one `CLOCK_MONOTONIC` | โœ… | โŒ | โŒ | โš ๏ธ | โš ๏ธ | +| Wait & trigger on rare GPU idle bubbles / stream gaps / spikes | โœ… | โŒ | โŒ | โŒ | โŒ | +| Direct JSON / JSONL output for one-off scripts & RSI loops | โœ… | โŒ | โš ๏ธ | โŒ | โš ๏ธ | +| Multi-process & multi-GPU timeline alignment / rank budgets | โœ… | โš ๏ธ | โŒ | โœ… | โš ๏ธ | +| Visual GUI / kernel roofline & hardware counters | โŒ2 | โŒ | โŒ | โœ… | โœ… | -To install only the CLI, use pip or the release archive: +1. CPU, CPython stacks/GIL, syscalls, uprobes, and CUDA kernels/copies/APIs attach live; NVTX ranges require `NVTX_INJECTION64_PATH` before the first NVTX call.
2. Once a bottleneck is isolated inside a single GPU kernel or needs GUI inspection, hand off to `ncu` or `nsys`.
+ +## ๐Ÿ“ฆ Install + +### CLI (Linux x86_64, glibc โ‰ฅ 2.34) ```bash pip install xprobe ``` -See [Installation](docs/installation.md) for the release archive, SPDX SBOMs, -and GitHub-hosted build attestation verification. +Or install the standalone release archive to `~/.local` (no Python required): + +```bash +curl --proto '=https' --tlsv1.2 -fsSL \ + https://raw.githubusercontent.com/itdevwu/xprobe/v0.7.0/install.sh | sh +``` + +Both ship the CLI plus CUDA 12 and CUDA 13 CUPTI Agents. See [Installation](docs/installation.md) for SHA-256 checksums, SPDX SBOMs, and GitHub build attestations. + +### AI Agent Skill (Claude Code, Codex, Cursor) + +```bash +npx skills add itdevwu/xprobe +``` -## Measure +Installs the [`xprobe-perf-profiling`](skills/xprobe-perf-profiling/SKILL.md) skill from [skills.sh](https://skills.sh) with exact JSON/JSONL artifact layouts, one-off scripting recipes, RSI comparison patterns, and the bundled `analyze_trace.py` analyzer. To pin the Skill to a release, see [Installation](docs/installation.md#ai-agent-skill). -Triage an unknown process over one representative window. Findings are ranked -by their estimated share of the window, and each carries a ready next step: +## ๐Ÿš€ Quick examples ```bash -xprobe measure --pid 4242 --triage --duration-ms 2000 > triage.json -jq '.findings[0].next.spec' triage.json > next.json -xprobe measure --spec next.json +# 1. Sample CPython 3.9โ€“3.14 stacks & GIL holder from outside the process (no -X perf) +xprobe measure --pid 4242 --python-sample --duration-ms 2000 + +# 2. Aggregate GPU kernels or memcpy (including pageable vs pinned transfers) +xprobe measure --pid 4242 --from cuda:kernel_start --to cuda:kernel_end \ + --match exact --aggregate --duration-ms 2000 + +# 3. Measure exact launch-to-kernel latency (or up to 8 edges via --spec graph.json) +xprobe measure --pid 4242 --from cuda:launch_api:exit \ + --to 'cuda:kernel_start:name~flash.*' --match exact --samples 200 + +# 4. Wait for a rare โ‰ฅ10 ms GPU idle bubble and keep ยฑ50 ms of context around it +xprobe measure --pid 4242 --trigger-idle-ms 10 --pre-ms 50 --post-ms 50 \ + --timeout-ms 300000 --events-out spikes ``` -Measure a known boundary directly, or several related boundaries from one -capture with a [measurement graph](docs/cli-contract.md#measurement-graphs): +### Pipe into one-off scripts & RSI loops + +When stdout is piped, every command emits one strict JSON object alongside raw JSONL traces and a `.manifest.json` (`CLOCK_MONOTONIC` window, UTC `wall_clock` anchors, and `cuda_devices` GPU UUIDs): ```bash -xprobe measure --pid 4242 \ - --from 'cuda:launch_api:exit' \ - --to 'cuda:kernel_start:name~flash.*' \ - --match exact --samples 100 +# Capture once, diff metrics across optimization iterations, or join traces in Python +before=$(xprobe measure --spec kernel.json | jq '.measurement.latency_ns.p95') +# ... apply kernel / runtime change ... +after=$(xprobe measure --spec kernel.json | jq '.measurement.latency_ns.p95') + +# Slice a GPU bubble alongside concurrent Python GIL samples, or compare multi-GPU ranks +skills/xprobe-perf-profiling/scripts/analyze_trace.py trace.jsonl --slice-gap 1 --python-samples py.jsonl +skills/xprobe-perf-profiling/scripts/analyze_trace.py rank0.jsonl rank1.jsonl rank2.jsonl rank3.jsonl ``` -Output is JSON whenever stdout is not a terminal. Results carry latency -statistics, a `good`/`caution` quality verdict, rank exemplar pairs, and the -path of the bounded event capture, which `measure --input` re-correlates -offline. See the [CLI contract](docs/cli-contract.md) for every mode. +Because concurrent captures on one host share `CLOCK_MONOTONIC`, you can also join traces across different processes (for example, an API/scheduler process and its GPU workers) in a few lines of Python, or re-correlate saved Event JSONL offline with `xprobe measure --input`. -## Public CLI +## ๐Ÿ› ๏ธ Commands & runtime notes | Command | Purpose | | --- | --- | -| `doctor` | Report local eBPF, ptrace, NVIDIA, CUDA, and CUPTI capabilities | +| `doctor` | Check local eBPF, ptrace, NVIDIA driver, CUDA, and CUPTI availability | | `discover` | List NVML-confirmed CUDA context holders under a process-tree root | -| `validate` | Check an event pair, graph, or inventory mode without attaching | -| `measure` | Triage, inventory, or correlate bounded live or recorded evidence | +| `validate` | Dry-run selectors, policies, or graph specs without attaching | +| `measure` | Capture latency pairs, measurement graphs, inventories, triggers, or offline `--input` traces | -`measure --pid` automatically loads the matching CUDA 12 or CUDA 13 CUPTI Agent -when a selected endpoint requires it. It reports the target mutation on stderr -and in JSON, disables collection afterward, and leaves the shared object mapped -for safe reactivation. NVTX ranges are the exception: set -`NVTX_INJECTION64_PATH` before the target's first NVTX call because online -attach cannot retrofit an initialized NVTX dispatch. +- **Live CUDA attach**: `measure --pid` automatically loads the matching CUDA 12 or 13 CUPTI Agent via ptrace (requires same mount namespace and ptrace permission), reports the injection on stderr and in JSON, disables collection on stop, and leaves the `.so` mapped for safe reuse. +- **NVTX ranges**: set `NVTX_INJECTION64_PATH` before the target's first NVTX call (CUDA's NVTX dispatch cannot be retrofitted after initialization). +- **Clock safety**: GPU-only durations work on all supported CUDA majors; cross CPU/GPU subtraction enforces runtime clock alignment and returns `CLOCK_ALIGNMENT_FAILED` instead of silently mixing unaligned clocks. -## Support +## ๐Ÿ“‹ Support -| Surface | Current support | +| Surface | Support | | --- | --- | -| OS/architecture | Linux x86_64, glibc 2.34 or newer | -| Triage | One window of thread time, cgroup throttling, CPU samples, syscalls, NVML health, and CUDA kernels | -| Measurement graphs | Up to eight edges from one capture | -| CPU inventory | PID-scoped sampled user stacks with native ELF and CPython perf-map symbols | -| Host events | ELF functions, named syscall/tracepoint boundaries, and CPython GC USDT | -| Coarse aggregation | Bounded syscall lifecycle and CUDA kernel/memcpy/memset groups, with pageable/pinned copies | -| CUDA callbacks | Runtime and Driver API entry/exit | -| GPU activity | Kernel, memcpy, and memset start/end | -| Application ranges | Bounded ASCII NVTX thread and process ranges | -| CUDA/CUPTI | 12.x and 13.x with automatic major selection | -| Correlation | exact, first-after, nearest, stack-nested, stream-order | -| Online injection | same mount namespace; ptrace permission required | - -GPU-to-GPU durations remain available across the supported majors. Cross -CPU/GPU subtraction requires the Agent's runtime alignment check to pass; -otherwise `measure` returns `CLOCK_ALIGNMENT_FAILED` rather than treating an -offset CUPTI clock as host monotonic. - -## Documentation +| Platform | Linux x86_64, glibc 2.34+, CUDA/CUPTI 12.x & 13.x | +| Python | External CPython 3.9โ€“3.14 stacks, GIL holder, blocked native waits, and GC USDT | +| CPU & Linux | PID-scoped perf callchains (ELF + perf-map), uprobes (symbol/C++/offset), syscalls, tracepoints | +| GPU & CUDA | Runtime/Driver APIs (`cuda:launch_api`), kernels, memcpy (`pageable`/`pinned`), memset, ASCII NVTX | +| Modes | Exact pairs, 8-edge measurement graphs, coarse aggregates, triggered ring capture, `--triage` snapshot | +| Correlation | `exact`, `stack-nested`, `stream-order`, `first-after`, `nearest` | + +## ๐Ÿ“š Documentation - [Installation](docs/installation.md) -- [Architecture](docs/architecture.md) - [CLI contract](docs/cli-contract.md) +- [Agent integration](docs/agent-integration.md) +- [Architecture](docs/architecture.md) - [CUPTI agent and injection](docs/cupti-agent.md) +- [Benchmarks](docs/benchmarks.md) - [Development and hardware tests](docs/development.md) - [Releasing](docs/releasing.md) -- [Agent integration](docs/agent-integration.md) -- [Public JSON schemas](schemas/) +- [JSON Schemas](schemas/) -Source builds and hardware tests are documented under -[Development](docs/development.md). Implemented behavior is defined by code, -tests, and schemas. Licensed under Apache-2.0. +Implemented behavior is defined by code, tests, and schemas. Licensed under Apache-2.0. README visuals embed subsets of [Maple Mono](https://github.com/subframe7536/maple-font) and [Geist](https://vercel.com/font) (SIL OFL-1.1). diff --git a/benchmarks/cuda-callback/run.py b/benchmarks/cuda-callback/run.py index d3279d3..f40ee60 100755 --- a/benchmarks/cuda-callback/run.py +++ b/benchmarks/cuda-callback/run.py @@ -38,10 +38,16 @@ def read_capture(path: pathlib.Path) -> tuple[dict[str, int], list[dict[str, int assert header["abi_version"] == 4, header assert header["header_size"] == HEADER.size, header assert header["record_size"] == RECORD.size, header - assert len(data) == HEADER.size + header["record_count"] * RECORD.size, header + start = HEADER.size + # A device table of 48-byte entries may follow the header. + if header["feature_flags"] & 128: + count, entry_size = struct.unpack_from("<2I", data, HEADER.size) + assert entry_size == 48 and 0 < count <= 64, (count, entry_size) + start += 8 + count * entry_size + assert len(data) == start + header["record_count"] * RECORD.size, header records = [] - for offset in range(HEADER.size, len(data), RECORD.size): + for offset in range(start, len(data), RECORD.size): fields = RECORD.unpack_from(data, offset) records.append( { diff --git a/benchmarks/python-sampling/run-inside.py b/benchmarks/python-sampling/run-inside.py new file mode 100644 index 0000000..4c401e2 --- /dev/null +++ b/benchmarks/python-sampling/run-inside.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Target throughput with and without xprobe Python sampling, in one image.""" + +import json +import os +import statistics +import subprocess +import sys +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +XPROBE = "/workspace/target/debug/xprobe" +SECONDS = 2.0 +DEPTH = 30 +ROUNDS = 3 + + +def run_case(sampled: bool) -> tuple[float, dict | None]: + with tempfile.TemporaryDirectory() as directory: + go = os.path.join(directory, "go") + workload = subprocess.Popen( + [sys.executable, os.path.join(HERE, "workload.py"), str(DEPTH), str(SECONDS), go], + stdout=subprocess.PIPE, + text=True, + ) + assert workload.stdout.readline().strip() == "ready" + sampler = None + if sampled: + sampler = subprocess.Popen( + [ + XPROBE, "measure", "--pid", str(workload.pid), "--python-sample", + "--duration-ms", str(int(SECONDS * 1000) + 300), "--json", + "--events-out", os.path.join(directory, "samples.jsonl"), + ], + stdout=subprocess.PIPE, + text=True, + ) + # Let the sampler locate the interpreter before the window opens. + time.sleep(0.15) + open(go, "w").close() + iterations = int(workload.stdout.readline()) + workload.wait(timeout=10) + result = None + if sampler is not None: + stdout, _ = sampler.communicate(timeout=30) + result = json.loads(stdout) + assert result["ok"] is True, result + return iterations / SECONDS, result + + +def main() -> None: + baseline, sampled, results = [], [], [] + for _ in range(ROUNDS): + baseline.append(run_case(False)[0]) + throughput, result = run_case(True) + sampled.append(throughput) + results.append(result) + collection = results[-1]["collection"] + print( + json.dumps( + { + "python": sys.version.split()[0], + "stack_depth": DEPTH, + "baseline_iterations_per_second": statistics.median(baseline), + "sampled_iterations_per_second": statistics.median(sampled), + "overhead_ratio": statistics.median(baseline) / statistics.median(sampled), + "gil_hz_achieved": collection["gil_hz_achieved"], + "inconsistent_reads": collection["inconsistent_reads"], + "gil_samples": collection["gil_samples"], + "read_latency": collection["read_latency"], + }, + sort_keys=True, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/python-sampling/run.py b/benchmarks/python-sampling/run.py new file mode 100644 index 0000000..a870db9 --- /dev/null +++ b/benchmarks/python-sampling/run.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Run the Python sampling overhead benchmark in each listed python image.""" + +import json +import pathlib +import subprocess +import sys + +TARGET_RATIO = 1.02 + + +def main() -> None: + images = sys.argv[1:] or ["python:3.10", "python:3.12"] + workspace = pathlib.Path(__file__).resolve().parents[2] + reports = [] + for image in images: + completed = subprocess.run( + [ + "docker", "run", "--rm", + "--volume", f"{workspace}:/workspace:ro", + image, "python3", "/workspace/benchmarks/python-sampling/run-inside.py", + ], + check=False, + capture_output=True, + text=True, + ) + if completed.returncode != 0: + sys.stdout.write(completed.stdout) + sys.stderr.write(completed.stderr) + raise SystemExit(completed.returncode) + report = json.loads(completed.stdout.strip().splitlines()[-1]) + report["image"] = image + report["project_target_ratio"] = TARGET_RATIO + report["project_target_met"] = report["overhead_ratio"] <= TARGET_RATIO + reports.append(report) + print(json.dumps({"ok": True, "reports": reports}, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/benchmarks/python-sampling/workload.py b/benchmarks/python-sampling/workload.py new file mode 100644 index 0000000..270f38c --- /dev/null +++ b/benchmarks/python-sampling/workload.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""A hot leaf under a deep Python stack; prints iterations in a fixed window. + +usage: workload.py +""" + +import ctypes +import os +import sys +import time + +# Allow a non-ancestor sampler under kernel.yama.ptrace_scope=1 (benchmark only). +ctypes.CDLL(None).prctl(0x59616D61, ctypes.c_ulong(-1), 0, 0, 0) + + +def leaf(): + total = 0 + for value in range(200): + total += value * value + return total + + +def descend(depth, deadline): + if depth: + return descend(depth - 1, deadline) + iterations = 0 + while time.perf_counter() < deadline: + leaf() + iterations += 1 + return iterations + + +depth, seconds, go = int(sys.argv[1]), float(sys.argv[2]), sys.argv[3] +print("ready", flush=True) +while not os.path.exists(go): + time.sleep(0.001) +print(descend(depth, time.perf_counter() + seconds), flush=True) +# Stay alive until a sampler that outlasts the window has finished. +time.sleep(2) diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 0000000..571d191 --- /dev/null +++ b/clippy.toml @@ -0,0 +1,2 @@ +# Proper names that doc comments use as words, not code. +doc-valid-idents = ["CPython", "PyTorch", "CUDA", ".."] diff --git a/cupti/include/xprobe/cupti_agent.h b/cupti/include/xprobe/cupti_agent.h index 1ceac41..fcc8414 100644 --- a/cupti/include/xprobe/cupti_agent.h +++ b/cupti/include/xprobe/cupti_agent.h @@ -10,7 +10,7 @@ extern "C" { #define XPROBE_CUPTI_AGENT_ABI_VERSION 4U #define XPROBE_CUPTI_OUTPUT_MAGIC "XPCUPTI" #define XPROBE_CUPTI_CONTROL_MAGIC "XPCTRL\0" -#define XPROBE_CUPTI_CONTROL_VERSION 5U +#define XPROBE_CUPTI_CONTROL_VERSION 6U #define XPROBE_CUPTI_NAME_LENGTH 128U #define XPROBE_CUPTI_FILTER_COUNT 8U #define XPROBE_CUPTI_VALUE_UNKNOWN UINT32_MAX @@ -20,12 +20,25 @@ enum xprobe_cupti_feature { XPROBE_CUPTI_FEATURE_TRANSFER_RECORDS = 1U << 1, XPROBE_CUPTI_FEATURE_AGGREGATE_RECORDS = 1U << 2, XPROBE_CUPTI_FEATURE_NVTX_RECORDS = 1U << 3, - XPROBE_CUPTI_FEATURE_MEMORY_KINDS = 1U << 4 + XPROBE_CUPTI_FEATURE_MEMORY_KINDS = 1U << 4, + /* Peer-to-peer copies (CUPTI MEMCPY2) are captured with other copies. */ + XPROBE_CUPTI_FEATURE_PEER_MEMCPY = 1U << 5, + /* Records come from a ring: record_offset plus record_count may exceed + * record_capacity. */ + XPROBE_CUPTI_FEATURE_RING_RECORDS = 1U << 6, + /* A device table follows the header: the UUID of every CUDA device + * ordinal the target sees, so device IDs compare across processes. */ + XPROBE_CUPTI_FEATURE_DEVICE_TABLE = 1U << 7 }; enum xprobe_cupti_capture_mode { XPROBE_CUPTI_CAPTURE_EXACT = 0, - XPROBE_CUPTI_CAPTURE_AGGREGATE = 1 + XPROBE_CUPTI_CAPTURE_AGGREGATE = 1, + /* Exact records in a ring: the newest record_capacity records are kept + * and capture never stops at the limit. A snapshot's record_offset is the + * first record it returns; a larger value than requested means the + * records in between were overwritten before they were read. */ + XPROBE_CUPTI_CAPTURE_RING = 2 }; enum xprobe_cupti_agent_status { @@ -48,7 +61,10 @@ enum xprobe_cupti_stop_reason { XPROBE_CUPTI_STOP_REQUESTED = 1, XPROBE_CUPTI_STOP_RECORD_LIMIT = 2, XPROBE_CUPTI_STOP_CUPTI_ERROR = 3, - XPROBE_CUPTI_STOP_OUTPUT_ERROR = 4 + XPROBE_CUPTI_STOP_OUTPUT_ERROR = 4, + /* STOP could not disable every callback or activity kind; the Agent + * keeps serving so CLOSE can retry. */ + XPROBE_CUPTI_STOP_CLEANUP_ERROR = 5 }; enum xprobe_cupti_control_command { @@ -116,6 +132,36 @@ struct xprobe_cupti_output_header { uint64_t record_offset; }; +enum { XPROBE_CUPTI_MAX_DEVICES = 64 }; + +/* callback_domain of a GPU activity start record whose activity was still + * running at STOP. CUPTI's start for an in-flight record may be missing or + * unconverted, so timestamp_ns is 0 and the reader places it at its stream's + * previous end: it marks the stream busy, not a measured start. */ +enum { XPROBE_CUPTI_RECORD_START_UNKNOWN = 1 }; + +/* With XPROBE_CUPTI_FEATURE_DEVICE_TABLE, the header is followed by this + * table and `device_count` entries, then the records. */ +struct xprobe_cupti_device_table { + uint32_t device_count; + uint32_t entry_size; +}; + +enum { XPROBE_CUPTI_DEVICE_MIG = 1 }; + +struct xprobe_cupti_device_entry { + /* The CUDA device ordinal, as in each record's device_id. */ + uint32_t ordinal; + /* XPROBE_CUPTI_DEVICE_MIG when the ordinal is a MIG instance. */ + uint32_t flags; + /* The device's UUID (cuDeviceGetUuid_v2): a MIG instance's own UUID + * under MIG, as nvidia-smi prints after "MIG-", else after "GPU-". */ + uint8_t uuid[16]; + /* The physical GPU's UUID (cuDeviceGetUuid), valid with the MIG flag. */ + uint8_t gpu_uuid[16]; + uint64_t reserved; +}; + struct xprobe_cupti_record { uint64_t timestamp_ns; uint32_t kind; diff --git a/cupti/src/cupti_agent.c b/cupti/src/cupti_agent.c index 22a6d12..23b9f14 100644 --- a/cupti/src/cupti_agent.c +++ b/cupti/src/cupti_agent.c @@ -61,6 +61,7 @@ int xprobe_cupti_agent_flush(void) #include #include +#include #include #include #include @@ -85,7 +86,11 @@ extern CUptiResult CUPTIAPI cuptiNvtxInitialize2(void *get_export_table); #define XPROBE_CUPTI_DEFAULT_RECORD_CAPACITY 100000U #define XPROBE_CUPTI_ACTIVITY_BUFFER_SIZE (8U * 1024U * 1024U) #define XPROBE_CUPTI_CLOCK_MARGIN_NS 1000000000U +/* Launch API entries a snapshot's clock check compares kernels with. */ +#define XPROBE_CUPTI_LAUNCH_SAMPLES 64U #define XPROBE_CUPTI_CORRELATION_CLOCK_MARGIN_NS 1000000U +/* Kernels whose launch API is checked against the kernel's start. */ +#define XPROBE_CUPTI_CORRELATION_CHECKS 4U _Static_assert(sizeof(struct xprobe_cupti_output_header) == 88U, "unexpected CUPTI output header layout"); @@ -123,7 +128,12 @@ struct xprobe_nvtx_range_slot { }; static struct xprobe_cupti_record *records; -static _Atomic unsigned char *record_ready; +/* Per slot: the logical record index plus one once the record is written, + * zero while it is empty or being rewritten. Ring snapshots read slots as a + * sequence lock against this value. */ +static _Atomic uint64_t *record_sequence; +/* Ring mode: verified copies of the records a snapshot returns. */ +static struct xprobe_cupti_record *ring_snapshot; static struct xprobe_cupti_aggregate_slot *aggregate_slots; static struct xprobe_nvtx_range_slot *nvtx_range_slots; static uint64_t nvtx_range_capacity; @@ -131,6 +141,10 @@ static uint64_t record_capacity; static uint32_t capture_mode; static _Atomic uint64_t record_count; static _Atomic uint64_t committed_record_count; +/* Ring mode: callbacks between taking a record index and publishing or + * dropping it. With none pending, an index whose slot never shows it was + * dropped rather than still being written. */ +static _Atomic uint64_t ring_writers; static _Atomic uint64_t agent_dropped_records; static _Atomic uint64_t cupti_dropped_records; /* Set while a forced flush hands over buffers that may hold activity still @@ -152,6 +166,20 @@ static uint32_t runtime_cupti_version; static int64_t activity_timestamp_offset_ns; static uint64_t capture_start_timestamp_ns; static _Atomic int clock_alignment_warning_emitted; +/* CUDA device ordinal to UUID, read once at ARM from the loaded driver. */ +static struct xprobe_cupti_device_entry device_entries[XPROBE_CUPTI_MAX_DEVICES]; +static uint32_t device_count; +/* Set while the Agent itself calls the driver, so its calls are never + * recorded as the target's. */ +static _Thread_local int agent_driver_call; +/* Whether this capture's activity timestamps were seen on CLOCK_MONOTONIC: + * unknown until an activity is checked, and unaligned once one fails. */ +enum { + XPROBE_CLOCK_UNKNOWN = 0, + XPROBE_CLOCK_ALIGNED = 1, + XPROBE_CLOCK_UNALIGNED = 2 +}; +static _Atomic int activity_clock; static CUpti_SubscriberHandle subscriber; static int subscriber_active; static int agent_initialized; @@ -168,30 +196,54 @@ static struct xprobe_cupti_filter capture_filters[XPROBE_CUPTI_FILTER_COUNT]; /* Written only while capture is inactive; hot paths scan just these slots. */ static size_t capture_filter_count; static _Atomic int capture_filter_enabled; +static _Atomic int capture_peer_memcpy; static _Atomic int nvtx_injection_active; static pthread_once_t injection_agent_once = PTHREAD_ONCE_INIT; static int injection_agent_status = XPROBE_CUPTI_AGENT_UNAVAILABLE; #define XPROBE_CUPTI_ACTIVITY_KERNEL (1U << 0) #define XPROBE_CUPTI_ACTIVITY_MEMCPY (1U << 1) #define XPROBE_CUPTI_ACTIVITY_MEMSET (1U << 2) +#define XPROBE_CUPTI_ACTIVITY_MEMCPY_PEER (1U << 3) + +/* CUPTI reports peer-to-peer copies only as MEMCPY2 records. The Agent is + * built against one CUPTI header and runs against CUDA 12.0 through 13.x, + * whose CUpti_ActivityMemcpyPtoP4 layouts are identical; pin the fields it + * reads so a header change fails the build instead of misreading records. */ +_Static_assert(offsetof(CUpti_ActivityMemcpyPtoP4, copyKind) == 4U, "PtoP4 copyKind"); +_Static_assert(offsetof(CUpti_ActivityMemcpyPtoP4, srcKind) == 5U, "PtoP4 srcKind"); +_Static_assert(offsetof(CUpti_ActivityMemcpyPtoP4, dstKind) == 6U, "PtoP4 dstKind"); +_Static_assert(offsetof(CUpti_ActivityMemcpyPtoP4, bytes) == 8U, "PtoP4 bytes"); +_Static_assert(offsetof(CUpti_ActivityMemcpyPtoP4, start) == 16U, "PtoP4 start"); +_Static_assert(offsetof(CUpti_ActivityMemcpyPtoP4, end) == 24U, "PtoP4 end"); +_Static_assert(offsetof(CUpti_ActivityMemcpyPtoP4, deviceId) == 32U, "PtoP4 deviceId"); +_Static_assert(sizeof(struct xprobe_cupti_device_table) == 8U, "device table header"); +_Static_assert(sizeof(struct xprobe_cupti_device_entry) == 48U, "device table entry"); +_Static_assert(sizeof(((CUuuid *)0)->bytes) == 16U, "CUuuid size"); +_Static_assert(offsetof(CUpti_ActivityMemcpyPtoP4, contextId) == 36U, "PtoP4 contextId"); +_Static_assert(offsetof(CUpti_ActivityMemcpyPtoP4, streamId) == 40U, "PtoP4 streamId"); +_Static_assert(offsetof(CUpti_ActivityMemcpyPtoP4, correlationId) == 60U, + "PtoP4 correlationId"); static int shutdown_agent(void); +static void read_device_table(void); static int activate_capture(void); static int allocate_capture(uint64_t capacity, int needs_nvtx) { struct xprobe_cupti_record *new_records; - _Atomic unsigned char *new_ready; + struct xprobe_cupti_record *new_ring_snapshot; + _Atomic uint64_t *new_ready; struct xprobe_cupti_aggregate_slot *new_aggregate_slots; struct xprobe_nvtx_range_slot *new_nvtx_range_slots; if (capacity == 0U || capacity > SIZE_MAX / sizeof(*records) || - capacity > SIZE_MAX / sizeof(*record_ready)) { + capacity > SIZE_MAX / sizeof(*record_sequence)) { fprintf(stderr, "xprobe CUPTI: invalid record capacity %llu\n", (unsigned long long)capacity); return XPROBE_CUPTI_AGENT_OUTPUT_ERROR; } new_records = NULL; + new_ring_snapshot = NULL; new_ready = NULL; new_aggregate_slots = NULL; new_nvtx_range_slots = NULL; @@ -204,11 +256,15 @@ static int allocate_capture(uint64_t capacity, int needs_nvtx) } else { new_records = calloc((size_t)capacity, sizeof(*new_records)); new_ready = malloc((size_t)capacity * sizeof(*new_ready)); + if (capture_mode == XPROBE_CUPTI_CAPTURE_RING) { + new_ring_snapshot = calloc((size_t)capacity, sizeof(*new_ring_snapshot)); + } } if (needs_nvtx != 0) { if (capacity > SIZE_MAX / sizeof(*nvtx_range_slots)) { fprintf(stderr, "xprobe CUPTI: NVTX range capacity exceeds size_t\n"); free(new_records); + free(new_ring_snapshot); free(new_ready); free(new_aggregate_slots); return XPROBE_CUPTI_AGENT_OUTPUT_ERROR; @@ -218,12 +274,14 @@ static int allocate_capture(uint64_t capacity, int needs_nvtx) } if ((capture_mode == XPROBE_CUPTI_CAPTURE_AGGREGATE && new_aggregate_slots == NULL) || - (capture_mode == XPROBE_CUPTI_CAPTURE_EXACT && + (capture_mode != XPROBE_CUPTI_CAPTURE_AGGREGATE && (new_records == NULL || new_ready == NULL)) || + (capture_mode == XPROBE_CUPTI_CAPTURE_RING && new_ring_snapshot == NULL) || (needs_nvtx != 0 && new_nvtx_range_slots == NULL)) { fprintf(stderr, "xprobe CUPTI: failed to allocate %llu capture records\n", (unsigned long long)capacity); free(new_records); + free(new_ring_snapshot); free(new_ready); free(new_aggregate_slots); free(new_nvtx_range_slots); @@ -235,11 +293,13 @@ static int allocate_capture(uint64_t capacity, int needs_nvtx) } } free(records); - free(record_ready); + free(ring_snapshot); + free(record_sequence); free(aggregate_slots); free(nvtx_range_slots); records = new_records; - record_ready = new_ready; + ring_snapshot = new_ring_snapshot; + record_sequence = new_ready; aggregate_slots = new_aggregate_slots; nvtx_range_slots = new_nvtx_range_slots; nvtx_range_capacity = needs_nvtx != 0 ? capacity : 0U; @@ -258,7 +318,7 @@ static void reset_capture(void) } } else { for (index = 0U; index < record_capacity; ++index) { - atomic_store_explicit(&record_ready[index], 0U, memory_order_relaxed); + atomic_store_explicit(&record_sequence[index], 0U, memory_order_relaxed); } } for (index = 0U; index < nvtx_range_capacity; ++index) { @@ -267,9 +327,11 @@ static void reset_capture(void) } atomic_store_explicit(&record_count, 0U, memory_order_relaxed); atomic_store_explicit(&committed_record_count, 0U, memory_order_relaxed); + atomic_store_explicit(&ring_writers, 0U, memory_order_relaxed); atomic_store_explicit(&agent_dropped_records, 0U, memory_order_relaxed); atomic_store_explicit(&cupti_dropped_records, 0U, memory_order_relaxed); atomic_store_explicit(&capture_has_timed_activity, 0, memory_order_relaxed); + atomic_store_explicit(&capture_peer_memcpy, 0, memory_order_relaxed); atomic_store_explicit(&unknown_records, 0U, memory_order_relaxed); atomic_store_explicit(&requested_buffers, 0U, memory_order_relaxed); atomic_store_explicit(&completed_buffers, 0U, memory_order_relaxed); @@ -277,6 +339,8 @@ static void reset_capture(void) atomic_store_explicit(&output_written, 0, memory_order_relaxed); atomic_store_explicit(&clock_alignment_warning_emitted, 0, memory_order_relaxed); + atomic_store_explicit(&activity_clock, XPROBE_CLOCK_UNKNOWN, + memory_order_relaxed); atomic_store_explicit(&capture_state, XPROBE_CUPTI_CAPTURE_IDLE, memory_order_relaxed); atomic_store_explicit(&stop_reason, XPROBE_CUPTI_STOP_NONE, @@ -596,10 +660,45 @@ static int capture_filter_matches(const struct xprobe_cupti_record *record) return 0; } +/* Ring slot sequence words: the record's logical index plus one, with these + * flags while a writer or the snapshot reader owns the slot body. */ +#define XPROBE_RING_WRITING (UINT64_C(1) << 63) +#define XPROBE_RING_READING (UINT64_C(1) << 62) +#define XPROBE_RING_INDEX (~(XPROBE_RING_WRITING | XPROBE_RING_READING)) +/* Committed records one callback advances over; the reader finishes. */ +#define XPROBE_COMMIT_STEPS 64U +/* Claim attempts before a contended ring record is given up. */ +#define XPROBE_CLAIM_ATTEMPTS 8U + +static void advance_committed_records(uint64_t steps); + +/* Claim a ring slot for record `index` in a bounded number of attempts. + * The slot must hold an older record and be idle; otherwise the record is + * given up, so no writer or reader ever shares a slot body with another. + * The reader reports a given-up record as a gap in the logical offsets. */ +static int claim_ring_slot(uint64_t slot, uint64_t index) +{ + _Atomic uint64_t *sequence = &record_sequence[slot]; + uint64_t expected = atomic_load_explicit(sequence, memory_order_acquire); + + for (unsigned attempt = 0U; attempt < XPROBE_CLAIM_ATTEMPTS; ++attempt) { + if ((expected & (XPROBE_RING_WRITING | XPROBE_RING_READING)) != 0U || + (expected & XPROBE_RING_INDEX) >= index + 1U) { + return 0; + } + if (atomic_compare_exchange_weak_explicit( + sequence, &expected, XPROBE_RING_WRITING | (index + 1U), + memory_order_acq_rel, memory_order_acquire)) { + return 1; + } + } + return 0; +} + static void enqueue_record(const struct xprobe_cupti_record *record) { uint64_t index; - uint64_t committed; + uint64_t slot; if (atomic_load_explicit(&capture_state, memory_order_relaxed) != XPROBE_CUPTI_CAPTURE_ACTIVE) { @@ -608,6 +707,18 @@ static void enqueue_record(const struct xprobe_cupti_record *record) if (capture_filter_matches(record) == 0) { return; } + if (capture_mode == XPROBE_CUPTI_CAPTURE_RING) { + atomic_fetch_add_explicit(&ring_writers, 1U, memory_order_seq_cst); + index = atomic_fetch_add_explicit(&record_count, 1U, memory_order_seq_cst); + slot = index % record_capacity; + if (claim_ring_slot(slot, index) != 0) { + records[slot] = *record; + atomic_store_explicit(&record_sequence[slot], index + 1U, + memory_order_release); + } + atomic_fetch_sub_explicit(&ring_writers, 1U, memory_order_seq_cst); + return; + } index = atomic_fetch_add_explicit(&record_count, 1U, memory_order_relaxed); if (index >= record_capacity) { atomic_store_explicit(&stop_reason, XPROBE_CUPTI_STOP_RECORD_LIMIT, @@ -616,13 +727,28 @@ static void enqueue_record(const struct xprobe_cupti_record *record) XPROBE_CUPTI_CAPTURE_LIMIT_REACHED, memory_order_release); return; + } else { + slot = index; } - records[index] = *record; - atomic_store_explicit(&record_ready[index], 1U, memory_order_release); + records[slot] = *record; + atomic_store_explicit(&record_sequence[slot], index + 1U, memory_order_release); + advance_committed_records(XPROBE_COMMIT_STEPS); +} + +/* Advance the exact-mode committed count over at most `steps` records + * written in order. Ring mode reads slot states directly instead. */ +static void advance_committed_records(uint64_t steps) +{ + uint64_t committed = + atomic_load_explicit(&committed_record_count, memory_order_acquire); + + for (uint64_t step = 0U; step < steps && committed < record_capacity; ++step) { + uint64_t sequence = + atomic_load_explicit(&record_sequence[committed], memory_order_acquire); - committed = atomic_load_explicit(&committed_record_count, memory_order_acquire); - while (committed < record_capacity && - atomic_load_explicit(&record_ready[committed], memory_order_acquire) != 0U) { + if (sequence <= committed) { + return; + } if (atomic_compare_exchange_weak_explicit( &committed_record_count, &committed, committed + 1U, memory_order_release, memory_order_acquire)) { @@ -1107,7 +1233,9 @@ static void nvtx_callback(CUpti_CallbackId callback_id, } level = *(const int *)data->functionReturnValue; if (level < 0) { - atomic_fetch_add_explicit(&unknown_records, 1U, memory_order_relaxed); + /* CUPTI tracks push levels only while NVTX callbacks are on, so + * popping a range pushed before ARM has no level: it ended a + * range the capture never saw start, like an orphan end. */ return; } tid = current_tid(); @@ -1128,6 +1256,9 @@ static void CUPTIAPI api_callback(void *userdata, CUpti_CallbackDomain domain, uint64_t timestamp_ns; (void)userdata; + if (agent_driver_call != 0) { + return; + } if (domain == CUPTI_CB_DOMAIN_NVTX) { nvtx_callback(callback_id, callback_data); return; @@ -1168,16 +1299,27 @@ static void CUPTIAPI activity_buffer_requested(uint8_t **buffer, size_t *size, atomic_fetch_add_explicit(&requested_buffers, 1U, memory_order_relaxed); } +/* Mark the start record of an activity still running at STOP; see + * XPROBE_CUPTI_RECORD_START_UNKNOWN. */ +static void mark_running_start(struct xprobe_cupti_record *record, int running) +{ + if (running != 0) { + record->timestamp_ns = 0U; + record->callback_domain = XPROBE_CUPTI_RECORD_START_UNKNOWN; + } +} + static void enqueue_kernel_record(uint32_t device_id, uint32_t context_id, uint32_t stream_id, uint32_t correlation_id, int32_t grid_x, int32_t grid_y, int32_t grid_z, int32_t block_x, int32_t block_y, int32_t block_z, const char *name, uint32_t kind, - uint64_t timestamp_ns) + uint64_t timestamp_ns, int running) { struct xprobe_cupti_record record; initialize_record(&record, kind, normalize_activity_timestamp(timestamp_ns)); + mark_running_start(&record, running); record.device_id = device_id; record.context_id = context_id; record.stream_id = stream_id; @@ -1192,14 +1334,52 @@ static void enqueue_kernel_record(uint32_t device_id, uint32_t context_id, enqueue_record(&record); } +/* An activity inside the capture ended after ARM; on CLOCK_MONOTONIC it + * also ended before now. Each one is checked while buffers are processed, + * where both timestamps are known even when only start records are kept. */ +static void check_activity_clock(uint64_t end_ns) +{ + uint64_t now_ns; + + if (atomic_load_explicit(&activity_clock, memory_order_relaxed) == + XPROBE_CLOCK_UNALIGNED) { + return; + } + if (monotonic_timestamp_ns(&now_ns) != XPROBE_CUPTI_AGENT_READY || + (end_ns > now_ns && end_ns - now_ns > XPROBE_CUPTI_CLOCK_MARGIN_NS)) { + atomic_store_explicit(&activity_clock, XPROBE_CLOCK_UNALIGNED, + memory_order_relaxed); + return; + } + /* Only an unknown verdict becomes aligned; unaligned is final. */ + int expected = XPROBE_CLOCK_UNKNOWN; + (void)atomic_compare_exchange_strong_explicit( + &activity_clock, &expected, XPROBE_CLOCK_ALIGNED, memory_order_relaxed, + memory_order_relaxed); +} + /* * Decide whether a filter-matching activity belongs to the capture. CUPTI * hands over records whose timestamps were lost when its device buffers * overflow; such a record cannot be placed in time, so it is counted as a * dropped record instead of being skipped as pre-capture activity. */ +/* Whether an activity record belongs to the capture: 0 if not, 1 for both + * boundaries, or XPROBE_ACTIVITY_RUNNING when a forced flush delivered an + * activity still running at STOP. Only its start, if anything, is known; it + * is kept as a start record (flagged when the start is unknown) because + * dropping it would leave its stream and device looking idle. */ +enum { XPROBE_ACTIVITY_RUNNING = 2 }; + static int activity_in_capture(uint64_t start_ns, uint64_t end_ns) { + /* CUPTI hands over an activity still running at a forced flush with no + * end, and on current drivers no start either. */ + if (end_ns == 0U && + capture_mode != XPROBE_CUPTI_CAPTURE_AGGREGATE && + atomic_load_explicit(&forced_flush_active, memory_order_acquire) != 0) { + return XPROBE_ACTIVITY_RUNNING; + } if (start_ns == 0U || end_ns == 0U || end_ns < start_ns) { if (atomic_load_explicit(&forced_flush_active, memory_order_acquire) == 0 && @@ -1210,10 +1390,16 @@ static int activity_in_capture(uint64_t start_ns, uint64_t end_ns) } return 0; } - if (normalize_activity_timestamp(start_ns) < capture_start_timestamp_ns) { + /* Event captures keep activity still running at ARM, so work that + * overlaps the capture is not hidden. Aggregates count whole durations, + * so they keep only activity that started after ARM. */ + if (normalize_activity_timestamp( + capture_mode == XPROBE_CUPTI_CAPTURE_AGGREGATE ? start_ns : end_ns) < + capture_start_timestamp_ns) { return 0; } atomic_store_explicit(&capture_has_timed_activity, 1, memory_order_relaxed); + check_activity_clock(normalize_activity_timestamp(end_ns)); return 1; } @@ -1224,7 +1410,9 @@ static int activity_in_capture(uint64_t start_ns, uint64_t end_ns) (kernel)->name) == 0) { \ return; \ } \ - if (activity_in_capture((kernel)->start, (kernel)->end) == 0) { \ + int xprobe_in_capture = \ + activity_in_capture((kernel)->start, (kernel)->end); \ + if (xprobe_in_capture == 0) { \ return; \ } \ if (capture_mode == XPROBE_CUPTI_CAPTURE_AGGREGATE) { \ @@ -1239,13 +1427,16 @@ static int activity_in_capture(uint64_t start_ns, uint64_t end_ns) (kernel)->correlationId, (kernel)->gridX, (kernel)->gridY, \ (kernel)->gridZ, (kernel)->blockX, (kernel)->blockY, \ (kernel)->blockZ, (kernel)->name, XPROBE_CUPTI_GPU_KERNEL_START, \ - (kernel)->start); \ + (kernel)->start, xprobe_in_capture == XPROBE_ACTIVITY_RUNNING); \ + if (xprobe_in_capture == XPROBE_ACTIVITY_RUNNING) { \ + return; \ + } \ enqueue_kernel_record( \ (kernel)->deviceId, (kernel)->contextId, (kernel)->streamId, \ (kernel)->correlationId, (kernel)->gridX, (kernel)->gridY, \ (kernel)->gridZ, (kernel)->blockX, (kernel)->blockY, \ (kernel)->blockZ, (kernel)->name, XPROBE_CUPTI_GPU_KERNEL_END, \ - (kernel)->end); \ + (kernel)->end, 0); \ } while (0) static void enqueue_kernel_activity(const CUpti_Activity *activity) @@ -1280,28 +1471,79 @@ static void set_transfer_bytes(struct xprobe_cupti_record *record, uint64_t byte record->grid_y = (uint32_t)(bytes >> 32U); } -static void enqueue_memcpy_record(const CUpti_ActivityMemcpy6 *memcpy_record, - uint32_t kind, uint64_t timestamp_ns) +/* The fields xprobe reads from a MEMCPY or MEMCPY2 (peer-to-peer) record. */ +struct xprobe_memcpy_activity { + uint32_t copy_kind; + uint32_t src_kind; + uint32_t dst_kind; + uint64_t bytes; + uint64_t start; + uint64_t end; + uint32_t device_id; + uint32_t context_id; + uint32_t stream_id; + uint32_t correlation_id; + uint32_t runtime_correlation_id; +}; + +static void enqueue_memcpy_record(const struct xprobe_memcpy_activity *memcpy_record, + uint32_t kind, uint64_t timestamp_ns, int running) { struct xprobe_cupti_record record; initialize_record(&record, kind, normalize_activity_timestamp(timestamp_ns)); - record.device_id = memcpy_record->deviceId; - record.context_id = memcpy_record->contextId; - record.stream_id = memcpy_record->streamId; - record.correlation_id = memcpy_record->correlationId; - record.runtime_correlation_id = memcpy_record->runtimeCorrelationId; + mark_running_start(&record, running); + record.device_id = memcpy_record->device_id; + record.context_id = memcpy_record->context_id; + record.stream_id = memcpy_record->stream_id; + record.correlation_id = memcpy_record->correlation_id; + record.runtime_correlation_id = memcpy_record->runtime_correlation_id; set_transfer_bytes(&record, memcpy_record->bytes); - record.grid_z = (uint32_t)memcpy_record->copyKind; + record.grid_z = memcpy_record->copy_kind; enqueue_record(&record); } +static void handle_memcpy_activity(const struct xprobe_memcpy_activity *memcpy_record) +{ + uint32_t semantic_kind = semantic_memcpy_kind(memcpy_record->copy_kind); + + if (values_match_capture(XPROBE_CUPTI_GPU_MEMCPY_START, + XPROBE_CUPTI_GPU_MEMCPY_END, 0U, semantic_kind, + NULL) == 0) { + return; + } + int in_capture = activity_in_capture(memcpy_record->start, memcpy_record->end); + + if (in_capture == 0) { + return; + } + if (capture_mode == XPROBE_CUPTI_CAPTURE_AGGREGATE) { + aggregate_activity(XPROBE_CUPTI_GPU_MEMCPY_START, memcpy_record->device_id, + semantic_kind, memcpy_record->src_kind, + memcpy_record->dst_kind, NULL, + normalize_activity_timestamp(memcpy_record->start), + normalize_activity_timestamp(memcpy_record->end), + memcpy_record->bytes); + return; + } + if (in_capture == XPROBE_ACTIVITY_RUNNING) { + enqueue_memcpy_record(memcpy_record, XPROBE_CUPTI_GPU_MEMCPY_START, + memcpy_record->start, 1); + return; + } + enqueue_memcpy_record(memcpy_record, XPROBE_CUPTI_GPU_MEMCPY_START, + memcpy_record->start, 0); + enqueue_memcpy_record(memcpy_record, XPROBE_CUPTI_GPU_MEMCPY_END, + memcpy_record->end, 0); +} + static void enqueue_memset_record(const CUpti_ActivityMemset4 *memset_record, - uint32_t kind, uint64_t timestamp_ns) + uint32_t kind, uint64_t timestamp_ns, int running) { struct xprobe_cupti_record record; initialize_record(&record, kind, normalize_activity_timestamp(timestamp_ns)); + mark_running_start(&record, running); record.device_id = memset_record->deviceId; record.context_id = memset_record->contextId; record.stream_id = memset_record->streamId; @@ -1335,34 +1577,41 @@ static void CUPTIAPI activity_buffer_completed(CUcontext context, uint32_t strea if (activity->kind == CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL) { enqueue_kernel_activity(activity); } else if (activity->kind == CUPTI_ACTIVITY_KIND_MEMCPY) { - const CUpti_ActivityMemcpy6 *memcpy_record = + const CUpti_ActivityMemcpy6 *copy = (const CUpti_ActivityMemcpy6 *)activity; - if (values_match_capture( - XPROBE_CUPTI_GPU_MEMCPY_START, - XPROBE_CUPTI_GPU_MEMCPY_END, 0U, - semantic_memcpy_kind((uint32_t)memcpy_record->copyKind), - NULL) == 0) { - continue; - } - if (activity_in_capture(memcpy_record->start, memcpy_record->end) == - 0) { - continue; - } - if (capture_mode == XPROBE_CUPTI_CAPTURE_AGGREGATE) { - aggregate_activity( - XPROBE_CUPTI_GPU_MEMCPY_START, memcpy_record->deviceId, - semantic_memcpy_kind((uint32_t)memcpy_record->copyKind), - (uint32_t)memcpy_record->srcKind, - (uint32_t)memcpy_record->dstKind, NULL, - normalize_activity_timestamp(memcpy_record->start), - normalize_activity_timestamp(memcpy_record->end), - memcpy_record->bytes); - continue; - } - enqueue_memcpy_record(memcpy_record, XPROBE_CUPTI_GPU_MEMCPY_START, - memcpy_record->start); - enqueue_memcpy_record(memcpy_record, XPROBE_CUPTI_GPU_MEMCPY_END, - memcpy_record->end); + const struct xprobe_memcpy_activity memcpy_record = { + .copy_kind = (uint32_t)copy->copyKind, + .src_kind = (uint32_t)copy->srcKind, + .dst_kind = (uint32_t)copy->dstKind, + .bytes = copy->bytes, + .start = copy->start, + .end = copy->end, + .device_id = copy->deviceId, + .context_id = copy->contextId, + .stream_id = copy->streamId, + .correlation_id = copy->correlationId, + .runtime_correlation_id = copy->runtimeCorrelationId, + }; + handle_memcpy_activity(&memcpy_record); + } else if (activity->kind == CUPTI_ACTIVITY_KIND_MEMCPY2) { + /* A peer copy has no runtime correlation ID; deviceId, contextId, + * and streamId name the stream it runs on. */ + const CUpti_ActivityMemcpyPtoP4 *copy = + (const CUpti_ActivityMemcpyPtoP4 *)activity; + const struct xprobe_memcpy_activity memcpy_record = { + .copy_kind = (uint32_t)copy->copyKind, + .src_kind = (uint32_t)copy->srcKind, + .dst_kind = (uint32_t)copy->dstKind, + .bytes = copy->bytes, + .start = copy->start, + .end = copy->end, + .device_id = copy->deviceId, + .context_id = copy->contextId, + .stream_id = copy->streamId, + .correlation_id = copy->correlationId, + .runtime_correlation_id = 0U, + }; + handle_memcpy_activity(&memcpy_record); } else if (activity->kind == CUPTI_ACTIVITY_KIND_MEMSET) { const CUpti_ActivityMemset4 *memset_record = (const CUpti_ActivityMemset4 *)activity; @@ -1371,8 +1620,10 @@ static void CUPTIAPI activity_buffer_completed(CUcontext context, uint32_t strea NULL) == 0) { continue; } - if (activity_in_capture(memset_record->start, memset_record->end) == - 0) { + int in_capture = + activity_in_capture(memset_record->start, memset_record->end); + + if (in_capture == 0) { continue; } if (capture_mode == XPROBE_CUPTI_CAPTURE_AGGREGATE) { @@ -1383,10 +1634,15 @@ static void CUPTIAPI activity_buffer_completed(CUcontext context, uint32_t strea memset_record->bytes); continue; } + if (in_capture == XPROBE_ACTIVITY_RUNNING) { + enqueue_memset_record(memset_record, XPROBE_CUPTI_GPU_MEMSET_START, + memset_record->start, 1); + continue; + } enqueue_memset_record(memset_record, XPROBE_CUPTI_GPU_MEMSET_START, - memset_record->start); + memset_record->start, 0); enqueue_memset_record(memset_record, XPROBE_CUPTI_GPU_MEMSET_END, - memset_record->end); + memset_record->end, 0); } else { atomic_fetch_add_explicit(&unknown_records, 1U, memory_order_relaxed); } @@ -1528,25 +1784,57 @@ static int receive_all(int descriptor, void *data, size_t size) return 0; } -static int activity_timestamps_are_host_monotonic(uint64_t available) +static int activity_timestamps_are_host_monotonic( + const struct xprobe_cupti_record *checked, uint64_t available) { uint64_t capture_end_timestamp_ns; - const struct xprobe_cupti_record *first_kernel = NULL; if (monotonic_timestamp_ns(&capture_end_timestamp_ns) != XPROBE_CUPTI_AGENT_READY) { return 0; } + unsigned correlation_checks = 0U; + /* Launch calls to compare kernel starts with, gathered once so the check + * stays linear in the reply. */ + struct { + uint32_t correlation_id; + uint64_t timestamp_ns; + } launches[XPROBE_CUPTI_LAUNCH_SAMPLES]; + unsigned launch_count = 0U; + int activity = atomic_load_explicit(&activity_clock, memory_order_relaxed); + /* A start may predate ARM, so only an end or a start after its launch + * call bounds the clock from both sides. */ + int bounded = activity == XPROBE_CLOCK_ALIGNED; + + if (activity == XPROBE_CLOCK_UNALIGNED) { + goto unaligned; + } + for (uint64_t index = 0U; + index < available && launch_count < XPROBE_CUPTI_LAUNCH_SAMPLES; ++index) { + if (checked[index].kind == XPROBE_CUPTI_CUDA_API_ENTRY) { + launches[launch_count].correlation_id = checked[index].correlation_id; + launches[launch_count].timestamp_ns = checked[index].timestamp_ns; + ++launch_count; + } + } for (uint64_t index = 0U; index < available; ++index) { - const struct xprobe_cupti_record *record = &records[index]; + const struct xprobe_cupti_record *record = &checked[index]; uint64_t timestamp_ns = record->timestamp_ns; - int is_activity = record->kind >= XPROBE_CUPTI_GPU_KERNEL_START && - record->kind <= XPROBE_CUPTI_GPU_MEMSET_END; - - if (is_activity == 0) { + int is_start = record->kind == XPROBE_CUPTI_GPU_KERNEL_START || + record->kind == XPROBE_CUPTI_GPU_MEMCPY_START || + record->kind == XPROBE_CUPTI_GPU_MEMSET_START; + int is_end = record->kind == XPROBE_CUPTI_GPU_KERNEL_END || + record->kind == XPROBE_CUPTI_GPU_MEMCPY_END || + record->kind == XPROBE_CUPTI_GPU_MEMSET_END; + + /* Activity running at STOP has no end, and its start was checked + * when it was recorded; it says nothing about the clock. */ + if ((is_start == 0 && is_end == 0) || record->callback_domain != 0U) { continue; } - if ((timestamp_ns < capture_start_timestamp_ns && + /* An activity running at ARM keeps its earlier start, so a start is + * bounded only by the capture's end; an end by both. */ + if ((is_end != 0 && timestamp_ns < capture_start_timestamp_ns && capture_start_timestamp_ns - timestamp_ns > XPROBE_CUPTI_CLOCK_MARGIN_NS) || (timestamp_ns > capture_end_timestamp_ns && @@ -1554,29 +1842,34 @@ static int activity_timestamps_are_host_monotonic(uint64_t available) XPROBE_CUPTI_CLOCK_MARGIN_NS)) { goto unaligned; } - if (first_kernel == NULL && - record->kind == XPROBE_CUPTI_GPU_KERNEL_START) { - first_kernel = record; - } - } - if (first_kernel != NULL) { - for (uint64_t index = 0U; index < available; ++index) { - const struct xprobe_cupti_record *record = &records[index]; - - if (record->kind == XPROBE_CUPTI_CUDA_API_ENTRY && - record->correlation_id == first_kernel->correlation_id) { - if (first_kernel->timestamp_ns < record->timestamp_ns && - record->timestamp_ns - first_kernel->timestamp_ns > - XPROBE_CUPTI_CORRELATION_CLOCK_MARGIN_NS) { - goto unaligned; + if (is_end != 0) { + bounded = 1; + } + if (record->kind == XPROBE_CUPTI_GPU_KERNEL_START && + timestamp_ns >= capture_start_timestamp_ns && + correlation_checks < XPROBE_CUPTI_CORRELATION_CHECKS) { + /* A kernel cannot start before the API call that launched it. */ + for (unsigned api = 0U; api < launch_count; ++api) { + if (launches[api].correlation_id == record->correlation_id) { + if (timestamp_ns < launches[api].timestamp_ns && + launches[api].timestamp_ns - timestamp_ns > + XPROBE_CUPTI_CORRELATION_CLOCK_MARGIN_NS) { + goto unaligned; + } + ++correlation_checks; + bounded = 1; + break; } - break; } } } - return 1; + return bounded; unaligned: + /* Once any reply is unaligned, every later one is too, so one capture + * never mixes clock labels. */ + atomic_store_explicit(&activity_clock, XPROBE_CLOCK_UNALIGNED, + memory_order_relaxed); if (atomic_exchange_explicit(&clock_alignment_warning_emitted, 1, memory_order_relaxed) == 0) { fprintf(stderr, @@ -1617,7 +1910,9 @@ static uint64_t aggregate_observed_records(void) } static void initialize_output_header(struct xprobe_cupti_output_header *header, - uint64_t available, uint64_t record_offset) + uint64_t available, uint64_t record_offset, + const struct xprobe_cupti_record *checked, + uint64_t checked_count) { uint64_t observed = capture_mode == XPROBE_CUPTI_CAPTURE_AGGREGATE @@ -1633,10 +1928,19 @@ static void initialize_output_header(struct xprobe_cupti_output_header *header, if (atomic_load_explicit(&nvtx_injection_active, memory_order_acquire) != 0) { header->feature_flags |= XPROBE_CUPTI_FEATURE_NVTX_RECORDS; } + if (atomic_load_explicit(&capture_peer_memcpy, memory_order_relaxed) != 0) { + header->feature_flags |= XPROBE_CUPTI_FEATURE_PEER_MEMCPY; + } + if (capture_mode == XPROBE_CUPTI_CAPTURE_RING) { + header->feature_flags |= XPROBE_CUPTI_FEATURE_RING_RECORDS; + } + if (device_count != 0U) { + header->feature_flags |= XPROBE_CUPTI_FEATURE_DEVICE_TABLE; + } if (capture_mode == XPROBE_CUPTI_CAPTURE_AGGREGATE) { header->feature_flags |= XPROBE_CUPTI_FEATURE_AGGREGATE_RECORDS | XPROBE_CUPTI_FEATURE_MEMORY_KINDS; - } else if (activity_timestamps_are_host_monotonic(available) != 0) { + } else if (activity_timestamps_are_host_monotonic(checked, checked_count) != 0) { header->feature_flags |= XPROBE_CUPTI_FEATURE_HOST_MONOTONIC_TIMESTAMPS; } header->capture_state = @@ -1689,15 +1993,102 @@ static int write_aggregate_records(int descriptor, return 0; } +/* Copy the contiguous ring records from `requested` that are still intact + * into ring_snapshot, setting `*first` to the index of the first and + * returning how many. A record overwritten by a newer one, or dropped by a + * writer that could not claim its slot, is a gap: one at the start moves + * `*first` past it, and one later ends this copy so the next snapshot + * reports it. A record still being written ends the copy. */ +static uint64_t copy_ring_records(uint64_t requested, uint64_t *first) +{ + uint64_t end = atomic_load_explicit(&record_count, memory_order_seq_cst); + uint64_t oldest = end > record_capacity ? end - record_capacity : 0U; + uint64_t count = 0U; + + *first = requested > oldest ? requested : oldest; + for (uint64_t index = *first; index < end; ++index) { + uint64_t slot = index % record_capacity; + uint64_t expected = index + 1U; + uint64_t seen; + + /* Own the slot while copying it; a writer that finds it owned drops + * its record and counts the loss instead of rewriting it. */ + if (atomic_compare_exchange_strong_explicit( + &record_sequence[slot], &expected, XPROBE_RING_READING | (index + 1U), + memory_order_acq_rel, memory_order_acquire)) { + ring_snapshot[count] = records[slot]; + ++count; + atomic_store_explicit(&record_sequence[slot], index + 1U, + memory_order_release); + continue; + } + seen = expected & XPROBE_RING_INDEX; + if (seen == index + 1U) { + /* Still being written. */ + break; + } + if (seen < index + 1U) { + /* Not yet claimed, or given up. With no writer pending, its + * writer is done: read the slot again before calling it a gap. */ + if (atomic_load_explicit(&ring_writers, memory_order_seq_cst) != 0U) { + break; + } + expected = index + 1U; + if (atomic_compare_exchange_strong_explicit( + &record_sequence[slot], &expected, + XPROBE_RING_READING | (index + 1U), memory_order_acq_rel, + memory_order_acquire)) { + ring_snapshot[count] = records[slot]; + ++count; + atomic_store_explicit(&record_sequence[slot], index + 1U, + memory_order_release); + continue; + } + } + if (count != 0U) { + break; + } + *first = index + 1U; + } + return count; +} + +static int write_device_table(int descriptor, + int (*write_function)(int, const void *, size_t)) +{ + struct xprobe_cupti_device_table table = { + .device_count = device_count, + .entry_size = (uint32_t)sizeof(device_entries[0]), + }; + + if (device_count == 0U) { + return 0; + } + if (write_function(descriptor, &table, sizeof(table)) != 0) { + return -1; + } + return write_function(descriptor, device_entries, + device_count * sizeof(device_entries[0])); +} + static int write_capture(int descriptor, int is_socket, uint64_t record_offset) { struct xprobe_cupti_output_header header; - uint64_t available = - atomic_load_explicit(&committed_record_count, memory_order_acquire); int (*write_function)(int, const void *, size_t) = is_socket != 0 ? send_all : write_all; + uint64_t available; int result; + if (capture_mode == XPROBE_CUPTI_CAPTURE_EXACT) { + /* Callbacks advance the commit count a bounded step at a time; the + * reader finishes the job before taking its snapshot. */ + advance_committed_records(UINT64_MAX); + } + /* A ring's offsets are logical indices of every record taken. */ + available = capture_mode == XPROBE_CUPTI_CAPTURE_RING + ? atomic_load_explicit(&record_count, memory_order_seq_cst) + : atomic_load_explicit(&committed_record_count, memory_order_acquire); + if ((capture_mode == XPROBE_CUPTI_CAPTURE_AGGREGATE && record_offset != 0U) || record_offset > available) { @@ -1708,8 +2099,26 @@ static int write_capture(int descriptor, int is_socket, uint64_t record_offset) (unsigned long long)available); return -1; } - initialize_output_header(&header, available, record_offset); + if (capture_mode == XPROBE_CUPTI_CAPTURE_RING) { + uint64_t first = 0U; + uint64_t count = copy_ring_records(record_offset, &first); + + initialize_output_header(&header, first + count, first, ring_snapshot, count); + result = write_function(descriptor, &header, sizeof(header)); + if (result == 0) { + result = write_device_table(descriptor, write_function); + } + if (result == 0) { + result = write_function(descriptor, ring_snapshot, + count * sizeof(records[0])); + } + return result; + } + initialize_output_header(&header, available, record_offset, records, available); result = write_function(descriptor, &header, sizeof(header)); + if (result == 0) { + result = write_device_table(descriptor, write_function); + } if (result == 0 && capture_mode == XPROBE_CUPTI_CAPTURE_AGGREGATE) { result = write_aggregate_records(descriptor, write_function); } else if (result == 0) { @@ -1731,6 +2140,8 @@ static int write_output(void) remember_output_error(); return XPROBE_CUPTI_AGENT_OUTPUT_ERROR; } + /* Outside CUDA initialization and every lock: the driver is ready. */ + read_device_table(); result = write_capture(descriptor, 0, 0U); if (close(descriptor) != 0 && result == 0) { result = -1; @@ -1908,9 +2319,20 @@ static int stop_capture(void) if (enabled_activity_mask != 0U) { status = flush_activity_buffers(1, 1); } - if (status == XPROBE_CUPTI_AGENT_READY && - (subscriber_active != 0 || enabled_activity_mask != 0U)) { - status = shutdown_agent(); + /* Disable callbacks and activity even after a failed flush; the failed + * capture state already tells the caller the records are incomplete. */ + if (subscriber_active != 0 || enabled_activity_mask != 0U) { + int shutdown_status = shutdown_agent(); + + if (shutdown_status != XPROBE_CUPTI_AGENT_READY) { + atomic_store_explicit(&capture_state, XPROBE_CUPTI_CAPTURE_FAILED, + memory_order_release); + atomic_store_explicit(&stop_reason, XPROBE_CUPTI_STOP_CLEANUP_ERROR, + memory_order_relaxed); + } + if (status == XPROBE_CUPTI_AGENT_READY) { + status = shutdown_status; + } } if (status == XPROBE_CUPTI_AGENT_READY && atomic_load_explicit(&capture_state, memory_order_acquire) == @@ -1967,11 +2389,13 @@ static void *serve_snapshots(void *unused) request.version != XPROBE_CUPTI_CONTROL_VERSION || (request.command < XPROBE_CUPTI_CONTROL_ARM || request.command > XPROBE_CUPTI_CONTROL_CLOSE) || - request.capture_mode > XPROBE_CUPTI_CAPTURE_AGGREGATE || + request.capture_mode > XPROBE_CUPTI_CAPTURE_RING || (request.command != XPROBE_CUPTI_CONTROL_ARM && request.filter_count != 0U)) { fprintf(stderr, "xprobe CUPTI: invalid snapshot control request\n"); - } else if (pthread_mutex_lock(&flush_mutex) != 0) { + } else if ((read_device_table(), pthread_mutex_lock(&flush_mutex)) != 0) { + /* The device table is read before the lock, so a driver call + * never holds up a flush or a callback waiting on it. */ fprintf(stderr, "xprobe CUPTI: failed to lock snapshot flush mutex\n"); } else { int command_status = XPROBE_CUPTI_AGENT_READY; @@ -1990,9 +2414,13 @@ static void *serve_snapshots(void *unused) } } else { command_status = stop_capture(); + /* Keep serving after a failed cleanup so CLOSE can retry. */ close_requested = - request.command == XPROBE_CUPTI_CONTROL_CLOSE; + request.command == XPROBE_CUPTI_CONTROL_CLOSE && + atomic_load_explicit(&stop_reason, memory_order_relaxed) != + XPROBE_CUPTI_STOP_CLEANUP_ERROR; } + /* The reply's capture state and stop reason carry the outcome. */ (void)command_status; if (write_capture(client, 1, request.record_offset) != 0) { fprintf(stderr, "xprobe CUPTI: failed to send snapshot: %s\n", @@ -2101,6 +2529,7 @@ static int disable_activities(void) } activities[] = { {XPROBE_CUPTI_ACTIVITY_MEMSET, CUPTI_ACTIVITY_KIND_MEMSET}, {XPROBE_CUPTI_ACTIVITY_MEMCPY, CUPTI_ACTIVITY_KIND_MEMCPY}, + {XPROBE_CUPTI_ACTIVITY_MEMCPY_PEER, CUPTI_ACTIVITY_KIND_MEMCPY2}, {XPROBE_CUPTI_ACTIVITY_KERNEL, CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL}, }; @@ -2149,10 +2578,13 @@ static int shutdown_agent(void) } else { result = cuptiUnsubscribe(subscriber); if (result != CUPTI_SUCCESS) { + /* Keep the subscriber marked active so a retry still + * unsubscribes it. */ report_cupti_error("cuptiUnsubscribe", result); status = XPROBE_CUPTI_AGENT_CUPTI_ERROR; + } else { + subscriber_active = 0; } - subscriber_active = 0; } } if (pthread_mutex_unlock(&subscriber_mutex) != 0) { @@ -2337,6 +2769,90 @@ static int enable_api_callbacks(CUpti_CallbackDomain domain, return enable_filtered_callbacks(domain, callback_count); } +/* Read every CUDA ordinal's UUID from the driver the target loaded, once + * the driver can report them: a capture armed during cuInit retries at its + * first write. No device table is sent while the driver cannot. */ +static _Atomic int device_warning_emitted; + +static void device_warning(const char *message) +{ + if (atomic_exchange_explicit(&device_warning_emitted, 1, memory_order_relaxed) == 0) { + fprintf(stderr, "xprobe CUPTI: %s; device UUIDs are unavailable\n", message); + } +} + +static void read_device_table(void) +{ + if (device_count != 0U) { + return; + } + typedef CUresult (*count_function)(int *); + typedef CUresult (*get_function)(CUdevice *, int); + typedef CUresult (*uuid_function)(CUuuid *, CUdevice); + void *driver = dlopen("libcuda.so.1", RTLD_NOW | RTLD_NOLOAD); + count_function get_count; + get_function get_device; + uuid_function get_uuid; + uuid_function get_gpu_uuid; + int count = 0; + + if (driver == NULL) { + device_warning("libcuda.so.1 is not loaded"); + return; + } + /* POSIX defines dlsym results as convertible to function pointers; + * copying the bytes keeps ISO C from objecting. */ +#define XPROBE_DRIVER_SYMBOL(target, name) \ + do { \ + void *symbol = dlsym(driver, name); \ + memcpy(&(target), &symbol, sizeof(target)); \ + } while (0) + XPROBE_DRIVER_SYMBOL(get_count, "cuDeviceGetCount"); + XPROBE_DRIVER_SYMBOL(get_device, "cuDeviceGet"); + XPROBE_DRIVER_SYMBOL(get_uuid, "cuDeviceGetUuid_v2"); + XPROBE_DRIVER_SYMBOL(get_gpu_uuid, "cuDeviceGetUuid"); + if (get_uuid == NULL) { + get_uuid = get_gpu_uuid; + } +#undef XPROBE_DRIVER_SYMBOL + agent_driver_call = 1; + if (get_count == NULL || get_device == NULL || get_uuid == NULL || + get_count(&count) != CUDA_SUCCESS || count < 0) { + agent_driver_call = 0; + device_warning("the CUDA driver did not report its devices"); + (void)dlclose(driver); + return; + } + for (int ordinal = 0; + ordinal < count && ordinal < (int)XPROBE_CUPTI_MAX_DEVICES; ++ordinal) { + CUdevice device; + CUuuid uuid; + CUuuid gpu_uuid; + struct xprobe_cupti_device_entry *entry = &device_entries[device_count]; + + if (get_device(&device, ordinal) != CUDA_SUCCESS || + get_uuid(&uuid, device) != CUDA_SUCCESS) { + device_warning("the CUDA driver did not report a device UUID"); + device_count = 0U; + break; + } + memset(entry, 0, sizeof(*entry)); + entry->ordinal = (uint32_t)ordinal; + memcpy(entry->uuid, uuid.bytes, sizeof(entry->uuid)); + /* Under MIG the two UUIDs differ: the instance's and its GPU's. */ + if (get_gpu_uuid != NULL && get_gpu_uuid != get_uuid && + get_gpu_uuid(&gpu_uuid, device) == CUDA_SUCCESS && + memcmp(gpu_uuid.bytes, uuid.bytes, sizeof(uuid.bytes)) != 0) { + entry->flags = XPROBE_CUPTI_DEVICE_MIG; + memcpy(entry->gpu_uuid, gpu_uuid.bytes, sizeof(entry->gpu_uuid)); + } + ++device_count; + } + agent_driver_call = 0; + /* The driver stays loaded by the target; this only drops our reference. */ + (void)dlclose(driver); +} + static int activate_capture(void) { #if CUPTI_API_VERSION >= 130000 @@ -2417,12 +2933,18 @@ static int activate_capture(void) return XPROBE_CUPTI_AGENT_CUPTI_ERROR; } if (needs_memcpy != 0 && - enable_activity(XPROBE_CUPTI_ACTIVITY_MEMCPY, - CUPTI_ACTIVITY_KIND_MEMCPY) != - XPROBE_CUPTI_AGENT_READY) { + (enable_activity(XPROBE_CUPTI_ACTIVITY_MEMCPY, + CUPTI_ACTIVITY_KIND_MEMCPY) != + XPROBE_CUPTI_AGENT_READY || + enable_activity(XPROBE_CUPTI_ACTIVITY_MEMCPY_PEER, + CUPTI_ACTIVITY_KIND_MEMCPY2) != + XPROBE_CUPTI_AGENT_READY)) { shutdown_agent(); return XPROBE_CUPTI_AGENT_CUPTI_ERROR; } + if (needs_memcpy != 0) { + atomic_store_explicit(&capture_peer_memcpy, 1, memory_order_relaxed); + } if (needs_memset != 0 && enable_activity(XPROBE_CUPTI_ACTIVITY_MEMSET, CUPTI_ACTIVITY_KIND_MEMSET) != diff --git a/cupti/tests/cuda_gap_fixture.cu b/cupti/tests/cuda_gap_fixture.cu new file mode 100644 index 0000000..3f06a30 --- /dev/null +++ b/cupti/tests/cuda_gap_fixture.cu @@ -0,0 +1,96 @@ +// Steady stream of small kernels with rare host-side bubbles, for +// triggered-capture tests. argv[1] is created when CUDA is ready; the loop +// stops when argv[2] exists. +// +// About once a second the whole GPU idles for 30 ms. Half a second later the +// main stream pauses for 30 ms again, but a kernel on a side stream keeps the +// device busy throughout: a stream gap that is not device idle time. +#include + +#include +#include + +__global__ void xprobe_trigger_kernel(int *output) +{ + if (threadIdx.x == 0) { + atomicAdd(output, 1); + } +} + +__device__ unsigned long long xprobe_global_ns() +{ + unsigned long long now; + asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(now)); + return now; +} + +// Keeps the device busy for `duration_ns` of GPU wall time. +__global__ void xprobe_side_kernel(unsigned long long duration_ns, int *output) +{ + const unsigned long long start = xprobe_global_ns(); + while (xprobe_global_ns() - start < duration_ns) { + } + if (threadIdx.x == 0) { + atomicAdd(output, 1); + } +} + +int main(int argc, char **argv) +{ + if (argc != 3) { + std::fprintf(stderr, "usage: %s \n", argv[0]); + return 2; + } + int *device_output = nullptr; + cudaStream_t main_stream = nullptr; + cudaStream_t side_stream = nullptr; + cudaError_t result = cudaMalloc(&device_output, sizeof(*device_output)); + if (result == cudaSuccess) { + result = cudaMemset(device_output, 0, sizeof(*device_output)); + } + // Non-blocking streams do not synchronize with each other implicitly. + if (result == cudaSuccess) { + result = cudaStreamCreateWithFlags(&main_stream, cudaStreamNonBlocking); + } + if (result == cudaSuccess) { + result = cudaStreamCreateWithFlags(&side_stream, cudaStreamNonBlocking); + } + if (result == cudaSuccess) { + result = cudaDeviceSynchronize(); + } + if (result != cudaSuccess) { + std::fprintf(stderr, "CUDA setup failed: %s\n", cudaGetErrorString(result)); + return 13; + } + std::FILE *ready = std::fopen(argv[1], "w"); + if (ready == nullptr || std::fclose(ready) != 0) { + std::perror("ready file"); + return 15; + } + for (unsigned iteration = 1; access(argv[2], F_OK) != 0; ++iteration) { + const bool idle = iteration % 2000 == 0; + const bool side = iteration % 2000 == 1000; + if (side) { + xprobe_side_kernel<<<1, 32, 0, side_stream>>>(45000000ULL, device_output); + } + for (int launch = 0; launch < 20; ++launch) { + xprobe_trigger_kernel<<<1, 32, 0, main_stream>>>(device_output); + } + result = cudaStreamSynchronize(main_stream); + if (result != cudaSuccess) { + std::fprintf(stderr, "kernel loop failed: %s\n", cudaGetErrorString(result)); + return 13; + } + usleep(idle || side ? 30000 : 200); + if (side) { + result = cudaStreamSynchronize(side_stream); + if (result != cudaSuccess) { + std::fprintf(stderr, "side kernel failed: %s\n", cudaGetErrorString(result)); + return 13; + } + } + } + cudaStreamDestroy(side_stream); + cudaStreamDestroy(main_stream); + return cudaFree(device_output) == cudaSuccess ? 0 : 13; +} diff --git a/docs/agent-integration.md b/docs/agent-integration.md index 3bcf144..85bbc11 100644 --- a/docs/agent-integration.md +++ b/docs/agent-integration.md @@ -1,58 +1,26 @@ # Agent integration -xprobe exposes shell commands, versioned JSON, JSON Schema, and one canonical -Skill. It does not call model APIs or provide an agent daemon. +xprobe exposes four CLI commands, versioned JSON/JSONL, JSON Schemas, and one official Agent Skill. It does not call model APIs or run a daemon. -The canonical workflow is -`skills/xprobe-measure-latency/SKILL.md`. `AGENTS.md`, `CLAUDE.md`, and -`.cursor/rules/xprobe.mdc` are discovery points and must not duplicate command -sequences or correlation rules. +The canonical Skill lives at `skills/xprobe-perf-profiling/SKILL.md`. `AGENTS.md`, `CLAUDE.md`, and `.cursor/rules/xprobe.mdc` point to it without duplicating command lists or schema rules. ## Install the Skill -The canonical directory follows the open Agent Skills format and is shared by -Codex, Claude Code, Cursor, and other compatible clients. The user installs the -released Skill through the `skills` CLI; the activated Skill then bootstraps or -repairs the matching xprobe CLI itself: +The Skill follows the open Agent Skills format and works with Codex, Claude Code, Cursor, and compatible clients: ```bash -npx skills@1 add \ - https://github.com/itdevwu/xprobe/tree/v0.6.3/skills/xprobe-measure-latency \ - --global +npx skills add itdevwu/xprobe ``` -For automation, add `--agent codex|claude-code|cursor --copy --yes`. Omit -`--global` for repository-scoped installation. The Skill is self-contained; -install its whole directory so its references, examples, and analysis script -remain available. +To pin a release or install non-interactively, see [Installation](installation.md#ai-agent-skill). Keep the full directory intact so `references/`, `examples/`, and `scripts/analyze_trace.py` remain available. -The Skill's `SKILL.md` is the agent-facing workflow; this page does not -restate it. It drives a two-command path for unknown live work: `measure ---triage` over one representative window, then the ranked finding's ready -`MeasurementSpec` or a measurement graph. Existing artifacts are analyzed -offline without installing a collector, and an escalation ladder covers what -the first pass cannot explain before handing off to kernel or runtime -profilers. Selection and concurrency across processes stay in the agent; -xprobe adds no multi-process command and never claims cross-process causality. +The Skill focuses on what agents need to get right on the first try: exact stdout and JSONL artifact shapes (`references/data-format.md`), selector/graph syntax (`references/selectors.md`), composable one-off Python scripting recipes (cross-source, cross-process `CLOCK_MONOTONIC` alignment, `wall_clock` log joining, and RSI before/after diffs), and hard runtime limits. -## Contract test +## Automated checks ```bash just test-agent-contract just test-skill-install ``` -The test requires the visible command set to be exactly `doctor`, `discover`, -`validate`, and `measure`, invokes them in strict JSON mode, and verifies -schemas and the bundled trace analyzer. For the Skill it enforces a word budget -for the entry point and all references, resolves every link, rejects orphaned -references, checks that every documented `xprobe` command uses flags its -subcommand accepts, validates the example specs, and checks routing for -existing artifacts, unknown workloads, known boundaries, graphs, deeper -escalation, Python semantics, multiple processes, and containers. -The installation test uses the real third-party CLI in isolated home directories -and verifies byte-for-byte copies for Codex, Claude Code, and Cursor. - -This is interface conformance, not model evaluation. External harnesses may -evaluate task success, command count, cleanup, mutation disclosure, and result -interpretation without adding model-specific behavior to xprobe. +`test-agent-contract` verifies that the public CLI is exactly `doctor`, `discover`, `validate`, and `measure`, invokes them in JSON mode, checks all JSON Schemas, runs the `analyze_trace.py` fixture suite, and validates the Skill (word budget, links, no orphaned references, documented `xprobe` flags against `--help`, cited artifact fields against `schemas/`, valid JSON blocks, and example specs). `test-skill-install` runs the third-party `skills` CLI in isolated home directories and checks byte-for-byte copies for Codex, Claude Code, and Cursor. diff --git a/docs/architecture.md b/docs/architecture.md index 5ece33b..774020f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,214 +1,93 @@ # Architecture -This document describes the implemented xprobe architecture. +How xprobe is structured and how data moves through it. -## Boundary +## Overview ```text -human or coding agent +human or AI agent | - | doctor -> discover -> validate -> measure - | versioned JSON + | doctor | discover | validate | measure + | versioned JSON + raw JSONL v xprobe CLI | - +-- core: procfs identity, ELF discovery/resolution, validation, injection - +-- collector: PID-scoped eBPF and CUPTI snapshots - +-- correlator: bounded pairing, quality, statistics, evidence - +-- exporter: JSONL and Chrome trace artifacts + +-- core: procfs identity, ELF/symbol/layout resolution, validation, ptrace injection, clock anchors + +-- collector: PID-scoped eBPF, perf CPU sampling, external CPython reading, CUPTI Agent control & ABI + +-- correlator: pairing policies, span evaluation, statistics, quality verdicts + +-- exporter: Event JSONL, capture manifests, Chrome Trace Event Format v -running process or completed capture files +live Linux process or saved capture files ``` -There is no daemon and no persistent session API. A foreground `measure` owns -attachment, collection, correlation, logical CUPTI shutdown, and cleanup. +xprobe has no daemon and no persistent session API. Each foreground `measure` owns attachment, collection, correlation, logical CUPTI stop, and cleanup. -## Workspace +## Workspace layout -| Path | Responsibility | +| Path | Role | | --- | --- | -| `xprobe/cli` | Four public commands, rendering, exit codes, orchestration | -| `xprobe/core` | doctor, process identity, discovery, ELF resolution, validation, ptrace injection, inventory normalization | -| `xprobe/protocol` | Strict serde contracts and generated JSON Schema | -| `xprobe/collector` | eBPF collection, CUPTI selector filters, control protocol and ABI decoding | -| `xprobe/correlator` | Selector matching, pair evidence, statistics and quality | -| `xprobe/exporter` | Event JSONL and Chrome Trace Event Format | -| `bpf/` | PID-scoped uprobe, USDT, syscall, tracepoint, and aggregate programs | -| `cupti/` | Reusable in-process CUDA callback/activity agent | - -## Identity and discovery - -A target identity is its PID plus `/proc//stat` start time. xprobe verifies -that pair before and after metadata operations and attachment. PID reuse returns -`TARGET_REUSED`; disappearance returns `TARGET_EXITED`. - -`discover` queries NVML compute processes, verifies each PID's ancestry under -the requested process-tree root, and returns only confirmed CUDA context -holders with stable process identity, parent PID, command line, and GPU UUIDs. -It does not attach and does not choose a worker. That orchestration belongs to -the calling Agent or user. A multi-process investigation uses one bounded -command per selected PID/start-time identity; concurrency and per-worker failure -handling remain in the caller, and event correlation never crosses processes. - -Host selector resolution converts ELF virtual addresses through load segments -to file offsets, then through `/proc//maps` to runtime addresses. This -supports executables, PIE, and shared libraries without assuming that a mapping -base is a symbol address. Raw ELF names are matched without demangling the -symbol table. A full C++ signature uses the explicit `symbol=` selector form; -the resolver checks exported dynamic symbols first, falls back to the complete -table, and returns both the attachable mangled name and readable signature. - -CPU stack analysis resolves sampled instruction pointers through the target's -mapped ELF load segments and symbol tables. Only modules containing retained -sampled addresses are read, and only the symbols containing those offsets are -demangled; lookup still uses each module's complete text-symbol table, so -zero-size symbols keep their next-symbol bound. CPython frames are resolved -independently from `/tmp/perf-.map` when the interpreter exposes an active -perf trampoline. Native coverage remains usable when Python semantic symbols -are inactive or unsupported. CPython GC resolution parses `.note.stapsdt` from -the mapped interpreter or `libpython` and accepts the selector only when both -required markers are present in one ELF. +| `xprobe/cli` | Public commands (`doctor`, `discover`, `validate`, `measure`), rendering, exit codes, orchestration | +| `xprobe/core` | `doctor`, process identity, `discover`, ELF/USDT/Python layout resolution, `validate`, ptrace injection, wall-clock anchoring, triage rules | +| `xprobe/protocol` | Strict serde types and generated JSON Schemas (`schemas/`) | +| `xprobe/collector` | eBPF uprobes/syscalls/tracepoints/USDT, perf CPU sampling, external CPython sampling, CUPTI control protocol & ABI decoding | +| `xprobe/correlator` | Pairing policies, trigger span evaluation, statistics, quality verdicts | +| `xprobe/exporter` | Event JSONL, `.manifest.json`, and Chrome Trace Event Format | +| `bpf/` | PID-scoped eBPF programs (uprobe, USDT, syscall, tracepoint, syscall aggregate) | +| `cupti/` | Reusable in-process CUPTI callback, activity, ring, and aggregate Agent (`libxprobe-cupti.so`) | + +## Process identity and discovery + +- Target processes are identified by `(pid, /proc//stat start_time)` and re-verified around metadata inspection and attach. Reuse returns `TARGET_REUSED`; exit returns `TARGET_EXITED`. +- `discover --pid ROOT` queries NVML for compute processes, verifies ancestry under `ROOT`, and returns confirmed CUDA context holders with process identity, parent PID, command line, and GPU UUIDs. It does not attach or pick a worker for you. +- Multi-process and multi-GPU runs invoke one `measure` per PID; concurrent captures on the same host share `CLOCK_MONOTONIC` (and map GPUs by UUID via `cuda_devices`), while CLI correlation stays single-process. + +## Symbol, probe, and layout resolution + +- **Native ELF**: converts ELF virtual addresses through load segments to file offsets, then through `/proc//maps` to runtime addresses (supporting executables, PIE, and shared libraries). Plain names match raw ELF symbols; C++ `symbol=` checks exported dynamic symbols first and falls back to the full symbol table. +- **CPU stacks**: resolves sampled instruction pointers from mapped ELF load segments and text-symbol tables (only loading modules that appear in samples). CPython frames are resolved separately from `/tmp/perf-.map` when active; native frames remain available otherwise. +- **CPython GC**: parses `.note.stapsdt` in the mapped interpreter or `libpython` and requires both `python:gc__start` and `python:gc__done` markers in one ELF. +- **External CPython layout**: built-in CPython 3.9โ€“3.14 interpreter offsets are checked against `_Py_DebugOffsets` on 3.13+. ## Validation -`validate` is read-only. It resolves ELF, USDT, and Linux syscall probes, -parses named tracepoint and CUDA selectors, checks correlation-policy -compatibility, and reports eBPF, CUPTI, callback, activity, and clock -requirements. CUPTI activation is one of: +`validate` is read-only. It resolves host/USDT/syscall probes, parses tracepoint and CUDA selectors, checks policy compatibility, and reports required capabilities. CUPTI activation is one of: - `not_required` - `already_loaded` -- `injection_required` -- `startup_required` - -`injection_required` keeps validation valid when all semantic requirements are -met, sets `target_mutation: true`, and emits `TARGET_PROCESS_WILL_BE_MODIFIED`. -`startup_required` is specific to an NVTX selector whose target did not load -the Agent before NVTX initialized. Online attach cannot rewrite that dispatch -table, so validation returns an explicit issue instead of promising injection. -Malformed selectors, unresolved symbols, invalid policies, and unavailable -required host collection remain explicit issues or errors. - -CPU sampling and syscall aggregation use dedicated validation contracts. They -check target identity and current perf-event or eBPF capability without -attaching, report no target mutation, and preserve unavailable Python semantic -symbolization as status rather than inventing frames. - -## Collection - -Host events use libbpf-rs. ELF functions attach one PID-scoped uprobe or -uretprobe per unique endpoint. Linux syscall endpoints share raw -`sys_enter`/`sys_exit` links and compare up to two configured x86_64 syscall -numbers after PID-namespace filtering. Only matching entries read the six -scalar ABI registers; exits retain the scalar return value. Pointer-referenced -memory is never read. - -Named tracepoints attach by category and name and retain timestamp, PID/TID, -CPU, and selector identity without copying payload fields. The two endpoint -links are armed together after attachment, so setup events cannot enter the -capture. Linux records use a `--max-events`-sized ring buffer and fixed record -layout. Ring exhaustion, scalar-read failure, malformed records, and -duration-capacity exhaustion remain explicit failures. Rust ownership detaches -all links on every return path. - -CPython GC uses the same bounded Linux ring and two `SEC("usdt")` programs. -libbpf attaches each marker to the exact mapped ELF returned by validation; -both links attach before the shared map is armed. Events retain identity, -timestamp, provider, and marker name only. Exact correlation follows one -ordered start/end lifecycle per process thread. - -CPU inventory opens one bounded software CPU-clock perf event per current -target thread and samples userspace callchains into fixed capacities. It counts -exact raw stacks before deterministic top-group truncation, then resolves native -ELF and optional Python perf-map frames into stack groups and -inclusive/exclusive hotspots. Sample loss, truncated callchains, thread fanout, -group pressure, and symbol coverage remain first-class output. - -Syscall inventory uses PID-filtered raw entry/exit programs with a bounded LRU -map for per-thread starts and a bounded per-CPU hash for aggregate groups. The -hot path retains syscall number, timestamp, scalar return status, and integer -duration accounting; it emits no per-call ring records. Userspace merges the -per-CPU values and maps known x86_64 numbers to selector hints. - -CUDA events use an in-process CUPTI Agent. CUDA 12 and CUDA 13 builds share the -same source and capture ABI but link their matching CUPTI SONAME. Loading the -Agent creates a control socket; `measure` separately arms one fresh, -`--max-events`-bounded capture with up to eight filters for its CUDA endpoints -(control protocol v5 carries the active filter count, and hot paths scan only -active filters). Runtime and -Driver callbacks plus kernel, memcpy, and memset activity are filtered before -fixed records consume capacity. Callback hot paths do not perform blocking I/O -or allocation. - -NVTX startup injection installs CUPTI routing before the first NVTX call and -keeps one dormant subscriber alive for the process lifetime. Each ARM enables -only the six supported global ASCII/Ex range callbacks. A preallocated, -open-addressed table retains matching starts until a thread pop or process -range end recovers the same bounded name and start thread. Thread keys combine -TID with the returned nesting level; process keys use the returned 64-bit NVTX -range ID and permit a different end thread. STOP disables callback domains but -does not unsubscribe the routing required by CUDA 13. - -Broad inventory remains in the foreground `measure` primitive. CPU sampling, -syscall aggregation, and GPU aggregation have separate result schemas because -their quality and capacity meanings differ. Their groups are hypotheses for a -later validated exact capture, not event timelines that can be re-correlated. - -Triage runs these inventories concurrently in one foreground `measure`, between -two procfs `schedstat` and cgroup `cpu.stat` snapshots, while sampling NVML -through `nvidia-smi`. Deterministic rules in core turn the summaries into ranked -findings with a proposed exact `MeasurementSpec`. Each full inventory stays in -its own artifact with its own contract; the triage result references them -instead of merging them into one timeline. - -Broad GPU inventory uses aggregate mode. The -Agent updates a `--max-groups`-bounded table for matching kernel, memcpy, or -memset activity and returns only final count/duration/byte summaries. Exact -measurement remains the evidence path; aggregate output has a separate result -contract and cannot be exported as event JSONL. Kernel names are retained as -fixed 127-byte observed prefixes. Complete names produce exact selector hints; -a full name buffer is marked incomplete and produces a prefix hint that remains -filterable before event reservation. - -CUPTI activity timestamps are normalized to `CLOCK_MONOTONIC` through its -timestamp callback or an explicit CUDA 12 clock calibration. Activity that -began before the ARM epoch is excluded. The Agent verifies the retained window -before setting the host-monotonic ABI feature, preserving GPU same-domain -durations while preventing invalid cross-domain subtraction. - -Snapshot flushes and reads only records after a checked caller watermark. The -CLI rejects noncontiguous offsets and counter rollback while accumulating the -bounded capture. Stop flushes the final delta and disables CUPTI but retains an -externally managed socket for a later ARM. Automatically injected collection -closes its private socket after the final capture. Neither path unloads the -shared object. - -## Online injection - -When CUDA collection is required and no compatibility socket was supplied, -`measure` derives the major from mapped CUPTI/CUDART libraries and selects the -matching installed Agent. It then uses ptrace on Linux x86_64. It resolves target `malloc`, `free`, -`dlopen`, and `dlsym`, executes them on one stopped target thread, and calls -`xprobe_cupti_agent_start` with a private socket path. Each remote call saves and -restores registers and the touched stack word. An unexpected trap, timeout, or -syscall error fails explicitly; the cleanup path restores target state before -detach. - -The target must share xprobe's mount namespace so the agent path has the same -meaning. ptrace policy, credentials, and LSMs still apply. xprobe warns on -stderr and records `CUPTI_AGENT_INJECTED` in the result. It never `dlclose`s the -agent because unloading callback code in a live CUDA process is unsafe. - -## Correlation and evidence - -Every exact live measurement runs one shared capture loop over a plan of -validated endpoints and merged requirements. The loop owns attachment, polling, -timeout, CUPTI shutdown, cleanup, and artifact preservation; an evaluator owns -correlation and sample completion. A single edge and a measurement graph differ -only in their evaluator: a graph validates the merged capture once and -correlates each edge independently. - -All sources normalize into the versioned `Event` type. `measure` supports: +- `injection_required` โ€” valid when semantic checks pass; sets `target_mutation: true` and emits `TARGET_PROCESS_WILL_BE_MODIFIED`. +- `startup_required` โ€” NVTX selector on a process that did not preload the Agent before NVTX initialized; validation fails with an explicit issue because online attach cannot rewrite NVTX dispatch. + +CPU sampling, syscall aggregation, and measurement graphs each have their own validation response shapes without attaching. + +## Collection paths + +### Host eBPF (`bpf/`, `xprobe/collector`) +- **Uprobes**: one PID-scoped `uprobe`/`uretprobe` per unique endpoint. +- **Syscalls**: shared raw `sys_enter`/`sys_exit` links filtering PID and up to two x86_64 syscall numbers before reading the six scalar ABI registers (entry) and return value (exit). Pointer arguments are never dereferenced. +- **Tracepoints & CPython GC USDT**: record identity and timestamps only; both endpoint links attach before arming so setup events cannot leak in. +- **Syscall aggregate**: PID-filtered raw entry/exit programs aggregating into a fixed LRU in-flight map and per-CPU hash map, merged in userspace with selector hints. +- Rust ownership detaches all links on every return path. + +### CPU and external Python sampling +- **`--cpu-sample`**: opens software CPU-clock perf events per target thread, groups exact raw callchains before top-group truncation, and resolves native ELF + optional `/tmp/perf-.map` frames while keeping loss, truncation, and symbol-coverage counters visible. +- **`--python-sample`**: reads CPython 3.9โ€“3.14 interpreter memory from outside the target via `process_vm_readv` (no perf events, eBPF, `-X perf`, or injection; needs ptrace access). Samples the GIL holder at `--python-hz` (default 2000) and all threads at `--python-threads-hz` (default 100), discarding inconsistent reads and reading `/proc//task//syscall` for blocked threads' native waits. Writes every timestamped sample (`CLOCK_MONOTONIC`) to a JSONL artifact. + +### CUDA / CUPTI (`cupti/`, `xprobe/collector/src/cupti.rs`) +- Separate `libxprobe-cupti.so` builds link `libcupti.so.12` and `libcupti.so.13` from one source and ABI. +- Control protocol v6 sends `ARM`, `SNAPSHOT`, `STOP`, and `CLOSE` over a mode-0600 Unix socket with up to eight endpoint filters and three capture modes: + - **Exact**: records matching events up to `--max-events` and returns contiguous deltas on `SNAPSHOT`/`STOP`. + - **Aggregate**: updates a fixed `--max-groups` hash table in the Agent for kernel, memcpy (with `src_memory`/`dst_memory`), and memset summaries. + - **Ring (`--trigger-*`)**: keeps the newest `--max-events` records in a sequence-locked ring while the CLI evaluates device idle, stream gap, activity duration, or CUDA edge latency spans on each snapshot and writes `--pre-ms`/`--post-ms` windows around firing spans. +- Online injection uses Linux x86_64 ptrace (same mount namespace required) to remotely call `malloc`, `free`, `dlopen`, `dlsym`, and `xprobe_cupti_agent_start`, restoring registers and touched stack words on every path. `STOP`/`CLOSE` disable CUPTI logically without ever calling `dlclose`. +- Activity timestamps normalize to `CLOCK_MONOTONIC` when runtime alignment is verified; otherwise GPU-only spans stay in the `cupti` clock and cross CPU/GPU subtraction fails with `CLOCK_ALIGNMENT_FAILED`. +- NVTX requires `NVTX_INJECTION64_PATH` before the target's first NVTX call; see [CUPTI Agent](cupti-agent.md) for ABI and lifecycle details. + +### Triage snapshot (`--triage`) +Runs procfs `schedstat`, cgroup `cpu.stat`, CPU sampling, external Python sampling (when CPython), syscall aggregate, NVML device health, and CUDA kernel aggregate concurrently in one window. Each full inventory is written to its own artifact; rule-based `findings` in `xprobe/core/src/triage.rs` are optional hints over those summaries. + +## Correlation, manifests, and schemas + +Single-edge and measurement-graph live runs share one capture loop (attach, poll, timeout, CUPTI stop, cleanup, artifact write). A graph validates once and correlates each edge independently without implying cross-edge causality. | Policy | Pairing | Confidence | | --- | --- | --- | @@ -216,24 +95,12 @@ All sources normalize into the versioned `Event` type. `measure` supports: | `first-after` | First unused end at or after each start | heuristic | | `nearest` | Nearest unused end by timestamp | heuristic | | `stack-nested` | Per-thread LIFO host entry/return | high | -| `stream-order` | Ordered activity within device/context/stream | high | - -Statistics are derived from every matched start/end pair. Measurement results -use schema `3.0`: by default `evidence` inlines one exemplar pair per latency -rank (min, p50, p90, p99, max) and references the bounded event artifact that -live captures always write; `--evidence full` also inlines every pair. The -artifact re-correlates deterministically with `measure --input`. A -deterministic `quality` verdict summarizes timeout, correlation confidence, -ambiguity, unmatched events, clock error, and sample count. Drops, unmatched -events, ambiguity, policy, confidence, and clock quality remain visible. A normalized -CUPTI event without a reported interpolation bound makes -`estimated_error_ns: null` and emits `CLOCK_ERROR_UNAVAILABLE`. - -## Contracts and failure model - -Public records use schema version `2.0`; generated schemas are checked in and -tested for drift. Unknown fields and unsupported versions fail deserialization. -Expected capability absence is represented as available/restricted/unavailable -data. Unexpected I/O, malformed procfs/ELF/capture data, target changes, -collector errors, and cleanup failures return errors rather than partial -success. +| `stream-order` | Activity end to next kernel, copy, or memset start on the same device/context/stream | high | + +Live event captures always write Event JSONL (or Chrome trace with `--format chrome`) plus `.manifest.json` (schema `1.0`) recording target identity, `CLOCK_MONOTONIC` window, `wall_clock` UTC anchors (`xprobe/core/src/clock.rs`), `all_gpu_activity`, `cuda_devices` UUIDs, losses, and SHA-256. Offline `measure --input` verifies the manifest and re-correlates deterministically. + +### Schema versions & errors +- **Schema `3.0`**: `MeasurementResult`, `AggregateInventoryResult`, `MeasurementGraphSpec`/`ValidationResult`/`Result`, `PythonSampleResult`, `TriageResult`, `TriggerResult`. +- **Schema `2.0`**: `Event` JSONL, `MeasurementSpec`, `CapabilityReport`, `DiscoveryResult`, `ValidationResult`, CPU sample & syscall aggregate results, `ErrorResponse`. +- **Schema `1.0`**: `CaptureManifest`. +- Unknown JSON fields and unsupported schema versions fail deserialization. Malformed data, I/O errors, target exit/reuse, drops, and cleanup failures return explicit JSON errors rather than partial success. diff --git a/docs/assets/fonts/Geist-Bold.woff2 b/docs/assets/fonts/Geist-Bold.woff2 new file mode 100644 index 0000000..7b03813 Binary files /dev/null and b/docs/assets/fonts/Geist-Bold.woff2 differ diff --git a/docs/assets/fonts/Geist-Regular.woff2 b/docs/assets/fonts/Geist-Regular.woff2 new file mode 100644 index 0000000..679164f Binary files /dev/null and b/docs/assets/fonts/Geist-Regular.woff2 differ diff --git a/docs/assets/fonts/MapleMono-Bold.woff2 b/docs/assets/fonts/MapleMono-Bold.woff2 new file mode 100644 index 0000000..69455d2 Binary files /dev/null and b/docs/assets/fonts/MapleMono-Bold.woff2 differ diff --git a/docs/assets/fonts/MapleMono-Regular.woff2 b/docs/assets/fonts/MapleMono-Regular.woff2 new file mode 100644 index 0000000..a623431 Binary files /dev/null and b/docs/assets/fonts/MapleMono-Regular.woff2 differ diff --git a/docs/assets/fonts/OFL-Geist.txt b/docs/assets/fonts/OFL-Geist.txt new file mode 100644 index 0000000..999fa23 --- /dev/null +++ b/docs/assets/fonts/OFL-Geist.txt @@ -0,0 +1,93 @@ +Copyright 2026 The Geist Project Authors (https://github.com/vercel/geist-font) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/docs/assets/fonts/OFL-MapleMono.txt b/docs/assets/fonts/OFL-MapleMono.txt new file mode 100644 index 0000000..65ea530 --- /dev/null +++ b/docs/assets/fonts/OFL-MapleMono.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Maple Mono Project Authors (https://github.com/subframe7536/maple-font) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/docs/assets/social-preview.png b/docs/assets/social-preview.png index b0092f5..25cec32 100644 Binary files a/docs/assets/social-preview.png and b/docs/assets/social-preview.png differ diff --git a/docs/assets/social-preview.svg b/docs/assets/social-preview.svg index e76538c..2189bc9 100644 --- a/docs/assets/social-preview.svg +++ b/docs/assets/social-preview.svg @@ -1 +1,7 @@ -xprobeWhy is my CPU, Python, or CUDA process slow? Two commands.xprobe: triage a slow process, then measure the exact latencyA terminal runs xprobe triage on a PyTorch CUDA process. Ranked findings show a CPU hotspot, a dominant GPU kernel, and power-capped GPU clocks. A second command measures request to launch 1.14 ms, launch to kernel 99 microseconds, and kernel duration 1.2 microseconds on CPU and GPU timelines.Why is PID 4242 slow?$xprobe measure --pid 4242 --triage --duration-ms 20001CPU_HOTSPOTlibgomp worker spinning: 77% of sampled stacks76%2GPU_KERNEL_DOMINANTampere_sgemm_128x64_nn: all kernel time, GPU busy 54%54%3GPU_CLOCK_LIMITEDsw_power_cap under loadn/aโ†’ each finding ships a ready next spec$xprobe measure --spec next.jsonCPUGPUrequestcudaLaunchKernel returnskernelrequest โ†’ launch 1.14 ms (first-after)launch โ†’ kernel 99 ยตs (exact)kernel 1.2 ยตs (exact)Two commands. Bounded capture. No daemon. Evidence an agent can read. +xprobeML infra profiler for AI agents โ€” minimizing friction on the path to RSI.xprobe: live CPU, Python, and CUDA profiling inside an RSI loopLive xprobe captures align a 14.2 ms GPU idle bubble with Python GIL stacks on CLOCK_MONOTONIC, feed JSONL into an agent analysis script, and verify an illustrative RSI optimization that drops GPU idle share from 34% to 6% and step p95 from 42.1 ms to 27.8 ms.xprobe ยท live CPU + Python + CUDA profilingCLOCK_MONOTONIC$xprobe measure --pid 4242 --trigger-idle-ms 10 --events-out spikesGPU JSONL$xprobe measure --pid 4242 --python-sample --duration-ms 2000Python JSONL1 ยท ALIGNED TIMELINEHOST/PYlaunch โ†’ kernel (exact)GIL: tokenize() ยท 68%GPUattngemmgemmattngemmgemm14.2 ms GPU idle bubble0 msgap_startgap_end+50 ms2 ยท AGENT SCRIPT & PATCH$ analyze_trace.py spikes/window-1.jsonlโ†’ 14.2 ms idle ยท 68% GIL in tokenize()โ†’ patch: async HtoD + off-GIL tokenizer3 ยท RSI DIFFKEEP โœ“GPU idle share34% โ†’ 6%beforeafterStep latency p9542.1 ms โ†’ 27.8 ms (-34%)beforeafter1. Live profile (JSONL)โ†’2. Slice & diagnoseโ†’3. Patch codeโ†’4. Re-verify & repeat โ†ป diff --git a/docs/assets/xprobe-flow-dark.svg b/docs/assets/xprobe-flow-dark.svg index f7b5d22..6448ce2 100644 --- a/docs/assets/xprobe-flow-dark.svg +++ b/docs/assets/xprobe-flow-dark.svg @@ -1,34 +1,35 @@ -xprobe: triage a slow process, then measure the exact latencyA terminal runs xprobe triage on a PyTorch CUDA process. Ranked findings show a CPU hotspot, a dominant GPU kernel, and power-capped GPU clocks. A second command measures request to launch 1.14 ms, launch to kernel 99 microseconds, and kernel duration 1.2 microseconds on CPU and GPU timelines.Why is PID 4242 slow?$xprobe measure --pid 4242 --triage --duration-ms 20001CPU_HOTSPOTlibgomp worker spinning: 77% of sampled stacks76%2GPU_KERNEL_DOMINANTampere_sgemm_128x64_nn: all kernel time, GPU busy 54%54%3GPU_CLOCK_LIMITEDsw_power_cap under loadn/aโ†’ each finding ships a ready next spec$xprobe measure --spec next.jsonCPUGPUrequestcudaLaunchKernel returnskernelrequest โ†’ launch 1.14 ms (first-after)launch โ†’ kernel 99 ยตs (exact)kernel 1.2 ยตs (exact)Two commands. Bounded capture. No daemon. Evidence an agent can read. +xprobe: live CPU, Python, and CUDA profiling inside an RSI loopLive xprobe captures align a 14.2 ms GPU idle bubble with Python GIL stacks on CLOCK_MONOTONIC, feed JSONL into an agent analysis script, and verify an illustrative RSI optimization that drops GPU idle share from 34% to 6% and step p95 from 42.1 ms to 27.8 ms.xprobe ยท live CPU + Python + CUDA profilingCLOCK_MONOTONIC$xprobe measure --pid 4242 --trigger-idle-ms 10 --events-out spikesGPU JSONL$xprobe measure --pid 4242 --python-sample --duration-ms 2000Python JSONL1 ยท ALIGNED TIMELINEHOST/PYlaunch โ†’ kernel (exact)GIL: tokenize() ยท 68%GPUattngemmgemmattngemmgemm14.2 ms GPU idle bubble0 msgap_startgap_end+50 ms2 ยท AGENT SCRIPT & PATCH$ analyze_trace.py spikes/window-1.jsonlโ†’ 14.2 ms idle ยท 68% GIL in tokenize()โ†’ patch: async HtoD + off-GIL tokenizer3 ยท RSI DIFFKEEP โœ“GPU idle share34% โ†’ 6%beforeafterStep latency p9542.1 ms โ†’ 27.8 ms (-34%)beforeafter1. Live profile (JSONL)โ†’2. Slice & diagnoseโ†’3. Patch codeโ†’4. Re-verify & repeat โ†ป diff --git a/docs/assets/xprobe-flow-light.svg b/docs/assets/xprobe-flow-light.svg index ea0aabc..1f701a4 100644 --- a/docs/assets/xprobe-flow-light.svg +++ b/docs/assets/xprobe-flow-light.svg @@ -1,34 +1,35 @@ -xprobe: triage a slow process, then measure the exact latencyA terminal runs xprobe triage on a PyTorch CUDA process. Ranked findings show a CPU hotspot, a dominant GPU kernel, and power-capped GPU clocks. A second command measures request to launch 1.14 ms, launch to kernel 99 microseconds, and kernel duration 1.2 microseconds on CPU and GPU timelines.Why is PID 4242 slow?$xprobe measure --pid 4242 --triage --duration-ms 20001CPU_HOTSPOTlibgomp worker spinning: 77% of sampled stacks76%2GPU_KERNEL_DOMINANTampere_sgemm_128x64_nn: all kernel time, GPU busy 54%54%3GPU_CLOCK_LIMITEDsw_power_cap under loadn/aโ†’ each finding ships a ready next spec$xprobe measure --spec next.jsonCPUGPUrequestcudaLaunchKernel returnskernelrequest โ†’ launch 1.14 ms (first-after)launch โ†’ kernel 99 ยตs (exact)kernel 1.2 ยตs (exact)Two commands. Bounded capture. No daemon. Evidence an agent can read. +xprobe: live CPU, Python, and CUDA profiling inside an RSI loopLive xprobe captures align a 14.2 ms GPU idle bubble with Python GIL stacks on CLOCK_MONOTONIC, feed JSONL into an agent analysis script, and verify an illustrative RSI optimization that drops GPU idle share from 34% to 6% and step p95 from 42.1 ms to 27.8 ms.xprobe ยท live CPU + Python + CUDA profilingCLOCK_MONOTONIC$xprobe measure --pid 4242 --trigger-idle-ms 10 --events-out spikesGPU JSONL$xprobe measure --pid 4242 --python-sample --duration-ms 2000Python JSONL1 ยท ALIGNED TIMELINEHOST/PYlaunch โ†’ kernel (exact)GIL: tokenize() ยท 68%GPUattngemmgemmattngemmgemm14.2 ms GPU idle bubble0 msgap_startgap_end+50 ms2 ยท AGENT SCRIPT & PATCH$ analyze_trace.py spikes/window-1.jsonlโ†’ 14.2 ms idle ยท 68% GIL in tokenize()โ†’ patch: async HtoD + off-GIL tokenizer3 ยท RSI DIFFKEEP โœ“GPU idle share34% โ†’ 6%beforeafterStep latency p9542.1 ms โ†’ 27.8 ms (-34%)beforeafter1. Live profile (JSONL)โ†’2. Slice & diagnoseโ†’3. Patch codeโ†’4. Re-verify & repeat โ†ป diff --git a/docs/benchmarks.md b/docs/benchmarks.md index 12a93e6..6a424e0 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -1,104 +1,72 @@ # Precision and overhead benchmarks -Run the CPU and Python inventory benchmark through the pinned -capability-limited container: +## Sample measurements + +One run on WSL2 with an RTX 3060 Laptop GPU (xprobe 0.7), measured as the ratio of target throughput without vs. with profiling over 2 s per case (lower is better; `1.00` = zero overhead): + +| Collector | Workload | Throughput ratio | Event / sample rate | +| --- | --- | --- | --- | +| CUPTI callbacks + activity | Paced kernels | 1.0005 | ~6,800 events/s | +| CUPTI callbacks + activity | Empty-launch stress | 1.285 | ~2.7 ยตs per launch | +| Uprobe entry + return | Native function | 1.042 | ~1,300 pairs/s | +| CPU sampling (`--cpu-sample`) | Native | 1.011 | 199 Hz | +| CPU sampling (`--cpu-sample`) | CPython 3.12 (`-X perf`) | 1.027 | 199 Hz | +| CPython GC USDT | CPython 3.12 | 1.020 | GC lifecycles | +| External Python sampling (32-frame stack) | CPython 3.10 | 0.991 | 2,000 Hz GIL, p50 read 68 ยตs | +| External Python sampling (32-frame stack) | CPython 3.12 | 0.984 | 2,000 Hz GIL, p50 read 39 ยตs | +| `perf record` | Native | 1.009 | 199 Hz | +| `py-spy record` (default, pauses target) | CPython 3.12 | 1.184 | 199 Hz | + +Per-event cost varies with kernel version, virtualization, and workload shape; re-run on your target host before drawing conclusions. + +## Running the benchmarks + +Every benchmark uses fresh targets per case (profilers never coexist in the same process) and emits one JSON report. + +### CPU and Python (`just benchmark-cpu` / `just benchmark-cpu-host`) ```bash just benchmark-cpu ``` -For an already-provisioned Linux host with `perf`, `py-spy`, CPython 3.12 or -newer with `-X perf`, perf-event access, and eBPF attach permission, use -`just benchmark-cpu-host`. +Runs inside a pinned capability-limited container (`just benchmark-cpu-host` runs directly on a Linux host with `perf`, `py-spy`, CPython 3.12+ `-X perf`, and perf/eBPF permissions). Compares baseline, xprobe CPU sampling, syscall aggregate, exact uprobe/GC USDT (using inventory selector hints), `perf`, and `py-spy`. Reports throughput, collector CPU/RSS, target RSS, artifact size, sample loss, and symbol coverage, failing on drops or missing symbols. -The benchmark uses a fresh target for every case. Native and Python workloads -are each measured without a profiler, with bounded xprobe CPU sampling, and -with their corresponding broad profiler (`perf` or `py-spy`). A native syscall -inventory is measured separately. The native exact measurement uses selector -hints emitted by the sampled inventory; the Python exact measurement uses GC -USDT only after validation proves that capability. Profilers never coexist. +### External CPython sampler (`just benchmark-python-sampling`) -The JSON report includes throughput, collector CPU and peak RSS, target RSS, -artifact size, sample loss, stack and symbol coverage, retained capacity, and -exact-correlation quality. It rejects incomplete or lossy xprobe captures, -missing native or Python symbols, malformed comparison artifacts, and empty -exact measurements. It does not enforce an overhead winner: the observations -are workload-specific and do not establish that any profiler is universally -faster. +```bash +just benchmark-python-sampling +``` + +Runs a 32-frame hot Python leaf in `python:3.10` and `python:3.12` containers (3 runs each, baseline vs. `--python-sample` defaults) and checks the median throughput ratio against the `1.02` target along with achieved GIL Hz, discarded reads, and read latency. CPython <3.11 reads one frame per syscall; 3.11+ reads the contiguous frame stack at once. -Run the reproducible GPU benchmark with the pinned CUDA devel image: +### GPU callback overhead and timing precision (`just benchmark-gpu`) ```bash just benchmark-gpu ``` -The benchmark uses the actual visible GPU and reports one JSON document. It -compares the duration of a dedicated kernel from CUPTI Activity with an -independent CUDA Event measurement. It also compares the median host wall time -with and without the CUPTI Agent for two workloads: five rounds of 1,000 empty -kernel launches, and five rounds of 200 approximately 1 ms kernels. - -The run fails on malformed captures, unknown or dropped records, a precision -error above `max(250 us, 10%)`, or an overhead ratio above `25x`. The broad -overhead limit catches broken instrumentation. The empty-launch result is a -high-event-rate stress metric. The paced workload verifies its observed event -rate is below 10,000 events/s before reporting whether the current `<2%` -engineering target was met. That target is an observation, not a compatibility -promise, and should be evaluated on representative applications as well. +Compares CUPTI kernel duration against an independent CUDA Event timer (fails above `max(250 ยตs, 10%)`), and measures host wall time with vs. without the CUPTI Agent on 5ร—1,000 empty launches (high-rate stress) and 5ร—200 ~1 ms paced kernels (checked against `<2%` overhead when `<10,000 events/s`; `25x` ceiling catches broken instrumentation). Keep the complete JSON output (includes GPU model, driver, compute capability, and drop counters). -The output records the GPU name, driver, compute capability, workload shape, -reference and CUPTI durations, error, baseline and instrumented medians, overhead -ratio, ABI metadata, and drop counters. Keep complete JSON output with benchmark -results; do not label a run by a GPU model inferred from machine documentation. - -For aggregate inventory changes, run: +### Aggregate vs. raw GPU capture (`just benchmark-aggregate`) ```bash just benchmark-aggregate ``` -This benchmark keeps a two-kernel CUDA workload at a high event rate and -captures it once as raw exact events and once into a four-slot aggregate table. -It fails unless both captures are complete and drop-free, the aggregate count -exceeds table capacity without saturation, and exactly two groups are retained. -It also requires aggregate capture to use less collector CPU, collector peak -RSS, target-process RSS growth, and artifact space than raw broad capture. - -The resource comparison uses `wait4` for collector CPU and peak RSS and samples -target RSS from procfs while the command runs. It deliberately does not gate on -short GPU throughput windows: device clock changes can make those samples move -opposite to profiler overhead. The JSON output includes every asserted resource -and collection value so regressions remain diagnosable. +Captures a high-rate two-kernel CUDA workload once as raw exact events and once into a 4-slot aggregate table. Verifies zero drops, exact 2-group retention without table saturation, and lower collector CPU, collector peak RSS (`wait4`), target RSS growth (procfs), and artifact size for aggregate mode. -Run the agent-orchestrated worker benchmark with: +### Multi-process CUDA workers (`just benchmark-multiprocess`) ```bash just benchmark-multiprocess ``` -Fresh homogeneous batches of one, two, and four CUDA workers are discovered by -PID plus start time. One representative worker supplies a broad aggregate -inventory; its selector hints are validated for every worker before independent -spec-based measurements start concurrently. The benchmark rejects identity -changes, missing injection warnings, path reuse, non-overlapping commands, -incomplete captures, and drops. - -Its JSON keeps validation, command timing, quality, artifact metadata, and -baseline-versus-collection throughput per worker. Perturbation is reported -without a fixed pass ratio because shared GPU scheduling and first injection -cost vary by workload and worker count. +Spawns 1, 2, and 4 CUDA workers, discovers them via `discover`, gathers selector hints from one worker, validates all workers, and runs concurrent per-worker specs. Fails on identity mismatch, missing injection warnings, path reuse, non-overlapping windows, or drops, and reports per-worker overhead and timing. -Run the framework-level PyTorch benchmark with: +### PyTorch end-to-end (`just benchmark-pytorch`) ```bash just benchmark-pytorch ``` -It measures the same warmed-up `torch.mm` plus stream-synchronization workload -without an Agent, with the Agent idle, during a bounded xprobe capture, and with -PyTorch Profiler. PyTorch Profiler runs in a separate process so the two CUPTI -subscribers never coexist. The benchmark reports throughput ratios, validation, -matched/unmatched/ambiguous samples, completeness, drops, retained capacity and -buffer utilization. A broad `25x` ceiling catches broken instrumentation; the -reported `1.05` project target remains an observation rather than a compatibility -promise. +Measures warmed-up `torch.mm` + stream synchronization across four separate runs: baseline, idle mapped Agent, active xprobe capture, and `torch.profiler` (separate process so CUPTI subscribers never collide). Reports throughput ratios (against the `1.05` target and `25x` ceiling), sample quality, drops, and buffer utilization. diff --git a/docs/cli-contract.md b/docs/cli-contract.md index c3326a4..1b09327 100644 --- a/docs/cli-contract.md +++ b/docs/cli-contract.md @@ -1,32 +1,26 @@ -# CLI contract +# CLI reference -xprobe exposes exactly four public commands: `doctor`, `discover`, `validate`, -and `measure`. +xprobe exposes four public commands: `doctor`, `discover`, `validate`, and `measure`. ## Common behavior -When stdout is not a terminal, every command writes one versioned JSON document -to stdout; on a terminal it prints a human-readable report. `--json` forces -JSON and `--human` forces the report; they cannot be combined. -`--non-interactive` and `--no-color` are accepted for compatibility: commands -never prompt and never color. Diagnostics, including the online-injection -warning, go to stderr. +- When stdout is not a terminal, every command writes one versioned JSON document to stdout; on a terminal it prints a human-readable report. `--json` forces JSON and `--human` forces text (mutually exclusive). +- `--non-interactive` and `--no-color` are accepted for scripting compatibility (xprobe never prompts or colors output). Diagnostics and injection warnings go to stderr. +- Schema versions: + - **`3.0`**: measurement, measurement-graph (spec, validate, result), GPU `--aggregate`, `--python-sample`, `--triage`, and `--trigger-*` results. + - **`2.0`**: `doctor`, `discover`, single-edge `validate`/`MeasurementSpec`, `--cpu-sample`, `--syscall-aggregate`, errors, and Event JSONL lines. + - **`1.0`**: capture manifests (`.manifest.json`). + - Unknown JSON fields and unsupported versions fail deserialization. -Measurement results carry `schema_version: "3.0"`; every other success record, -error record, and Event JSONL line carries `"2.0"`. Unknown JSON fields and -unsupported schema versions are rejected. xprobe maintains only the -current schema during the pre-1.0 protocol transition. - -| Exit | Meaning | +| Exit code | Meaning | | --- | --- | -| `0` | Command completed and emitted a result | -| `1` | Validation, collection, decode, export, cleanup, or internal failure | -| `2` | Invalid CLI syntax from Clap | +| `0` | Command succeeded and printed a result | +| `1` | Validation, collection, decode, export, cleanup, or internal error | +| `2` | Invalid CLI syntax (Clap) | | `3` | Target missing, exited, or reused | | `4` | Permission denied for inspection, eBPF, or ptrace | -Runtime failures use `schemas/error.schema.json` and include a stable code, -message, recoverability, details, and hints. +Runtime errors conform to `schemas/error.schema.json` and carry a stable `code`, `message`, `recoverable`, `details`, and `hints`. ## `doctor` @@ -34,47 +28,23 @@ message, recoverability, details, and hints. xprobe doctor ``` -Reports Linux/kernel identity, BTF, BPF/perf permissions, lockdown, ptrace -policy, NVIDIA driver, CUDA toolkit/driver, CUPTI, namespaces, and conservative -capability booleans. `ok: true` means diagnosis completed, not that every -capability is available. The CUPTI check lists each supported installed major -and its resolved library path. Privilege checks read the effective capability set -(`CapEff`), not the user ID: root inside a container without `CAP_BPF` and -`CAP_PERFMON` (or `CAP_SYS_ADMIN`) reports eBPF as restricted, and online -injection needs `CAP_SYS_PTRACE` unless `ptrace_scope` permits same-user -tracing. +Reports kernel/OS identity, BTF, BPF/perf permissions, lockdown, ptrace policy, NVIDIA driver, CUDA toolkit/driver, CUPTI libraries (each supported installed major and resolved path), namespaces, and capability booleans. `ok: true` means diagnostics completed, not that every collector is available. + +Privilege checks read `CapEff` (effective capability set), not UID: root in a container without `CAP_BPF` and `CAP_PERFMON` (or `CAP_SYS_ADMIN`) reports eBPF restricted, and live injection needs `CAP_SYS_PTRACE` unless `ptrace_scope` allows same-user tracing. ## `discover` ```bash -xprobe discover --pid 4242 [--limit 200] +xprobe discover --pid 4242 --limit 200 ``` -Treats the PID as a process-tree root and queries NVML for active CUDA compute -processes without attaching. It returns only root/descendant context holders, -including PID plus procfs start time, parent PID, executable, command line, and -GPU UUIDs. `limit` must be positive. `total_candidates` and `truncated` -describe bounded output. The caller chooses one candidate and passes its PID to -`validate` and `measure`; xprobe does not guess among workers. - -NVML lists compute processes from every container sharing the GPU. A listed PID -that is not visible in the caller's PID namespace, or that exits before -inspection, cannot be a candidate; it is reported in a -`NVML_PROCESS_UNAVAILABLE` warning with its `nvml_pids` instead of failing the -command. When none of them is visible, a `NVML_PID_NAMESPACE_MISMATCH` -warning explains that NVML reported host PIDs: inside a container, pass the -worker's namespace-local PID directly to `validate` and `measure`. Root exit and other inspection failures remain errors. - -This process-candidate response is discovery schema `2.0`. xprobe does not emit -or maintain the pre-0.3 event-discovery shape. +Queries NVML for active CUDA compute processes under process-tree root `--pid` without attaching, returning confirmed CUDA context holders (PID, procfs start time, parent PID, executable, command line, GPU UUIDs). `--limit` must be positive; `total_candidates` and `truncated` report output bounds. `discover` does not pick a worker or cover non-CUDA CPU/Python processes. -An unavailable or failed NVML query is an explicit command error, not an empty -candidate list. +Because NVML lists processes across all containers sharing a GPU, PIDs invisible in the caller's PID namespace (or exited during inspection) emit `NVML_PROCESS_UNAVAILABLE` with `nvml_pids` instead of failing. When none are visible, `NVML_PID_NAMESPACE_MISMATCH` notes that NVML returned host PIDs โ€” inside a container, pass the namespace-local PID directly to `validate`/`measure`. A failed NVML query or missing root PID returns an error. ## Selectors -Selectors are supplied by the caller and checked by `validate` before any -attachment. Host selector forms are: +Selectors are validated before any attachment: ```text uprobe:::entry @@ -88,39 +58,20 @@ syscall::exit tracepoint:: python:gc_start python:gc_end +cuda:runtime_api::entry|exit +cuda:driver_api::entry|exit +cuda:launch_api:entry|exit +cuda:kernel_start|kernel_end[:name~REGEX] +cuda:memcpy_start|memcpy_end[:kind=HtoD|DtoH|DtoD|HtoH|PtoP] +cuda:memset_start|memset_end +cuda:nvtx_range_start|nvtx_range_end:name~REGEX ``` -The `symbol=` form allows `::` and other punctuation in a full C++ signature. -Resolution returns the attachable mangled ELF name in `symbol` and its readable -signature in `symbol_demangled`; captured host events retain both. It works for -mapped CPython, native extension, and framework libraries, but does not resolve -Python frames or `module.qualname` names. - -Named syscall selectors are Linux x86_64 endpoints resolved by `validate`. -Their eBPF path filters PID and syscall number before reserving an event, -records the six scalar syscall ABI registers on entry, and records the scalar -return value on exit. It never dereferences pointer arguments. Named -tracepoints record identity and timestamp only; they do not copy the tracepoint -payload. Unsupported syscall names and unavailable tracepoints fail explicitly. - -Python GC selectors are capability-based, not process-name based. Validation -reads the target's mapped CPython executable and `libpython` ELF metadata and -requires both `python:gc__start` and `python:gc__done` USDT markers. Captured -events contain process/thread identity, timestamp, mapped binary, provider, and -marker name without copying generation or object payloads. - -CUDA forms include Runtime/Driver API entry/exit, kernel/memcpy/memset activity -start/end, and NVTX range boundaries. `cuda:launch_api:entry|exit` matches every -kernel launch API in one endpoint: Runtime `cudaLaunchKernel`, -`cudaLaunchKernelExC`, and `cudaLaunchCooperativeKernel`, and Driver -`cuLaunchKernel`, `cuLaunchKernelEx`, and `cuLaunchCooperativeKernel`, so -launches from cuBLAS and from Triton or other Driver API callers pair exactly -with their kernels. A Runtime launch and the Driver launch it makes internally -count once, as the Runtime call. It uses two of the eight Agent name filters. Kernel selectors accept `name~REGEX`; -memcpy selectors accept `kind=`. NVTX selectors are -`cuda:nvtx_range_start:name~REGEX` and -`cuda:nvtx_range_end:name~REGEX`; their name expression must reduce to one -nonempty exact, prefix, suffix, or contains filter shorter than 128 bytes. +- **Host C/C++**: `symbol=` handles `::` and punctuation in demangled C++ signatures, returning both the attachable mangled ELF name (`symbol`) and `symbol_demangled`. Does not resolve Python frames. +- **Syscalls & tracepoints**: Linux x86_64 syscalls filter PID and syscall number in BPF before reading the six scalar entry registers and scalar return value (pointer arguments are never dereferenced). Tracepoints record identity and timestamp only. Unsupported names fail explicitly. +- **CPython GC**: capability-based (`validate` inspects mapped Python/`libpython` ELF metadata for both `python:gc__start` and `python:gc__done` USDT markers). Records identity, timestamp, binary, provider, and marker name only. +- **CUDA launch**: `cuda:launch_api:entry|exit` matches Runtime (`cudaLaunchKernel`, `cudaLaunchKernelExC`, `cudaLaunchCooperativeKernel`) and Driver (`cuLaunchKernel`, `cuLaunchKernelEx`, `cuLaunchCooperativeKernel`) launch APIs in one endpoint (covering cuBLAS, Triton, and Driver callers; a Runtime call and its inner Driver call count once as the Runtime call; uses 2 of 8 Agent filters). +- **NVTX & kernel regex**: NVTX `name~REGEX` must reduce to one nonempty exact, prefix, suffix, or contains literal shorter than 128 bytes. Kernel regexes matching that rule filter in the CUPTI Agent hot path; more complex regexes filter in Rust after a broader capture. ## `validate` @@ -131,261 +82,126 @@ xprobe validate --pid 4242 \ --match exact ``` -Validation is read-only. It verifies target identity, resolves host and Python -USDT selectors, parses CUDA filters, and checks collection and correlation -requirements. `validate --cpu-sample` checks target threads, perf-event access, -and Python symbolization status. `validate --syscall-aggregate` checks the -bounded eBPF aggregate path. Inventory modes do not take event-pair selectors. -Results conform to `schemas/validate.schema.json`. - -`validate --spec graph.json` validates a measurement graph without `--pid`; the -spec's target selects the process. It emits -`schemas/measurement-graph-validate.schema.json` (schema `3.0`) with each named -endpoint's resolution, each edge's policy recommendation, requirements merged -across edges, and issues scoped to the graph, an endpoint, or an edge. Unknown -or unused endpoints, duplicate edge names, missing bounds, and more than two -syscall, tracepoint, or USDT endpoints are issues, not command errors. - -Supported policies are `exact`, `first-after`, `nearest`, `stack-nested`, and -`stream-order`. Exact uses deterministic CUPTI correlation IDs, NVTX range -kind/ID, one named syscall's per-thread entry/exit lifecycle, or one CPython GC -start/end lifecycle on the same thread. Nested -requires entry/return of the same host function. Stream order requires GPU -activity endpoints. Temporal policies always warn that they are heuristic. -`policy_recommendation` reports the strongest compatible policy, a stable -machine-readable reason, and all compatible alternatives. The caller still -chooses the policy; xprobe does not silently replace or retry it. - -`requirements.agent_activation` is `not_required`, `already_loaded`, -`injection_required`, or `startup_required`. Online injection handles ordinary -CUDA callbacks and activity; `injection_required` sets `target_mutation: true` -and emits `TARGET_PROCESS_WILL_BE_MODIFIED`. NVTX dispatch is fixed by its first -API initialization, so an unmapped Agent produces `startup_required` and an -invalid result. Restart the target with `NVTX_INJECTION64_PATH` set to the -matching xprobe Agent before its first NVTX call. A mapped Agent is verified -again at ARM through the capture feature flag. Callers must stop on -`valid: false`. -Mapped CUDA/CUPTI majors that conflict or fall outside 12 and 13 produce -`UNSUPPORTED_CUDA_VERSION`. -CUDA major support does not imply host-clock alignment: `measure` accepts -GPU-only pairs in the CUPTI clock and rejects CPU/GPU subtraction when the -capture omits the host-monotonic feature flag. +Read-only check of target identity, probe resolution, CUDA filters, correlation compatibility, and runtime requirements (`schemas/validate.schema.json`). + +- `--cpu-sample` checks target threads, perf-event access, and Python perf-map symbolization status. +- `--syscall-aggregate` checks the eBPF syscall aggregate path. +- `--spec graph.json` validates a measurement graph without `--pid` (`schemas/measurement-graph-validate.schema.json`, schema `3.0`), scoping issues to the graph, an endpoint, or an edge. +- `policy_recommendation` reports the strongest compatible policy, a machine-readable reason, and compatible alternatives without silently changing `--match`. +- `requirements.agent_activation` is `not_required`, `already_loaded`, `injection_required` (sets `target_mutation: true` and warns `TARGET_PROCESS_WILL_BE_MODIFIED`), or `startup_required` (NVTX selector without preloaded Agent โ€” returns `valid: false`). +- Conflicting or unsupported CUDA majors (outside 12 and 13) return `UNSUPPORTED_CUDA_VERSION`. + +### Correlation policies + +| Policy | Behavior | +| --- | --- | +| `exact` | CUPTI correlation ID, NVTX range kind/ID, same-thread syscall entry/exit, or same-thread CPython GC start/end | +| `stack-nested` | Same-thread LIFO host function entry/return | +| `stream-order` | GPU activity end to the next kernel, copy, or memset start on the same device/context/stream; records all GPU activity (6 of 8 Agent filters, warns `STREAM_ORDER_CAPTURES_ALL_ACTIVITY`); overlapping ends, tied successors, or truncated names that cannot decide the selector are marked ambiguous | +| `first-after`, `nearest` | Temporal matching across unrelated sources (always warned as heuristic) | ## `measure` -Live target: +Exactly one source mode is used: `--pid`, one or more `--input`, or `--spec`. Live runs require `--samples` or `--duration-ms`; offline `--input` correlates all events when neither is set. Defaults: `--timeout-ms 30000`, `--max-events 100000`. + +### Common command forms ```bash +# Live CUDA launch-to-kernel latency xprobe measure --pid 4242 \ - --from 'cuda:launch_api:exit' \ - --to 'cuda:kernel_start:name~flash.*' \ - --match exact --samples 100 --timeout-ms 30000 \ - --events-out /tmp/xprobe-events.jsonl -``` - -Linux syscall duration: + --from 'cuda:launch_api:exit' --to 'cuda:kernel_start:name~flash.*' \ + --match exact --samples 100 --timeout-ms 30000 --events-out /tmp/xprobe-events.jsonl -```bash +# Syscall duration xprobe measure --pid 4242 \ --from 'syscall:mmap:entry' --to 'syscall:mmap:exit' \ --match exact --samples 100 --max-events 1000 -``` -CPU/Python hotspot inventory: +# CPython GC duration +xprobe measure --pid 4242 \ + --from python:gc_start --to python:gc_end --match exact --samples 100 --max-events 1000 -```bash +# NVTX range (target started with NVTX_INJECTION64_PATH) +xprobe measure --pid 4242 \ + --from 'cuda:nvtx_range_start:name~^forward$' \ + --to 'cuda:nvtx_range_end:name~^forward$' --match exact --samples 100 --max-events 1000 + +# CPU callchain hotspot inventory xprobe measure --pid 4242 --cpu-sample --duration-ms 1000 \ - --frequency-hz 99 --max-samples 10000 --max-groups 256 \ - --stack-depth 64 --max-threads 1024 -``` + --frequency-hz 99 --max-samples 10000 --max-groups 256 --stack-depth 64 --max-threads 1024 -Syscall lifecycle inventory: +# External CPython stacks & GIL holder +xprobe measure --pid 4242 --python-sample --duration-ms 2000 -```bash +# Syscall totals inventory xprobe measure --pid 4242 --syscall-aggregate --duration-ms 1000 \ --max-groups 256 --max-inflight 1024 -``` -CPython garbage-collection duration: +# GPU kernel/memcpy/memset totals inventory +xprobe measure --pid 4242 --from 'cuda:kernel_start' --to 'cuda:kernel_end' \ + --match exact --aggregate --duration-ms 1000 --max-groups 4096 -```bash -xprobe measure --pid 4242 \ - --from python:gc_start --to python:gc_end \ - --match exact --samples 100 --max-events 1000 -``` +# Same-window multi-source snapshot +xprobe measure --pid 4242 --triage --duration-ms 2000 -NVTX application range: +# Offline re-correlation of saved captures +xprobe measure --input host.json --input cupti.bin \ + --from 'uprobe:/srv/app/server:request:entry' \ + --to 'cuda:kernel_start:name~flash.*' --match first-after --samples 100 -```bash -xprobe measure --pid 4242 \ - --from 'cuda:nvtx_range_start:name~^forward$' \ - --to 'cuda:nvtx_range_end:name~^forward$' \ - --match exact --samples 100 --max-events 1000 +# Versioned spec or measurement graph +xprobe measure --spec measurement.json ``` -Completed captures: +### Inventory & snapshot modes -```bash -xprobe measure --input host.json --input cupti.bin \ - --from 'uprobe:/srv/app/server:request:entry' \ - --to 'cuda:kernel_start:name~flash.*' \ - --match first-after --samples 100 -``` +- **`--cpu-sample`** (live, `--duration-ms`, schema `2.0`): PID-scoped userspace callchain sampling (defaults: 99 Hz, 10,000 samples, 256 groups, depth 64, 1,024 threads). Resolves ELF symbols and `/tmp/perf-.map` Python frames independently, reporting `python_status`, uprobe selector hints, lost samples, and truncation. +- **`--python-sample`** (live, `--duration-ms`, schema `3.0`): reads CPython 3.9โ€“3.14 memory via `process_vm_readv` without perf events, eBPF, `-X perf`, or injection (needs ptrace access). Samples the GIL holder at `--python-hz` (default 2000) and all threads at `--python-threads-hz` (default 100), verifying offsets against `_Py_DebugOffsets` on 3.13+ (unsupported/free-threaded builds return `UNSUPPORTED_PYTHON_VERSION`). Discards racing reads (`inconsistent_reads`), reports blocked threads' `/proc//task//syscall` native waits, and writes every timestamped sample (`CLOCK_MONOTONIC`) to a JSONL artifact (`schemas/python-sample-record.schema.json`). Frames report `first_line` (function start), not current line. +- **`--syscall-aggregate`** (live, `--duration-ms`, schema `2.0`): PID-filtered BPF maps (`--max-inflight`, `--max-groups`) emitting per-syscall count, errors, min/mean/max/total duration, and selector hints. No per-call event stream or pointer values. +- **`--aggregate`** (live, `--duration-ms`, schema `3.0`): Agent-side aggregation (`--max-groups`, default 4,096) for one matching kernel, memcpy, or memset start/end pair. Kernel regex must reduce to a hot-path literal filter; names truncated at 127 bytes set `name_complete: false` with a prefix hint. Memcpy groups split by `src_memory` and `dst_memory` (`pageable`, `pinned`, `device`, `managed`, etc.). +- **`--triage`** (live, `--duration-ms`, schema `3.0`): concurrently collects procfs thread times, cgroup CPU throttling, CPU samples, external Python samples (when CPython), syscall aggregate, NVML device health, and CUDA kernel aggregate (may inject CUPTI). Writes full inventories to per-source artifacts, keeps top 5 entries inline, and attaches optional rule-based `findings` and `not_covered` notes. Unavailable or saturated sources become `unavailable` with `TRIAGE_SOURCE_UNAVAILABLE` rather than failing the whole run. -Versioned live spec: +Inventory modes (`--cpu-sample`, `--syscall-aggregate`, `--aggregate`) do not write Event JSONL and cannot be passed to `--input` or `--events-out`. -```bash -xprobe measure --spec measurement.json -``` +### Live capture & CUDA Agent behavior -Same-window triage of an unknown live workload: +- Host endpoints attach all eBPF links before arming. Duration captures that hit `--max-events` fail with `EVENT_RATE_TOO_HIGH`. +- CUDA endpoints auto-select `--agent`, `XPROBE_CUPTI_AGENT_PATH`, `../lib/xprobe/cuda12|cuda13`, or the matching build path. Live injection requires Linux x86_64, a shared mount namespace, and ptrace permission, emits a stderr warning and `CUPTI_AGENT_INJECTED`, disables CUPTI on stop, and removes its private socket while leaving the `.so` mapped. +- NVTX thread ranges track `(tid, push_level)`; process ranges track `range_id` across threads (`start_tid`). Supports ASCII `PushA`/`StartA` and `Ex` forms (no wide/registered strings or CUPTI Range Profiling). -```bash -xprobe measure --pid 4242 --triage --duration-ms 2000 -``` +### Offline `--input` & capture manifests + +- Accepts CUPTI ABI binary, host-capture JSON, or Event JSONL. Repeated `--input` files are merged after rejecting mixed targets (same PID with different start times) and duplicate event content. +- Live captures always write the full capture with mode `0600` (`--events-out PATH` or a private mode-`0700` temp directory), defaulting to JSONL (`--format chrome` writes Chrome Trace Event Format). +- Beside every Event JSONL, xprobe writes `.manifest.json` (`schemas/capture-manifest.schema.json`, schema `1.0`) containing target identity, `CLOCK_MONOTONIC` window, selectors, `all_gpu_activity`, `peer_copies`, losses, `cuda_devices` UUIDs, `wall_clock` UTC start/end anchors (each bracketed by two monotonic reads with `uncertainty_ns`), size, and SHA-256. +- Offline `--input` verifies the manifest's size/SHA-256 and restores recorded losses and coverage. Without manifests, coverage is `unverified` (or `unverified_merge`), and `stream-order` falls back to heuristic with a caution. +- Even when correlation, clock, drop, or capacity errors occur after collection, the artifact is still written and its path is included in the JSON error (`TRACE_EXPORT_FAILED` preserves the original error code in `details`). + +### Results (`schemas/measurement-result.schema.json`, schema `3.0`) -Broad GPU activity inventory: +Includes `status`, `measurement.latency_ns` & `measurement.samples`, `quality` (`good` or `caution` with coded issues), `correlation`, `clock`, `collection` (completeness, CUPTI utilization/drops, `cuda_devices`, `wall_clock`), `evidence` (rank exemplars min/p50/p90/p99/max, artifact path, and with `--evidence full` all pairs), and `warnings`. + +Error codes include `NO_MATCHED_SAMPLES`, `CLOCK_ALIGNMENT_FAILED`, `EVENT_RATE_TOO_HIGH`, `EVENTS_DROPPED`, `TRIGGER_NOT_OBSERVED`, `TARGET_EXITED`, `TARGET_REUSED`, and `CLEANUP_FAILED`. Structured `details` and `hints` carry machine-readable follow-up data. + +### Triggered capture (`--trigger-*`) ```bash -xprobe measure --pid 4242 \ - --from 'cuda:kernel_start' --to 'cuda:kernel_end' \ - --match exact --aggregate --duration-ms 1000 --max-groups 4096 +xprobe measure --pid 4242 --trigger-idle-ms 10 --pre-ms 50 --post-ms 50 \ + --timeout-ms 300000 --max-events 400000 --events-out /tmp/spikes ``` -Exactly one source mode is used: `--pid`, one or more `--input`, or `--spec`. -Live measurement requires at least one positive `--samples` or `--duration-ms` -bound; completed `--input` captures are already bounded and correlate every -event when neither is set. `--timeout-ms` defaults to 30 seconds and -`--max-events` to 100,000. - -`--cpu-sample` is live-only and requires `--duration-ms`. It opens bounded -userspace callchain sampling events for the target's current threads. Defaults -are 99 Hz, 10,000 observed samples, 256 retained stack groups, depth 64, and -1,024 threads. The result uses -`schemas/cpu-sample-inventory-result.schema.json`: exact raw stack counts are -grouped deterministically, hotspots report inclusive/exclusive counts and -proportions, and attachable native frames include uprobe selector hints. Native -ELF and `/tmp/perf-.map` Python symbols are resolved independently. -`python_status` and resolved/unresolved frame counts prevent native fallback -from being mislabeled as Python semantic coverage. Lost samples, truncated -stacks, thread coverage, and capacity pressure remain visible. - -`--triage` is live-only, requires `--duration-ms`, and emits -`schemas/triage-result.schema.json` (schema `3.0`). Within one window it -concurrently collects procfs per-thread on-CPU, runqueue, and blocked time; -cgroup CPU throttling; a CPU sample inventory; a syscall aggregate; NVML device -health (utilization, clock event reasons, temperature, power, PCIe link); and, -when the target has loaded libcuda, a CUDA kernel aggregate, which may inject -the CUPTI Agent under the same rules as `measure`. The result keeps the top -five hotspots, syscall groups, and kernel groups inline and writes each full -inventory to a private artifact referenced from `sources`. `findings` are -deterministic and ranked by an estimated share of the window; a finding whose -impact cannot be bounded has `impact_share: null` and ranks last. Each finding -carries an environment action or a ready `MeasurementSpec` for `measure ---spec`, with record capacity sized from the observed rate. A source that is not -permitted, absent, or exceeds its bounded capacity is `unavailable` with a -reason and a `TRIAGE_SOURCE_UNAVAILABLE` warning; target exit or reuse, cleanup, -and internal failures fail the command. `not_covered` lists what triage cannot -answer, including where blocked threads wait. Blocked time includes idle -waiting, so read it per thread. NVML utilization is a device-wide sampled -estimate. - -`--syscall-aggregate` is live-only and requires `--duration-ms`. PID-filtered -raw syscall entry/exit programs retain at most `--max-inflight` thread starts -and `--max-groups` syscall groups in BPF maps, then emit one bounded summary. -Known x86_64 numbers include names and exact entry/exit selector hints; unknown -numbers remain numeric. `schemas/syscall-aggregate-result.schema.json` exposes -entries, matched and unmatched exits, inflight-at-end, drops, occupancy, errors, -and total/min/max/mean duration. It contains no pointer values or per-call event -stream. - -`--aggregate` is live-only, duration-bounded, and accepts one matching kernel, -memcpy, or memset activity start/end pair. It uses `--max-groups` (default -4,096), does not accept `--samples` or `--events-out`, and emits -`schemas/aggregate-inventory-result.schema.json`. The result is a coarse -inventory, not exact event evidence: it reports count, total/min/max/mean -duration, optional transferred bytes, table occupancy, and drop completeness. -Memcpy groups also split by `src_memory` and `dst_memory` (`pageable`, -`pinned`, `device`, `managed`, ...); pageable host memory forces staged, -synchronous copies. Aggregate results use schema `3.0`. -Aggregate kernel regex must be reducible to an exact, prefix, suffix, or -contains filter because this mode intentionally has no Rust-side event pass. -Each kernel group reports `name_complete`. CUPTI names that fill the fixed -127-byte observed prefix are marked `false`; their selector hints use that -prefix instead of claiming an exact full name, so the next capture can still -filter in the Agent hot path. - -The three inventory modes have distinct result contracts and contain no exact -event timeline. They cannot be passed to `measure --input` or exported with -`--events-out`. Their groups and hotspots are evidence for choosing selectors; -read-only validation still precedes the resulting exact measurement. - -Live host endpoints attach PID-scoped eBPF probes. Linux syscall endpoints use -raw tracepoints so they do not depend on tracingfs event IDs; ordinary named -tracepoints use their kernel category and name. CPython GC endpoints attach to -the exact mapped ELF selected by validation. Every endpoint link is attached -before collection is armed. A samples-bound Linux capture -allows bounded startup slack for a target already inside an event boundary. A -duration capture that fills `--max-events` returns `EVENT_RATE_TOO_HIGH` rather -than reporting partial success. CUDA endpoints automatically activate the CUPTI -agent. If it is absent, `--agent` or -`XPROBE_CUPTI_AGENT_PATH` selects the shared object; otherwise xprobe searches -`../lib/xprobe/cuda12` or `../lib/xprobe/cuda13` according to the target and -then the matching development build path. An unobservable target major is -accepted only when exactly one supported CUPTI major is installed. Injection -requires Linux x86_64, a shared mount namespace, and ptrace permission. It emits -a stderr warning and `CUPTI_AGENT_INJECTED`. Each live call arms a fresh -`--max-events`-bounded capture with endpoint filters. Final stop disables CUPTI; -automatic injection also removes its private socket while leaving the `.so` -mapped. - -NVTX thread ranges preserve nesting through the thread ID and zero-based push -level. Process ranges preserve the NVTX range ID and may end on a different -thread; evidence reports both boundary threads plus `start_tid`. Names are -copied into the fixed record bound with `name_complete`. ASCII -`nvtxRangePushA`/`nvtxRangeStartA` and ASCII messages in their `Ex` forms are -supported; wide and registered-string messages are not collected. This is -timeline boundary collection only. It does not enable CUPTI Range Profiling, -metric replay, or kernel performance-counter passes. - -Completed inputs may be CUPTI ABI binary, bounded host-capture JSON, or Event -JSONL. Repeated inputs are merged after target-PID checks. Unknown records, -mixed targets, malformed captures, and excessive event counts fail explicitly. - -Results conform to `schemas/measurement-result.schema.json` (schema `3.0`) and -contain: - -- status and latency statistics; -- a `quality` verdict (`good` or `caution`) with coded issues; -- matched, unmatched, ambiguous, and dropped counts; -- method, confidence, and score; -- clock alignment and optional estimated error; -- collection completeness, host/CUDA totals, and CUPTI capacity, observed, - retained, dropped, and utilization values when an ABI envelope provides them; -- `evidence`: one exemplar start/end pair per latency rank (min, p50, p90, - p99, max), the artifact path, format, and event count, and with - `--evidence full` every matched pair; -- structured warnings. - -Live captures always write the complete bounded capture with mode `0600`: -`--events-out PATH` chooses the file; otherwise it goes to a new mode `0700` -directory under the temporary directory. `measure --input` with the same -selectors re-correlates it deterministically. Completed `--input` measurements -write an artifact only with `--events-out`. The default format is JSONL; `--format chrome` writes Chrome Trace Event -Format. Once collection has produced a capture, correlation, clock, drop, or -capacity failures still write it and identify its path, format, and event count -in the JSON error. Artifact failure returns `TRACE_EXPORT_FAILED` and preserves -the original measurement error code in `details`. - -No matched pairs return `NO_MATCHED_SAMPLES`. Cross-clock subtraction without -declared alignment returns `CLOCK_ALIGNMENT_FAILED`. Drops and unknown clock -error are never silently converted to high-quality results. Error `details` and -`hints` carry selectors, policies, counters, clock domains, and explicit next -actions where applicable; callers must not infer these fields from messages. +Waits for rare slow spans using an in-Agent ring of `--max-events` records and writes `window-N.events.jsonl` plus manifest into `--events-out` (directory) for `--pre-ms` before to `--post-ms` after each firing span, up to `--windows` non-overlapping windows (default 1): + +- `--trigger-idle-ms`: device runs no kernel, copy, or memset of the target on any stream. +- `--trigger-gap-ms`: gap between an activity end and the next kernel, copy, or memset on the same stream. +- `--trigger-duration-ms`: single kernel, copy, or memset duration. +- `--trigger-latency-ms`: `--from`/`--to` CUDA edge latency under `--match`. + +Idle, gap, duration, and `stream-order` latency triggers record all GPU activity. A window that overlaps overwritten or dropped records is not written and counts in `lost_windows`. If a record read later shows activity inside an idle or gap window, the window is dropped and counts in `revoked_windows`, and capture keeps waiting for another span until the timeout. Latency and duration windows are written as they fired. `observed` counts every span seen, including those whose records the CLI no longer holds. If no window is written, timeout returns `TRIGGER_NOT_OBSERVED` with `longest_ns` in `details`; if every window lost records, it returns `EVENTS_DROPPED`. Emits `schemas/trigger-result.schema.json` (schema `3.0`). ## Measurement graphs -A graph measures several edges from one bounded capture of one process: +Measures 1โ€“8 edges over 1โ€“8 named endpoints from one capture (`schemas/measurement-graph-spec.schema.json`, schema `3.0`): ```json { @@ -412,31 +228,7 @@ A graph measures several edges from one bounded capture of one process: } ``` -`measure --spec graph.json` accepts this `schemas/measurement-graph-spec.schema.json` -document. `target.process_start_time` may be omitted: xprobe then reads -the current start time of `pid` and verifies that identity around attach, as -`measure --pid` does. A spec that does not match the schema fails with an error -naming the schema and the offending field. A graph has 1โ€“8 named endpoints and 1โ€“8 edges; every edge sets -`samples` or the graph sets `duration_ms`. Collectors attach once per unique -endpoint: uprobes have no further limit, CUDA endpoints share up to eight Agent -filters, and syscall, tracepoint, and USDT endpoints share two Linux collector -slots. `max_events` bounds the whole capture. Collection ends when every edge -reaches its samples or the duration elapses. - -The capture is validated once, then each edge is correlated independently with -the single-edge rules. A graph never joins edges into per-request paths and -never implies causality between edges. Results use -`schemas/measurement-graph-result.schema.json` (schema `3.0`): per-edge -statistics, quality verdict, correlation, clock quality, and evidence, one -shared collection summary, and the shared event artifact. Each edge's -`evidence.artifact` also points at that artifact, so single-edge and graph -consumers read the path from the same place. Any invalid edge or -edge correlation failure fails the whole command with the edge name in the -message and `details.edge`; the captured events are still written to the -artifact so the caller can re-correlate edges with `measure --input`. - -## Compatibility - -Earlier low-level command spellings remain hidden during the pre-1.0 transition so -existing integration fixtures can decode captures. They are not public API and -must not be used by Skills or new automation. +- `target.process_start_time` is optional (`measure` reads and verifies it around attach). +- Either every edge sets `samples` or the graph sets `duration_ms`; `max_events` caps the capture. +- Collectors attach once per unique endpoint: uprobes are unlimited; CUDA endpoints share 8 Agent filters; syscall, tracepoint, and USDT endpoints share 2 Linux slots. +- Each edge correlates independently (`schemas/measurement-graph-result.schema.json`, schema `3.0`). Any failing edge fails the command (with `details.edge`) while still writing the shared Event JSONL artifact for offline `measure --input`. diff --git a/docs/cupti-agent.md b/docs/cupti-agent.md index 27e6403..29d9797 100644 --- a/docs/cupti-agent.md +++ b/docs/cupti-agent.md @@ -1,118 +1,80 @@ # CUPTI Agent and online injection -`libxprobe-cupti.so` collects CUDA Runtime/Driver callback boundaries, -kernel/memcpy/memset activity, and selected NVTX timeline range boundaries -inside the target process. Normal users invoke it through `measure --pid`; it -is a bounded collector, not a daemon or a persistent profiling session. +`libxprobe-cupti.so` runs inside a CUDA target process to collect Runtime/Driver API callbacks, kernel/memcpy/memset activity, and ASCII NVTX range boundaries. Users normally drive it through `xprobe measure --pid`; it is not a daemon or persistent profiling session. -Release packages contain separate Agents linked to `libcupti.so.12` and -`libcupti.so.13`. xprobe selects the major from the target's mapped CUDA -libraries, or from one unambiguous installed CUPTI major when the target does -not expose one. A conflict, unsupported major, or missing Agent fails before -ptrace attachment. +Release packages ship separate builds linked to `libcupti.so.12` and `libcupti.so.13`. `measure` picks the major from the target's mapped CUDA libraries (or from the single installed CUPTI major when the target doesn't expose one) and fails before ptrace attach on conflict, unsupported major, or missing `.so`. ## Measurement lifecycle -Validation is read-only. When it reports `injection_required`, `measure` warns -before remotely calling target-side `dlopen`, `dlsym`, and -`xprobe_cupti_agent_start` through ptrace. Loading the shared object establishes -a mode-0600 Unix control socket but does not start CUPTI collection. - -Each measurement sends `ARM` with its event capacity and at most two endpoint -filters. The Agent allocates fresh capture storage, installs the filters, and -then enables callbacks and activity collection. API names and domains, memcpy -directions, and simple kernel-name exact/prefix/suffix/contains patterns are -filtered before they consume capture capacity. Complex kernel regular -expressions use a wider Agent filter and retain exact Rust-side matching. - -NVTX differs from ordinary online CUDA injection. Set -`NVTX_INJECTION64_PATH` to the matching Agent before the target's first NVTX -call; an initialized NVTX dispatch cannot be retrofitted by attach. Startup -installs routing and a dormant CUPTI subscriber. ARM enables only range -StartA/StartEx/End and PushA/PushEx/Pop callbacks, with bounded name matching -before timestamping or table insertion. STOP disables those callbacks but -retains the subscriber because CUDA 13 still references it. The Agent copies -only ASCII range names, IDs, kind, and thread identity. It does not copy NVTX -payload, color, category, registered strings, wide strings, or environments. - -An aggregate ARM uses a fixed-capacity hash table instead of event records. -Kernel activity is grouped by name and device, memcpy by direction and device, -and memset by device. The activity callback updates count, total/min/max -duration, and transfer bytes without materializing start/end events. Aggregate -collection uses one final CLI read instead of incremental snapshots, and table -saturation fails instead of returning a sampled inventory. - -`SNAPSHOT` flushes pending activity and returns records after the caller's -checked record offset. The CLI accumulates only contiguous deltas rather than -retransferring and decoding the growing capture. `STOP` returns the final delta -and disables CUPTI while retaining the socket, so a preloaded Agent can service -a later bounded measurement. An automatically injected measurement uses -`CLOSE`, which performs the same logical stop and then removes its private -socket. In both cases the shared object remains mapped; it must not be passed to -`dlclose` while CUDA may still reference callback code. - -Activity records that began before the ARM epoch are excluded as a whole. This -prevents CUPTI's boundary records, which can have an unavailable start -timestamp, from becoming malformed or unmatched in-window evidence. - -The target and xprobe must share a mount namespace. ptrace credentials, Yama, -seccomp, and LSM policy still apply. Every remote call restores the stopped -thread's registers and touched stack state before detach, including failure -paths. +1. **Validate & inject**: `validate` is read-only. When it reports `injection_required`, `measure` warns on stderr and uses Linux x86_64 ptrace to call target `dlopen`, `dlsym`, and `xprobe_cupti_agent_start`. Loading opens a mode-0600 Unix control socket without enabling CUPTI yet. +2. **ARM**: `measure` sends `ARM` with record capacity and up to eight endpoint filters. The Agent allocates fresh storage, installs filters, and enables only the required callbacks and activity families. + - API names/domains, memcpy directions, and exact/prefix/suffix/contains kernel or NVTX patterns under 128 bytes filter in the Agent hot path before consuming capacity. + - Complex kernel regexes use a wider Agent filter and apply full regex matching in Rust. +3. **SNAPSHOT**: flushes pending CUPTI activity and returns only contiguous records after the caller's checked offset. +4. **STOP / CLOSE**: flushes the final delta and disables CUPTI callbacks/activity. + - `STOP` keeps the control socket open so a preloaded Agent can handle later captures. + - `CLOSE` (used after automatic injection) also removes the private socket. + - Neither path calls `dlclose`: unloading callback code in a live CUDA process is unsafe. + +**Prerequisites**: target and xprobe must share a mount namespace, and ptrace permissions (Yama, `CAP_SYS_PTRACE`, seccomp, LSM) apply. Every remote ptrace call saves and restores registers and touched stack memory on both success and failure. + +### NVTX ranges + +Online attach cannot retrofit an already initialized NVTX dispatch table. Set `NVTX_INJECTION64_PATH` to the matching Agent `.so` before the target's first NVTX call. + +- Startup installs NVTX routing and a dormant CUPTI subscriber kept alive for the process lifetime (CUDA 13 continues referencing it across captures). +- `ARM` enables only the six ASCII/Ex range callbacks (`StartA`/`StartEx`/`End`, `PushA`/`PushEx`/`Pop`) with name matching before timestamping or table insertion; `STOP` disables those callbacks without unsubscribing. +- Only ASCII range names, IDs, kind, and thread IDs are copied (no payload, color, category, registered strings, wide strings, or env vars). +- Because CUPTI tracks push levels only while callbacks are enabled, a pop of a range pushed before `ARM` reports no level and is ignored. + +### Aggregate mode + +An aggregate `ARM` allocates a fixed `--max-groups` hash table instead of per-event records: +- Kernels group by `(name, device_id)`; memcpy by `(direction, src_memory, dst_memory, device_id)`; memset by `device_id`. +- Activity callbacks update count, min/max/total duration, and bytes in place. +- The CLI reads the table once at `STOP`; table saturation fails explicitly instead of silently sampling. + +### Capture window edges + +- Activity that ended before `ARM` is excluded; activity still running at `ARM` keeps its earlier start so overlapping work isn't hidden. +- Activity still running at `STOP` keeps a start record so the stream and GPU stay busy through the capture end rather than looking idle. CUPTI may report no start for it, or one not yet converted to host time, so the Agent writes the record without a time and flags it (`XPROBE_CUPTI_RECORD_START_UNKNOWN`); the clock check skips it. The CLI sets its time to the stream's last activity end, or to the capture start if nothing else ran, and adds the `start_unknown` attribute. It is never used as a duration, gap, or latency endpoint. +- Records with unavailable timestamps after the first timed activity count as dropped. ## Control and capture ABI -Control version 4 uses one fixed 328-byte native-endian request defined by -`cupti/include/xprobe/cupti_agent.h`. It contains magic, version, command, -capacity, record offset, capture mode, and two fixed endpoint filters. Commands -are `ARM`, `SNAPSHOT`, `STOP`, and `CLOSE`. Exact ARM requires offset zero; -later exact commands return records at or after the requested offset followed -by EOF. Aggregate mode requires offset zero for every command. - -Capture ABI v4 starts with an 88-byte header and zero or more 200-byte records. -The header reports capture state and stop reason, configured capacity, observed -and retained counts, Agent and CUPTI drops, unknown activity, record sizes, and -feature flags. It also reports the payload record offset so the caller can -reject gaps, replays, and counter rollback. Exact capacity comes from -`--max-events` and aggregate table capacity from `--max-groups`; there is no -special 2^16 limit. Reaching either configured limit freezes capture and causes -measurement to fail explicitly instead of returning partial success. - -Exact records preserve process/thread, device/context/stream, correlation IDs, -callback domain/ID, dimensions or transfer metadata, and one bounded name. -NVTX records reuse the fixed layout for a 64-bit range ID, thread/process kind, -start thread, and explicit name completeness flag. Their exact correlation is -range identity, including a synthesized TID plus nesting level for thread -ranges; it is not a claim that arbitrary adjacent events are causally related. -Aggregate records contain a bounded group key and exact integer counters, not -event evidence or a latency distribution; they therefore do not report -percentiles or correlation confidence. -Activity timestamps are normalized to `CLOCK_MONOTONIC` through the CUPTI -timestamp callback or CUDA 12 clock calibration. If alignment cannot be -established, GPU durations remain usable in the CUPTI domain but host/GPU -subtraction fails with `CLOCK_ALIGNMENT_FAILED`. CUPTI provides no numeric -interpolation error bound, so normalized results emit -`CLOCK_ERROR_UNAVAILABLE`. - -## Hot-path constraints - -ARM enables only activity families and Runtime/Driver callback IDs required by -the validated endpoints. The API callback checks its fixed filter before -reading time or constructing a record. Activity decoding checks event family, -name, and transfer direction before copying fixed metadata, and stops -converting records after the capture limit. These paths do not allocate, -perform file or socket I/O, symbolize names, or take blocking locks. NVTX range -callbacks use only fixed records and a preallocated table; CUPTI Range -Profiling metrics and replay are outside this timeline collector. Flushing, -control, and incremental response I/O run on the control thread. +Defined in `cupti/include/xprobe/cupti_agent.h`: + +### Control protocol v6 (`xprobe_cupti_control_request`, 1192 bytes) +- Native-endian request carrying magic (`XPCTRL\0`), version (`6`), command (`ARM`/`SNAPSHOT`/`STOP`/`CLOSE`), `record_capacity`, `record_offset`, `capture_mode` (`EXACT=0`, `AGGREGATE=1`, `RING=2`), `filter_count`, and up to 8 fixed `xprobe_cupti_filter` entries. +- Exact `ARM` requires offset 0; subsequent snapshots return records at/after `record_offset` followed by EOF. Aggregate mode uses offset 0 on every command. + +### Ring mode (`--trigger-*`) +- Keeps the newest `record_capacity` exact records in a ring without stopping at the limit. +- Each slot carries its logical index; snapshots copy under a sequence lock so overwritten slots are discarded along with older records. +- The response header's `record_offset` is the first returned record; a value above the requested offset counts overwritten records. Sets `XPROBE_CUPTI_FEATURE_RING_RECORDS`. + +### Capture ABI v4 (`xprobe_cupti_output_header`, 88 bytes) +- Followed by an optional device table (`XPROBE_CUPTI_FEATURE_DEVICE_TABLE`: count, entry size, and 48-byte `xprobe_cupti_device_entry` records mapping each CUDA ordinal to its GPU/MIG UUID, read from the driver outside CUDA init and Agent locks without recording the Agent's own driver calls). +- Followed by 200-byte exact records (`xprobe_cupti_record`) or aggregate records (`xprobe_cupti_aggregate_record`). +- Header tracks capture state, stop reason, capacity, observed/retained counts, Agent and CUPTI drops, unknown records, record sizes, feature flags, and payload offset (so the CLI rejects gaps, replays, or counter rollback). +- Capacity comes directly from `--max-events` / `--max-groups` (no `2^16` cap). Reaching the limit freezes capture and fails explicitly. +- If `STOP` fails to disable every callback/activity kind, it reports stop reason `5` (`XPROBE_CUPTI_STOP_CLEANUP_ERROR`) and keeps the socket open so the CLI returns `CLEANUP_FAILED` and retries `CLOSE`. + +### Record semantics & clock normalization +- **Peer-to-peer copies**: collected via CUPTI `MEMCPY2` records (`XPROBE_CUPTI_FEATURE_PEER_MEMCPY`); they carry `stream_id` and no runtime correlation ID. +- **NVTX records**: carry 64-bit range ID, thread/process kind, `start_tid`, and `name_complete`. Thread ranges key on `(tid, push_level)`; process ranges key on `range_id` and may end on another thread. +- **Clock alignment**: activity timestamps normalize to `CLOCK_MONOTONIC` via the CUPTI timestamp callback or CUDA 12 clock calibration. The Agent sets `XPROBE_CUPTI_FEATURE_HOST_MONOTONIC_TIMESTAMPS` only after verifying an activity ended between `ARM` and the check, or a kernel started no earlier than its launch call. If alignment cannot be proven, GPU-only durations remain usable in raw `cupti` time and cross CPU/GPU subtraction returns `CLOCK_ALIGNMENT_FAILED`. Because CUPTI provides no numeric error bound, normalized results emit `CLOCK_ERROR_UNAVAILABLE`. + +## Hot-path rules + +- `ARM` enables only the activity kinds and Runtime/Driver callback IDs needed by the validated endpoints. +- Callbacks and activity decoders check filters before reading time or writing records, and stop immediately once capacity is reached. +- Hot paths never allocate, perform file/socket I/O, symbolize names, or take blocking locks. Flushing and socket I/O run on the control thread. +- CUPTI Range Profiling metrics and replay passes are out of scope for this timeline collector. ## Verification -`just test-cupti-live` checks ABI and activity collection. `just -test-injection-live` performs first-load and reactivation measurements against -one mapped Agent. `just test-multisource-live` covers host/GPU orchestration and -repeated ARM/STOP windows. CUDA 12 variants exercise the same paths against the -other linked major, and `just benchmark-gpu` checks callback overhead and -timestamp precision. `just benchmark-aggregate` drives a high-rate two-kernel -workload and compares bounded aggregation with raw broad capture for collection -completeness, process resources, and artifact size. +- `just test-cupti-live` / `just test-cupti-live-cuda12`: ABI and activity collection on CUDA 13 and 12. +- `just test-injection-live` / `just test-injection-live-cuda12`: first-load injection and reactivation. +- `just test-multisource-live` / `just test-multisource-live-cuda12`: host + GPU orchestration and repeated `ARM`/`STOP`. +- `just benchmark-gpu` & `just benchmark-aggregate`: callback overhead, timestamp precision, and aggregate vs raw resource use. diff --git a/docs/development.md b/docs/development.md index 5fb927f..0028914 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,11 +1,8 @@ -# Development environment +# Development and hardware tests -## Native toolchain +## Toolchain -Rust is managed with `rustup` and pinned by `rust-toolchain.toml`; local -builds, CI, and release packaging use the same compiler and Clippy. Update the -pin in a dedicated change. Native build tools are isolated in the checked-in -Mamba environment: +Rust is pinned in `rust-toolchain.toml` (update it only in a dedicated commit). Native build dependencies live in the checked-in Mamba environment: ```bash mamba env create --file environment.yml @@ -14,217 +11,51 @@ just build just test ``` -The environment contains Clang, CMake, Ninja, pkg-config, Just, Python, `perf`, -`py-spy`, and the autotools required to compile vendored libbpf, libelf, and -zlib. A system C compiler and Linux UAPI/multiarch headers are also required. -CUDA is not installed into the Mamba environment. CI compiles CUDA 12 and CUDA -13 CUPTI Agents without a GPU in pinned NVIDIA devel images, checks their -SONAMEs, and rejects ABI-only output or build-time RPATHs. Live CUDA behavior -is tested locally with Docker and NVIDIA Container Toolkit. CPU comparison -tools and a USDT-enabled CPython are installed inside the pinned benchmark -container; they are not host or release archive dependencies. +`xprobe-dev` provides Clang, CMake, Ninja, pkg-config, Just, Python, `perf`, `py-spy`, and the autotools needed for vendored `libbpf`/`libelf`/`zlib` (a system C compiler and Linux UAPI headers are also needed). CUDA is not installed in `xprobe-dev`; CI builds CUDA 12 and 13 Agents in pinned NVIDIA devel images, checks SONAMEs, and rejects build-time RPATHs. Local GPU tests run through Docker + NVIDIA Container Toolkit. -## Releases +For release packaging and verification, see [Releasing](releasing.md). -Release packaging, the local live gate, and public verification are described -in [Releasing](releasing.md). +## Test recipes -## eBPF tests +Run `just --list` for the complete list. Key suites: -Compile the BPF object without attaching it: +| Recipe | What it tests | Notes | +| --- | --- | --- | +| `just test` | Rust unit/integration tests, CTest, CLI/Skill checks, `analyze_trace.py` fixtures | Offline, no GPU | +| `just lint-commits` | Commit titles fit in 72 characters and follow emoji conventional commits; bodies wrap at 80 | Checks `origin/master..HEAD`; `gitlint install-hook` runs it on each commit | +| `just test-agent-contract` | Public CLI shape, schemas, Skill links/flags/fields, analyzer fixtures | Run after CLI/schema/docs/Skill edits | +| `just test-skill-install` | Real `npx skills` copy into isolated Codex, Claude Code, and Cursor homes | Needs Node.js | +| `just test-install` | Archive install/uninstall, glibc 2.34 check, wheel/SBOM checks | Offline | +| `just test-bpf` | Compiles BPF objects without attaching | Offline | +| `just test-bpf-live` | Live uprobe, syscall, tracepoint, CPython GC USDT, syscall aggregate | Docker (`BPF`/`PERFMON`/`SYS_ADMIN`/`SYS_RESOURCE`, no `--privileged`) | +| `just test-cpu-live` | Live CPU sampling (native + CPython 3.12+ `-X perf`) | Host with sibling perf permission | +| `just test-python-sample-live` | External CPython 3.9โ€“3.14 stack/GIL/native-wait sampler | Host/container with ptrace access | +| `just gpu-smoke` | Docker + NVIDIA runtime check (pinned CUDA 13.3 base image) | Needs GPU | +| `just test-cupti-live` / `-cuda12` / `-cuda12-min` | Live CUPTI ABI, kernel/memcpy/memset, and CUDA 12.0 min-compat | Pinned CUDA 13.3 / 12.9 / 12.0 images | +| `just test-nvtx-live` / `-cuda12` | Startup NVTX injection, nested/process ranges, truncation, logical stop reuse | Pinned CUDA 13 / 12 images | +| `just test-injection-live` / `-cuda12` | Live ptrace injection, stop, and reactivation twice | Adds `SYS_PTRACE`, no `--privileged` | +| `just test-multisource-live` / `-cuda12` | Combined host uprobe + CUPTI capture and repeated `ARM`/`STOP` | Needs GPU + BPF | +| `just test-trigger-live` | Ring capture for idle, stream gap, duration, and latency triggers | Needs GPU | +| `just test-pytorch-symbols` | Real CPython / native extension / `libtorch` C++ symbol resolution | Set `PYTORCH_PYTHON=/path/to/python` | +| `just test-pytorch-live` / `test-pytorch-cuda-live` / `test-triage-live` | Live PyTorch eager, compiled Triton, transfers, NVTX, and triage | Uses pinned PyTorch image, or set `PYTORCH_ENV` to mount local env | -```bash -just test-bpf -``` - -Run the real PID-scoped ELF and Linux event tests in the pinned container: - -```bash -just test-bpf-live -``` +Benchmark recipes (`benchmark-cpu`, `benchmark-cpu-host`, `benchmark-python-sampling`, `benchmark-gpu`, `benchmark-aggregate`, `benchmark-multiprocess`, `benchmark-pytorch`) are documented in [Benchmarks](benchmarks.md). -The live suite captures function entry/return, mmap/munmap lifecycle, generic -raw tracepoint, CPython-compatible GC USDT lifecycle, syscall aggregate, and -host-capacity failure paths from controlled targets. It -requires Docker daemon access and grants the container `BPF`, -`PERFMON`, `SYS_ADMIN`, and `SYS_RESOURCE`, with seccomp disabled for BPF/perf -syscalls. It does not use `--privileged`, does not require GPU access, mounts the -workspace read-only, and removes the container after the test. +## Host GPU checks -Run the ignored live CPU sampling tests on a host whose perf policy permits -sibling-process sampling: - -```bash -just test-cpu-live -``` - -They cover a busy native process and CPython 3.12+ `-X perf` symbolization. -The target interpreter must provide perf trampoline support for the Python -case; unsupported interpreters remain a valid native-only product path but are -not a substitute for this live gate. - -Run the comparative CPU/Python perturbation benchmark after changing CPU -sampling, symbolization, syscall aggregation, Python GC probes, or the Skill's -broad-to-narrow route: - -```bash -just benchmark-cpu -``` - -The default recipe installs `perf`, `py-spy`, and a USDT-enabled CPython inside -the pinned capability-limited container. Use `just benchmark-cpu-host` when the -same tools and attach permissions are already available on the host. See -`docs/benchmarks.md` for reported metrics and interpretation. - -Resolve real CPython, native extension, and libtorch C++ symbols with a local -Python environment containing PyTorch: - -```bash -PYTORCH_PYTHON=/path/to/env/bin/python just test-pytorch-symbols -``` - -Run the corresponding live `torch.mm` entry/return measurement in the pinned -NVIDIA PyTorch container: - -```bash -just test-pytorch-live -``` - -By default the live recipes use a pinned NVIDIA PyTorch image with Ubuntu 24.04 -and CUDA 12.9, so live checks do not depend on the host Mamba environment. -During local development, set `PYTORCH_ENV` to the `xprobe-pytorch` -environment to mount it into the already-pinned CUDA fixtures instead of -pulling the PyTorch image. The compiled-Triton case checks Dynamo, Triton, and -NumPy support before starting and fails with an explicit message otherwise. Run eager matrix multiplication, convolution, -compiled Triton, bidirectional transfer, selected-kernel, and -stream-synchronization profiling on the local GPU. The test also wraps an eager -operation in an NVTX range and verifies exact range-ID matching: - -```bash -just test-pytorch-cuda-live -just benchmark-pytorch -``` - -## GPU checks - -Run host diagnostics outside restricted sandboxes when GPU device access is -required: +When inspecting a local NVIDIA host outside a restricted sandbox: ```bash nvidia-smi xprobe doctor ``` -Record the actual GPU model, driver version, compute capability, and available -memory in test output. Do not infer them from the machine description. - -## CUDA container policy - -GPU runtime smoke tests use a pinned CUDA 13.3 base image: - -```bash -just gpu-smoke -``` - -The image reference includes the NGC digest in `justfile`. This check verifies -container runtime and driver access only; it does not provide CUDA headers or -CUPTI development files. - -Live CUPTI tests use pinned NVIDIA CUDA 12.9 and CUDA 13.3 devel images -containing CUDA headers, `nvcc`, and CUPTI: - -```bash -just test-cupti-live-cuda12 -just test-cupti-live-cuda12-min -just test-cupti-live -``` - -The minimum-version check builds the release-style Agent with CUDA 12.9 and -runs it against CUDA 12.0. GPU-only durations remain available when the runtime -cannot prove host-clock alignment; cross CPU/GPU measurement then fails with -`CLOCK_ALIGNMENT_FAILED` instead of reporting a shifted latency. - -Run the bounded NVTX fixture against both supported CUPTI majors: - -```bash -just test-nvtx-live-cuda12 -just test-nvtx-live -``` - -It covers nested ASCII and extended ranges, cross-thread process ranges, -bounded-name truncation, capacity failure and reuse after logical stop. NVTX -initialization occurs before the fixture's first NVTX call; the test also -verifies that the subscriber remains mapped while callback domains are dormant -between captures. - -Run online ptrace injection, stop, and reactivation twice against a target that -does not preload the agent: - -```bash -just test-injection-live-cuda12 -just test-injection-live -``` - -This container adds `SYS_PTRACE` and disables seccomp for ptrace only. It mounts -the workspace read-only and does not use `--privileged`. - -Run the combined host uprobe and CUPTI measurement test with both GPU and BPF -access: - -```bash -just test-multisource-live-cuda12 -just test-multisource-live -``` - -Run the deterministic Agent-facing CLI contract test after changing commands, -schemas, Skills, or platform entry files: - -```bash -just test-agent-contract -``` - -Run the CUDA Event precision and callback overhead benchmark after changing the -CUPTI timing or callback hot path: - -```bash -just benchmark-gpu -``` - -Run the high-rate bounded-inventory benchmark after changing aggregate storage, -capacity, or activity accounting: - -```bash -just benchmark-aggregate -``` - -Run the concurrent worker benchmark after changing multi-process Skill guidance -or per-worker orchestration: - -```bash -just benchmark-multiprocess -``` - -See `docs/agent-integration.md` and `docs/benchmarks.md` for the tested contract -and benchmark interpretation. - -The startup-injection test mounts the workspace read-only, compiles the agent -and a CUDA fixture inside the container, and verifies three API -entries, API exits, kernel starts, and kernel ends, three memcpy intervals, and -one memset interval with matching correlation IDs. The resulting capture is -decoded by the host CLI and checked as ordered Event JSONL, then measured for -exact kernel, memcpy, memset, and API-to-kernel durations. The fixture queries -the GPU compute capability and compiles matching SASS so the driver does not -need to JIT toolkit-version PTX. - -Container policy: +Record the actual GPU model, driver version, compute capability, and memory from live output rather than assuming from machine specs. -- pin a concrete image tag and digest in the repository; -- verify host-driver compatibility before compiling examples; -- validate GPU access with `docker run --rm --gpus all nvidia-smi`; -- mount the repository read-only and build in container-local temporary space; -- do not use a floating `latest` tag; -- do not use `--privileged` for GPU-only tests. +## Container rules for live tests -eBPF attachment tests are host-sensitive and are separate from CUDA compilation -tests. The target and collector run in the same container PID namespace; host -PID visibility is not required for the current fixture. +- Pin concrete image tags and digests in `justfile`; never use floating `latest`. +- Mount the workspace read-only and compile fixtures in container-local temp directories. +- Grant only the minimum capabilities a test needs (`SYS_PTRACE` for injection; `BPF`/`PERFMON`/`SYS_ADMIN`/`SYS_RESOURCE` for eBPF); never use `--privileged`. +- Keep target and collector in the same container PID and mount namespaces. +- CUDA fixtures query the actual GPU compute capability and compile matching SASS to avoid PTX JIT skew. diff --git a/docs/installation.md b/docs/installation.md index 2106415..1c8bdd1 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -1,55 +1,30 @@ # Installation -The released xprobe package supports Linux x86_64 with glibc 2.34 or newer. It -contains the CLI and separate CUDA 12 and CUDA 13 CUPTI Agents. A CUDA toolkit -is not required to install xprobe; NVIDIA driver and CUPTI availability matter -only when measuring GPU events. +xprobe release packages target Linux x86_64 with glibc 2.34 or newer and include both the CLI and separate CUDA 12 / CUDA 13 CUPTI Agents. No CUDA toolkit is needed to install xprobe; the NVIDIA driver and CUPTI only matter when profiling GPU events. -## Agent-managed installation +## Python package (recommended) -For agent use, install the version-matched Skill and let the agent bootstrap or -repair the CLI under a writable prefix. This is the only installation command a -user needs to run: - -```bash -npx skills@1 add \ - https://github.com/itdevwu/xprobe/tree/v0.6.3/skills/xprobe-measure-latency \ - --global -``` - -The Skill verifies `xprobe --version`, installs the matching release when -needed, and runs `doctor` when capabilities are unknown or an environment check -fails. It has the live context needed to adjust PATH, prefix, namespace, -permission, NVIDIA, CUDA, and CUPTI issues. Node.js is required only for Skill -installation. - -## Python package - -The same CLI and both CUPTI Agents are published on PyPI as a -`manylinux_2_34_x86_64` wheel with no Python dependencies: +Published on PyPI as a `manylinux_2_34_x86_64` wheel with zero Python dependencies: ```bash pip install xprobe xprobe --version ``` -pip installs `xprobe` into the environment's `bin/` and the Agents into its -`lib/xprobe/cuda12` and `lib/xprobe/cuda13`, the layout the CLI searches; this -holds for virtual environments, conda, and `pip install --user`. The Skill and -schemas are installed under `share/xprobe`. The wheel is built from the same -verified files as the release archive. +For pre-releases (`X.Y.Z.devN`), pass `--pre` (`pip install --pre xprobe`). + +`pip` installs `xprobe` into `/bin/` and the CUPTI Agents into `/lib/xprobe/cuda12` and `cuda13` (the layout the CLI searches automatically), plus `schemas/` and `skills/` under `/share/xprobe`. This works in virtualenvs, conda/mamba, and `pip install --user`. -## Direct CLI installation +## Standalone release archive -The versioned bootstrap installs to `~/.local` without root access: +Install to `~/.local` without Python or root: ```bash curl --proto '=https' --tlsv1.2 -fsSL \ - https://raw.githubusercontent.com/itdevwu/xprobe/v0.6.3/install.sh | sh + https://raw.githubusercontent.com/itdevwu/xprobe/v0.7.0/install.sh | sh ``` -The bootstrap downloads the release archive and its SHA256 file, verifies the -archive, and then installs this layout: +The script downloads the release tarball and `.sha256`, verifies the digest, and installs: ```text ~/.local/bin/xprobe @@ -59,24 +34,18 @@ archive, and then installs this layout: ~/.local/share/xprobe/ ``` -Add `~/.local/bin` to `PATH` when it is not already present. To use another -prefix, download the script and pass `--prefix`: +Add `~/.local/bin` to `PATH` if needed. To install elsewhere, download and pass `--prefix` (use `sudo` for system directories like `/opt/xprobe` or `/usr/local`; the script never elevates privileges itself): ```bash curl --proto '=https' --tlsv1.2 -fsSLO \ - https://raw.githubusercontent.com/itdevwu/xprobe/v0.6.3/install.sh + https://raw.githubusercontent.com/itdevwu/xprobe/v0.7.0/install.sh sh install.sh --prefix /opt/xprobe ``` -Writing a system prefix such as `/usr/local` may require running the downloaded -script with `sudo`. The installer never elevates privileges itself. - -## Verify before installation - -For a fully explicit archive workflow: +### Verify checksum, SBOM, and attestation ```bash -version=0.6.3 +version=0.7.0 base=https://github.com/itdevwu/xprobe/releases/download/v$version archive=xprobe-$version-linux-x86_64.tar.gz @@ -97,63 +66,49 @@ tar -xzf "$archive" "./xprobe-$version-linux-x86_64/install.sh" ``` -The checksum detects archive corruption. The two `gh` commands additionally -require signed provenance and SPDX claims from this repository's release -workflow on a GitHub-hosted runner. The downloaded SPDX JSON is the inspectable -release SBOM. The unpacked package can also be run in place as long as its -`bin` and `lib` layout remains together. +The unpacked tarball can also be run in place as long as `bin/` and `lib/` stay together. -## Upgrade and removal +### Upgrade and uninstall -Run the newer version's installer with the same prefix to replace the installed -files. Remove an installation with the matching script: +Re-run the new release's installer with the same `--prefix` to upgrade, or uninstall cleanly: ```bash sh install.sh --prefix "$HOME/.local" --uninstall ``` -The uninstall operation removes only xprobe-owned files below `bin/xprobe`, -`lib/xprobe`, `include/xprobe`, and `share/xprobe`. +Uninstall removes only xprobe-owned files under `bin/xprobe`, `lib/xprobe`, `include/xprobe`, and `share/xprobe`. + +## AI Agent Skill + +Install the `xprobe-perf-profiling` Skill for Claude Code, Codex, Cursor, and compatible agents from [skills.sh](https://skills.sh) (Node.js is needed only for the `skills` CLI): -## Manual Skill repair +```bash +npx skills add itdevwu/xprobe +``` -The xprobe CLI works independently of an AI agent. When a Skill installation is -missing or damaged, manually install the complete version-matched directory: +This installs the Skill from the default branch. To pin it to this release: ```bash npx skills@1 add \ - https://github.com/itdevwu/xprobe/tree/v0.6.3/skills/xprobe-measure-latency \ + https://github.com/itdevwu/xprobe/tree/v0.7.0/skills/xprobe-perf-profiling \ --global ``` -The command interactively selects among detected agents. A non-interactive -installation names the target explicitly: +For non-interactive installs: ```bash npx --yes skills@1 add \ - https://github.com/itdevwu/xprobe/tree/v0.6.3/skills/xprobe-measure-latency \ + https://github.com/itdevwu/xprobe/tree/v0.7.0/skills/xprobe-perf-profiling \ --agent codex --global --copy --yes ``` -Use `claude-code` or `cursor` for those clients. Omit `--global` to install into -the current project. Review the Skill before use because Agent Skills can direct -an agent to execute commands with its granted permissions. - -Without Node.js, copy the complete `skills/xprobe-measure-latency` directory -from the release archive into the Skill directory documented by the target -agent. Do not copy only `SKILL.md`; its references, examples, and trace-analysis -script are part of the contract. +Use `claude-code` or `cursor` for those clients, or omit `--global` for project-scoped installation. Without Node.js, copy the entire `skills/xprobe-perf-profiling` directory from the release archive (`share/xprobe/skills/xprobe-perf-profiling`) into your agent's skills directory so `references/`, `examples/`, and `scripts/analyze_trace.py` stay intact. ## Runtime check -After installing the CLI, run: - ```bash xprobe --version xprobe doctor ``` -Host selectors require eBPF/perf permissions. Online CUDA Agent injection -requires ptrace permission and a shared mount namespace with the target. Read -the individual `doctor` checks rather than treating diagnostic completion as a -claim that every collector is available. +Host eBPF/perf collectors need BPF/perf permissions. Live CUDA Agent injection needs ptrace permission and a shared mount namespace with the target. Check the individual fields in `doctor` output (`ok: true` means diagnostics completed, not that every collector is enabled). diff --git a/docs/releasing.md b/docs/releasing.md index a49d57f..7294c00 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1,20 +1,21 @@ # Releasing -Work on a feature or fix branch, rebase-merge the pull request into `master`, -then tag the merged commit. The steps below gate every release. +Work on a feature or fix branch, rebase-merge into `master`, then tag the merged commit. -## 1. Prepare the version +## 1. Bump versions -Bump the workspace version in `Cargo.toml` and `CMakeLists.txt`, the installer -default in `install.sh`, the Skill's supported `major.minor.x` and install -links in `skills/xprobe-measure-latency/references/setup.md`, and the versioned -links in `README.md`, `docs/installation.md`, and `docs/agent-integration.md`. -`just test-agent-contract` checks that these agree. +Update the version in: +- `Cargo.toml` and `CMakeLists.txt` +- `install.sh` (default version) +- Versioned links in `README.md`, `docs/installation.md`, and `docs/agent-integration.md` -## 2. Run the local live gate +`just test-agent-contract` verifies these agree. -GitHub Actions runs only what hosted runners support. Before tagging, run the -complete live suite on the NVIDIA development machine: +Pre-releases use `X.Y.Z-dev.N` (CMake takes `X.Y.Z`, PyPI wheel uses PEP 440 `X.Y.Z.devN` so `pip install xprobe` skips them unless `--pre` or an exact version is requested). Tag pre-releases on the feature branch. + +## 2. Run the live hardware suite + +GitHub Actions runners have no GPU. Before tagging, run the full live suite on the NVIDIA development machine: ```bash mamba env create --file environment-pytorch.yml @@ -22,14 +23,11 @@ PYTORCH_ENV="$(mamba run -n xprobe-pytorch python -c 'import sys; print(sys.pref just test-release-live ``` -`environment-pytorch.yml` pins the PyTorch fixture: Python 3.11, because torch -2.3 Dynamo does not support 3.12, plus Triton and NumPy 1.x. The gate covers -BPF and perf attachment, CUDA 12 and 13, injection, NVTX, mixed host/GPU -collection, triage, PyTorch, concurrent workers, and the release benchmarks. +`environment-pytorch.yml` pins Python 3.11 + PyTorch + Triton + NumPy 1.x. `test-release-live` covers BPF/perf, CUDA 12 & 13 CUPTI, injection, NVTX, multi-source, triggers, external Python sampling, PyTorch, triage, and all release benchmarks. -## 3. Package +## 3. Package and test locally -A release archive requires one Agent built against each supported CUPTI major: +A release archive bundles one CUPTI Agent per supported CUDA major: ```bash CUDA_PATH=/opt/cuda-12 cmake -S . -B build/cuda12 -G Ninja \ @@ -44,26 +42,16 @@ scripts/package-release.sh tests/install/test_install.sh dist/xprobe-*-linux-x86_64.tar.gz ``` -Packaging checks both CUPTI SONAMEs, rejects build-time RPATHs, and rejects CLI -or Agent ELF dependencies above `GLIBC_2.34`. The archive test accepts a mocked -glibc 2.34 runtime, rejects 2.33, installs into a temporary prefix, runs the -binary, verifies both Agents, and uninstalls. The tag workflow independently -rebuilds both Agents, packages on Ubuntu 22.04, attests the archive and SBOM, -and publishes them. +`package-release.sh` checks both CUPTI SONAMEs, rejects build-time RPATHs, and enforces a `GLIBC_2.34` ceiling on the CLI and both Agents. `test_install.sh` checks glibc 2.34 acceptance / 2.33 rejection, install, Agents, and uninstall. -The same job builds the PyPI wheel from the verified staging directory with -`scripts/build-wheel.py` and installs it with `tests/install/test_wheel.sh`. -After the GitHub release passes public verification, the `pypi` job publishes -the wheel through PyPI trusted publishing (OIDC, environment `pypi`; no token is -stored), then downloads it back from PyPI and repeats the installation test. +On tag push, CI rebuilds both Agents on Ubuntu 22.04, packages and attests the archive + SPDX SBOM, builds the PyPI wheel (`scripts/build-wheel.py`, tested by `tests/install/test_wheel.sh`), publishes to GitHub Releases, and publishes the wheel via PyPI OIDC trusted publishing before re-verifying the downloaded wheel. ## 4. Verify the public release -A release is complete only after the public artifact passes: +A release is complete only after verifying the published archive: ```bash scripts/verify-public-release.sh X.Y.Z ``` -It downloads the published archive and checksum, verifies the SBOM, repeats the -installation test, and inspects every shipped ELF against the glibc ceiling. +This downloads the public archive and checksum, checks the SBOM, repeats the installation test, and inspects every shipped ELF against the `GLIBC_2.34` ceiling. diff --git a/environment.yml b/environment.yml index 792d483..e8ddd6b 100644 --- a/environment.yml +++ b/environment.yml @@ -13,6 +13,7 @@ dependencies: - flex>=2.6 - gawk>=5.3 - gettext>=0.25 + - gitlint-core>=0.19 - just>=1.40 - linux-perf>=7.1 - make>=4.4 diff --git a/install.sh b/install.sh index b307d9d..dbebcea 100755 --- a/install.sh +++ b/install.sh @@ -2,7 +2,7 @@ set -eu repository=${XPROBE_REPOSITORY:-itdevwu/xprobe} -version=${XPROBE_VERSION:-0.6.3} +version=${XPROBE_VERSION:-0.7.0} if [ -n "${XPROBE_PREFIX:-}" ]; then prefix=$XPROBE_PREFIX elif [ -n "${HOME:-}" ]; then @@ -19,7 +19,7 @@ Install a released xprobe binary and its CUDA Agents. Usage: install.sh [--version VERSION] [--prefix DIR] [--uninstall] Options: - --version VERSION Release to install (default: 0.6.3) + --version VERSION Release to install (default: 0.7.0) --prefix DIR Installation prefix (default: $HOME/.local) --uninstall Remove xprobe from the selected prefix -h, --help Show this help diff --git a/justfile b/justfile index 863684c..7049bf9 100644 --- a/justfile +++ b/justfile @@ -80,6 +80,12 @@ test-cupti-burst-live-cuda12: build test-multisource-live: build python3 tests/integration/test_multisource.py "{{cuda13_devel_image}}" target/debug/xprobe +test-python-sample-live: build + python3 tests/integration/test_python_sample.py + +test-trigger-live: build + python3 tests/integration/test_trigger.py "{{cuda13_devel_image}}" target/debug/xprobe + test-multisource-live-cuda12: build python3 tests/integration/test_multisource.py "{{cuda12_devel_image}}" target/debug/xprobe @@ -116,6 +122,8 @@ test-release-live: just test-nvtx-live just test-injection-live just test-multisource-live + just test-trigger-live + just test-python-sample-live just test-pytorch-live just test-pytorch-cuda-live just test-triage-live @@ -137,6 +145,9 @@ benchmark-multiprocess: benchmark-pytorch: build if [[ -n "${PYTORCH_ENV:-}" ]]; then python3 benchmarks/pytorch/run.py --image "{{cuda12_devel_image}}" --pytorch-env "${PYTORCH_ENV}"; else python3 benchmarks/pytorch/run.py --image "{{pytorch_image}}"; fi +benchmark-python-sampling: build + python3 benchmarks/python-sampling/run.py + benchmark-cpu: build python3 benchmarks/cpu-inventory/run-container.py "{{cuda12_devel_image}}" @@ -149,6 +160,10 @@ fmt: fmt-check: cargo fmt --all --check +# Commit messages on this branch that are not on master yet. +lint-commits range="origin/master..HEAD": + gitlint --commits {{range}} + lint: cargo clippy --workspace --all-targets -- -D warnings diff --git a/schemas/aggregate-inventory-result.schema.json b/schemas/aggregate-inventory-result.schema.json index a7023b1..dd17a7f 100644 --- a/schemas/aggregate-inventory-result.schema.json +++ b/schemas/aggregate-inventory-result.schema.json @@ -53,6 +53,13 @@ "completeness": { "$ref": "#/$defs/CaptureCompleteness" }, + "cuda_devices": { + "description": "The UUID behind each CUDA device ordinal in the groups.", + "type": "array", + "items": { + "$ref": "#/$defs/CudaDevice" + } + }, "dropped_activities": { "type": "integer", "format": "uint64", @@ -255,6 +262,33 @@ "complete" ] }, + "CudaDevice": { + "description": "One CUDA device as the target saw it. `device_id` is the process's CUDA\nordinal, which `CUDA_VISIBLE_DEVICES` renumbers; the UUID names the\nphysical GPU across processes and in `nvidia-smi`.", + "type": "object", + "properties": { + "device_id": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "gpu_uuid": { + "description": "The physical GPU's `GPU-โ€ฆ` UUID when `uuid` names a MIG instance.", + "type": [ + "string", + "null" + ] + }, + "uuid": { + "description": "`GPU-โ€ฆ`, or `MIG-โ€ฆ` for a MIG instance, as `nvidia-smi -L` prints.", + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "device_id", + "uuid" + ] + }, "MemcpyKind": { "type": "string", "enum": [ diff --git a/schemas/capture-manifest.schema.json b/schemas/capture-manifest.schema.json new file mode 100644 index 0000000..91c5ab7 --- /dev/null +++ b/schemas/capture-manifest.schema.json @@ -0,0 +1,248 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "CaptureManifest", + "description": "What one bounded capture covered, written to `.manifest.json`.\n\nEvent JSONL records only events. The manifest records how they were\ncollected, so offline correlation can tell \"not observed\" from \"not\ncaptured\" and keep losses that the live command reported.", + "type": "object", + "properties": { + "all_gpu_activity": { + "description": "Every kernel, copy, and memset on the target was recorded, not only\nthe selected endpoints.", + "type": "boolean" + }, + "artifact": { + "description": "The artifact this manifest describes; a mismatch makes it stale.", + "$ref": "#/$defs/ManifestArtifact" + }, + "capture_failed": { + "description": "A collector entered a failed state.", + "type": "boolean" + }, + "cuda_devices": { + "description": "The UUID behind each CUDA device ordinal in the events.", + "type": "array", + "items": { + "$ref": "#/$defs/CudaDevice" + } + }, + "dropped_records": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "peer_copies": { + "description": "Peer-to-peer copies were recorded with other copies.", + "type": "boolean" + }, + "record_limit_reached": { + "description": "The configured record limit that stopped the capture, if any.", + "type": [ + "integer", + "null" + ], + "format": "uint64", + "minimum": 0 + }, + "schema_version": { + "$ref": "#/$defs/ManifestVersion" + }, + "selectors": { + "description": "Endpoint selectors the collectors were armed for.", + "type": "array", + "items": { + "type": "string" + } + }, + "target": { + "$ref": "#/$defs/TargetIdentity" + }, + "unknown_records": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "wall_clock": { + "description": "Maps the events' host-clock timestamps to wall time.", + "anyOf": [ + { + "$ref": "#/$defs/WallClock" + }, + { + "type": "null" + } + ] + }, + "window": { + "description": "`CLOCK_MONOTONIC` nanoseconds from the first collector armed to the\nfinal collection.", + "$ref": "#/$defs/CaptureWindow" + } + }, + "additionalProperties": false, + "required": [ + "schema_version", + "artifact", + "target", + "window", + "selectors", + "all_gpu_activity", + "peer_copies", + "dropped_records", + "unknown_records", + "capture_failed" + ], + "$defs": { + "CaptureWindow": { + "description": "`CLOCK_MONOTONIC` interval the capture's coverage holds for: from the\ncollector's ARM acknowledgment until after its final read. Activity that\nwas already running at ARM may begin before `start_ns`.", + "type": "object", + "properties": { + "end_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "start_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "start_ns", + "end_ns" + ] + }, + "ClockAnchor": { + "description": "The wall clock read against `CLOCK_MONOTONIC`: `realtime_ns` is\n`CLOCK_REALTIME` (nanoseconds since the Unix epoch, UTC) when\n`CLOCK_MONOTONIC` was `monotonic_ns`, to within `uncertainty_ns`.", + "type": "object", + "properties": { + "monotonic_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "realtime_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "uncertainty_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "monotonic_ns", + "realtime_ns", + "uncertainty_ns" + ] + }, + "CudaDevice": { + "description": "One CUDA device as the target saw it. `device_id` is the process's CUDA\nordinal, which `CUDA_VISIBLE_DEVICES` renumbers; the UUID names the\nphysical GPU across processes and in `nvidia-smi`.", + "type": "object", + "properties": { + "device_id": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "gpu_uuid": { + "description": "The physical GPU's `GPU-โ€ฆ` UUID when `uuid` names a MIG instance.", + "type": [ + "string", + "null" + ] + }, + "uuid": { + "description": "`GPU-โ€ฆ`, or `MIG-โ€ฆ` for a MIG instance, as `nvidia-smi -L` prints.", + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "device_id", + "uuid" + ] + }, + "ExportFormat": { + "type": "string", + "enum": [ + "jsonl", + "chrome" + ] + }, + "ManifestArtifact": { + "type": "object", + "properties": { + "bytes": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "events": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "format": { + "$ref": "#/$defs/ExportFormat" + }, + "sha256": { + "description": "Lowercase hexadecimal SHA-256 of the artifact bytes.", + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "format", + "events", + "bytes", + "sha256" + ] + }, + "ManifestVersion": { + "description": "Version of the capture manifest contract.", + "type": "string", + "enum": [ + "1.0" + ] + }, + "TargetIdentity": { + "type": "object", + "properties": { + "pid": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "process_start_time": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "pid", + "process_start_time" + ] + }, + "WallClock": { + "description": "Wall-clock anchors at the start and end of a capture. A host-clock\ntimestamp `t` is `realtime_ns + (t - monotonic_ns)` from the nearer\nanchor; when the two anchors' offsets differ, the wall clock was stepped\nor slewed during the capture and wall times carry that error.", + "type": "object", + "properties": { + "end": { + "$ref": "#/$defs/ClockAnchor" + }, + "start": { + "$ref": "#/$defs/ClockAnchor" + } + }, + "additionalProperties": false, + "required": [ + "start", + "end" + ] + } + } +} diff --git a/schemas/cpu-sampling-validate.schema.json b/schemas/cpu-sampling-validate.schema.json index 1590213..3d09884 100644 --- a/schemas/cpu-sampling-validate.schema.json +++ b/schemas/cpu-sampling-validate.schema.json @@ -115,11 +115,13 @@ "CUPTI_AGENT_NOT_LOADED", "CUDA_CONTEXT_NOT_FOUND", "UNSUPPORTED_CUDA_VERSION", + "UNSUPPORTED_PYTHON_VERSION", "EVENT_RATE_TOO_HIGH", "SESSION_LIMIT_EXCEEDED", "NO_MATCHED_SAMPLES", "HIGH_UNMATCHED_RATE", "EVENTS_DROPPED", + "TRIGGER_NOT_OBSERVED", "CLOCK_ALIGNMENT_FAILED", "TRACE_EXPORT_FAILED", "CLEANUP_FAILED", diff --git a/schemas/error.schema.json b/schemas/error.schema.json index ff9126a..be3d2e2 100644 --- a/schemas/error.schema.json +++ b/schemas/error.schema.json @@ -36,11 +36,13 @@ "CUPTI_AGENT_NOT_LOADED", "CUDA_CONTEXT_NOT_FOUND", "UNSUPPORTED_CUDA_VERSION", + "UNSUPPORTED_PYTHON_VERSION", "EVENT_RATE_TOO_HIGH", "SESSION_LIMIT_EXCEEDED", "NO_MATCHED_SAMPLES", "HIGH_UNMATCHED_RATE", "EVENTS_DROPPED", + "TRIGGER_NOT_OBSERVED", "CLOCK_ALIGNMENT_FAILED", "TRACE_EXPORT_FAILED", "CLEANUP_FAILED", diff --git a/schemas/measurement-graph-result.schema.json b/schemas/measurement-graph-result.schema.json index c43b6c9..7a037f1 100644 --- a/schemas/measurement-graph-result.schema.json +++ b/schemas/measurement-graph-result.schema.json @@ -96,6 +96,51 @@ "complete" ] }, + "CaptureCoverage": { + "description": "What is known about which events the capture could have recorded.", + "type": "object", + "properties": { + "all_gpu_activity": { + "description": "Every kernel, copy, and memset on the target was recorded, so stream\norder can see each activity's true successor.", + "type": "boolean" + }, + "source": { + "$ref": "#/$defs/CoverageSource" + } + }, + "additionalProperties": false, + "required": [ + "source", + "all_gpu_activity" + ] + }, + "ClockAnchor": { + "description": "The wall clock read against `CLOCK_MONOTONIC`: `realtime_ns` is\n`CLOCK_REALTIME` (nanoseconds since the Unix epoch, UTC) when\n`CLOCK_MONOTONIC` was `monotonic_ns`, to within `uncertainty_ns`.", + "type": "object", + "properties": { + "monotonic_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "realtime_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "uncertainty_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "monotonic_ns", + "realtime_ns", + "uncertainty_ns" + ] + }, "ClockDomain": { "type": "string", "enum": [ @@ -130,6 +175,21 @@ "completeness": { "$ref": "#/$defs/CaptureCompleteness" }, + "coverage": { + "description": "Results written before xprobe recorded coverage read as unverified.", + "$ref": "#/$defs/CaptureCoverage", + "default": { + "all_gpu_activity": false, + "source": "unverified" + } + }, + "cuda_devices": { + "description": "The UUID behind each CUDA device ordinal in the events; empty when the\ncapture had no CUDA source or the driver did not report UUIDs.", + "type": "array", + "items": { + "$ref": "#/$defs/CudaDevice" + } + }, "cuda_events": { "type": "integer", "format": "uint64", @@ -154,6 +214,17 @@ "type": "integer", "format": "uint64", "minimum": 0 + }, + "wall_clock": { + "description": "Maps the events' host-clock timestamps to wall time, for live\ncaptures and inputs whose manifest recorded it.", + "anyOf": [ + { + "$ref": "#/$defs/WallClock" + }, + { + "type": "null" + } + ] } }, "additionalProperties": false, @@ -194,6 +265,57 @@ "score" ] }, + "CoverageSource": { + "oneOf": [ + { + "description": "Collected live by this command.", + "type": "string", + "const": "live" + }, + { + "description": "Read from one artifact without a manifest.", + "type": "string", + "const": "unverified" + }, + { + "description": "Read from artifacts whose capture manifests match them.", + "type": "string", + "const": "manifest" + }, + { + "description": "Merged from artifacts without manifests that place them in one window\nof one target.", + "type": "string", + "const": "unverified_merge" + } + ] + }, + "CudaDevice": { + "description": "One CUDA device as the target saw it. `device_id` is the process's CUDA\nordinal, which `CUDA_VISIBLE_DEVICES` renumbers; the UUID names the\nphysical GPU across processes and in `nvidia-smi`.", + "type": "object", + "properties": { + "device_id": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "gpu_uuid": { + "description": "The physical GPU's `GPU-โ€ฆ` UUID when `uuid` names a MIG instance.", + "type": [ + "string", + "null" + ] + }, + "uuid": { + "description": "`GPU-โ€ฆ`, or `MIG-โ€ฆ` for a MIG instance, as `nvidia-smi -L` prints.", + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "device_id", + "uuid" + ] + }, "CudaEvent": { "type": "object", "properties": { @@ -1058,6 +1180,23 @@ "process_start_time" ] }, + "WallClock": { + "description": "Wall-clock anchors at the start and end of a capture. A host-clock\ntimestamp `t` is `realtime_ns + (t - monotonic_ns)` from the nearer\nanchor; when the two anchors' offsets differ, the wall clock was stepped\nor slewed during the capture and wall times carry that error.", + "type": "object", + "properties": { + "end": { + "$ref": "#/$defs/ClockAnchor" + }, + "start": { + "$ref": "#/$defs/ClockAnchor" + } + }, + "additionalProperties": false, + "required": [ + "start", + "end" + ] + }, "Warning": { "type": "object", "properties": { diff --git a/schemas/measurement-graph-validate.schema.json b/schemas/measurement-graph-validate.schema.json index 50b2bdd..ea20f6f 100644 --- a/schemas/measurement-graph-validate.schema.json +++ b/schemas/measurement-graph-validate.schema.json @@ -99,11 +99,13 @@ "CUPTI_AGENT_NOT_LOADED", "CUDA_CONTEXT_NOT_FOUND", "UNSUPPORTED_CUDA_VERSION", + "UNSUPPORTED_PYTHON_VERSION", "EVENT_RATE_TOO_HIGH", "SESSION_LIMIT_EXCEEDED", "NO_MATCHED_SAMPLES", "HIGH_UNMATCHED_RATE", "EVENTS_DROPPED", + "TRIGGER_NOT_OBSERVED", "CLOCK_ALIGNMENT_FAILED", "TRACE_EXPORT_FAILED", "CLEANUP_FAILED", diff --git a/schemas/measurement-result.schema.json b/schemas/measurement-result.schema.json index d3a2e70..f9b8b79 100644 --- a/schemas/measurement-result.schema.json +++ b/schemas/measurement-result.schema.json @@ -87,6 +87,51 @@ "complete" ] }, + "CaptureCoverage": { + "description": "What is known about which events the capture could have recorded.", + "type": "object", + "properties": { + "all_gpu_activity": { + "description": "Every kernel, copy, and memset on the target was recorded, so stream\norder can see each activity's true successor.", + "type": "boolean" + }, + "source": { + "$ref": "#/$defs/CoverageSource" + } + }, + "additionalProperties": false, + "required": [ + "source", + "all_gpu_activity" + ] + }, + "ClockAnchor": { + "description": "The wall clock read against `CLOCK_MONOTONIC`: `realtime_ns` is\n`CLOCK_REALTIME` (nanoseconds since the Unix epoch, UTC) when\n`CLOCK_MONOTONIC` was `monotonic_ns`, to within `uncertainty_ns`.", + "type": "object", + "properties": { + "monotonic_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "realtime_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "uncertainty_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "monotonic_ns", + "realtime_ns", + "uncertainty_ns" + ] + }, "ClockDomain": { "type": "string", "enum": [ @@ -121,6 +166,21 @@ "completeness": { "$ref": "#/$defs/CaptureCompleteness" }, + "coverage": { + "description": "Results written before xprobe recorded coverage read as unverified.", + "$ref": "#/$defs/CaptureCoverage", + "default": { + "all_gpu_activity": false, + "source": "unverified" + } + }, + "cuda_devices": { + "description": "The UUID behind each CUDA device ordinal in the events; empty when the\ncapture had no CUDA source or the driver did not report UUIDs.", + "type": "array", + "items": { + "$ref": "#/$defs/CudaDevice" + } + }, "cuda_events": { "type": "integer", "format": "uint64", @@ -145,6 +205,17 @@ "type": "integer", "format": "uint64", "minimum": 0 + }, + "wall_clock": { + "description": "Maps the events' host-clock timestamps to wall time, for live\ncaptures and inputs whose manifest recorded it.", + "anyOf": [ + { + "$ref": "#/$defs/WallClock" + }, + { + "type": "null" + } + ] } }, "additionalProperties": false, @@ -185,6 +256,57 @@ "score" ] }, + "CoverageSource": { + "oneOf": [ + { + "description": "Collected live by this command.", + "type": "string", + "const": "live" + }, + { + "description": "Read from one artifact without a manifest.", + "type": "string", + "const": "unverified" + }, + { + "description": "Read from artifacts whose capture manifests match them.", + "type": "string", + "const": "manifest" + }, + { + "description": "Merged from artifacts without manifests that place them in one window\nof one target.", + "type": "string", + "const": "unverified_merge" + } + ] + }, + "CudaDevice": { + "description": "One CUDA device as the target saw it. `device_id` is the process's CUDA\nordinal, which `CUDA_VISIBLE_DEVICES` renumbers; the UUID names the\nphysical GPU across processes and in `nvidia-smi`.", + "type": "object", + "properties": { + "device_id": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "gpu_uuid": { + "description": "The physical GPU's `GPU-โ€ฆ` UUID when `uuid` names a MIG instance.", + "type": [ + "string", + "null" + ] + }, + "uuid": { + "description": "`GPU-โ€ฆ`, or `MIG-โ€ฆ` for a MIG instance, as `nvidia-smi -L` prints.", + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "device_id", + "uuid" + ] + }, "CudaEvent": { "type": "object", "properties": { @@ -973,6 +1095,23 @@ "failed" ] }, + "WallClock": { + "description": "Wall-clock anchors at the start and end of a capture. A host-clock\ntimestamp `t` is `realtime_ns + (t - monotonic_ns)` from the nearer\nanchor; when the two anchors' offsets differ, the wall clock was stepped\nor slewed during the capture and wall times carry that error.", + "type": "object", + "properties": { + "end": { + "$ref": "#/$defs/ClockAnchor" + }, + "start": { + "$ref": "#/$defs/ClockAnchor" + } + }, + "additionalProperties": false, + "required": [ + "start", + "end" + ] + }, "Warning": { "type": "object", "properties": { diff --git a/schemas/python-sample-record.schema.json b/schemas/python-sample-record.schema.json new file mode 100644 index 0000000..4cca513 --- /dev/null +++ b/schemas/python-sample-record.schema.json @@ -0,0 +1,114 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "PythonSampleRecord", + "description": "One line of a Python sample artifact.", + "type": "object", + "properties": { + "frames": { + "description": "Innermost frame first.", + "type": "array", + "items": { + "$ref": "#/$defs/PythonFrame" + } + }, + "gil": { + "description": "Taken as the GIL holder rather than in a sweep of every thread.", + "type": "boolean" + }, + "native": { + "description": "Where the thread was blocked in native code, for sweep samples of a\nthread that was not running.", + "anyOf": [ + { + "$ref": "#/$defs/PythonNativeLeaf" + }, + { + "type": "null" + } + ] + }, + "pid": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "tid": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0 + }, + "timestamp_ns": { + "description": "`CLOCK_MONOTONIC` time just before the stack was read.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "truncated": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "timestamp_ns", + "pid", + "gil", + "truncated", + "frames" + ], + "$defs": { + "PythonFrame": { + "description": "One Python function in a sampled stack.", + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "first_line": { + "description": "The line where the function starts, not the line that was running.", + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "function": { + "description": "`co_qualname` (3.11+) or `co_name`.", + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "function", + "file", + "first_line" + ] + }, + "PythonNativeLeaf": { + "description": "Where a blocked thread waits in native code, from\n`/proc//task//syscall`.", + "type": "object", + "properties": { + "module": { + "description": "The mapped object and symbol of its user-space program counter.", + "type": [ + "string", + "null" + ] + }, + "symbol": { + "type": [ + "string", + "null" + ] + }, + "syscall": { + "description": "The system call it is blocked in, if any.", + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + } + } +} diff --git a/schemas/python-sample-result.schema.json b/schemas/python-sample-result.schema.json new file mode 100644 index 0000000..92967a9 --- /dev/null +++ b/schemas/python-sample-result.schema.json @@ -0,0 +1,586 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "PythonSampleResult", + "description": "Result of `measure --python-sample`, schema `3.0`.", + "type": "object", + "properties": { + "artifact": { + "description": "Every sample with its timestamp, one `PythonSampleRecord` per line.", + "anyOf": [ + { + "$ref": "#/$defs/EvidenceArtifact" + }, + { + "type": "null" + } + ] + }, + "collection": { + "$ref": "#/$defs/PythonSampleCollection" + }, + "inventory": { + "$ref": "#/$defs/PythonSampleInventory" + }, + "ok": { + "type": "boolean" + }, + "schema_version": { + "$ref": "#/$defs/SchemaVersion3" + }, + "session_id": { + "type": "string" + }, + "status": { + "$ref": "#/$defs/SessionStatus" + }, + "target": { + "$ref": "#/$defs/TargetIdentity" + }, + "warnings": { + "type": "array", + "default": [], + "items": { + "$ref": "#/$defs/Warning" + } + } + }, + "additionalProperties": false, + "required": [ + "schema_version", + "ok", + "session_id", + "status", + "target", + "inventory", + "collection" + ], + "$defs": { + "ClockAnchor": { + "description": "The wall clock read against `CLOCK_MONOTONIC`: `realtime_ns` is\n`CLOCK_REALTIME` (nanoseconds since the Unix epoch, UTC) when\n`CLOCK_MONOTONIC` was `monotonic_ns`, to within `uncertainty_ns`.", + "type": "object", + "properties": { + "monotonic_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "realtime_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "uncertainty_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "monotonic_ns", + "realtime_ns", + "uncertainty_ns" + ] + }, + "EvidenceArtifact": { + "description": "Bounded capture written by `measure`; re-correlate it with `measure --input`.", + "type": "object", + "properties": { + "events": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "format": { + "$ref": "#/$defs/ExportFormat" + }, + "path": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "path", + "format", + "events" + ] + }, + "ExportFormat": { + "type": "string", + "enum": [ + "jsonl", + "chrome" + ] + }, + "PythonFrame": { + "description": "One Python function in a sampled stack.", + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "first_line": { + "description": "The line where the function starts, not the line that was running.", + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "function": { + "description": "`co_qualname` (3.11+) or `co_name`.", + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "function", + "file", + "first_line" + ] + }, + "PythonHotspot": { + "type": "object", + "properties": { + "exclusive_proportion": { + "type": "number", + "format": "double" + }, + "exclusive_samples": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "frame": { + "$ref": "#/$defs/PythonFrame" + }, + "inclusive_proportion": { + "type": "number", + "format": "double" + }, + "inclusive_samples": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "frame", + "inclusive_samples", + "exclusive_samples", + "inclusive_proportion", + "exclusive_proportion" + ] + }, + "PythonNativeLeaf": { + "description": "Where a blocked thread waits in native code, from\n`/proc//task//syscall`.", + "type": "object", + "properties": { + "module": { + "description": "The mapped object and symbol of its user-space program counter.", + "type": [ + "string", + "null" + ] + }, + "symbol": { + "type": [ + "string", + "null" + ] + }, + "syscall": { + "description": "The system call it is blocked in, if any.", + "type": [ + "string", + "null" + ] + } + }, + "additionalProperties": false + }, + "PythonNativeWait": { + "description": "Thread samples blocked at one native leaf.", + "type": "object", + "properties": { + "leaf": { + "$ref": "#/$defs/PythonNativeLeaf" + }, + "proportion": { + "description": "Share of thread samples.", + "type": "number", + "format": "double" + }, + "samples": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "leaf", + "samples", + "proportion" + ] + }, + "PythonSampleCollection": { + "type": "object", + "properties": { + "elapsed_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "gil_hz_achieved": { + "description": "GIL ticks per second actually reached.", + "type": "number", + "format": "double" + }, + "gil_hz_requested": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "gil_released_ticks": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "gil_samples": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "gil_ticks": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "inconsistent_reads": { + "description": "Reads discarded because the innermost frame, a code object, a frame\nmapping, or the GIL holder changed while they were read.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "late_ticks": { + "description": "Ticks that started after their deadline.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "native_unreadable": { + "description": "Swept threads whose `/proc//task//syscall` could not be\nread or parsed.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "over_capacity": { + "description": "Samples not kept because the capacity was reached.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "python_binary": { + "type": "string" + }, + "python_version": { + "description": "`3.N` of the target interpreter.", + "type": "string" + }, + "read_latency": { + "description": "Wall time of one kept stack read.", + "anyOf": [ + { + "$ref": "#/$defs/ReadLatency" + }, + { + "type": "null" + } + ] + }, + "sample_capacity": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "stack_depth": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "thread_samples": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "thread_sweeps": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "threads": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "threads_hz_achieved": { + "type": "number", + "format": "double" + }, + "threads_hz_requested": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "tid_source": { + "$ref": "#/$defs/PythonTidSource" + }, + "truncated_stacks": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "wall_clock": { + "description": "Maps sample timestamps to wall time.", + "anyOf": [ + { + "$ref": "#/$defs/WallClock" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false, + "required": [ + "python_version", + "python_binary", + "tid_source", + "elapsed_ns", + "gil_hz_requested", + "gil_hz_achieved", + "threads_hz_requested", + "threads_hz_achieved", + "gil_ticks", + "gil_samples", + "gil_released_ticks", + "thread_sweeps", + "thread_samples", + "threads", + "inconsistent_reads", + "native_unreadable", + "late_ticks", + "sample_capacity", + "over_capacity", + "stack_depth", + "truncated_stacks" + ] + }, + "PythonSampleInventory": { + "type": "object", + "properties": { + "duration_ms": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "gil_hotspots": { + "type": "array", + "items": { + "$ref": "#/$defs/PythonHotspot" + } + }, + "gil_released_proportion": { + "description": "Share of GIL ticks on which no thread held the GIL: native code that\nreleased it, I/O, or idle waiting.", + "type": "number", + "format": "double" + }, + "gil_stack_groups": { + "description": "Stacks of the GIL holder; proportions are of GIL ticks, so they sum\nwith `gil_released_proportion` to one.", + "type": "array", + "items": { + "$ref": "#/$defs/PythonStackGroup" + } + }, + "name": { + "type": [ + "string", + "null" + ] + }, + "native_waits": { + "description": "Native leaves of blocked threads in the sweeps; a running thread has\nnone.", + "type": "array", + "items": { + "$ref": "#/$defs/PythonNativeWait" + } + }, + "thread_stack_groups": { + "description": "Stacks of every thread from the slower sweeps; proportions are of\nthread samples.", + "type": "array", + "items": { + "$ref": "#/$defs/PythonStackGroup" + } + } + }, + "additionalProperties": false, + "required": [ + "duration_ms", + "gil_stack_groups", + "gil_hotspots", + "gil_released_proportion", + "thread_stack_groups", + "native_waits" + ] + }, + "PythonStackGroup": { + "description": "Identical stacks, innermost frame first.", + "type": "object", + "properties": { + "frames": { + "type": "array", + "items": { + "$ref": "#/$defs/PythonFrame" + } + }, + "proportion": { + "description": "Share of the samples this group was drawn from.", + "type": "number", + "format": "double" + }, + "samples": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "frames", + "samples", + "proportion" + ] + }, + "PythonTidSource": { + "description": "How a sample's thread was mapped to a Linux TID.", + "oneOf": [ + { + "description": "`PyThreadState.native_thread_id` (3.11+).", + "type": "string", + "const": "native" + }, + { + "description": "The TID glibc stores in `struct pthread` (before 3.11).", + "type": "string", + "const": "pthread" + }, + { + "description": "No consistent TID mapping; samples carry no TID.", + "type": "string", + "const": "unmapped" + } + ] + }, + "ReadLatency": { + "type": "object", + "properties": { + "max_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "p50_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "p99_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "p50_ns", + "p99_ns", + "max_ns" + ] + }, + "SchemaVersion3": { + "description": "Version of records whose shape changed in xprobe 0.6.\n\nRecords keep their own version so unchanged contracts, such as Event JSONL\nartifacts, remain readable at `2.0`.", + "type": "string", + "enum": [ + "3.0" + ] + }, + "SessionStatus": { + "type": "string", + "enum": [ + "completed", + "timed_out", + "cancelled", + "failed" + ] + }, + "TargetIdentity": { + "type": "object", + "properties": { + "pid": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "process_start_time": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "pid", + "process_start_time" + ] + }, + "WallClock": { + "description": "Wall-clock anchors at the start and end of a capture. A host-clock\ntimestamp `t` is `realtime_ns + (t - monotonic_ns)` from the nearer\nanchor; when the two anchors' offsets differ, the wall clock was stepped\nor slewed during the capture and wall times carry that error.", + "type": "object", + "properties": { + "end": { + "$ref": "#/$defs/ClockAnchor" + }, + "start": { + "$ref": "#/$defs/ClockAnchor" + } + }, + "additionalProperties": false, + "required": [ + "start", + "end" + ] + }, + "Warning": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": true, + "default": {} + }, + "message": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "code", + "message" + ] + } + } +} diff --git a/schemas/syscall-aggregate-validate.schema.json b/schemas/syscall-aggregate-validate.schema.json index 3f5beb5..6eefaf6 100644 --- a/schemas/syscall-aggregate-validate.schema.json +++ b/schemas/syscall-aggregate-validate.schema.json @@ -89,11 +89,13 @@ "CUPTI_AGENT_NOT_LOADED", "CUDA_CONTEXT_NOT_FOUND", "UNSUPPORTED_CUDA_VERSION", + "UNSUPPORTED_PYTHON_VERSION", "EVENT_RATE_TOO_HIGH", "SESSION_LIMIT_EXCEEDED", "NO_MATCHED_SAMPLES", "HIGH_UNMATCHED_RATE", "EVENTS_DROPPED", + "TRIGGER_NOT_OBSERVED", "CLOCK_ALIGNMENT_FAILED", "TRACE_EXPORT_FAILED", "CLEANUP_FAILED", diff --git a/schemas/triage-result.schema.json b/schemas/triage-result.schema.json index c0b0a1d..714deb0 100644 --- a/schemas/triage-result.schema.json +++ b/schemas/triage-result.schema.json @@ -20,6 +20,13 @@ "$ref": "#/$defs/CpuHotspot" } }, + "cuda_devices": { + "description": "The UUID behind each CUDA ordinal in `gpu_activity`; GPU findings\ncover only GPUs the target ran work on.", + "type": "array", + "items": { + "$ref": "#/$defs/CudaDevice" + } + }, "findings": { "description": "Ranked by estimated window share; findings without an estimate last.", "type": "array", @@ -27,6 +34,14 @@ "$ref": "#/$defs/TriageFinding" } }, + "gil_released_proportion": { + "description": "Share of GIL ticks with no thread running Python, when sampled.", + "type": [ + "number", + "null" + ], + "format": "double" + }, "gpu_activity": { "type": "array", "items": { @@ -34,6 +49,7 @@ } }, "gpu_devices": { + "description": "NVML health of every GPU on the host; `uuid` ties it to `cuda_devices`.", "type": "array", "items": { "$ref": "#/$defs/GpuDeviceHealth" @@ -49,6 +65,13 @@ "ok": { "type": "boolean" }, + "python_hotspots": { + "description": "Python functions holding the GIL, from external CPython sampling.", + "type": "array", + "items": { + "$ref": "#/$defs/PythonHotspot" + } + }, "schema_version": { "$ref": "#/$defs/SchemaVersion3" }, @@ -100,6 +123,7 @@ "findings", "threads", "cpu_hotspots", + "python_hotspots", "syscalls", "gpu_devices", "gpu_activity", @@ -405,6 +429,33 @@ "language" ] }, + "CudaDevice": { + "description": "One CUDA device as the target saw it. `device_id` is the process's CUDA\nordinal, which `CUDA_VISIBLE_DEVICES` renumbers; the UUID names the\nphysical GPU across processes and in `nvidia-smi`.", + "type": "object", + "properties": { + "device_id": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "gpu_uuid": { + "description": "The physical GPU's `GPU-โ€ฆ` UUID when `uuid` names a MIG instance.", + "type": [ + "string", + "null" + ] + }, + "uuid": { + "description": "`GPU-โ€ฆ`, or `MIG-โ€ฆ` for a MIG instance, as `nvidia-smi -L` prints.", + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "device_id", + "uuid" + ] + }, "GpuDeviceHealth": { "description": "NVML device health sampled through the triage window.\n\nUtilization is the driver's sampled share of time with at least one kernel\nrunning; it is an estimate, not an exact busy-interval union.", "type": "object", @@ -638,6 +689,65 @@ "width_max" ] }, + "PythonFrame": { + "description": "One Python function in a sampled stack.", + "type": "object", + "properties": { + "file": { + "type": "string" + }, + "first_line": { + "description": "The line where the function starts, not the line that was running.", + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "function": { + "description": "`co_qualname` (3.11+) or `co_name`.", + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "function", + "file", + "first_line" + ] + }, + "PythonHotspot": { + "type": "object", + "properties": { + "exclusive_proportion": { + "type": "number", + "format": "double" + }, + "exclusive_samples": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "frame": { + "$ref": "#/$defs/PythonFrame" + }, + "inclusive_proportion": { + "type": "number", + "format": "double" + }, + "inclusive_samples": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "frame", + "inclusive_samples", + "exclusive_samples", + "inclusive_proportion", + "exclusive_proportion" + ] + }, "SchemaVersion": { "type": "string", "enum": [ @@ -950,7 +1060,8 @@ "cpu_sample", "syscall_aggregate", "gpu_health", - "gpu_activity" + "gpu_activity", + "python_sample" ] }, "TriageSourceStatus": { diff --git a/schemas/trigger-result.schema.json b/schemas/trigger-result.schema.json new file mode 100644 index 0000000..1c90b5b --- /dev/null +++ b/schemas/trigger-result.schema.json @@ -0,0 +1,925 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "TriggerResult", + "description": "Result of `measure --trigger-*`, schema `3.0`.", + "type": "object", + "properties": { + "collection": { + "$ref": "#/$defs/TriggerCollection" + }, + "observed": { + "$ref": "#/$defs/TriggerObservation" + }, + "ok": { + "type": "boolean" + }, + "schema_version": { + "$ref": "#/$defs/SchemaVersion3" + }, + "session_id": { + "type": "string" + }, + "status": { + "description": "`timed_out` when the deadline passed with fewer windows than requested;\notherwise `completed`, even when windows were lost or revoked.", + "$ref": "#/$defs/SessionStatus" + }, + "target": { + "$ref": "#/$defs/TargetIdentity" + }, + "trigger": { + "$ref": "#/$defs/TriggerCondition" + }, + "warnings": { + "type": "array", + "items": { + "$ref": "#/$defs/Warning" + } + }, + "windows": { + "type": "array", + "items": { + "$ref": "#/$defs/TriggerWindow" + } + } + }, + "additionalProperties": false, + "required": [ + "schema_version", + "ok", + "session_id", + "status", + "target", + "trigger", + "observed", + "windows", + "collection", + "warnings" + ], + "$defs": { + "ArgumentValue": { + "type": "object", + "properties": { + "abi_type": { + "type": "string" + }, + "index": { + "type": "integer", + "format": "uint16", + "maximum": 65535, + "minimum": 0 + }, + "read_error": { + "type": [ + "string", + "null" + ] + }, + "value": true + }, + "additionalProperties": false, + "required": [ + "index", + "abi_type" + ] + }, + "ClockAnchor": { + "description": "The wall clock read against `CLOCK_MONOTONIC`: `realtime_ns` is\n`CLOCK_REALTIME` (nanoseconds since the Unix epoch, UTC) when\n`CLOCK_MONOTONIC` was `monotonic_ns`, to within `uncertainty_ns`.", + "type": "object", + "properties": { + "monotonic_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "realtime_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "uncertainty_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "monotonic_ns", + "realtime_ns", + "uncertainty_ns" + ] + }, + "ClockDomain": { + "type": "string", + "enum": [ + "host_monotonic", + "cupti", + "cupti_normalized_to_host_monotonic" + ] + }, + "CudaEvent": { + "type": "object", + "properties": { + "block": { + "anyOf": [ + { + "$ref": "#/$defs/Dim3" + }, + { + "type": "null" + } + ] + }, + "bytes": { + "type": [ + "integer", + "null" + ], + "format": "uint64", + "minimum": 0 + }, + "callback_domain": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0 + }, + "callback_id": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0 + }, + "context_id": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0 + }, + "correlation_id": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0 + }, + "device_id": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0 + }, + "end_ns": { + "type": [ + "integer", + "null" + ], + "format": "uint64", + "minimum": 0 + }, + "grid": { + "anyOf": [ + { + "$ref": "#/$defs/Dim3" + }, + { + "type": "null" + } + ] + }, + "kernel_name": { + "type": [ + "string", + "null" + ] + }, + "kernel_name_mangled": { + "type": [ + "string", + "null" + ] + }, + "memcpy_kind": { + "anyOf": [ + { + "$ref": "#/$defs/MemcpyKind" + }, + { + "type": "null" + } + ] + }, + "runtime_correlation_id": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0 + }, + "start_ns": { + "type": [ + "integer", + "null" + ], + "format": "uint64", + "minimum": 0 + }, + "stream_id": { + "type": [ + "integer", + "null" + ], + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false + }, + "Dim3": { + "type": "object", + "properties": { + "x": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "y": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "z": { + "type": "integer", + "format": "uint32", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "x", + "y", + "z" + ] + }, + "Event": { + "type": "object", + "properties": { + "attributes": { + "type": "object", + "additionalProperties": true, + "default": {} + }, + "clock_domain": { + "$ref": "#/$defs/ClockDomain" + }, + "cpu": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0 + }, + "cuda": { + "anyOf": [ + { + "$ref": "#/$defs/CudaEvent" + }, + { + "type": "null" + } + ] + }, + "event_id": { + "type": "string" + }, + "event_type": { + "$ref": "#/$defs/EventType" + }, + "host": { + "anyOf": [ + { + "$ref": "#/$defs/HostEvent" + }, + { + "type": "null" + } + ] + }, + "nvtx": { + "anyOf": [ + { + "$ref": "#/$defs/NvtxEvent" + }, + { + "type": "null" + } + ], + "default": null + }, + "pid": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "process_start_time": { + "type": [ + "integer", + "null" + ], + "format": "uint64", + "minimum": 0 + }, + "schema_version": { + "$ref": "#/$defs/SchemaVersion" + }, + "sequence": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "session_id": { + "type": "string" + }, + "source": { + "$ref": "#/$defs/EventSource" + }, + "tid": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "timestamp_error_ns": { + "type": [ + "integer", + "null" + ], + "format": "uint64", + "minimum": 0 + }, + "timestamp_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "timestamp_raw": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "schema_version", + "session_id", + "event_id", + "sequence", + "source", + "event_type", + "pid", + "tid", + "timestamp_raw", + "timestamp_ns", + "clock_domain" + ] + }, + "EventSource": { + "type": "string", + "enum": [ + "ebpf", + "cupti_callback", + "cupti_activity", + "marker" + ] + }, + "EventType": { + "type": "string", + "enum": [ + "host_function_entry", + "host_function_exit", + "kernel_function_entry", + "kernel_function_exit", + "tracepoint", + "syscall_entry", + "syscall_exit", + "cuda_api_entry", + "cuda_api_exit", + "gpu_kernel_start", + "gpu_kernel_end", + "gpu_memcpy_start", + "gpu_memcpy_end", + "gpu_memset_start", + "gpu_memset_end", + "nvtx_range_start", + "nvtx_range_end", + "python_gc_start", + "python_gc_end", + "marker" + ] + }, + "EvidenceArtifact": { + "description": "Bounded capture written by `measure`; re-correlate it with `measure --input`.", + "type": "object", + "properties": { + "events": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "format": { + "$ref": "#/$defs/ExportFormat" + }, + "path": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "path", + "format", + "events" + ] + }, + "ExportFormat": { + "type": "string", + "enum": [ + "jsonl", + "chrome" + ] + }, + "HostEvent": { + "type": "object", + "properties": { + "arguments": { + "type": "array", + "default": [], + "items": { + "$ref": "#/$defs/ArgumentValue" + } + }, + "binary_path": { + "type": [ + "string", + "null" + ] + }, + "build_id": { + "type": [ + "string", + "null" + ] + }, + "offset": { + "type": [ + "integer", + "null" + ], + "format": "uint64", + "minimum": 0 + }, + "probe_kind": { + "$ref": "#/$defs/HostProbeKind" + }, + "return_value": { + "type": [ + "integer", + "null" + ], + "format": "int64" + }, + "symbol": { + "type": [ + "string", + "null" + ] + }, + "symbol_demangled": { + "type": [ + "string", + "null" + ], + "default": null + } + }, + "additionalProperties": false, + "required": [ + "probe_kind" + ] + }, + "HostProbeKind": { + "type": "string", + "enum": [ + "uprobe", + "uretprobe", + "kprobe", + "kretprobe", + "tracepoint", + "syscall", + "usdt" + ] + }, + "MatchPolicy": { + "type": "string", + "enum": [ + "exact", + "first_after", + "nearest", + "stack_nested", + "stream_order" + ] + }, + "MatchedEventPair": { + "type": "object", + "properties": { + "end": { + "$ref": "#/$defs/Event" + }, + "latency_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "start": { + "$ref": "#/$defs/Event" + } + }, + "additionalProperties": false, + "required": [ + "start", + "end", + "latency_ns" + ] + }, + "MemcpyKind": { + "type": "string", + "enum": [ + "HtoD", + "DtoH", + "DtoD", + "HtoH", + "PtoP", + "unknown" + ] + }, + "NvtxEvent": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "name_complete": { + "type": "boolean" + }, + "range_id": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "range_kind": { + "$ref": "#/$defs/NvtxRangeKind" + }, + "start_tid": { + "type": "integer", + "format": "uint32", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "name", + "name_complete", + "range_kind", + "range_id", + "start_tid" + ] + }, + "NvtxRangeKind": { + "type": "string", + "enum": [ + "thread", + "process" + ] + }, + "SchemaVersion": { + "type": "string", + "enum": [ + "2.0" + ] + }, + "SchemaVersion3": { + "description": "Version of records whose shape changed in xprobe 0.6.\n\nRecords keep their own version so unchanged contracts, such as Event JSONL\nartifacts, remain readable at `2.0`.", + "type": "string", + "enum": [ + "3.0" + ] + }, + "SessionStatus": { + "type": "string", + "enum": [ + "completed", + "timed_out", + "cancelled", + "failed" + ] + }, + "TargetIdentity": { + "type": "object", + "properties": { + "pid": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "process_start_time": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "pid", + "process_start_time" + ] + }, + "TriggerCollection": { + "type": "object", + "properties": { + "dropped_records": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "lost_windows": { + "description": "Windows discarded because records inside them were lost.", + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "observed_records": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "overwritten_records": { + "description": "Records the ring overwrote before they were read.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "revoked_windows": { + "description": "Windows discarded because their firing span no longer crossed the\nthreshold once every record had arrived.", + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "ring_capacity": { + "description": "Agent ring and CLI retention bound, in records.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "wall_clock": { + "description": "Maps window timestamps to wall time.", + "anyOf": [ + { + "$ref": "#/$defs/WallClock" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false, + "required": [ + "ring_capacity", + "observed_records", + "overwritten_records", + "dropped_records", + "lost_windows", + "revoked_windows" + ] + }, + "TriggerCondition": { + "type": "object", + "properties": { + "end_selector": { + "type": [ + "string", + "null" + ] + }, + "kind": { + "$ref": "#/$defs/TriggerKind" + }, + "match_policy": { + "anyOf": [ + { + "$ref": "#/$defs/MatchPolicy" + }, + { + "type": "null" + } + ] + }, + "post_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "pre_ns": { + "description": "Context kept before the firing span's start and after its end.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "start_selector": { + "description": "Edge selectors and policy of a latency trigger.", + "type": [ + "string", + "null" + ] + }, + "threshold_ns": { + "description": "A span fires when it lasts at least this long.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "windows": { + "description": "Windows to write before stopping; later windows start after the\nprevious one ends.", + "type": "integer", + "format": "uint32", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "kind", + "threshold_ns", + "pre_ns", + "post_ns", + "windows" + ] + }, + "TriggerKind": { + "description": "What a trigger measures on each span it evaluates.", + "oneOf": [ + { + "description": "A gap on one stream: an activity end to the next kernel, copy, or\nmemset start on that stream, even while other streams keep the\ndevice busy.", + "type": "string", + "const": "gap" + }, + { + "description": "Idle time on one device: no kernel, copy, or memset of the target on\nany of its streams.", + "type": "string", + "const": "idle" + }, + { + "description": "One kernel, copy, or memset from start to end.", + "type": "string", + "const": "duration" + }, + { + "description": "One edge between two selectors under a correlation policy.", + "type": "string", + "const": "latency" + } + ] + }, + "TriggerObservation": { + "description": "Every span evaluated while waiting, fired or not.", + "type": "object", + "properties": { + "longest": { + "description": "The longest span seen, whether or not its window could be written.", + "anyOf": [ + { + "$ref": "#/$defs/MatchedEventPair" + }, + { + "type": "null" + } + ] + }, + "over_threshold": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "spans": { + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "spans", + "over_threshold" + ] + }, + "TriggerWindow": { + "type": "object", + "properties": { + "artifact": { + "$ref": "#/$defs/EvidenceArtifact" + }, + "clock_domain": { + "$ref": "#/$defs/ClockDomain" + }, + "end_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "fired": { + "description": "The span that crossed the threshold.", + "$ref": "#/$defs/MatchedEventPair" + }, + "index": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "longest": { + "description": "The longest spans of the trigger's kind inside the window.", + "type": "array", + "items": { + "$ref": "#/$defs/MatchedEventPair" + } + }, + "start_ns": { + "description": "Window bounds in the events' clock, clipped to what was captured.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "truncated": { + "description": "The capture began after `pre_ns` before the span or ended before\n`post_ns` after it, so the window is shorter than requested.", + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "index", + "fired", + "start_ns", + "end_ns", + "clock_domain", + "truncated", + "longest", + "artifact" + ] + }, + "WallClock": { + "description": "Wall-clock anchors at the start and end of a capture. A host-clock\ntimestamp `t` is `realtime_ns + (t - monotonic_ns)` from the nearer\nanchor; when the two anchors' offsets differ, the wall clock was stepped\nor slewed during the capture and wall times carry that error.", + "type": "object", + "properties": { + "end": { + "$ref": "#/$defs/ClockAnchor" + }, + "start": { + "$ref": "#/$defs/ClockAnchor" + } + }, + "additionalProperties": false, + "required": [ + "start", + "end" + ] + }, + "Warning": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "details": { + "type": "object", + "additionalProperties": true, + "default": {} + }, + "message": { + "type": "string" + } + }, + "additionalProperties": false, + "required": [ + "code", + "message" + ] + } + } +} diff --git a/schemas/validate.schema.json b/schemas/validate.schema.json index 1a50ed3..2137123 100644 --- a/schemas/validate.schema.json +++ b/schemas/validate.schema.json @@ -98,11 +98,13 @@ "CUPTI_AGENT_NOT_LOADED", "CUDA_CONTEXT_NOT_FOUND", "UNSUPPORTED_CUDA_VERSION", + "UNSUPPORTED_PYTHON_VERSION", "EVENT_RATE_TOO_HIGH", "SESSION_LIMIT_EXCEEDED", "NO_MATCHED_SAMPLES", "HIGH_UNMATCHED_RATE", "EVENTS_DROPPED", + "TRIGGER_NOT_OBSERVED", "CLOCK_ALIGNMENT_FAILED", "TRACE_EXPORT_FAILED", "CLEANUP_FAILED", diff --git a/scripts/build-wheel.py b/scripts/build-wheel.py index 84ce9b4..9f034f6 100755 --- a/scripts/build-wheel.py +++ b/scripts/build-wheel.py @@ -98,10 +98,11 @@ def link(match: re.Match[str]) -> str: def build(stage: pathlib.Path, output: pathlib.Path) -> pathlib.Path: - match = re.fullmatch(r"xprobe-(\d+\.\d+\.\d+)-linux-x86_64", stage.name) + match = re.fullmatch(r"xprobe-(\d+\.\d+\.\d+)(?:-dev\.(\d+))?-linux-x86_64", stage.name) if match is None: raise SystemExit(f"unexpected staging directory name: {stage.name}") - version = match.group(1) + # Cargo's X.Y.Z-dev.N is PEP 440's X.Y.Z.devN. + version = match.group(1) + (f".dev{match.group(2)}" if match.group(2) else "") data_dir = f"{NAME}-{version}.data" dist_info = f"{NAME}-{version}.dist-info" diff --git a/scripts/package-release.sh b/scripts/package-release.sh index b88e18e..f67b3a7 100755 --- a/scripts/package-release.sh +++ b/scripts/package-release.sh @@ -25,7 +25,7 @@ verify_agent() { echo "CUDA ${major} CUPTI agent was not found: ${agent}" >&2 exit 1 } - dynamic=$(readelf -d "${agent}") + dynamic=$(LC_ALL=C readelf -d "${agent}") grep -Fq "Shared library: [libcupti.so.${major}]" <<<"${dynamic}" || { echo "${agent} is not linked to libcupti.so.${major}" >&2 exit 1 diff --git a/scripts/render-readme-art.py b/scripts/render-readme-art.py index a93b7a7..34e3519 100755 --- a/scripts/render-readme-art.py +++ b/scripts/render-readme-art.py @@ -1,243 +1,379 @@ #!/usr/bin/env python3 -"""Render the README hero animation as light and dark SVGs. +"""Render the README hero visual (light & dark SVGs) and social preview card. -The numbers come from the v0.6.0 live release gate on an RTX 3060: the PyTorch -CUDA triage fixture and the multisource request/launch/kernel graph. Rerun -after changing the story: +Illustrates an end-to-end RSI optimization loop: live GPU + Python capture on +CLOCK_MONOTONIC, JSONL alignment of a GPU idle bubble to a Python GIL stall, +and automated before/after verification. Rerun after edits: scripts/render-readme-art.py docs/assets """ +import base64 import pathlib import sys from html import escape WIDTH, HEIGHT = 960, 540 -CYCLE_S = 14.0 -FONT = "ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace" -SANS = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif" +CYCLE_S = 6.2 +FONT = "'Maple Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace" +SANS = "'Geist', -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif" +FONTS_DIR = pathlib.Path(__file__).resolve().parents[1] / "docs/assets/fonts" +EMBEDDED_FONTS = ( + ("Maple Mono", "400", "MapleMono-Regular.woff2"), + ("Maple Mono", "600 700", "MapleMono-Bold.woff2"), + ("Geist", "400 500", "Geist-Regular.woff2"), + ("Geist", "600 700", "Geist-Bold.woff2"), +) + + +def font_face_css() -> str: + rules = [] + for family, weight, filename in EMBEDDED_FONTS: + data = base64.b64encode((FONTS_DIR / filename).read_bytes()).decode("ascii") + rules.append( + f"@font-face {{ font-family: '{family}'; font-weight: {weight}; " + f"font-style: normal; src: url('data:font/woff2;base64,{data}') format('woff2'); }}" + ) + return "\n".join(rules) THEMES = { "light": { "bg": "#ffffff", "panel": "#f6f8fa", + "card": "#ffffff", + "code_bg": "#eff2f5", "border": "#d0d7de", + "grid": "#e6ebf1", "text": "#1f2328", "muted": "#59636e", - "prompt": "#0969da", - "cpu": "#8250df", - "gpu": "#1a7f37", - "env": "#9a6700", - "track": "#eaeef2", + "blue": "#0969da", + "blue_soft": "#dbeafe", + "purple": "#8250df", + "purple_soft": "#f3e8ff", + "green": "#1a7f37", + "green_soft": "#dcfce7", + "amber": "#bf5700", + "amber_soft": "#ffedd5", + "bar_bg": "#eaeef2", }, "dark": { "bg": "#0d1117", "panel": "#161b22", + "card": "#0d1117", + "code_bg": "#11161d", "border": "#30363d", + "grid": "#21262d", "text": "#e6edf3", "muted": "#8d96a0", - "prompt": "#4493f8", - "cpu": "#ab7df8", - "gpu": "#3fb950", - "env": "#d29922", - "track": "#21262d", + "blue": "#4493f8", + "blue_soft": "#142640", + "purple": "#ab7df8", + "purple_soft": "#281c40", + "green": "#3fb950", + "green_soft": "#132d1c", + "amber": "#f0883e", + "amber_soft": "#332010", + "bar_bg": "#21262d", }, } -# (start, end) as fractions of the cycle for each stage. -STAGES = { - "cmd1": (0.02, 0.10), - "find1": (0.12, 0.16), - "find2": (0.16, 0.20), - "find3": (0.20, 0.24), - "next": (0.27, 0.31), - "cmd2": (0.34, 0.42), - "lanes": (0.44, 0.48), - "edge1": (0.50, 0.55), - "edge2": (0.56, 0.61), - "edge3": (0.62, 0.67), - "tagline": (0.72, 0.77), -} -HOLD_UNTIL = 0.93 - - -def keyframes(name: str, start: float, end: float, kind: str) -> str: - """Hidden until start, shown from end to the loop's end. - The whole scene fades out and back in around the loop boundary, so - individual elements never need their own exit frames. - """ - s, e = (round(v * 100, 2) for v in (start, end)) - if kind == "type": - hidden, shown = "transform: scaleX(1)", "transform: scaleX(0)" - elif kind == "grow": - hidden, shown = "transform: scaleX(0)", "transform: scaleX(1)" - else: - hidden = "opacity: 0; transform: translateY(6px)" - shown = "opacity: 1; transform: translateY(0)" - return f"@keyframes {name} {{ 0%, {s}% {{ {hidden} }} {e}%, 100% {{ {shown} }} }}" +def text(x, y, content, size, fill, cls="mono", weight="400", anchor="start") -> str: + return ( + f'{escape(content)}' + ) -def scene_keyframes() -> str: - h = round(HOLD_UNTIL * 100, 2) +def pill(x, y, w, h, label, fg, bg, stroke=None, stroke_opacity=None, size=11, cls="mono", weight="600", box_cls="") -> str: + border = f' stroke="{stroke}" stroke-width="1"' if stroke else "" + if stroke and stroke_opacity is not None: + border += f' stroke-opacity="{stroke_opacity}"' + rect_cls = f' class="{box_cls}"' if box_cls else "" return ( - f"@keyframes scene {{ 0% {{ opacity: 0 }} 1.5%, {h}% {{ opacity: 1 }} " - f"99%, 100% {{ opacity: 0 }} }}" + f'' + + text(x + w / 2, y + h / 2 + size * 0.35, label, size, fg, cls=cls, weight=weight, anchor="middle") ) -def style(theme: dict) -> str: - rules = [ +def style(t: dict, animated: bool, embed_fonts: bool = True) -> str: + base = [ + *([font_face_css()] if embed_fonts else []), f".mono {{ font-family: {FONT}; }}", f".sans {{ font-family: {SANS}; }}", - ".anim { transform-box: fill-box; }", - scene_keyframes(), - f".scene {{ animation: scene {CYCLE_S}s linear infinite; }}", ] - for name, (start, end) in STAGES.items(): - kind = "type" if name.startswith("cmd") else "fade" - rules.append(keyframes(f"k-{name}", start, end, kind)) - rules.append( - f".{name} {{ animation: k-{name} {CYCLE_S}s ease-out infinite; " - f"{'transform-origin: right center;' if kind == 'type' else ''} }}" - ) - for name in ("find1", "find2", "find3"): - start, end = STAGES[name] - rules.append(keyframes(f"g-{name}", end, end + 0.06, "grow")) - rules.append( - f".bar-{name} {{ animation: g-{name} {CYCLE_S}s ease-out infinite; " - "transform-origin: left center; }" - ) - rules.append( - "@media (prefers-reduced-motion: reduce) { * { animation: none !important; } " - ".cover { display: none; } }" + if not animated: + base.append(".scan { display: none; }") + return "\n".join(base) + base.extend( + [ + # Every animation shares an identical 0% and 100% state for seamless looping. + # Stage 1 (2-22%): live capture command strip + f"@keyframes pulse-s1 {{ 0%, 1% {{ stroke: {t['border']}; stroke-width: 1; }} 5%, 19% {{ stroke: {t['blue']}; stroke-width: 1.8; }} 24%, 100% {{ stroke: {t['border']}; stroke-width: 1; }} }}", + # Stage 1-2 (5-54%): live scan playhead sweeping across the aligned timeline + "@keyframes sweep-scan { " + "0%, 4% { transform: translateX(0px); opacity: 0; } " + "8% { transform: translateX(0px); opacity: 1; } " + "23% { transform: translateX(244px); opacity: 1; } " + "41% { transform: translateX(488px); opacity: 1; } " + "50% { transform: translateX(750px); opacity: 0.9; } " + "55% { transform: translateX(750px); opacity: 0; } " + "56%, 100% { transform: translateX(0px); opacity: 0; } }", + # Stage 2 (20-52%): timeline card & bubble-to-GIL alignment lock-on + f"@keyframes pulse-s2-card {{ 0%, 19% {{ stroke: {t['border']}; stroke-width: 1; }} 23%, 49% {{ stroke: {t['amber']}; stroke-width: 1.8; }} 54%, 100% {{ stroke: {t['border']}; stroke-width: 1; }} }}", + "@keyframes lock-bubble { 0%, 20% { opacity: 0.25; } 26%, 49% { opacity: 1; } 57%, 100% { opacity: 0.25; } }", + "@keyframes lock-link { 0%, 21% { opacity: 0.25; } 27%, 49% { opacity: 1; } 57%, 100% { opacity: 0.25; } }", + # Stage 3 (50-72%): agent JSONL script & patch card + f"@keyframes pulse-s3 {{ 0%, 49% {{ stroke: {t['border']}; stroke-width: 1; }} 53%, 69% {{ stroke: {t['purple']}; stroke-width: 1.8; }} 74%, 100% {{ stroke: {t['border']}; stroke-width: 1; }} }}", + f"@keyframes pulse-arrow {{ 0%, 58% {{ stroke: {t['muted']}; opacity: 0.5; }} 66%, 75% {{ stroke: {t['green']}; opacity: 1; }} 81%, 100% {{ stroke: {t['muted']}; opacity: 0.5; }} }}", + # Stage 4 (71-97%): re-measure & keep card + smooth shrink & dimmed reset + f"@keyframes pulse-s4 {{ 0%, 70% {{ stroke: {t['border']}; stroke-width: 1; }} 74%, 93% {{ stroke: {t['green']}; stroke-width: 1.8; }} 98%, 100% {{ stroke: {t['border']}; stroke-width: 1; }} }}", + "@keyframes shrink-idle { " + "0%, 69% { transform: scaleX(5.52); opacity: 0.22; } " + "73% { transform: scaleX(5.52); opacity: 1; } " + "83%, 93% { transform: scaleX(1); opacity: 1; } " + "97% { transform: scaleX(1); opacity: 0.22; } " + "99%, 100% { transform: scaleX(5.52); opacity: 0.22; } }", + "@keyframes shrink-p95 { " + "0%, 69% { transform: scaleX(1.52); opacity: 0.22; } " + "73% { transform: scaleX(1.52); opacity: 1; } " + "83%, 93% { transform: scaleX(1); opacity: 1; } " + "97% { transform: scaleX(1); opacity: 0.22; } " + "99%, 100% { transform: scaleX(1.52); opacity: 0.22; } }", + # Bottom 4-step RSI loop indicator pills + "@keyframes pill-1 { 0%, 1% { opacity: 0.52; } 5%, 19% { opacity: 1; } 24%, 100% { opacity: 0.52; } }", + "@keyframes pill-2 { 0%, 19% { opacity: 0.52; } 23%, 49% { opacity: 1; } 54%, 100% { opacity: 0.52; } }", + "@keyframes pill-3 { 0%, 49% { opacity: 0.52; } 53%, 69% { opacity: 1; } 74%, 100% { opacity: 0.52; } }", + "@keyframes pill-4 { 0%, 70% { opacity: 0.52; } 74%, 93% { opacity: 1; } 98%, 100% { opacity: 0.52; } }", + f".s1 {{ animation: pulse-s1 {CYCLE_S}s ease-in-out infinite; }}", + f".scan {{ animation: sweep-scan {CYCLE_S}s linear infinite; }}", + f".s2-card {{ animation: pulse-s2-card {CYCLE_S}s ease-in-out infinite; }}", + f".s2-band {{ animation: lock-bubble {CYCLE_S}s ease-in-out infinite; }}", + f".s2-link {{ animation: lock-link {CYCLE_S}s ease-in-out infinite; }}", + f".s3 {{ animation: pulse-s3 {CYCLE_S}s ease-in-out infinite; }}", + f".s3-arrow {{ animation: pulse-arrow {CYCLE_S}s ease-in-out infinite; }}", + f".s4 {{ animation: pulse-s4 {CYCLE_S}s ease-in-out infinite; }}", + f".bar-idle {{ transform-box: fill-box; transform-origin: left center; animation: shrink-idle {CYCLE_S}s cubic-bezier(0.22, 1, 0.36, 1) infinite; }}", + f".bar-p95 {{ transform-box: fill-box; transform-origin: left center; animation: shrink-p95 {CYCLE_S}s cubic-bezier(0.22, 1, 0.36, 1) infinite; }}", + f".p1 {{ animation: pill-1 {CYCLE_S}s ease-in-out infinite; }}", + f".p2 {{ animation: pill-2 {CYCLE_S}s ease-in-out infinite; }}", + f".p3 {{ animation: pill-3 {CYCLE_S}s ease-in-out infinite; }}", + f".p4 {{ animation: pill-4 {CYCLE_S}s ease-in-out infinite; }}", + "@media (prefers-reduced-motion: reduce) { " + "* { animation: none !important; } " + ".scan { display: none !important; } " + ".s2-band, .s2-link, .bar-idle, .bar-p95, .p1, .p2, .p3, .p4 { opacity: 1 !important; } }", + ] ) - return "\n".join(rules) + return "\n".join(base) -def text(x, y, content, size, fill, cls="mono", weight="400", anchor="start") -> str: - return ( - f'{escape(content)}' +def render(theme_name: str, animated: bool = True, embed_fonts: bool = True) -> str: + t = THEMES[theme_name] + bx0, bx1 = 384, 628 + bmid = (bx0 + bx1) / 2 + defs = ( + "" + '' + f'' + f'' + "" + '' + '' + "" ) + parts = [ + defs, + # Outer background and window container + f'', + f'', + # Window header bar + '', + '', + '', + text(92, 39, "xprobe ยท live CPU + Python + CUDA profiling", 13, t["muted"], cls="sans", weight="500"), + pill(772, 24, 152, 22, "CLOCK_MONOTONIC", t["blue"], t["blue_soft"], stroke=t["border"], size=10.5), + f'', + # Step 1: Live Capture commands + f'', + text(50, 88, "$", 13.5, t["blue"], weight="700"), + text(66, 88, "xprobe measure --pid 4242 --trigger-idle-ms 10 --events-out spikes", 13.5, t["text"]), + text(910, 88, "GPU JSONL", 11.5, t["green"], weight="600", anchor="end"), + text(50, 110, "$", 13.5, t["blue"], weight="700"), + text(66, 110, "xprobe measure --pid 4242 --python-sample --duration-ms 2000", 13.5, t["text"]), + text(910, 110, "Python JSONL", 11.5, t["purple"], weight="600", anchor="end"), + # Aligned Host/Python + GPU timeline card + f'', + text(50, 154, "1 ยท ALIGNED TIMELINE", 11, t["muted"], cls="sans", weight="700"), + ] + # Subtle vertical grid lines in timeline + for gx in (140, 265, 390, 515, 640, 765, 890): + parts.append(f'') -def command(y: int, line: str, stage: str, t: dict) -> str: - """A typed command: the text is revealed by a cover that shrinks away.""" - width = 22 + len(line) * 8.4 - return ( - f'{text(48, y, "$", 15, t["prompt"], weight="700")}' - f'{text(66, y, line, 15, t["text"])}' - f'' + # Vertical bubble-alignment highlight spanning Host/Python + GPU lanes + parts.extend( + [ + '', + f'', + f'', + f'', + "", + # Host / Python lane + text(48, 202, "HOST/PY", 11, t["purple"], weight="700"), + f'', + text(238, 179, "launch โ†’ kernel (exact)", 10.5, t["blue"], anchor="middle"), + f'', + text(bmid, 202, "GIL: tokenize() ยท 68%", 11.5, t["purple"], weight="700", anchor="middle"), + # Alignment connector between Python GIL stall and GPU idle bubble + '', + f'', + f'', + f'', + "", + # GPU lane + text(48, 252, "GPU", 11, t["green"], weight="700"), + f'', + ] ) - -def finding(y: int, rank: int, code: str, detail: str, share: float | None, - color: str, stage: str, t: dict) -> str: - bar_x, bar_w = 600, 260 - parts = [ - f'', - text(48, y, f"{rank}", 14, t["muted"]), - text(70, y, code, 14, color, weight="700"), - text(70, y + 19, detail, 12.5, t["muted"]), - f'', - ] - if share is None: - parts.append(text(bar_x + bar_w + 14, y, "n/a", 13, t["muted"])) - else: + # Host cuda:launch_api markers + exact correlation arcs to GPU kernels + kernels = ( + (134, 144, 70, "attn"), + (210, 220, 76, "gemm"), + (292, 302, 76, "gemm"), + (634, 644, 70, "attn"), + (710, 720, 78, "gemm"), + (794, 804, 86, "gemm"), + ) + for lx, kx, kw, klabel in kernels: parts.append( - f'' + f'' + f'' + f'' + + text(kx + kw / 2, 252, klabel, 11, t["green"], weight="600", anchor="middle") ) - parts.append(text(bar_x + bar_w + 14, y, f"{share:.0%}", 13, t["text"], weight="700")) - parts.append("") - return "".join(parts) + # GPU idle bubble block, animated live playhead, and timeline ticks + parts.extend( + [ + f'', + text(bmid, 252, "14.2 ms GPU idle bubble", 11.5, t["amber"], weight="700", anchor="middle"), + '', + '', + f'', + f'', + "", + text(140, 284, "0 ms", 10, t["muted"]), + text(bx0, 284, "gap_start", 10, t["amber"], anchor="middle"), + text(bx1, 284, "gap_end", 10, t["amber"], anchor="middle"), + text(890, 284, "+50 ms", 10, t["muted"], anchor="end"), + ] + ) -def timeline(t: dict) -> str: - lane_x0, lane_x1 = 150, 900 - cpu_y, gpu_y = 362, 440 - req, launch, kstart, kend = 190, 560, 690, 760 - parts = [ - '', - text(48, cpu_y + 5, "CPU", 13, t["cpu"], weight="700"), - text(48, gpu_y + 5, "GPU", 13, t["gpu"], weight="700"), - f'', - f'', - f'', - text(req, cpu_y - 14, "request", 12, t["muted"], anchor="middle"), - f'', - text(launch, cpu_y - 14, "cudaLaunchKernel returns", 12, t["muted"], anchor="middle"), - f'', - text((kstart + kend) / 2, gpu_y + 28, "kernel", 12, t["muted"], anchor="middle"), - "", - '', - f'', - text((req + launch) / 2, cpu_y + 22, "request โ†’ launch 1.14 ms (first-after)", 13, t["text"], anchor="middle"), - "", - '', - f'', - text(launch - 10, (cpu_y + gpu_y) / 2 + 8, "launch โ†’ kernel 99 ยตs (exact)", 13, t["text"], anchor="end"), - "", - '', - text(kend + 12, gpu_y + 5, "kernel 1.2 ยตs (exact)", 13, t["text"]), - "", - ] - return "".join(parts) + # Bottom Left: Step 2 - Agent one-off script & patch + parts.extend( + [ + f'', + text(50, 329, "2 ยท AGENT SCRIPT & PATCH", 11, t["purple"], cls="sans", weight="700"), + f'', + text(62, 372, "$ analyze_trace.py spikes/window-1.jsonl", 12, t["text"]), + text(62, 400, "โ†’ 14.2 ms idle ยท 68% GIL in tokenize()", 12, t["amber"]), + text(62, 428, "โ†’ patch: async HtoD + off-GIL tokenizer", 12, t["blue"], weight="600"), + ] + ) + # Connector arrow between Step 2 and Step 3 + parts.append( + f'' + ) + + # Bottom Right: Step 3 - Re-measure & Keep (RSI diff) + parts.extend( + [ + f'', + text(512, 329, "3 ยท RSI DIFF", 11, t["green"], cls="sans", weight="700"), + pill(846, 315, 66, 20, "KEEP โœ“", t["green"], t["green_soft"], stroke=t["green"], size=10.5), + # Metric 1: GPU idle share + text(512, 362, "GPU idle share", 12, t["text"], cls="sans", weight="600"), + text(910, 362, "34% โ†’ 6%", 12, t["green"], weight="700", anchor="end"), + text(512, 380, "before", 10, t["muted"]), + f'', + f'', + text(512, 395, "after", 10, t["muted"]), + f'', + f'', + # Metric 2: Step latency p95 + text(512, 420, "Step latency p95", 12, t["text"], cls="sans", weight="600"), + text(910, 420, "42.1 ms โ†’ 27.8 ms (-34%)", 12, t["green"], weight="700", anchor="end"), + text(512, 438, "before", 10, t["muted"]), + f'', + f'', + text(512, 453, "after", 10, t["muted"]), + f'', + f'', + ] + ) + + # Bottom RSI loop bar โ€” all 4 pills share uniform tinted fill + subtle border matching stages 1โ€“4 + loop_y = 480 + parts.extend( + [ + '' + + pill(88, loop_y, 186, 26, "1. Live profile (JSONL)", t["blue"], t["blue_soft"], stroke=t["blue"], stroke_opacity="0.35", size=11, cls="sans") + + "", + text(286, loop_y + 17, "โ†’", 14, t["muted"], cls="sans", anchor="middle"), + '' + + pill(298, loop_y, 174, 26, "2. Slice & diagnose", t["amber"], t["amber_soft"], stroke=t["amber"], stroke_opacity="0.35", size=11, cls="sans") + + "", + text(484, loop_y + 17, "โ†’", 14, t["muted"], cls="sans", anchor="middle"), + '' + + pill(496, loop_y, 152, 26, "3. Patch code", t["purple"], t["purple_soft"], stroke=t["purple"], stroke_opacity="0.35", size=11, cls="sans") + + "", + text(660, loop_y + 17, "โ†’", 14, t["muted"], cls="sans", anchor="middle"), + '' + + pill(672, loop_y, 200, 26, "4. Re-verify & repeat โ†ป", t["green"], t["green_soft"], stroke=t["green"], stroke_opacity="0.35", size=11, cls="sans") + + "", + ] + ) -def render(theme_name: str, animated: bool = True) -> str: - t = THEMES[theme_name] - body = [ - f'', - f'', - '' - '', - text(WIDTH / 2, 47, "Why is PID 4242 slow?", 14, t["muted"], cls="sans", anchor="middle"), - '', - command(90, "xprobe measure --pid 4242 --triage --duration-ms 2000", "cmd1", t), - finding(130, 1, "CPU_HOTSPOT", "libgomp worker spinning: 77% of sampled stacks", 0.76, t["cpu"], "find1", t), - finding(174, 2, "GPU_KERNEL_DOMINANT", "ampere_sgemm_128x64_nn: all kernel time, GPU busy 54%", 0.54, t["gpu"], "find2", t), - finding(218, 3, "GPU_CLOCK_LIMITED", "sw_power_cap under load", None, t["env"], "find3", t), - f'{text(48, 262, "โ†’ each finding ships a ready next spec", 13, t["prompt"])}', - command(304, "xprobe measure --spec next.json", "cmd2", t), - timeline(t), - f'' - f'{text(WIDTH / 2, 494, "Two commands. Bounded capture. No daemon. Evidence an agent can read.", 15, t["text"], cls="sans", weight="600", anchor="middle")}' - "", - "", - ] return ( f'' - "xprobe: triage a slow process, then measure the exact latency" - "A terminal runs xprobe triage on a PyTorch CUDA process. Ranked " - "findings show a CPU hotspot, a dominant GPU kernel, and power-capped GPU clocks. " - "A second command measures request to launch 1.14 ms, launch to kernel 99 " - "microseconds, and kernel duration 1.2 microseconds on CPU and GPU timelines." - + (f"" if animated else - f"") - + "".join(body) + 'xprobe: live CPU, Python, and CUDA profiling inside an RSI loop' + 'Live xprobe captures align a 14.2 ms GPU idle bubble with Python GIL ' + 'stacks on CLOCK_MONOTONIC, feed JSONL into an agent analysis script, and verify an ' + 'illustrative RSI optimization that drops GPU idle share from 34% to 6% and step p95 ' + 'from 42.1 ms to 27.8 ms.' + f"" + + "".join(parts) + "\n" ) def social_card() -> str: - """A 1280x640 repository social preview built from the final frame.""" + """A 1280x640 repository social preview built from the static dark frame.""" t = THEMES["dark"] - flow = render("dark", animated=False).split(">", 1)[1].rsplit("", 1)[0] - flow = flow.replace('", 1)[1].rsplit("", 1)[0] + flow = flow.replace( + '' f'' - f'' - + text(64, 96, "xprobe", 56, t["text"], cls="sans", weight="700") - + text(64, 140, "Why is my CPU, Python, or CUDA process slow? Two commands.", 26, t["muted"], cls="sans") - + f'{flow}' + f'' + + text(64, 86, "xprobe", 54, t["text"], cls="sans", weight="700") + + text(64, 128, "ML infra profiler for AI agents โ€” minimizing friction on the path to RSI.", 25, t["muted"], cls="sans") + + f'{flow}' + "\n" ) diff --git a/scripts/verify-public-release.sh b/scripts/verify-public-release.sh index e378abd..e6393c7 100755 --- a/scripts/verify-public-release.sh +++ b/scripts/verify-public-release.sh @@ -7,7 +7,7 @@ if [[ $# -ne 1 ]]; then fi version=${1#v} -[[ ${version} =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { +[[ ${version} =~ ^[0-9]+\.[0-9]+\.[0-9]+(-dev\.[0-9]+)?$ ]] || { echo "invalid release version: ${version}" >&2 exit 2 } @@ -91,7 +91,7 @@ verify_agent() { local agent=$1 local major=$2 local dynamic - dynamic=$(readelf -d "${agent}") + dynamic=$(LC_ALL=C readelf -d "${agent}") grep -Fq "Shared library: [libcupti.so.${major}]" <<<"${dynamic}" || { echo "${agent} is not linked to libcupti.so.${major}" >&2 exit 1 diff --git a/skills/xprobe-measure-latency/SKILL.md b/skills/xprobe-measure-latency/SKILL.md deleted file mode 100644 index 638fb7b..0000000 --- a/skills/xprobe-measure-latency/SKILL.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -name: xprobe-measure-latency -description: Find where time goes in a live or recorded Linux CPU, CPython, or NVIDIA CUDA workload with bounded xprobe evidence. Use to triage an unknown slow process, measure a known function, syscall, CUDA API, kernel, transfer, NVTX range, or event-to-event latency, measure several related latencies at once, compare workers or regressions, inspect an existing xprobe artifact, or install and repair xprobe. ---- - -# Profile workloads with xprobe - -Reach an answer in two commands: triage, then one exact measurement. Choose the -shortest route the evidence allows; never collect every source by checklist. - -Commands print JSON whenever stdout is not a terminal. Measurement, graph, and -triage results use schema version `3.0`; other records and Event JSONL use -`2.0`. Treat malformed output or an unknown version as an error. - -## Route the task - -- **Existing artifact**: analyze it offline. Re-correlate Event JSONL with - `measure --input`; summarize GPU activity with `scripts/analyze_trace.py`. - Skip installation, `doctor`, `discover`, and live attachment unless a new - capture is required. -- **Unknown live workload**: identify the process, then triage one - representative cycle (one request, batch, or iteration, after warmup): - - ```bash - xprobe measure --pid "$PID" --triage --duration-ms 2000 - ``` - - Read `findings` from rank 1. A finding's `next.spec` is a ready measurement: - write it to a file and run `xprobe measure --spec next.json`. An - `environment` finding (throttling, runqueue wait, GPU clock limits) is a - conclusion, not a cue to profile code. -- **Known boundary**: skip triage. Run read-only `validate` when injection or - selector resolution is uncertain, then one bounded `measure`. -- **Several related boundaries** (request โ†’ launch โ†’ kernel): one measurement - graph captures every edge at once; see [selectors](references/selectors.md). -- **CUDA worker unknown**: `discover --pid ROOT` lists CUDA context holders; pick - from workload evidence. For several workers read - [multi-process](references/multi-process.md). -- **Missing CLI, container target, or environment failure**: read - [setup](references/setup.md). Run `doctor` only when capability is unknown or - a command reports an environment failure. - -Read [interpreting results](references/interpreting.md) before stating a -latency claim, and [selectors](references/selectors.md) before writing a -selector yourself. - -## Read results - -- Triage: check `sources` before trusting silence. An `unavailable` source and - every `not_covered` item are questions triage did not answer. Shares are - estimates; blocked time includes idle waiting. -- Exact results: start from `quality.verdict` and its issues. `caution` limits - the claim; say why. Rank exemplars (min, p50, p90, p99, max) are inline; the - full capture is at `evidence.artifact.path`. -- A command error is not a result. Errors keep structured `details`, including - any preserved artifact path; follow `hints` instead of retrying blindly. - -## Dig deeper when the first pass is inconclusive - -Escalate one step at a time, each driven by the previous result; details are in -[deep dive](references/deep-dive.md). - -1. **Triage found nothing actionable**: fix `unavailable` sources first, then - widen the window to cover a slow cycle, or run the focused inventory triage - omits (memcpy/memset activity, larger CPU sample, `-X perf` for Python). -2. **A span is slow but unexplained**: split it with a measurement graph into - sub-edges, and follow sampled stacks down to a callee boundary. -3. **Only the tail is slow, or the GPU has bubbles**: rank the slowest pairs or - idle gaps and list what ran around them with `scripts/analyze_trace.py`; - re-correlate offline with `measure --input` before recapturing. -4. **Threads are blocked**: measure the dominant syscall exactly, check Python - GC lifecycles, and treat lock or I/O attribution as not yet covered. -5. **It is a regression**: run the same spec on the baseline and compare - distributions and quality, not single means. - -Stop escalating when a step adds no new boundary; report what is known, what -remains unexplained, and which hand-off tool fits. - -## Keep these invariants - -- Identify a live process by PID plus procfs start time; never reuse a PID-only - choice after a restart. -- Bound every capture by samples or duration, timeout, and capacity. -- Before CUDA injection, tell the user that `measure` will ptrace the process - and leave the CUPTI shared object mapped. NVTX needs the Agent at startup. -- Keep process and CUDA stream identity in every claim. Summed concurrent GPU - time is not wall time, sampled shares are estimates, and temporal correlation - is not exact causality. -- Record an application baseline for regressions or overhead claims. - -## Stop or hand off - -Stop on target exit or reuse, permission failure, invalid selectors, drops, or -a clock failure that invalidates the claim; report the structured error. Once -time is isolated inside one GPU kernel, hand off to NCU or PC sampling; once it -is isolated in code without an observable boundary, use a runtime-specific -profiler. Do not claim Python semantics when `python_status` says otherwise. diff --git a/skills/xprobe-measure-latency/agents/openai.yaml b/skills/xprobe-measure-latency/agents/openai.yaml deleted file mode 100644 index ffe2e5f..0000000 --- a/skills/xprobe-measure-latency/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Xprobe Workload Profiling" - short_description: "Triage and measure CPU, Python, and GPU latency" - default_prompt: "Use $xprobe-measure-latency to triage this workload and measure where its time goes." diff --git a/skills/xprobe-measure-latency/examples/coarse-kernel-inventory.json b/skills/xprobe-measure-latency/examples/coarse-kernel-inventory.json deleted file mode 100644 index 8cebf11..0000000 --- a/skills/xprobe-measure-latency/examples/coarse-kernel-inventory.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "schema_version": "2.0", - "name": "coarse_kernel_inventory", - "target": { - "pid": 1234, - "process_start_time": 987654 - }, - "start_selector": "cuda:kernel_start", - "end_selector": "cuda:kernel_end", - "match_policy": "exact", - "samples": null, - "duration_ms": 1000, - "timeout_ms": 30000, - "max_events": null, - "measurement_mode": "aggregate", - "max_groups": 4096 -} diff --git a/skills/xprobe-measure-latency/examples/coarse-memcpy-inventory.json b/skills/xprobe-measure-latency/examples/coarse-memcpy-inventory.json deleted file mode 100644 index 63afa08..0000000 --- a/skills/xprobe-measure-latency/examples/coarse-memcpy-inventory.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "schema_version": "2.0", - "name": "coarse_memcpy_inventory", - "target": { - "pid": 1234, - "process_start_time": 987654 - }, - "start_selector": "cuda:memcpy_start", - "end_selector": "cuda:memcpy_end", - "match_policy": "exact", - "samples": null, - "duration_ms": 1000, - "timeout_ms": 30000, - "max_events": null, - "measurement_mode": "aggregate", - "max_groups": 64 -} diff --git a/skills/xprobe-measure-latency/examples/cpu-hotspot-inventory.json b/skills/xprobe-measure-latency/examples/cpu-hotspot-inventory.json deleted file mode 100644 index f7110b4..0000000 --- a/skills/xprobe-measure-latency/examples/cpu-hotspot-inventory.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "schema_version": "2.0", - "name": "cpu_hotspot_inventory", - "target": { - "pid": 1234, - "process_start_time": 987654 - }, - "sample_event": "cpu_clock", - "frequency_hz": 99, - "duration_ms": 1000, - "timeout_ms": 30000, - "max_samples": 10000, - "max_groups": 256, - "stack_depth": 64, - "max_threads": 1024 -} diff --git a/skills/xprobe-measure-latency/examples/cuda-api-duration.json b/skills/xprobe-measure-latency/examples/cuda-api-duration.json deleted file mode 100644 index 8bb7aea..0000000 --- a/skills/xprobe-measure-latency/examples/cuda-api-duration.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "schema_version": "2.0", - "name": "cuda_stream_synchronize_duration", - "target": { - "pid": 1234, - "process_start_time": 987654 - }, - "start_selector": "cuda:runtime_api:cudaStreamSynchronize:entry", - "end_selector": "cuda:runtime_api:cudaStreamSynchronize:exit", - "match_policy": "exact", - "samples": 100, - "duration_ms": null, - "timeout_ms": 30000, - "max_events": 1000 -} diff --git a/skills/xprobe-measure-latency/examples/host-function-span.json b/skills/xprobe-measure-latency/examples/host-function-span.json deleted file mode 100644 index 1b586d8..0000000 --- a/skills/xprobe-measure-latency/examples/host-function-span.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "schema_version": "2.0", - "name": "host_function_span", - "target": { - "pid": 1234, - "process_start_time": 987654 - }, - "start_selector": "uprobe:/srv/app/server:handle_request:entry", - "end_selector": "uprobe:/srv/app/server:handle_request:return", - "match_policy": "stack_nested", - "samples": 100, - "duration_ms": null, - "timeout_ms": 30000, - "max_events": 1000 -} diff --git a/skills/xprobe-measure-latency/examples/memcpy-duration.json b/skills/xprobe-measure-latency/examples/memcpy-duration.json deleted file mode 100644 index 1864ccb..0000000 --- a/skills/xprobe-measure-latency/examples/memcpy-duration.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "schema_version": "2.0", - "name": "host_to_device_memcpy_duration", - "target": { - "pid": 1234, - "process_start_time": 987654 - }, - "start_selector": "cuda:memcpy_start:kind=HtoD", - "end_selector": "cuda:memcpy_end:kind=HtoD", - "match_policy": "exact", - "samples": 100, - "duration_ms": null, - "timeout_ms": 30000, - "max_events": 1000 -} diff --git a/skills/xprobe-measure-latency/examples/python-gc-duration.json b/skills/xprobe-measure-latency/examples/python-gc-duration.json deleted file mode 100644 index cdab62b..0000000 --- a/skills/xprobe-measure-latency/examples/python-gc-duration.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "schema_version": "2.0", - "name": "python_gc_duration", - "target": { - "pid": 1234, - "process_start_time": 987654 - }, - "start_selector": "python:gc_start", - "end_selector": "python:gc_end", - "match_policy": "exact", - "samples": 100, - "duration_ms": null, - "timeout_ms": 30000, - "max_events": 1000 -} diff --git a/skills/xprobe-measure-latency/examples/request-to-first-kernel.json b/skills/xprobe-measure-latency/examples/request-to-first-kernel.json deleted file mode 100644 index 2841abf..0000000 --- a/skills/xprobe-measure-latency/examples/request-to-first-kernel.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "schema_version": "2.0", - "name": "request_to_first_kernel", - "target": { - "pid": 1234, - "process_start_time": 987654 - }, - "start_selector": "uprobe:/srv/app/server:request_begin:entry", - "end_selector": "cuda:kernel_start:name~vector_add.*", - "match_policy": "first_after", - "samples": 100, - "duration_ms": null, - "timeout_ms": 30000, - "max_events": 2000 -} diff --git a/skills/xprobe-measure-latency/examples/same-stream-kernel-gap.json b/skills/xprobe-measure-latency/examples/same-stream-kernel-gap.json deleted file mode 100644 index da047d5..0000000 --- a/skills/xprobe-measure-latency/examples/same-stream-kernel-gap.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "schema_version": "2.0", - "name": "same_stream_kernel_gap", - "target": { - "pid": 1234, - "process_start_time": 987654 - }, - "start_selector": "cuda:kernel_end:name~^producer$", - "end_selector": "cuda:kernel_start:name~^consumer$", - "match_policy": "stream_order", - "samples": 100, - "duration_ms": null, - "timeout_ms": 30000, - "max_events": 2000 -} diff --git a/skills/xprobe-measure-latency/examples/syscall-duration.json b/skills/xprobe-measure-latency/examples/syscall-duration.json deleted file mode 100644 index a5b956e..0000000 --- a/skills/xprobe-measure-latency/examples/syscall-duration.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "schema_version": "2.0", - "name": "mmap_duration", - "target": { - "pid": 1234, - "process_start_time": 987654 - }, - "start_selector": "syscall:mmap:entry", - "end_selector": "syscall:mmap:exit", - "match_policy": "exact", - "samples": 100, - "duration_ms": null, - "timeout_ms": 30000, - "max_events": 1000 -} diff --git a/skills/xprobe-measure-latency/examples/syscall-inventory.json b/skills/xprobe-measure-latency/examples/syscall-inventory.json deleted file mode 100644 index 61dff2f..0000000 --- a/skills/xprobe-measure-latency/examples/syscall-inventory.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "schema_version": "2.0", - "name": "syscall_inventory", - "target": { - "pid": 1234, - "process_start_time": 987654 - }, - "duration_ms": 1000, - "timeout_ms": 30000, - "max_groups": 256, - "max_inflight": 1024 -} diff --git a/skills/xprobe-measure-latency/references/deep-dive.md b/skills/xprobe-measure-latency/references/deep-dive.md deleted file mode 100644 index 67a1959..0000000 --- a/skills/xprobe-measure-latency/references/deep-dive.md +++ /dev/null @@ -1,124 +0,0 @@ -# Dig deeper - -Use this when triage or the first exact measurement does not explain the -latency. Each step names the evidence that triggers it, the next bounded -command, and when to stop. Escalate one step at a time. - -## Triage found nothing actionable - -1. **Missing sources.** Read every `sources` entry. An `unavailable` syscall or - CPU source usually means missing BPF or perf permission; fix it through - [setup](setup.md) and triage again. Silence from a missing source is not - evidence of absence. -2. **Window missed the slow work.** Triage covers one window. If the problem is - intermittent or per-request, drive one slow request during the window or - lengthen `--duration-ms` to cover several cycles. -3. **Triage omits transfers.** GPU activity in triage covers kernels only. - Inventory copies and memsets explicitly; groups with `src_memory` or - `dst_memory` of `pageable` point at host buffers to pin: - - ```bash - xprobe measure --pid "$PID" --from cuda:memcpy_start --to cuda:memcpy_end \ - --match exact --aggregate --duration-ms 2000 --max-groups 256 - ``` - -4. **CPU time is spread thin.** A `CPU_BOUND` finding without a single hotspot - needs more samples or semantic frames. Raise frequency and duration, and for - CPython 3.12+ restart the target with `-X perf` so samples resolve to Python - functions: - - ```bash - xprobe measure --pid "$PID" --cpu-sample --duration-ms 5000 \ - --frequency-hz 499 --max-samples 50000 --max-groups 512 - ``` - - Read `stack_groups`, not only `hotspots`: inclusive callers show which - high-level operation owns the spread-out leaf time. - -## A span is slow but unexplained - -Split the span into sub-edges with one measurement graph instead of repeated -single captures. Choose intermediate endpoints from the sampled stacks (callee -`entry_selector_hint` and `return_selector_hint`), CUDA API boundaries, or NVTX -ranges, then compare edge p50/p99: - -```json -"edges": [ - {"name": "request_to_launch", "from": "request", "to": "launch_exit", - "match_policy": "first_after", "samples": 200}, - {"name": "launch_to_kernel", "from": "launch_exit", "to": "kernel_start", - "match_policy": "exact", "samples": 200} -] -``` - -The edge whose latency carries the regression is the next span to split. Edges -are independent pairings; they show where time is spent per edge, not that one -edge caused another. - -For a host function, descend one stack level at a time: measure the function -with `stack-nested`, then the heaviest callee from the CPU sample stack groups. -Stop when a callee no longer carries most of the parent's time. - -## Only the tail is slow - -Measure with `--evidence full`, then rank the slowest pairs and list -everything that happened around the slowest one: - -```bash -scripts/analyze_trace.py "$ARTIFACT" --measurement result.json \ - --slice-outlier 1 --window-ms 2 -``` - -`outliers.slowest` gives each slow pair's thread, stream, and correlation ID; -`slice` lists GC lifecycles, syscalls, API calls, copies, and kernels inside -the padded window. Report them as concurrent, not causal. Re-correlate the -same artifact through `measure --input` before recapturing. If the tail is -rare, raise `samples` so p99 rests on a few hundred pairs. - -## The GPU has bubbles - -`gpu.top_idle_gaps` ranks spans where a device ran no captured activity; -`streams[].top_gaps` ranks gaps between consecutive kernels on one stream. -Slice the largest bubble to see what the host did meanwhile: - -```bash -scripts/analyze_trace.py "$ARTIFACT" --slice-gap 1 --window-ms 1 -``` - -Gaps are between captured activities only: a narrow kernel selector hides the -kernels it filtered out, so capture all kernels on the stream before calling a -gap idle. - -## Threads are blocked - -Triage reports how long threads were blocked, not where. Narrow it: - -- `SYSCALL_TIME` points at a syscall; measure it exactly - (`syscall:NAME:entry` to `syscall:NAME:exit`). `futex` time indicates lock - or condition waits; `poll`, `epoll_wait`, `read`, and `recvfrom` indicate - I/O or idle event loops, so compare against the workload's expected idle. -- In CPython, validate `python:gc_start` to `python:gc_end` and measure GC - lifecycles when blocked or tail time coincides with allocation-heavy phases. -- In CUDA workloads, measure `cudaStreamSynchronize` or `cudaDeviceSynchronize` - entry to exit; long synchronization means the CPU waits on the GPU, so return - to the GPU findings. -- Lock owner and off-CPU stack attribution are not covered by this release; - say so instead of guessing. - -## It is a regression - -Run the same spec or graph on the baseline and the regressed build or host, -with the same workload phase, window, and bounds. Compare per-edge -distributions (p50, p90, p99), matched counts, and quality verdicts. A changed -`quality` issue or capacity pressure on one side makes the comparison -unreliable; fix that before attributing the difference. - -## Hand off - -- Time isolated inside one kernel: NCU or PC sampling for occupancy, memory, - and instruction stalls. -- Time isolated in code without an attachable boundary (JIT, generated, or - inlined code): a runtime-specific profiler or added instrumentation such as - an NVTX range or an exported function boundary. -- Python semantics unavailable (`python_status` not `active`): py-spy or the - framework profiler, reported as a separate tool's evidence. diff --git a/skills/xprobe-measure-latency/references/interpreting.md b/skills/xprobe-measure-latency/references/interpreting.md deleted file mode 100644 index 6c1aff6..0000000 --- a/skills/xprobe-measure-latency/references/interpreting.md +++ /dev/null @@ -1,83 +0,0 @@ -# Interpreting results - -Each result type has its own schema under `schemas/`; field meanings live -there. This page covers how to read them without overclaiming. - -## Triage - -- `findings` are ranked by `impact_share`, an estimated share of the window. - `null` means the evidence cannot bound the impact (clock limits, PCIe link); - such findings rank last but may still matter. -- `threads.top_threads` splits each whole-window thread into on-CPU, runqueue, - and blocked time. Blocked time includes idle waiting, so a mostly idle - thread pool is normal; read the busiest threads, not process totals. -- `gpu_devices` utilization is NVML's device-wide sampled estimate and includes - other processes on the GPU. `gpu_activity` lists the target's kernels with - summed durations, which double-count overlap. -- Full CPU, syscall, and GPU inventories are written to the artifacts listed in - `sources`; read them when the inline top five are not enough. - -## Exact measurements and graphs - -Start from `quality.verdict`: - -| Issue | Severity | Meaning | -| --- | --- | --- | -| `TIMED_OUT`, `INCOMPLETE_SESSION` | caution | Partial statistics | -| `HEURISTIC_CORRELATION`, `AMBIGUOUS_CORRELATION`, `AMBIGUOUS_PAIRS` | caution | Pairing is temporal or not unique | -| `UNMATCHED_EVENTS` | caution when unmatched exceed matched, else info | Selector scope or window edges | -| `CLOCK_ERROR_LARGE` | caution | Clock error โ‰ฅ 10% of p50 | -| `CLOCK_ERROR_UNAVAILABLE` | info | CUPTI gave no interpolation bound | -| `FEW_SAMPLES` | info | Tail ranks rest on < 100 pairs | - -Drops, no matched pairs, target changes, incomplete collection, and clock -misalignment are command errors, never results. Inspect the rank exemplars for -selector scope, thread or stream identity, and correlation IDs; use -`--evidence full` or the artifact when a claim depends on individual pairs. - -`completed` means the samples or duration bound was reached; `timed_out` is -partial. `duration-ms` measures from the first selected event and starts after -the capture is armed, so finish warmup before invoking `measure`. - -## Inventories - -CPU sampling, syscall aggregation, and GPU aggregation are separate contracts; -do not compare their capacities or completeness as one collector. - -- CPU samples: check lost samples, stack truncation, thread coverage, group - table use, and resolved native, Python, and unresolved frame counts before - using hotspot names. Proportions are sampled estimates. `python_status` - `inactive` or `unsupported` means native fallback; native frames remain - valid, Python semantics are not claimed. -- Syscall aggregation: durations are exact for matched lifecycles, but groups - have no order or percentiles; check unmatched, inflight, and drops. -- GPU aggregation: count, summed, min, max, and mean duration and bytes per - group; no ordering, overlap, or correlation. Memcpy groups split by - `src_memory` and `dst_memory`: a `pageable` host side means staged, - synchronous copies that pinned memory would avoid. - -## GPU concurrency - -Group GPU evidence by device, context, and stream. Events on different streams -overlap, and their order is not a request relationship. For wall-clock GPU -busy time, run the bundled analyzer on an exact Event JSONL artifact: - -```bash -scripts/analyze_trace.py capture.jsonl > capture-analysis.json -``` - -Use `gpu.busy_union_ns` for wall-clock busy time and `overlap_factor` to see -concurrency; summed activity is not wall time when the factor exceeds 1. -`launch_variants` separates one kernel name by grid and block shape, and -`streams` reports per-stream counts and the largest adjacent gaps. -`memcpy.by_kind` adds achieved `bandwidth_gbps` and `avg_bytes` per copy -direction; compare them with the PCIe link reported by triage. The analyzer -describes one capture window; it never relates distinct windows or assigns -work to requests. - -## Perturbation - -Profiling changes the workload. Record an application-level baseline before -and after, report whether the CUPTI Agent was injected (it stays mapped but -disabled), and treat a materially slower profiled run as a reason to narrow -selectors or shorten the window rather than as the answer. diff --git a/skills/xprobe-measure-latency/references/multi-process.md b/skills/xprobe-measure-latency/references/multi-process.md deleted file mode 100644 index a7f45f7..0000000 --- a/skills/xprobe-measure-latency/references/multi-process.md +++ /dev/null @@ -1,41 +0,0 @@ -# Multi-process workloads - -xprobe has no multi-process command. Selection and concurrency stay in the -agent; each `validate` and `measure` targets one PID plus process start time. - -## Select workers - -Run `discover --pid ROOT` after warmup and keep the candidate records. Select -from application ownership, command line, rank, and GPU UUID, not merely -because a process holds a CUDA context. For workers that configuration and -evidence show to be homogeneous, triage one representative worker and reuse its -selectors; otherwise treat each class separately. - -Name every spec, result, stderr log, and artifact with the worker's -`target.pid` and `target.process_start_time`. Never reuse an artifact path -across workers or attempts. - -## Validate, then capture concurrently - -Write one spec per worker with its own bounds. Validate each and require that -the response's `target` exactly matches the selected identity; a mismatch or -failure removes that worker rather than substituting a new PID. Disclose any -`injection_required` worker before measuring. - -Launch one bounded `measure --spec` per worker as native concurrent tool calls -so the windows cover the same workload cycle. Wait for every command. Do not -cancel sibling commands when one fails; mark the overall experiment incomplete -and report usable per-worker results separately. - -On one worker, a CPU sample inventory and GPU aggregate may also run as two -concurrent commands with separate bounds and outputs. Prefer triage when one -window must cover both. - -## Interpret without merging - -Read each result's quality independently and compare per-worker distributions -only when selectors, phase, and device assignment match. Do not concatenate -artifacts and correlate across processes: correlation IDs, streams, and threads -are process-scoped, and overlapping timestamps do not establish a relationship. -Concurrent captures perturb shared resources; record a workload baseline and -reduce the worker set if throughput changes materially. diff --git a/skills/xprobe-measure-latency/references/selectors.md b/skills/xprobe-measure-latency/references/selectors.md deleted file mode 100644 index 73373b9..0000000 --- a/skills/xprobe-measure-latency/references/selectors.md +++ /dev/null @@ -1,97 +0,0 @@ -# Selectors, policies, and specs - -Prefer selectors that xprobe emitted: triage `next.spec`, inventory -`*_selector_hint` fields, and analyzer `selector_hint`. Write one by hand only -when no emitted hint covers the boundary, and pass it through `validate`. - -## Selector syntax - -| Source | Selector | -| --- | --- | -| Native function | `uprobe:::entry\|return` | -| C++ signature with `::` | `uprobe::symbol=:entry\|return` | -| Stripped or local code | `uprobe::+0x:entry\|return` | -| Syscall | `syscall::entry\|exit` | -| Kernel tracepoint | `tracepoint::` (identity and timestamp only) | -| CPython GC | `python:gc_start`, `python:gc_end` | -| CUDA API | `cuda:runtime_api\|driver_api::entry\|exit` | -| Any kernel launch | `cuda:launch_api:entry\|exit` (Runtime and Driver launch APIs) | -| GPU activity | `cuda:kernel_start\|kernel_end[:name~REGEX]`, `cuda:memcpy_start\|memcpy_end[:kind=HtoD\|DtoH\|DtoD\|HtoH\|PtoP]`, `cuda:memset_start\|memset_end` | -| NVTX range | `cuda:nvtx_range_start\|nvtx_range_end:name~REGEX` | - -CUDA API selectors need a concrete Runtime or Driver API name; for launch -latency use `cuda:launch_api`, which also covers Triton and other Driver API -launchers and costs two Agent filters. Kernel and NVTX -regexes are filtered in the CUPTI hot path only when they reduce to an exact, -prefix, suffix, or contains literal under 128 bytes; anything else is applied -after a broader capture and fills capacity faster. Escape regex metacharacters. -A `name_complete: false` kernel group carries a truncated prefix: keep its -prefix hint and do not add an end anchor. - -## Derive a native boundary - -Use a CPU sample hotspot's `entry_selector_hint` and `return_selector_hint` -first. Without one, inspect the mapped object of this target: - -```bash -readlink -f "/proc/$PID/exe" -grep -F ' r-xp ' "/proc/$PID/maps" -readelf -Ws /path/to/object -nm -D --defined-only --demangle /path/to/object -``` - -Use a symbol when one exists; otherwise derive a file offset with `readelf` or -`objdump`. Never reuse a runtime virtual address as a file offset, and never -reuse a C++ signature, offset, or generated kernel name across builds without -validating it again. - -For eager PyTorch, prefer sampled boundaries in CPython, `torch._C`, or a -loaded libtorch object, such as `at::_ops::::call(...)` with -`stack-nested`. After `torch.compile` or Triton warmup, fused work no longer -sits inside eager operator boundaries: select by kernel name instead. Generated -CPU code without a file-backed ELF symbol cannot be a uprobe target. - -For CPython GC, check capability, not the process name: `validate` resolves the -USDT markers in the mapped interpreter or `libpython` and rejects builds without -them. Do not substitute a guessed symbol. - -```bash -xprobe validate --pid "$PID" --from python:gc_start --to python:gc_end --match exact -``` - -## Choose a policy - -| Policy | Use for | Confidence | -| --- | --- | --- | -| `exact` | Same CUPTI correlation ID (API โ†” its kernel or copy), kernel/copy start โ†” end, NVTX range ID, one syscall's entry โ†” exit on a thread, CPython GC start โ†” end | exact | -| `stack-nested` | Entry โ†” return of one host function per thread | high | -| `stream-order` | Activity end โ†” next start on one device stream | high | -| `first-after`, `nearest` | Host marker โ†” GPU activity and other unrelated sources | heuristic | - -`validate` reports `policy_recommendation` with a reason and the compatible -set; xprobe never changes the requested policy silently. Heuristic policies -never establish request-level causality. - -## Specs - -A single-edge `MeasurementSpec` (schema `2.0`) pins the target identity and -bounds; triage emits ready ones, and `examples/` holds templates. Run it with -`measure --spec FILE`. - -A measurement graph (schema `3.0`) names endpoints once and measures up to -eight edges from one capture. See `examples/request-path-graph.json`. Rules: - -- 1โ€“8 endpoints and 1โ€“8 edges; every edge sets `samples` or the graph sets - `duration_ms`; `max_events` bounds the whole capture. -- At most two syscall, tracepoint, or USDT endpoints; uprobe endpoints are not - limited further; CUDA endpoints share eight Agent filters. -- `validate --spec graph.json` reports issues scoped to the graph, an endpoint, - or an edge. Any failing edge fails `measure`; the artifact is still written. - -## Capacity - -Start an exact capture with modest record headroom: -`max_events โ‰ˆ 2 ร— samples ร— (records per start + records per end)` plus -expected unmatched records. Triage specs size capacity from the observed rate. -On `EVENT_RATE_TOO_HIGH`, narrow the selector before raising `max_events`, and -keep the window representative. diff --git a/skills/xprobe-measure-latency/references/setup.md b/skills/xprobe-measure-latency/references/setup.md deleted file mode 100644 index 426330b..0000000 --- a/skills/xprobe-measure-latency/references/setup.md +++ /dev/null @@ -1,90 +0,0 @@ -# Setup - -The user installs this Skill once; the agent bootstraps and verifies the CLI. -Offline analysis of an existing artifact needs no CLI. - -## Check and bootstrap xprobe - -This Skill supports xprobe `0.6.x`. Install the matching release when the CLI is -absent, reports another version, or fails a required capability: - -```bash -command -v xprobe >/dev/null 2>&1 && xprobe --version -curl --proto '=https' --tlsv1.2 -fsSL \ - https://raw.githubusercontent.com/itdevwu/xprobe/v0.6.3/install.sh \ - -o /tmp/xprobe-install.sh -sh /tmp/xprobe-install.sh -export PATH="$HOME/.local/bin:$PATH" -xprobe --version -xprobe doctor -``` - -The bootstrap verifies the archive and installs under `~/.local`; pass -`--prefix DIR` for another root and export its `bin`. Where pip is the natural -installer, `pip install "xprobe==$VERSION"` installs the same CLI and Agents into -the active environment. Surface PATH, -permission, driver, CUDA, or CUPTI failures from `doctor` details; do not -measure on an unverified installation. CUDA is needed only for GPU selectors. - -## Containerized live target - -A host-side `measure` cannot inject into a target with a different mount -namespace. Run xprobe in the application container itself, or through a -launcher that enters both its PID and mount namespaces; a sidecar is not -equivalent. Do not guess a pod, container, or PID: identify the container from -workload evidence first. - -Inside, resolve the namespace-local PID and its `/proc/PID/stat` start time -again, rerun `doctor` and `validate` there, and write outputs to a path shared -with the caller. Entering a namespace does not add capabilities the container -was not granted: report missing ptrace, perf, BPF, NVIDIA device, or CUPTI -access as an environment failure instead of falling back to host-side -injection. - -## Build locally when the release cannot run - -The release archive needs host glibc 2.34 or newer. Otherwise build the -matching source with the host glibc: - -```bash -git clone --depth 1 --branch v0.6.3 https://github.com/itdevwu/xprobe.git -cd xprobe -mamba env create --file environment.yml -mamba run -n xprobe-dev just build -export PATH="$PWD/target/debug:$PATH" -``` - -That suffices for CPU work. For GPU work, build one Agent against the target's -CUDA 12 or 13 toolkit and export it: - -```bash -mamba run -n xprobe-dev env CUDA_PATH=/opt/cuda-12 cmake -S . -B build/cuda12 -G Ninja \ - -DXPROBE_BUILD_BPF=ON -DXPROBE_REQUIRE_CUPTI=ON -DXPROBE_CUDA_MAJOR=12 -mamba run -n xprobe-dev cmake --build build/cuda12 --target xprobe-bpf xprobe-cupti -export XPROBE_CUPTI_AGENT_PATH="$PWD/build/cuda12/cupti/libxprobe-cupti.so" -``` - -CUDA/CUPTI majors other than 12 or 13 are not supported. Do not use -`scripts/package-release.sh` for a local build; it enforces the release glibc -ceiling. - -## NVTX ranges - -Online injection cannot attach to an already initialized NVTX dispatch. Restart -the target with the Agent configured before its first NVTX call, record the new -PID and start time, and validate again: - -```bash -NVTX_INJECTION64_PATH="$XPROBE_CUPTI_AGENT_PATH" python serve.py -``` - -## Repair the Skill - -When Skill files are missing or mismatched, reinstall the whole directory; its -references, examples, and analyzer are part of the contract: - -```bash -npx skills@1 add \ - https://github.com/itdevwu/xprobe/tree/v0.6.3/skills/xprobe-measure-latency \ - --global -``` diff --git a/skills/xprobe-measure-latency/scripts/analyze_trace.py b/skills/xprobe-measure-latency/scripts/analyze_trace.py deleted file mode 100755 index 9e32b12..0000000 --- a/skills/xprobe-measure-latency/scripts/analyze_trace.py +++ /dev/null @@ -1,629 +0,0 @@ -#!/usr/bin/env python3 -"""Summarize a bounded xprobe Event JSONL artifact. - -Beyond aggregate GPU timing, the report ranks idle gaps, optionally ranks the -slowest pairs of a measurement result, and can list every event inside a time -window ("vertical slice") around a gap, an outlier, or explicit timestamps. -Everything is descriptive: events inside a window are concurrent with it, not -proven causes. -""" - -import argparse -import collections -import json -import math -import pathlib -import re -import sys - - -ACTIVITY_TYPES = { - "gpu_kernel_start": ("kernel", "start"), - "gpu_kernel_end": ("kernel", "end"), - "gpu_memcpy_start": ("memcpy", "start"), - "gpu_memcpy_end": ("memcpy", "end"), - "gpu_memset_start": ("memset", "start"), - "gpu_memset_end": ("memset", "end"), -} - - -def percentile(values: list[int], percent: int) -> int | None: - if not values: - return None - ordered = sorted(values) - rank = max(1, math.ceil(percent * len(ordered) / 100)) - return ordered[rank - 1] - - -def duration_summary(values: list[int]) -> dict: - if not values: - return { - "count": 0, - "total_ns": 0, - "min_ns": None, - "p50_ns": None, - "p95_ns": None, - "max_ns": None, - } - return { - "count": len(values), - "total_ns": sum(values), - "min_ns": min(values), - "p50_ns": percentile(values, 50), - "p95_ns": percentile(values, 95), - "max_ns": max(values), - } - - -def interval_union_ns(intervals: list[tuple[int, int]]) -> int: - if not intervals: - return 0 - ordered = sorted(intervals) - union = 0 - current_start, current_end = ordered[0] - for start, end in ordered[1:]: - if start <= current_end: - current_end = max(current_end, end) - else: - union += current_end - current_start - current_start, current_end = start, end - return union + current_end - current_start - - -def dimensions(cuda: dict, field: str) -> tuple[int, int, int] | None: - value = cuda.get(field) - if value is None: - return None - return (value["x"], value["y"], value["z"]) - - -def activity_name(kind: str, cuda: dict) -> str: - if kind == "kernel": - return cuda.get("kernel_name") or "" - if kind == "memcpy": - return cuda.get("memcpy_kind") or "unknown" - return "memset" - - -def activity_key(kind: str, event: dict) -> tuple: - cuda = event.get("cuda") or {} - return ( - kind, - event.get("pid"), - cuda.get("device_id"), - cuda.get("context_id"), - cuda.get("stream_id"), - cuda.get("correlation_id"), - activity_name(kind, cuda), - ) - - -def pair_activities(events: list[dict]) -> tuple[list[dict], int, int]: - boundaries = [] - for event in events: - activity = ACTIVITY_TYPES.get(event.get("event_type")) - if activity is not None: - kind, boundary = activity - boundaries.append((event["timestamp_ns"], boundary != "start", kind, boundary, event)) - boundaries.sort(key=lambda item: (item[0], item[1])) - - starts: dict[tuple, collections.deque] = collections.defaultdict(collections.deque) - intervals = [] - unmatched_ends = 0 - for _, _, kind, boundary, event in boundaries: - key = activity_key(kind, event) - if boundary == "start": - starts[key].append(event) - continue - if not starts[key]: - unmatched_ends += 1 - continue - start = starts[key].popleft() - if start["clock_domain"] != event["clock_domain"]: - raise ValueError( - f"activity pair {start.get('event_id')} / {event.get('event_id')} " - "uses different clock domains" - ) - start_ns = start["timestamp_ns"] - end_ns = event["timestamp_ns"] - if end_ns < start_ns: - raise ValueError( - f"activity pair {start.get('event_id')} / {event.get('event_id')} " - "has a negative duration" - ) - cuda = start.get("cuda") or {} - intervals.append( - { - "kind": kind, - "name": activity_name(kind, cuda), - "pid": start.get("pid"), - "device_id": cuda.get("device_id"), - "context_id": cuda.get("context_id"), - "stream_id": cuda.get("stream_id"), - "start_ns": start_ns, - "end_ns": end_ns, - "duration_ns": end_ns - start_ns, - "grid": dimensions(cuda, "grid"), - "block": dimensions(cuda, "block"), - "bytes": cuda.get("bytes"), - } - ) - unmatched_starts = sum(len(queue) for queue in starts.values()) - return intervals, unmatched_starts, unmatched_ends - - -def selector_hint(name: str, names: list[str]) -> dict | None: - if name == "": - return None - escaped = re.escape(name) - if len(name) < 128: - regex = f"^{escaped}$" - scope = "exact_name" - else: - alternatives = [candidate for candidate in names if candidate != name] - candidates = [] - for length in range(min(16, len(name)), min(127, len(name)) + 1): - prefix = name[:length] - if all(not candidate.startswith(prefix) for candidate in alternatives): - candidates.append((length, f"^{re.escape(prefix)}.*", "prefix")) - break - suffix = name[-length:] - if all(not candidate.endswith(suffix) for candidate in alternatives): - candidates.append((length, f".*{re.escape(suffix)}$", "suffix")) - break - if not candidates: - return None - _, regex, filter_kind = min(candidates) - scope = f"{filter_kind}_unique_in_capture" - return { - "name_regex": regex, - "scope": scope, - "start_selector": f"cuda:kernel_start:name~{regex}", - "end_selector": f"cuda:kernel_end:name~{regex}", - } - - -def dimensions_object(value: tuple[int, int, int] | None) -> dict | None: - if value is None: - return None - return {"x": value[0], "y": value[1], "z": value[2]} - - -def kernel_report(intervals: list[dict]) -> dict: - kernels = [interval for interval in intervals if interval["kind"] == "kernel"] - names = sorted({interval["name"] for interval in kernels}) - total = sum(interval["duration_ns"] for interval in kernels) - grouped = collections.defaultdict(list) - for interval in kernels: - grouped[interval["name"]].append(interval) - - reports = [] - for name, group in grouped.items(): - variants = collections.defaultdict(list) - for interval in group: - variants[(interval["grid"], interval["block"])].append(interval["duration_ns"]) - reports.append( - { - "name": name, - "duration": duration_summary([item["duration_ns"] for item in group]), - "summed_kernel_time_share": round( - sum(item["duration_ns"] for item in group) / total, 6 - ) - if total - else None, - "selector_hint": selector_hint(name, names), - "launch_variants": [ - { - "grid": dimensions_object(grid), - "block": dimensions_object(block), - "duration": duration_summary(durations), - } - for (grid, block), durations in sorted( - variants.items(), key=lambda item: repr(item[0]) - ) - ], - } - ) - reports.sort(key=lambda item: (-item["duration"]["total_ns"], item["name"])) - kernel_intervals = [(item["start_ns"], item["end_ns"]) for item in kernels] - busy = interval_union_ns(kernel_intervals) - return { - "duration": duration_summary([item["duration_ns"] for item in kernels]), - "busy_union_ns": busy, - "overlap_factor": round(total / busy, 6) if busy else None, - "by_name": reports, - } - - -def bandwidth(group: list[dict]) -> dict: - """Achieved copy bandwidth over the summed copy time (bytes per ns = GB/s).""" - total_bytes = sum(item["bytes"] or 0 for item in group) - total_ns = sum(item["duration_ns"] for item in group) - return { - "total_bytes": total_bytes, - "avg_bytes": round(total_bytes / len(group), 1) if group else None, - "bandwidth_gbps": round(total_bytes / total_ns, 3) if total_ns else None, - } - - -def memcpy_report(intervals: list[dict]) -> dict: - copies = [interval for interval in intervals if interval["kind"] == "memcpy"] - grouped = collections.defaultdict(list) - for interval in copies: - grouped[interval["name"]].append(interval) - return { - "duration": duration_summary([item["duration_ns"] for item in copies]), - **bandwidth(copies), - "by_kind": [ - { - "kind": kind, - "duration": duration_summary([item["duration_ns"] for item in group]), - **bandwidth(group), - } - for kind, group in sorted(grouped.items()) - ], - } - - -def gap_entry(previous: dict, current: dict) -> dict: - return { - "start_ns": previous["end_ns"], - "end_ns": current["start_ns"], - "gap_ns": current["start_ns"] - previous["end_ns"], - "after": previous["name"], - "before": current["name"], - } - - -def top(entries: list[dict], key: str, limit: int) -> list[dict]: - return sorted(entries, key=lambda item: (-item[key], item["start_ns"]))[:limit] - - -def device_idle_gaps(intervals: list[dict], limit: int) -> list[dict]: - """Largest spans with no captured activity on a device: GPU bubbles.""" - grouped = collections.defaultdict(list) - for interval in intervals: - grouped[(interval["pid"], interval["device_id"])].append(interval) - gaps = [] - for (pid, device), group in grouped.items(): - ordered = sorted(group, key=lambda item: (item["start_ns"], item["end_ns"])) - busy_until = ordered[0] - for current in ordered[1:]: - if current["start_ns"] > busy_until["end_ns"]: - gaps.append({"pid": pid, "device_id": device, **gap_entry(busy_until, current)}) - if current["end_ns"] > busy_until["end_ns"]: - busy_until = current - return top(gaps, "gap_ns", limit) - - -def stream_report(intervals: list[dict], top_gaps: int) -> list[dict]: - grouped = collections.defaultdict(list) - for interval in intervals: - key = ( - interval["pid"], - interval["device_id"], - interval["context_id"], - interval["stream_id"], - ) - grouped[key].append(interval) - - reports = [] - for (pid, device, context, stream), group in grouped.items(): - kernels = sorted( - (item for item in group if item["kind"] == "kernel"), - key=lambda item: (item["start_ns"], item["end_ns"]), - ) - gaps = [] - gap_entries = [] - overlaps = [] - for previous, current in zip(kernels, kernels[1:]): - delta = current["start_ns"] - previous["end_ns"] - if delta >= 0: - gaps.append(delta) - gap_entries.append(gap_entry(previous, current)) - else: - overlaps.append(-delta) - reports.append( - { - "pid": pid, - "device_id": device, - "context_id": context, - "stream_id": stream, - "event_counts": dict( - sorted(collections.Counter(item["kind"] for item in group).items()) - ), - "summed_activity_ns": sum(item["duration_ns"] for item in group), - "busy_union_ns": interval_union_ns( - [(item["start_ns"], item["end_ns"]) for item in group] - ), - "adjacent_kernel_gaps": duration_summary(gaps), - "adjacent_kernel_overlaps": duration_summary(overlaps), - "top_gaps": top(gap_entries, "gap_ns", top_gaps), - } - ) - reports.sort( - key=lambda item: ( - item["pid"] if item["pid"] is not None else -1, - item["device_id"] if item["device_id"] is not None else -1, - item["context_id"] if item["context_id"] is not None else -1, - item["stream_id"] if item["stream_id"] is not None else -1, - ) - ) - return reports - - -def load_events(path: pathlib.Path) -> list[dict]: - events = [] - with path.open(encoding="utf-8") as source: - for line_number, line in enumerate(source, 1): - if not line.strip(): - continue - event = json.loads(line) - if event.get("schema_version") != "2.0": - raise ValueError( - f"{path}:{line_number}: expected schema_version 2.0" - ) - events.append(event) - if not events: - raise ValueError(f"{path}: trace contains no events") - return events - - -def event_label(event: dict) -> str | None: - cuda = event.get("cuda") or {} - host = event.get("host") or {} - nvtx = event.get("nvtx") or {} - attributes = event.get("attributes") or {} - return ( - cuda.get("kernel_name") - or attributes.get("cuda_api_name") - or nvtx.get("name") - or host.get("symbol_demangled") - or host.get("symbol") - or cuda.get("memcpy_kind") - ) - - -def slice_events(events: list[dict], start_ns: int, end_ns: int, limit: int) -> dict: - """Every event inside [start_ns, end_ns], in time order, bounded by limit.""" - inside = sorted( - (event for event in events if start_ns <= event["timestamp_ns"] <= end_ns), - key=lambda event: (event["timestamp_ns"], event.get("sequence", 0)), - ) - rows = [] - for event in inside[:limit]: - cuda = event.get("cuda") or {} - rows.append( - { - "timestamp_ns": event["timestamp_ns"], - "offset_ns": event["timestamp_ns"] - start_ns, - "event_type": event["event_type"], - "name": event_label(event), - "pid": event.get("pid"), - "tid": event.get("tid"), - "stream_id": cuda.get("stream_id"), - "correlation_id": cuda.get("correlation_id"), - "event_id": event.get("event_id"), - } - ) - return { - "start_ns": start_ns, - "end_ns": end_ns, - "events": rows, - "total_events": len(inside), - "truncated": len(inside) > limit, - "counts_by_type": dict( - sorted(collections.Counter(event["event_type"] for event in inside).items()) - ), - } - - -def measurement_outliers(path: pathlib.Path, limit: int) -> dict: - """Slowest pairs from a measure result; full evidence when available.""" - result = json.loads(path.read_text()) - if result.get("ok") is not True: - raise ValueError(f"{path}: not a successful measurement result") - edges = result.get("edges") - evidences = ( - [(edge["name"], edge["evidence"]) for edge in edges] - if edges is not None - else [(None, result["evidence"])] - ) - outliers = [] - sources = set() - for edge, evidence in evidences: - if evidence.get("pairs") is not None: - pairs = evidence["pairs"] - sources.add("full_evidence") - else: - pairs = [exemplar["pair"] for exemplar in evidence.get("exemplars", [])] - sources.add("rank_exemplars") - for pair in pairs: - start, end = pair["start"], pair["end"] - outliers.append( - { - "edge": edge, - "latency_ns": pair["latency_ns"], - "start_ns": start["timestamp_ns"], - "end_ns": end["timestamp_ns"], - "start_event": start.get("event_id"), - "end_event": end.get("event_id"), - "tid": start.get("tid"), - "stream_id": (start.get("cuda") or {}).get("stream_id"), - "correlation_id": (start.get("cuda") or {}).get("correlation_id"), - } - ) - outliers.sort(key=lambda item: (-item["latency_ns"], item["start_ns"])) - return { - "input": str(path), - "source": sorted(sources), - "slowest": outliers[:limit], - } - - -def analyze( - path: pathlib.Path, - *, - top_gaps: int = 5, - measurement: pathlib.Path | None = None, - outliers: int = 10, - window: tuple[str, object] | None = None, - window_ns: int = 0, - max_slice_events: int = 200, -) -> dict: - events = load_events(path) - intervals, unmatched_starts, unmatched_ends = pair_activities(events) - activity_ranges = [(item["start_ns"], item["end_ns"]) for item in intervals] - busy = interval_union_ns(activity_ranges) - summed = sum(item["duration_ns"] for item in intervals) - span = ( - max(item["end_ns"] for item in intervals) - - min(item["start_ns"] for item in intervals) - if intervals - else 0 - ) - warnings = [] - if unmatched_starts or unmatched_ends: - warnings.append( - { - "code": "UNPAIRED_ACTIVITY_BOUNDARIES", - "message": "activity metrics exclude unpaired start or end records", - } - ) - idle_gaps = device_idle_gaps(intervals, top_gaps) - outlier_report = measurement_outliers(measurement, outliers) if measurement else None - window_report = None - if window is not None: - kind, value = window - if kind == "gap": - if not 1 <= value <= len(idle_gaps): - raise ValueError(f"--slice-gap {value}: only {len(idle_gaps)} idle gaps") - target = idle_gaps[value - 1] - elif kind == "outlier": - if outlier_report is None: - raise ValueError("--slice-outlier requires --measurement") - if not 1 <= value <= len(outlier_report["slowest"]): - raise ValueError( - f"--slice-outlier {value}: only {len(outlier_report['slowest'])} outliers" - ) - target = outlier_report["slowest"][value - 1] - else: - target = {"start_ns": value[0], "end_ns": value[1]} - window_report = { - "around": {"kind": kind, "start_ns": target["start_ns"], "end_ns": target["end_ns"]}, - "window_ns": window_ns, - **slice_events( - events, - target["start_ns"] - window_ns, - target["end_ns"] + window_ns, - max_slice_events, - ), - } - if outlier_report and outlier_report["source"] == ["rank_exemplars"]: - warnings.append( - { - "code": "OUTLIERS_FROM_EXEMPLARS", - "message": "measurement has summary evidence; rerun with --evidence full to rank every pair", - } - ) - return { - "analysis_version": "1.1", - "input": str(path), - "events": { - "total": len(events), - "by_type": dict( - sorted(collections.Counter(event["event_type"] for event in events).items()) - ), - "paired_activities": len(intervals), - "unmatched_activity_starts": unmatched_starts, - "unmatched_activity_ends": unmatched_ends, - }, - "gpu": { - "span_ns": span, - "busy_union_ns": busy, - "summed_activity_ns": summed, - "overlap_factor": round(summed / busy, 6) if busy else None, - "busy_fraction_of_span": round(busy / span, 6) if span else None, - "top_idle_gaps": idle_gaps, - }, - "kernels": kernel_report(intervals), - "memcpy": memcpy_report(intervals), - "memset": { - "duration": duration_summary( - [ - item["duration_ns"] - for item in intervals - if item["kind"] == "memset" - ] - ) - }, - "streams": stream_report(intervals, top_gaps), - "outliers": outlier_report, - "slice": window_report, - "warnings": warnings, - } - - -def parse_around(value: str) -> tuple[int, int]: - start, _, end = value.partition(":") - start_ns = int(start) - end_ns = int(end) if end else start_ns - if end_ns < start_ns: - raise argparse.ArgumentTypeError("--around END_NS must not precede START_NS") - return (start_ns, end_ns) - - -def positive(value: str) -> int: - number = int(value) - if number < 1: - raise argparse.ArgumentTypeError("must be at least 1") - return number - - -def main() -> None: - parser = argparse.ArgumentParser( - description="Summarize kernels, copies, overlap, streams, gaps, outliers, " - "and time slices in xprobe Event JSONL" - ) - parser.add_argument("trace", type=pathlib.Path) - parser.add_argument("--top-gaps", type=positive, default=5, - help="idle gaps to rank per device and per stream") - parser.add_argument("--measurement", type=pathlib.Path, - help="measure result JSON whose slowest pairs to rank") - parser.add_argument("--outliers", type=positive, default=10, - help="slowest pairs to list from --measurement") - target = parser.add_mutually_exclusive_group() - target.add_argument("--slice-gap", type=positive, metavar="RANK", - help="list events around the RANK-th largest device idle gap") - target.add_argument("--slice-outlier", type=positive, metavar="RANK", - help="list events around the RANK-th slowest measured pair") - target.add_argument("--around", type=parse_around, metavar="START_NS[:END_NS]", - help="list events around explicit timestamps") - parser.add_argument("--window-ms", type=float, default=0.0, - help="padding before and after the slice target") - parser.add_argument("--max-slice-events", type=positive, default=200) - args = parser.parse_args() - if args.window_ms < 0: - parser.error("--window-ms must not be negative") - window = None - if args.slice_gap is not None: - window = ("gap", args.slice_gap) - elif args.slice_outlier is not None: - window = ("outlier", args.slice_outlier) - elif args.around is not None: - window = ("timestamps", args.around) - report = analyze( - args.trace, - top_gaps=args.top_gaps, - measurement=args.measurement, - outliers=args.outliers, - window=window, - window_ns=round(args.window_ms * 1_000_000), - max_slice_events=args.max_slice_events, - ) - json.dump(report, sys.stdout, indent=2, sort_keys=True) - sys.stdout.write("\n") - - -if __name__ == "__main__": - main() diff --git a/skills/xprobe-perf-profiling/SKILL.md b/skills/xprobe-perf-profiling/SKILL.md new file mode 100644 index 0000000..9a759f1 --- /dev/null +++ b/skills/xprobe-perf-profiling/SKILL.md @@ -0,0 +1,43 @@ +--- +name: xprobe-perf-profiling +description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA CUDA/PyTorch/vLLM workloads with xprobe. Use to find GPU idle bubbles, slow kernels, memory copy bottlenecks, Python GIL contention, CPU hotspots, syscall stalls, tail latency spikes, or multi-GPU/multi-process stragglers; to write one-off Python/jq analysis scripts over xprobe JSON/JSONL traces; or to embed profiling into automated performance optimization and RSI loops. +--- + +# Profile Linux & ML workloads with xprobe + +`xprobe` profiles live Linux CPU, Python, syscall, and CUDA processes (or re-analyzes saved traces) and emits strict JSON to stdout whenever stdout is not a terminal, plus raw JSONL event/sample artifacts. Run `xprobe --help` for full flags. + +## Commands + +| Need | Command | +| --- | --- | +| Check eBPF, ptrace, NVIDIA, CUDA/CUPTI | `xprobe doctor` | +| List CUDA context holders under a PID | `xprobe discover --pid "$ROOT"` | +| Dry-run selectors, symbols, or injection | `xprobe validate --pid "$PID" --from A --to B --match exact` | +| Python stacks & GIL holder (CPython 3.9โ€“3.14) | `xprobe measure --pid "$PID" --python-sample --duration-ms 2000` | +| Native CPU callchain hotspots | `xprobe measure --pid "$PID" --cpu-sample --duration-ms 2000` | +| Syscall count & duration totals | `xprobe measure --pid "$PID" --syscall-aggregate --duration-ms 2000` | +| GPU kernel / memcpy / memset totals | `xprobe measure --pid "$PID" --from cuda:kernel_start --to cuda:kernel_end --match exact --aggregate --duration-ms 2000` | +| Exact A โ†’ B latency (with Event JSONL) | `xprobe measure --pid "$PID" --from cuda:launch_api:exit --to cuda:kernel_start --match exact --samples 200` | +| Full GPU timeline / stream gaps / idle | `xprobe measure --pid "$PID" --from cuda:kernel_end --to cuda:kernel_start --match stream-order --duration-ms 2000 --events-out trace.jsonl` | +| Up to 8 edges in one capture | `xprobe measure --spec graph.json` | +| Wait for rare GPU bubble / gap / spike | `xprobe measure --pid "$PID" --trigger-idle-ms 10 --pre-ms 50 --post-ms 50 --events-out spikes` | +| Re-correlate a saved Event JSONL offline | `xprobe measure --input trace.jsonl --from A --to B --match exact` | +| Same-window cgroup / thread / NVML snapshot | `xprobe measure --pid "$PID" --triage --duration-ms 2000` | + +With `--triage`, read the raw inline inventories (`threads`, `cgroup`, `gpu_devices`, `cpu_hotspots`, `python_hotspots`, `syscalls`, `gpu_activity`) rather than relying on its static `findings` ranking. + +## Analyze outputs & build scripts + +- **Standard GPU analysis**: run `scripts/analyze_trace.py trace.jsonl` for per-GPU busy/idle/compute/comm budgets, top idle and stream gaps, kernel/memcpy stats, vertical time slices (`--slice-gap`, `--slice-outlier`, `--around`, `--python-samples`), or multi-rank comparison (`scripts/analyze_trace.py rank0.jsonl rank1.jsonl ...`). +- **Custom one-off scripts & RSI loops**: read [data-format.md](references/data-format.md) before writing Python/`jq` scripts. It gives the exact stdout keys, artifact file paths per mode, real JSONL line shapes, pairing keys, clock conversion math, and ready patterns for cross-source, cross-process, log-aligned, and before/after RSI comparisons. +- **Selectors, policies, and graph specs**: see [selectors.md](references/selectors.md) and the two templates under `examples/` (`request-path-graph.json`, `kernel-duration.json`). + +## Hard constraints + +- **Missing CLI / containers**: if `xprobe` is absent, install with `pip install xprobe` (or check `xprobe doctor`). A host process cannot inject CUPTI into a container with a different mount namespace; run `xprobe` inside the target's PID and mount namespaces. +- **CUDA injection & NVTX**: live CUDA capture attaches via ptrace and leaves the CUPTI `.so` mapped (logically disabled after stop). NVTX ranges require `NVTX_INJECTION64_PATH` set before the target's first NVTX call. +- **Process discovery**: `discover` lists NVML CUDA context holders only; locate pure CPU/Python/gateway PIDs with `ps` or workload metadata. +- **Flag bounds**: live `measure` requires `--samples` or `--duration-ms`. Inventory modes (`--aggregate`, `--cpu-sample`, `--python-sample`, `--syscall-aggregate`, `--triage`) accept `--duration-ms` only. +- **Cross-process & clocks**: run concurrent `xprobe measure --pid ...` commands to profile multiple processes or ranks. On one host, `host_monotonic`, `cupti_normalized_to_host_monotonic`, and Python sample `timestamp_ns` share `CLOCK_MONOTONIC` and can be joined directly in Python (or compared with `scripts/analyze_trace.py`). Never pass mixed-PID artifacts to `measure --input`, and never subtract raw `cupti` timestamps from host timestamps. +- **Accounting**: a single-stream gap is not GPU idle time, and summed concurrent kernel durations are not wall time. Always check `quality.verdict`, `dropped`, and `all_gpu_activity` before acting on numbers. diff --git a/skills/xprobe-perf-profiling/agents/openai.yaml b/skills/xprobe-perf-profiling/agents/openai.yaml new file mode 100644 index 0000000..6d823d2 --- /dev/null +++ b/skills/xprobe-perf-profiling/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Xprobe Performance Profiling" + short_description: "Profile Linux CPU, Python GIL, syscalls, and CUDA/GPU workloads" + default_prompt: "Use $xprobe-perf-profiling to profile this workload, analyze the JSON/JSONL output, and pinpoint where time is spent." diff --git a/skills/xprobe-measure-latency/examples/kernel-duration.json b/skills/xprobe-perf-profiling/examples/kernel-duration.json similarity index 100% rename from skills/xprobe-measure-latency/examples/kernel-duration.json rename to skills/xprobe-perf-profiling/examples/kernel-duration.json diff --git a/skills/xprobe-measure-latency/examples/request-path-graph.json b/skills/xprobe-perf-profiling/examples/request-path-graph.json similarity index 100% rename from skills/xprobe-measure-latency/examples/request-path-graph.json rename to skills/xprobe-perf-profiling/examples/request-path-graph.json diff --git a/skills/xprobe-perf-profiling/references/data-format.md b/skills/xprobe-perf-profiling/references/data-format.md new file mode 100644 index 0000000..a30648e --- /dev/null +++ b/skills/xprobe-perf-profiling/references/data-format.md @@ -0,0 +1,176 @@ +# Output formats, artifacts, and scripting recipes + +Every `xprobe` command prints one JSON document to stdout when stdout is not a terminal (`schema_version` `"3.0"` or `"2.0"`). Full JSON Schemas live under `schemas/`. Use this page to parse results and write one-off Python/`jq` scripts on the first try. + +## Stdout & artifact paths by mode + +| Mode | Artifact file path in stdout JSON | Main inline data in stdout JSON | +| --- | --- | --- | +| Single-edge `measure` | `evidence.artifact.path` (Event JSONL) | `measurement.{latency_ns, samples}`, `quality`, `evidence.exemplars`, `evidence.pairs` (with `--evidence full`) | +| Graph `measure --spec` | `artifact.path` (also on each `edges[].evidence.artifact.path`) | `edges[].{name, measurement, quality, evidence}` | +| `--python-sample` | `artifact.path` (Python sample JSONL) | `inventory.{gil_hotspots, gil_released_proportion, gil_stack_groups, thread_stack_groups, native_waits}`, `collection` | +| `--trigger-*` | `windows[].artifact.path` (one Event JSONL per window) | `trigger`, `observed`, `windows[].{fired, start_ns, end_ns, truncated, longest}`, `collection` | +| `--aggregate` | none (inline only) | `inventory.groups[]`, `collection.{cuda_devices, dropped_activities, table_utilization}` | +| `--cpu-sample` | none (inline only) | `inventory.{hotspots, stack_groups}`, `symbolization.python_status`, `collection` | +| `--syscall-aggregate` | none (inline only) | `inventory.groups[]`, `collection` | +| `--triage` | per-source paths in `sources[]` | `sources[]`, `not_covered`, `threads`, `cgroup`, `cpu_hotspots`, `python_hotspots`, `syscalls`, `gpu_activity`, `gpu_devices`, `findings` | + +Errors exit non-zero and print JSON (`ok: false`, `error.{code, message, details, hints}`), preserving any written artifact path in `details`. + +## Event JSONL (`*.jsonl`) + +One JSON object per line (`schema_version: "2.0"`). Concrete shapes for the main event kinds: + +```json +{"schema_version":"2.0","session_id":"s1","event_id":"e1","sequence":1,"source":"cupti_activity","event_type":"gpu_kernel_start","pid":4242,"tid":0,"timestamp_raw":1000,"timestamp_ns":1000,"clock_domain":"cupti_normalized_to_host_monotonic","cuda":{"device_id":0,"context_id":1,"stream_id":7,"correlation_id":99,"kernel_name":"flash_fwd","grid":{"x":64,"y":1,"z":1},"block":{"x":128,"y":1,"z":1}},"host":null,"nvtx":null,"attributes":{}} +{"schema_version":"2.0","session_id":"s1","event_id":"e2","sequence":2,"source":"cupti_callback","event_type":"cuda_api_exit","pid":4242,"tid":4242,"timestamp_raw":950,"timestamp_ns":950,"clock_domain":"host_monotonic","cuda":{"correlation_id":99,"callback_domain":2,"callback_id":211},"host":null,"nvtx":null,"attributes":{"cuda_api_name":"cudaLaunchKernel","cuda_api_domain":"runtime_api"}} +{"schema_version":"2.0","session_id":"s1","event_id":"e3","sequence":3,"source":"ebpf","event_type":"syscall_exit","pid":4242,"tid":4242,"timestamp_raw":900,"timestamp_ns":900,"clock_domain":"host_monotonic","cuda":null,"host":{"probe_kind":"syscall","symbol":"futex","return_value":0,"arguments":[]},"nvtx":null,"attributes":{}} +``` + +Key details that trip up scripts: + +- **`event_type` values**: `gpu_kernel_start|end`, `gpu_memcpy_start|end`, `gpu_memset_start|end`, `cuda_api_entry|exit`, `nvtx_range_start|end`, `host_function_entry|exit`, `kernel_function_entry|exit`, `syscall_entry|exit`, `tracepoint`, `python_gc_start|end`, `marker`. +- **Where names live**: `cuda.kernel_name`, `cuda.memcpy_kind` (`HtoD|DtoH|DtoD|HtoH|PtoP|unknown`), `cuda.bytes`, **`attributes.cuda_api_name`** (not inside `cuda`!), `nvtx.name` (plus `nvtx.range_kind`, `nvtx.range_id`, `nvtx.start_tid`), `host.symbol_demangled` / `host.symbol` / `host.binary_path` / `host.return_value`. +- **GPU activity is two lines**: a `*_start` and `*_end` paired by `(kind, pid, cuda.device_id, cuda.context_id, cuda.stream_id, cuda.correlation_id, name)`. Records with `attributes.get("start_unknown")` were still running at STOP: their time is their stream's previous end, they mark the stream busy, and they never give a duration, gap, or latency. +- **Clocks**: `host_monotonic` and `cupti_normalized_to_host_monotonic` both use `CLOCK_MONOTONIC` and compare directly with each other, with `--python-sample` timestamps, and across processes on the same host. Raw `cupti` timestamps only compare with raw `cupti` from the same capture. Within identical timestamps, order by `sequence`. + +## Capture manifest (`.manifest.json`) + +Written beside every Event JSONL (`schema_version: "1.0"`). Keep it beside the trace so `measure --input` and `analyze_trace.py` can verify completeness and map devices/clocks: + +```json +{ + "schema_version": "1.0", + "target": {"pid": 4242, "process_start_time": 987654}, + "window": {"start_ns": 1000000, "end_ns": 3000000}, + "selectors": ["cuda:kernel_end", "cuda:kernel_start"], + "all_gpu_activity": true, + "peer_copies": true, + "dropped_records": 0, + "unknown_records": 0, + "record_limit_reached": null, + "capture_failed": false, + "cuda_devices": [{"device_id": 0, "uuid": "GPU-xxxx", "gpu_uuid": null}], + "wall_clock": { + "start": {"monotonic_ns": 1000000, "realtime_ns": 1730000000000000000, "uncertainty_ns": 500}, + "end": {"monotonic_ns": 3000000, "realtime_ns": 1730000000002000000, "uncertainty_ns": 500} + }, + "artifact": {"format": "jsonl", "events": 5000, "bytes": 1234567, "sha256": "..."} +} +``` + +- `all_gpu_activity: true` is required for trustworthy GPU idle time (otherwise filtered-out kernels look like idle). +- `cuda_devices` maps process-local `device_id` (affected by `CUDA_VISIBLE_DEVICES`) to physical `uuid` (or MIG `uuid` + `gpu_uuid`). Always group cross-process GPUs by UUID. + +## Python sample JSONL (`--python-sample`) + +One line per sample at `result["artifact"]["path"]`: + +```json +{"timestamp_ns":1001234,"pid":4242,"tid":4242,"gil":true,"truncated":false,"frames":[{"function":"step","file":"train.py","first_line":40},{"function":"main","file":"train.py","first_line":10}],"native":null} +{"timestamp_ns":1005000,"pid":4242,"tid":4248,"gil":false,"truncated":false,"frames":[{"function":"recv","file":"comm.py","first_line":12}],"native":{"syscall":"futex","module":"libc.so.6","symbol":"__futex_abstimed_wait_common"}} +``` + +- `timestamp_ns` is `CLOCK_MONOTONIC` (joins directly with Event JSONL). +- `frames[0]` is the **innermost** frame; `first_line` is where the function starts, not the executing line. +- `gil: true` = high-rate GIL-holder ticks (default 2000 Hz); `gil: false` = all-thread sweep samples (default 100 Hz), with `native` populated when a swept thread was blocked in a syscall/native call. +- Stdout `collection` reports `gil_hz_achieved`, `inconsistent_reads`, `tid_source`, and `wall_clock`. + +## Inventory, measurement, and trigger stdout fields + +- **Exact / Graph**: `measurement.latency_ns.{min, mean, p50, p90, p95, p99, max}`, `measurement.samples.{matched, unmatched_start, unmatched_end, ambiguous, dropped}`, `quality.{verdict, issues}` (`good` or `caution`), `correlation.{method, confidence}`, `clock.{alignment, estimated_error_ns}`, `collection.{coverage, cupti, cuda_devices, wall_clock}`. `timed_out` stats are partial. +- **GPU `--aggregate`**: `inventory.groups[]` entries have `activity` (`kernel|memcpy|memset`), `name`, `name_complete`, `memcpy_kind`, `src_memory`, `dst_memory` (`pageable` = staged sync copy), `device_id`, `count`, `total_bytes`, `duration_ns.{min, mean, max, total}`, `start_selector_hint`, `end_selector_hint`. +- **CPU `--cpu-sample`**: `inventory.hotspots[]` (`frame.{symbol, module_path, language}`, `exclusive_proportion`, `inclusive_proportion`, `entry_selector_hint`, `return_selector_hint`), `inventory.stack_groups[]`, `symbolization.python_status` (`inactive`/`unsupported` means native frames only), `collection.{lost_samples, truncated_stacks, threads_attached, threads_observed}`. +- **Syscall `--syscall-aggregate`**: `inventory.groups[]` (`syscall_name`, `syscall_number`, `count`, `errors`, `duration_ns.{min, mean, max, total}`, `entry_selector_hint`, `exit_selector_hint`). Blocked time includes idle waiting. +- **Trigger `--trigger-*`**: `trigger.{kind, threshold_ns}`, `observed.{spans, over_threshold, longest}`, `windows[]` (`fired`, `start_ns`, `end_ns`, `truncated`, `longest`, `artifact`), `collection.{overwritten_records, dropped_records, lost_windows, revoked_windows}`. On timeout with no windows, fails with `TRIGGER_NOT_OBSERVED` and `details.longest_ns`. + +## Bundled analyzer (`scripts/analyze_trace.py`) + +Use it instead of rewriting interval-union math by hand: + +```bash +# Single trace: per-GPU busy/idle/compute/comm/transfer, kernels, memcpy bandwidth, stream gaps +scripts/analyze_trace.py trace.jsonl --comm-kernel 'nccl|custom_allreduce' + +# Vertical slice around the largest GPU idle gap + concurrent Python stacks +scripts/analyze_trace.py trace.jsonl --slice-gap 1 --window-ms 2 --python-samples py.jsonl + +# Slice around slowest measured pair or explicit CLOCK_MONOTONIC timestamps +scripts/analyze_trace.py trace.jsonl --measurement res.json --slice-outlier 1 +scripts/analyze_trace.py trace.jsonl --around 1000000:2000000 --python-samples py.jsonl + +# Multi-rank / multi-process comparison on one host (budgets over shared window) +scripts/analyze_trace.py rank0.jsonl rank1.jsonl rank2.jsonl rank3.jsonl +``` + +Key output fields: `devices[]` (`uuid`, `span`, `busy_ns`, `idle_ns`, `compute_ns`, `communication_ns`, `communication_only_ns`, `transfer_ns`, `top_idle_gaps`, `top_compute_gaps`), `kernels.by_name[]` (with `selector_hint` and `launch_variants`), `memcpy` (`bandwidth_gbps`), `streams[].top_gaps`, `gpu.top_idle_gaps`, `slice` (with `python`), `warnings` (`WALL_CLOCK_DRIFT`, `GPU_ACTIVITY_COVERAGE_UNKNOWN`, `CAPTURE_INCOMPLETE`). Multi-trace mode adds `devices[].shares` and `spread` (`compute_share`, `most_compute`, `most_communication_only`, `most_idle`). `--comm-kernel` defaults to `nccl`, unanchored so it matches mangled names such as `_Z40ncclDevKernel_AllReduce...`; extend it for custom collectives (vLLM, TRT-LLM, FlashInfer, NVSHMEM/DeepEP). + +## One-off script recipes & RSI loops + +### 1. Pair GPU intervals & compute true device busy/idle (avoid overlap double-counting) + +```python +import collections, json + +def load_gpu_intervals(jsonl_path): + starts, intervals = collections.defaultdict(collections.deque), [] + for line in open(jsonl_path): + e = json.loads(line) + t = e["event_type"] + if not t.startswith("gpu_") or e.get("attributes", {}).get("start_unknown"): + continue + c = e["cuda"] + kind = t.split("_")[1] # kernel | memcpy | memset + name = c.get("kernel_name") or c.get("memcpy_kind") or "memset" + key = (kind, e["pid"], c["device_id"], c["context_id"], c["stream_id"], c["correlation_id"], name) + if t.endswith("_start"): + starts[key].append(e) + elif starts[key]: + s = starts[key].popleft() + intervals.append((s["timestamp_ns"], e["timestamp_ns"], kind, name, c["device_id"], c["stream_id"], s["clock_domain"])) + return intervals + +def merge_union(spans): # [(start_ns, end_ns), ...] -> non-overlapping merged spans + merged = [] + for s, e in sorted(spans): + if merged and s <= merged[-1][1]: + merged[-1] = (merged[-1][0], max(merged[-1][1], e)) + else: + merged.append((s, e)) + return merged +``` + +### 2. Cross-process / cross-source timeline join (same host) + +Run concurrent `xprobe measure --pid ...` captures (e.g., API server `--python-sample` + GPU worker Event JSONL, or two GPU ranks). All `host_monotonic`, `cupti_normalized_to_host_monotonic`, and Python sample `timestamp_ns` values share the host `CLOCK_MONOTONIC`: + +```python +HOST_CLOCKS = {"host_monotonic", "cupti_normalized_to_host_monotonic"} +t0, t1 = gap_start_ns - 2_000_000, gap_end_ns + 2_000_000 +py_in_gap = [json.loads(l) for l in open("api_py.jsonl") if t0 <= json.loads(l)["timestamp_ns"] <= t1] +gpu_in_gap = [e for e in map(json.loads, open("worker_gpu.jsonl")) + if e["clock_domain"] in HOST_CLOCKS and t0 <= e["timestamp_ns"] <= t1] +``` + +For traces from **different hosts**, clocks are unrelated: compare normalized shares (`idle_ns / span_ns`) or map each trace through its manifest `wall_clock` to UTC. + +### 3. Convert `CLOCK_MONOTONIC` to UTC wall time (join with app logs) + +```python +wc = json.load(open("trace.jsonl.manifest.json"))["wall_clock"] +def mono_to_utc_ns(t_ns): + a = min((wc["start"], wc["end"]), key=lambda x: abs(t_ns - x["monotonic_ns"])) + return a["realtime_ns"] + (t_ns - a["monotonic_ns"]) +``` + +Check `abs((wc["end"]["realtime_ns"] - wc["end"]["monotonic_ns"]) - (wc["start"]["realtime_ns"] - wc["start"]["monotonic_ns"]))`: a large diff means wall clock drifted or stepped during capture. + +### 4. Quantitative before/after diff in an RSI loop + +Pin the exact same `--spec` (or CLI flags/bounds) before and after each optimization candidate: +- Guard every comparison: require `ok == True`, no drops, and check `quality.verdict` (plus `all_gpu_activity == True` when comparing `idle_ns`). +- Compare directly on machine-readable metrics: + - Latency edge: `measurement.latency_ns["p50"]` and `["p95"]` + - GPU budget (`analyze_trace.py`): `devices[0]["compute_ns"]`, `devices[0]["idle_ns"]`, `devices[0]["communication_only_ns"]`, or `kernels["by_name"]` totals + - Python GIL (`--python-sample`): `inventory["gil_released_proportion"]` and top `inventory["gil_hotspots"]` + - Copy overhead (`--aggregate`): `inventory["groups"]` grouped by `(memcpy_kind, src_memory, dst_memory)` diff --git a/skills/xprobe-perf-profiling/references/selectors.md b/skills/xprobe-perf-profiling/references/selectors.md new file mode 100644 index 0000000..b1ee632 --- /dev/null +++ b/skills/xprobe-perf-profiling/references/selectors.md @@ -0,0 +1,80 @@ +# Selectors, policies, specs, and overhead limits + +Prefer selector hints emitted by xprobe (`*_selector_hint` in inventories, `selector_hint` in `analyze_trace.py`). Use `xprobe validate` when a hand-written selector or policy is uncertain. + +## Selector syntax + +| Source | Selector | +| --- | --- | +| Native function | `uprobe:::entry\|return` | +| C++ signature with `::` | `uprobe::symbol=:entry\|return` | +| Stripped / local offset | `uprobe::+0x:entry\|return` | +| Syscall | `syscall::entry\|exit` | +| Kernel tracepoint | `tracepoint::` (identity + timestamp only) | +| CPython GC | `python:gc_start`, `python:gc_end` (requires USDT markers in mapped Python/`libpython`) | +| CUDA Runtime / Driver API | `cuda:runtime_api\|driver_api::entry\|exit` | +| Any kernel launch API | `cuda:launch_api:entry\|exit` (covers Runtime & Driver launches, including cuBLAS/Triton; uses 2 Agent filters) | +| GPU activity | `cuda:kernel_start\|kernel_end[:name~REGEX]`, `cuda:memcpy_start\|memcpy_end[:kind=HtoD\|DtoH\|DtoD\|HtoH\|PtoP]`, `cuda:memset_start\|memset_end` | +| NVTX range | `cuda:nvtx_range_start\|nvtx_range_end:name~REGEX` | + +### Resolving native symbols & offsets + +```bash +readlink -f "/proc/$PID/exe" +grep -F ' r-xp ' "/proc/$PID/maps" +readelf -Ws /path/to/object +nm -D --defined-only --demangle /path/to/object +``` + +Use file offsets (not runtime virtual addresses) for `+0x`. Re-validate C++ signatures, offsets, and generated kernel names across builds. JIT-generated CPU code without a file-backed ELF cannot be a uprobe target. + +## Match policies + +| Policy | Pairs | Confidence | +| --- | --- | --- | +| `exact` | Same CUPTI `correlation_id` (API โ†” kernel/copy), activity start โ†” end, NVTX range ID, syscall entry โ†” exit per thread, CPython GC start โ†” end | exact | +| `stack-nested` | Entry โ†” return of one host function per thread | high | +| `stream-order` | Activity end โ†” next kernel/copy/memset start on the same stream (records **all** GPU activity; uses 6 of 8 Agent filters) | high | +| `first-after`, `nearest` | Unrelated sources (e.g. host uprobe โ†” GPU kernel) | heuristic | + +`validate` returns `policy_recommendation` with compatible alternatives; `measure` never overrides `--match` silently. + +## JSON specs & measurement graphs + +For single-edge or repeatable RSI specs (`schema_version: "2.0"`), see [examples/kernel-duration.json](../examples/kernel-duration.json). + +To capture up to 8 related edges in **one** capture (`schema_version: "3.0"`), use a measurement graph ([examples/request-path-graph.json](../examples/request-path-graph.json)): + +```json +{ + "schema_version": "3.0", + "name": "request_path", + "target": {"pid": 1234, "process_start_time": 987654}, + "endpoints": { + "request": "uprobe:/srv/app/server:request_begin:entry", + "launch_exit": "cuda:launch_api:exit", + "kernel_start": "cuda:kernel_start:name~^vector_add", + "kernel_end": "cuda:kernel_end:name~^vector_add" + }, + "edges": [ + {"name": "request_to_launch", "from": "request", "to": "launch_exit", "match_policy": "first_after", "samples": 100}, + {"name": "launch_to_kernel", "from": "launch_exit", "to": "kernel_start", "match_policy": "exact", "samples": 100}, + {"name": "kernel_duration", "from": "kernel_start", "to": "kernel_end", "match_policy": "exact", "samples": 100} + ], + "duration_ms": null, + "timeout_ms": 30000, + "max_events": 4000 +} +``` + +Graph rules: +- `target.process_start_time` may be omitted (`measure` reads and verifies it around attach). +- 1โ€“8 endpoints and 1โ€“8 edges; either every edge sets `samples` or the graph sets `duration_ms`. +- Endpoint slot limits: uprobe endpoints are unlimited; CUDA endpoints share 8 CUPTI Agent filters; syscall, tracepoint, and USDT endpoints share 2 Linux collector slots. +- Any failing edge fails `measure`, while still writing the shared Event JSONL artifact so remaining edges can be re-correlated offline with `measure --input`. + +## Filter pushdown & overhead limits + +- **Agent hot-path filtering**: kernel and NVTX `name~REGEX` expressions run inside the CUPTI Agent only when they reduce to a literal exact, prefix (`^foo.*`), suffix (`.*foo$`), or contains (`.*foo.*`) shorter than 128 bytes. Complex regexes filter in the CLI after a broader capture and hit `--max-events` much faster. Escape regex metacharacters. If an aggregate group has `name_complete: false`, keep its truncated prefix without `$`. +- **Uprobe cost**: uprobes trap into the kernel on every call (costlier on VMs/WSL2). Avoid uprobes on functions called tens of thousands of times per second; measure a coarser caller or use `--cpu-sample` / `--syscall-aggregate`. +- **High-rate GPU workloads**: `stream-order` and `--trigger-*` record all GPU activity. On launch-bound workloads (tens of thousands of kernels/sec), keep `--duration-ms` short, bound hot paths with `--samples`, or size `--max-events` from an `--aggregate` count. On `EVENT_RATE_TOO_HIGH`, narrow the selector or shorten the window before raising `--max-events`. diff --git a/skills/xprobe-perf-profiling/scripts/analyze_trace.py b/skills/xprobe-perf-profiling/scripts/analyze_trace.py new file mode 100755 index 0000000..be2896e --- /dev/null +++ b/skills/xprobe-perf-profiling/scripts/analyze_trace.py @@ -0,0 +1,1181 @@ +#!/usr/bin/env python3 +"""Summarize bounded xprobe Event JSONL artifacts. + +For one artifact the report gives each GPU's time budget (busy, idle, compute, +communication, transfers), ranks device idle gaps and stream gaps, optionally +ranks the slowest pairs of a measurement result, and can list every event +inside a time window ("vertical slice") around a gap, an outlier, or explicit +timestamps. For several artifacts of one host, such as the ranks of a data- or +tensor-parallel job, it compares those budgets over the window they share. +Everything is descriptive: events inside a window are concurrent with it, and +ranks that overlap in time are compared, not shown to cause each other. +""" + +import argparse +import collections +import datetime +import hashlib +import json +import math +import pathlib +import re +import sys + + +ACTIVITY_TYPES = { + "gpu_kernel_start": ("kernel", "start"), + "gpu_kernel_end": ("kernel", "end"), + "gpu_memcpy_start": ("memcpy", "start"), + "gpu_memcpy_end": ("memcpy", "end"), + "gpu_memset_start": ("memset", "start"), + "gpu_memset_end": ("memset", "end"), +} + + +def percentile(values: list[int], percent: int) -> int | None: + if not values: + return None + ordered = sorted(values) + rank = max(1, math.ceil(percent * len(ordered) / 100)) + return ordered[rank - 1] + + +def duration_summary(values: list[int]) -> dict: + if not values: + return { + "count": 0, + "total_ns": 0, + "min_ns": None, + "p50_ns": None, + "p95_ns": None, + "max_ns": None, + } + return { + "count": len(values), + "total_ns": sum(values), + "min_ns": min(values), + "p50_ns": percentile(values, 50), + "p95_ns": percentile(values, 95), + "max_ns": max(values), + } + + +def interval_union_ns(intervals: list[tuple[int, int]]) -> int: + if not intervals: + return 0 + ordered = sorted(intervals) + union = 0 + current_start, current_end = ordered[0] + for start, end in ordered[1:]: + if start <= current_end: + current_end = max(current_end, end) + else: + union += current_end - current_start + current_start, current_end = start, end + return union + current_end - current_start + + +def dimensions(cuda: dict, field: str) -> tuple[int, int, int] | None: + value = cuda.get(field) + if value is None: + return None + return (value["x"], value["y"], value["z"]) + + +def activity_name(kind: str, cuda: dict) -> str: + if kind == "kernel": + return cuda.get("kernel_name") or "" + if kind == "memcpy": + return cuda.get("memcpy_kind") or "unknown" + return "memset" + + +def activity_key(kind: str, event: dict) -> tuple: + cuda = event.get("cuda") or {} + return ( + kind, + event.get("pid"), + cuda.get("device_id"), + cuda.get("context_id"), + cuda.get("stream_id"), + cuda.get("correlation_id"), + activity_name(kind, cuda), + ) + + +# Communication kernels are recognized by name; a heuristic that holds for +# NCCL builds and can be overridden with --comm-kernel. +DEFAULT_COMM_KERNEL = r"nccl" + + +def pair_activities(events: list[dict]) -> tuple[list[dict], int, int]: + boundaries = [] + for event in events: + activity = ACTIVITY_TYPES.get(event.get("event_type")) + # A start known only as running at STOP never pairs; it stays a + # busy marker that runs to the end of the capture. + if activity is not None and not (event.get("attributes") or {}).get("start_unknown"): + kind, boundary = activity + boundaries.append((event["timestamp_ns"], boundary != "start", kind, boundary, event)) + boundaries.sort(key=lambda item: (item[0], item[1])) + + starts: dict[tuple, collections.deque] = collections.defaultdict(collections.deque) + intervals = [] + unmatched_ends = 0 + for _, _, kind, boundary, event in boundaries: + key = activity_key(kind, event) + if boundary == "start": + starts[key].append(event) + continue + if not starts[key]: + unmatched_ends += 1 + continue + start = starts[key].popleft() + if start["clock_domain"] != event["clock_domain"]: + raise ValueError( + f"activity pair {start.get('event_id')} / {event.get('event_id')} " + "uses different clock domains" + ) + start_ns = start["timestamp_ns"] + end_ns = event["timestamp_ns"] + if end_ns < start_ns: + raise ValueError( + f"activity pair {start.get('event_id')} / {event.get('event_id')} " + "has a negative duration" + ) + cuda = start.get("cuda") or {} + intervals.append( + { + "kind": kind, + "name": activity_name(kind, cuda), + # The paired records themselves, so edge handling never + # confuses two activities that share a timestamp. + "events": (id(start), id(event)), + "pid": start.get("pid"), + "clock_domain": start["clock_domain"], + "device_id": cuda.get("device_id"), + "context_id": cuda.get("context_id"), + "stream_id": cuda.get("stream_id"), + "start_ns": start_ns, + "end_ns": end_ns, + "duration_ns": end_ns - start_ns, + "grid": dimensions(cuda, "grid"), + "block": dimensions(cuda, "block"), + "bytes": cuda.get("bytes"), + } + ) + unmatched_starts = sum(len(queue) for queue in starts.values()) + return intervals, unmatched_starts, unmatched_ends + + +def boundary_intervals( + events: list[dict], intervals: list[dict], window: tuple[int, int] | None = None +) -> list[dict]: + """Activity the capture saw only one boundary of, stretched to the edge + of the capture: the manifest's window on the host clock, else the first or + last event of its clock domain.""" + paired = {identity for interval in intervals for identity in interval["events"]} + clocks = collections.defaultdict(list) + for event in events: + clocks[event.get("clock_domain")].append(event["timestamp_ns"]) + edges = {clock: (min(times), max(times)) for clock, times in clocks.items()} + partial = [] + for event in events: + activity = ACTIVITY_TYPES.get(event.get("event_type")) + if activity is None or id(event) in paired: + continue + kind, boundary = activity + cuda = event.get("cuda") or {} + first, last = edges[event.get("clock_domain")] + if window is not None and event.get("clock_domain") in HOST_CLOCKS: + first, last = min(first, window[0]), max(last, window[1]) + start, end = (event["timestamp_ns"], last) if boundary == "start" else (first, event["timestamp_ns"]) + partial.append( + { + "kind": kind, + "name": activity_name(kind, cuda), + "pid": event.get("pid"), + "clock_domain": event.get("clock_domain"), + "device_id": cuda.get("device_id"), + "context_id": cuda.get("context_id"), + "stream_id": cuda.get("stream_id"), + "start_ns": start, + "end_ns": end, + "partial": True, + } + ) + return partial + + +def union(intervals: list[tuple[int, int]]) -> list[tuple[int, int]]: + """Merged, sorted intervals.""" + merged = [] + for start, end in sorted(intervals): + if merged and start <= merged[-1][1]: + merged[-1] = (merged[-1][0], max(merged[-1][1], end)) + else: + merged.append((start, end)) + return merged + + +def covered_ns(intervals: list[tuple[int, int]]) -> int: + return sum(end - start for start, end in intervals) + + +def subtract(base: list[tuple[int, int]], cut: list[tuple[int, int]]) -> list[tuple[int, int]]: + """Parts of merged `base` intervals not covered by merged `cut`, in one + pass over both sorted lists.""" + remaining = [] + index = 0 + for start, end in base: + cursor = start + while index < len(cut) and cut[index][1] <= cursor: + index += 1 + scan = index + while scan < len(cut) and cut[scan][0] < end: + cut_start, cut_end = cut[scan] + if cut_start > cursor: + remaining.append((cursor, cut_start)) + cursor = max(cursor, cut_end) + if cut_end >= end: + break + scan += 1 + if cursor < end: + remaining.append((cursor, end)) + return remaining + + +def clip(intervals: list[tuple[int, int]], window: tuple[int, int] | None) -> list[tuple[int, int]]: + if window is None: + return intervals + return [ + (max(start, window[0]), min(end, window[1])) + for start, end in intervals + if end > window[0] and start < window[1] + ] + + +def gaps_between(busy: list[tuple[int, int]], limit: int) -> list[dict]: + gaps = [ + {"start_ns": previous[1], "end_ns": current[0], "gap_ns": current[0] - previous[1]} + for previous, current in zip(busy, busy[1:]) + ] + return top(gaps, "gap_ns", limit) + + +def device_budgets( + intervals: list[dict], + uuids: dict, + comm_kernel: re.Pattern, + limit: int, + window: tuple[int, int] | None = None, +) -> list[dict]: + """Each GPU's time budget per process and clock domain. + + `busy` is the union of every kernel, copy, and memset; `compute` of + kernels that are not communication; `communication_only` is time when + only communication kernels ran, which on a collective is often a rank + waiting for its peers. Inside `window` the budgets are clipped to it. + """ + grouped = collections.defaultdict(list) + for interval in intervals: + if interval["device_id"] is None: + continue + grouped[(interval["pid"], interval["device_id"], interval["clock_domain"])].append(interval) + rows = [] + for (pid, device, clock), group in sorted(grouped.items(), key=lambda item: str(item[0])): + def merged(predicate): + return union(clip([(item["start_ns"], item["end_ns"]) for item in group if predicate(item)], window)) + + busy = merged(lambda item: True) + compute = merged(lambda item: item["kind"] == "kernel" and not comm_kernel.search(item["name"])) + communication = merged(lambda item: item["kind"] == "kernel" and comm_kernel.search(item["name"])) + transfer = merged(lambda item: item["kind"] != "kernel") + if window is not None: + span = window + elif busy: + span = (busy[0][0], busy[-1][1]) + else: + continue + span_ns = span[1] - span[0] + rows.append( + { + "pid": pid, + "device_id": device, + "uuid": uuids.get((pid, device)), + "clock_domain": clock, + "span": {"start_ns": span[0], "end_ns": span[1], "ns": span_ns}, + "busy_ns": covered_ns(busy), + "idle_ns": span_ns - covered_ns(busy), + "compute_ns": covered_ns(compute), + "communication_ns": covered_ns(communication), + "communication_only_ns": covered_ns(subtract(communication, compute)), + "summed_activity_ns": sum( + end - start + for start, end in clip( + [(item["start_ns"], item["end_ns"]) for item in group if not item.get("partial")], + window, + ) + ), + "transfer_ns": covered_ns(transfer), + "partial_activities": sum(1 for item in group if item.get("partial")), + "top_idle_gaps": gaps_between(busy, limit), + "top_compute_gaps": gaps_between(compute, limit), + } + ) + return rows + + +def selector_hint(name: str, names: list[str]) -> dict | None: + if name == "": + return None + escaped = re.escape(name) + if len(name) < 128: + regex = f"^{escaped}$" + scope = "exact_name" + else: + alternatives = [candidate for candidate in names if candidate != name] + candidates = [] + for length in range(min(16, len(name)), min(127, len(name)) + 1): + prefix = name[:length] + if all(not candidate.startswith(prefix) for candidate in alternatives): + candidates.append((length, f"^{re.escape(prefix)}.*", "prefix")) + break + suffix = name[-length:] + if all(not candidate.endswith(suffix) for candidate in alternatives): + candidates.append((length, f".*{re.escape(suffix)}$", "suffix")) + break + if not candidates: + return None + _, regex, filter_kind = min(candidates) + scope = f"{filter_kind}_unique_in_capture" + return { + "name_regex": regex, + "scope": scope, + "start_selector": f"cuda:kernel_start:name~{regex}", + "end_selector": f"cuda:kernel_end:name~{regex}", + } + + +def dimensions_object(value: tuple[int, int, int] | None) -> dict | None: + if value is None: + return None + return {"x": value[0], "y": value[1], "z": value[2]} + + +def kernel_report(intervals: list[dict]) -> dict: + kernels = [interval for interval in intervals if interval["kind"] == "kernel"] + names = sorted({interval["name"] for interval in kernels}) + total = sum(interval["duration_ns"] for interval in kernels) + grouped = collections.defaultdict(list) + for interval in kernels: + grouped[interval["name"]].append(interval) + + reports = [] + for name, group in grouped.items(): + variants = collections.defaultdict(list) + for interval in group: + variants[(interval["grid"], interval["block"])].append(interval["duration_ns"]) + reports.append( + { + "name": name, + "duration": duration_summary([item["duration_ns"] for item in group]), + "summed_kernel_time_share": round( + sum(item["duration_ns"] for item in group) / total, 6 + ) + if total + else None, + "selector_hint": selector_hint(name, names), + "launch_variants": [ + { + "grid": dimensions_object(grid), + "block": dimensions_object(block), + "duration": duration_summary(durations), + } + for (grid, block), durations in sorted( + variants.items(), key=lambda item: repr(item[0]) + ) + ], + } + ) + reports.sort(key=lambda item: (-item["duration"]["total_ns"], item["name"])) + kernel_intervals = [(item["start_ns"], item["end_ns"]) for item in kernels] + busy = interval_union_ns(kernel_intervals) + return { + "duration": duration_summary([item["duration_ns"] for item in kernels]), + "busy_union_ns": busy, + "overlap_factor": round(total / busy, 6) if busy else None, + "by_name": reports, + } + + +def bandwidth(group: list[dict]) -> dict: + """Achieved copy bandwidth over the summed copy time (bytes per ns = GB/s).""" + total_bytes = sum(item["bytes"] or 0 for item in group) + total_ns = sum(item["duration_ns"] for item in group) + return { + "total_bytes": total_bytes, + "avg_bytes": round(total_bytes / len(group), 1) if group else None, + "bandwidth_gbps": round(total_bytes / total_ns, 3) if total_ns else None, + } + + +def memcpy_report(intervals: list[dict]) -> dict: + copies = [interval for interval in intervals if interval["kind"] == "memcpy"] + grouped = collections.defaultdict(list) + for interval in copies: + grouped[interval["name"]].append(interval) + return { + "duration": duration_summary([item["duration_ns"] for item in copies]), + **bandwidth(copies), + "by_kind": [ + { + "kind": kind, + "duration": duration_summary([item["duration_ns"] for item in group]), + **bandwidth(group), + } + for kind, group in sorted(grouped.items()) + ], + } + + +def gap_entry(previous: dict, current: dict) -> dict: + return { + "start_ns": previous["end_ns"], + "end_ns": current["start_ns"], + "gap_ns": current["start_ns"] - previous["end_ns"], + "after": previous["name"], + "before": current["name"], + } + + +def top(entries: list[dict], key: str, limit: int) -> list[dict]: + return sorted(entries, key=lambda item: (-item[key], item["start_ns"]))[:limit] + + +def device_idle_gaps(intervals: list[dict], limit: int) -> list[dict]: + """Largest spans with no captured activity on a device: GPU bubbles. + + Activity is compared only within one process and clock domain.""" + grouped = collections.defaultdict(list) + for interval in intervals: + grouped[(interval["pid"], interval["device_id"], interval["clock_domain"])].append(interval) + gaps = [] + for (pid, device, clock), group in grouped.items(): + ordered = sorted(group, key=lambda item: (item["start_ns"], item["end_ns"])) + busy_until = ordered[0] + for current in ordered[1:]: + if current["start_ns"] > busy_until["end_ns"]: + gaps.append( + { + "pid": pid, + "device_id": device, + "clock_domain": clock, + **gap_entry(busy_until, current), + } + ) + if current["end_ns"] > busy_until["end_ns"]: + busy_until = current + return top(gaps, "gap_ns", limit) + + +def stream_report(intervals: list[dict], top_gaps: int) -> list[dict]: + grouped = collections.defaultdict(list) + for interval in intervals: + key = ( + interval["pid"], + interval["device_id"], + interval["context_id"], + interval["stream_id"], + interval["clock_domain"], + ) + grouped[key].append(interval) + + reports = [] + for (pid, device, context, stream, clock), group in grouped.items(): + kernels = sorted( + (item for item in group if item["kind"] == "kernel" and not item.get("partial")), + key=lambda item: (item["start_ns"], item["end_ns"]), + ) + overlaps = [ + previous["end_ns"] - current["start_ns"] + for previous, current in zip(kernels, kernels[1:]) + if current["start_ns"] < previous["end_ns"] + ] + # A stream gap is time no kernel, copy, or memset ran on the stream, + # including one still running from earlier or across a capture edge. + gaps = [] + gap_entries = [] + ordered = sorted(group, key=lambda item: (item["start_ns"], item["end_ns"])) + busy_until = ordered[0] + for current in ordered[1:]: + if current["start_ns"] > busy_until["end_ns"]: + gaps.append(current["start_ns"] - busy_until["end_ns"]) + gap_entries.append(gap_entry(busy_until, current)) + if current["end_ns"] > busy_until["end_ns"]: + busy_until = current + reports.append( + { + "pid": pid, + "device_id": device, + "context_id": context, + "stream_id": stream, + "clock_domain": clock, + "event_counts": dict( + sorted(collections.Counter(item["kind"] for item in group).items()) + ), + "summed_activity_ns": sum(item.get("duration_ns", 0) for item in group), + "busy_union_ns": interval_union_ns( + [(item["start_ns"], item["end_ns"]) for item in group] + ), + "gaps": duration_summary(gaps), + "adjacent_kernel_overlaps": duration_summary(overlaps), + "top_gaps": top(gap_entries, "gap_ns", top_gaps), + } + ) + reports.sort( + key=lambda item: ( + item["pid"] if item["pid"] is not None else -1, + item["device_id"] if item["device_id"] is not None else -1, + item["context_id"] if item["context_id"] is not None else -1, + item["stream_id"] if item["stream_id"] is not None else -1, + item["clock_domain"], + ) + ) + return reports + + +def load_events(path: pathlib.Path) -> list[dict]: + events = [] + with path.open(encoding="utf-8") as source: + for line_number, line in enumerate(source, 1): + if not line.strip(): + continue + event = json.loads(line) + if event.get("schema_version") != "2.0": + raise ValueError( + f"{path}:{line_number}: expected schema_version 2.0" + ) + events.append(event) + if not events: + raise ValueError(f"{path}: trace contains no events") + return events + + +def event_label(event: dict) -> str | None: + cuda = event.get("cuda") or {} + host = event.get("host") or {} + nvtx = event.get("nvtx") or {} + attributes = event.get("attributes") or {} + return ( + cuda.get("kernel_name") + or attributes.get("cuda_api_name") + or nvtx.get("name") + or host.get("symbol_demangled") + or host.get("symbol") + or cuda.get("memcpy_kind") + ) + + +def comparable_clocks(domains: set) -> set: + """Clock domains whose timestamps compare with these.""" + return HOST_CLOCKS if domains <= HOST_CLOCKS else domains + + +def slice_events( + events: list[dict], + start_ns: int, + end_ns: int, + limit: int, + pid: object = None, + clocks: set | None = None, +) -> dict: + """Events inside [start_ns, end_ns], in time order, bounded by limit; a + gap or outlier keeps only its own process and comparable clocks.""" + inside = sorted( + ( + event + for event in events + if start_ns <= event["timestamp_ns"] <= end_ns + and (pid is None or event.get("pid") == pid) + and (clocks is None or event.get("clock_domain") in clocks) + ), + key=lambda event: (event["timestamp_ns"], event.get("sequence", 0)), + ) + rows = [] + for event in inside[:limit]: + cuda = event.get("cuda") or {} + rows.append( + { + "timestamp_ns": event["timestamp_ns"], + "offset_ns": event["timestamp_ns"] - start_ns, + "event_type": event["event_type"], + "name": event_label(event), + "pid": event.get("pid"), + "tid": event.get("tid"), + "stream_id": cuda.get("stream_id"), + "correlation_id": cuda.get("correlation_id"), + "event_id": event.get("event_id"), + } + ) + return { + "start_ns": start_ns, + "end_ns": end_ns, + "events": rows, + "total_events": len(inside), + "truncated": len(inside) > limit, + "counts_by_type": dict( + sorted(collections.Counter(event["event_type"] for event in inside).items()) + ), + } + + +HOST_CLOCKS = {"host_monotonic", "cupti_normalized_to_host_monotonic"} + + +def load_python_samples(path: pathlib.Path) -> list[dict]: + """Records written by `measure --python-sample`.""" + samples = [] + for number, line in enumerate(path.read_text().splitlines(), 1): + if not line.strip(): + continue + record = json.loads(line) + if not isinstance(record, dict) or "timestamp_ns" not in record or "frames" not in record: + raise ValueError(f"{path}:{number}: not a Python sample record") + samples.append(record) + return samples + + +def frame_label(frame: dict) -> str: + return f"{frame['function']} ({frame['file']}:{frame['first_line']})" + + +def python_slice(samples: list[dict], start_ns: int, end_ns: int, limit: int = 10) -> dict: + """Python stacks sampled inside [start_ns, end_ns].""" + inside = [sample for sample in samples if start_ns <= sample["timestamp_ns"] <= end_ns] + gil = [sample for sample in inside if sample["gil"]] + stacks = collections.Counter( + tuple(frame_label(frame) for frame in sample["frames"]) for sample in gil + ) + waits = collections.Counter( + ( + sample["native"].get("syscall"), + sample["native"].get("module"), + sample["native"].get("symbol"), + ) + for sample in inside + if not sample["gil"] and sample.get("native") + ) + return { + "samples": len(inside), + "gil_samples": len(gil), + "gil_stacks": [ + {"frames": list(frames), "samples": count, "proportion": round(count / len(gil), 6)} + for frames, count in sorted(stacks.items(), key=lambda item: (-item[1], item[0]))[:limit] + ], + "threads": dict( + sorted(collections.Counter(str(sample.get("tid")) for sample in inside).items()) + ), + "native_waits": [ + {"syscall": syscall, "module": module, "symbol": symbol, "samples": count} + for (syscall, module, symbol), count in sorted( + waits.items(), key=lambda item: (-item[1], tuple(map(str, item[0]))) + )[:limit] + ], + } + + +def measurement_outliers(path: pathlib.Path, limit: int) -> dict: + """Slowest pairs from a measure result; full evidence when available.""" + result = json.loads(path.read_text()) + if result.get("ok") is not True: + raise ValueError(f"{path}: not a successful measurement result") + edges = result.get("edges") + evidences = ( + [(edge["name"], edge["evidence"]) for edge in edges] + if edges is not None + else [(None, result["evidence"])] + ) + outliers = [] + sources = set() + for edge, evidence in evidences: + if evidence.get("pairs") is not None: + pairs = evidence["pairs"] + sources.add("full_evidence") + else: + pairs = [exemplar["pair"] for exemplar in evidence.get("exemplars", [])] + sources.add("rank_exemplars") + for pair in pairs: + start, end = pair["start"], pair["end"] + outliers.append( + { + "edge": edge, + "latency_ns": pair["latency_ns"], + "start_ns": start["timestamp_ns"], + "end_ns": end["timestamp_ns"], + "start_event": start.get("event_id"), + "end_event": end.get("event_id"), + "pid": start.get("pid"), + "tid": start.get("tid"), + "stream_id": (start.get("cuda") or {}).get("stream_id"), + "correlation_id": (start.get("cuda") or {}).get("correlation_id"), + "clock_domains": sorted( + {str(start.get("clock_domain")), str(end.get("clock_domain"))} + ), + } + ) + outliers.sort(key=lambda item: (-item["latency_ns"], item["start_ns"])) + return { + "input": str(path), + "source": sorted(sources), + "slowest": outliers[:limit], + } + + +def load_manifest(path: pathlib.Path) -> dict | None: + """The capture manifest written beside an artifact, if any. A manifest + whose size or SHA-256 no longer matches the artifact describes other + events and is an error, as it is for `measure --input`.""" + manifest_path = path.with_name(path.name + ".manifest.json") + if not manifest_path.exists(): + return None + manifest = json.loads(manifest_path.read_text()) + artifact = manifest.get("artifact") or {} + data = path.read_bytes() + if artifact.get("bytes") != len(data) or artifact.get("sha256") != hashlib.sha256(data).hexdigest(): + raise ValueError( + f"{manifest_path} describes a different artifact than {path}; " + "delete the stale manifest to analyze the events without it" + ) + return manifest + + +def manifest_window(manifest: dict | None) -> tuple[int, int] | None: + if manifest is None: + return None + return manifest["window"]["start_ns"], manifest["window"]["end_ns"] + + +def capture_warnings(path: pathlib.Path, manifest: dict | None) -> list[dict]: + """What the manifest says the capture missed.""" + if manifest is None or not manifest.get("all_gpu_activity"): + warnings = [ + { + "code": "GPU_ACTIVITY_COVERAGE_UNKNOWN", + "message": f"no manifest records that {path} captured every kernel, copy, and memset; device idle time may include activity the capture filtered out", + } + ] + else: + warnings = [] + if manifest is None: + return warnings + losses = { + "dropped_records": manifest.get("dropped_records", 0), + "unknown_records": manifest.get("unknown_records", 0), + } + lost = {name: count for name, count in losses.items() if count} + if lost or manifest.get("record_limit_reached") is not None or manifest.get("capture_failed"): + warnings.append( + { + "code": "CAPTURE_INCOMPLETE", + "message": f"{path} lost records ({lost or 'none counted'}), hit its record limit, or failed; budgets and gaps miss that activity", + } + ) + return warnings + + +# Wall-clock offsets of a capture's start and end anchors that differ by more +# than this mean the wall clock was stepped or slewed during the capture. +WALL_CLOCK_DRIFT_NS = 1_000_000 + + +def wall_clock(manifest: dict | None): + """A function from host-clock nanoseconds to a UTC timestamp, and the + drift between the capture's start and end anchors; `None` without one.""" + anchors = (manifest or {}).get("wall_clock") + if not anchors: + return None, None + start, end = anchors["start"], anchors["end"] + + def offset(anchor: dict) -> int: + return anchor["realtime_ns"] - anchor["monotonic_ns"] + + def to_wall(monotonic_ns: int) -> str: + nearer = min((start, end), key=lambda anchor: abs(monotonic_ns - anchor["monotonic_ns"])) + realtime = monotonic_ns + offset(nearer) + seconds, nanoseconds = divmod(realtime, 1_000_000_000) + moment = datetime.datetime.fromtimestamp(seconds, datetime.timezone.utc) + return moment.strftime("%Y-%m-%dT%H:%M:%S") + f".{nanoseconds:09d}Z" + + return to_wall, offset(end) - offset(start) + + +def annotate_wall(node, to_wall, clocks: set) -> None: + """Add UTC wall times beside host-clock `start_ns`, `end_ns`, and + `timestamp_ns` fields; raw CUPTI timestamps are left alone. A node + without its own clock inherits its parent's.""" + if isinstance(node, list): + for item in node: + annotate_wall(item, to_wall, clocks) + return + if not isinstance(node, dict): + return + if node.get("clock_domains"): + clocks = set(node["clock_domains"]) + elif node.get("clock_domain"): + clocks = {node["clock_domain"]} + host = bool(clocks) and clocks <= HOST_CLOCKS + for field, wall in (("start_ns", "start_wall"), ("end_ns", "end_wall"), ("timestamp_ns", "wall_time")): + if host and isinstance(node.get(field), int): + node[wall] = to_wall(node[field]) + for value in list(node.values()): + annotate_wall(value, to_wall, clocks) + + +def device_uuids(manifest: dict | None) -> dict: + if manifest is None: + return {} + pid = manifest["target"]["pid"] + return {(pid, device["device_id"]): device["uuid"] for device in manifest.get("cuda_devices", [])} + + +def analyze( + path: pathlib.Path, + *, + top_gaps: int = 5, + comm_kernel: re.Pattern = re.compile(DEFAULT_COMM_KERNEL), + measurement: pathlib.Path | None = None, + outliers: int = 10, + window: tuple[str, object] | None = None, + window_ns: int = 0, + max_slice_events: int = 200, + python_samples: pathlib.Path | None = None, +) -> dict: + events = load_events(path) + manifest = load_manifest(path) + intervals, unmatched_starts, unmatched_ends = pair_activities(events) + # Activity seen at one boundary only ran to the edge of the capture; it + # keeps the device busy rather than leaving a false idle gap. + partial = boundary_intervals(events, intervals, manifest_window(manifest)) + summed = sum(item["duration_ns"] for item in intervals) + warnings = capture_warnings(path, manifest) + if unmatched_starts or unmatched_ends: + warnings.append( + { + "code": "UNPAIRED_ACTIVITY_BOUNDARIES", + "message": "durations exclude unpaired start or end records; device budgets stretch them to the capture edge", + } + ) + idle_gaps = device_idle_gaps(intervals + partial, top_gaps) + outlier_report = measurement_outliers(measurement, outliers) if measurement else None + window_report = None + if window is not None: + kind, value = window + if kind == "gap": + if not 1 <= value <= len(idle_gaps): + raise ValueError(f"--slice-gap {value}: only {len(idle_gaps)} idle gaps") + target = idle_gaps[value - 1] + elif kind == "outlier": + if outlier_report is None: + raise ValueError("--slice-outlier requires --measurement") + if not 1 <= value <= len(outlier_report["slowest"]): + raise ValueError( + f"--slice-outlier {value}: only {len(outlier_report['slowest'])} outliers" + ) + target = outlier_report["slowest"][value - 1] + else: + target = {"start_ns": value[0], "end_ns": value[1]} + start_ns = target["start_ns"] - window_ns + end_ns = target["end_ns"] + window_ns + if kind == "gap": + scope = {"pid": target["pid"], "clocks": comparable_clocks({target["clock_domain"]})} + elif kind == "outlier": + scope = {"pid": target["pid"], "clocks": comparable_clocks(set(target["clock_domains"]))} + else: + scope = {} + window_report = { + "around": {"kind": kind, "start_ns": target["start_ns"], "end_ns": target["end_ns"]}, + "window_ns": window_ns, + **slice_events(events, start_ns, end_ns, max_slice_events, **scope), + } + if python_samples is not None: + window_report["python"] = None + # Python samples use CLOCK_MONOTONIC; only host-clock slices line + # up with them. A gap or outlier carries its own clock and + # process; a time range uses the events inside it, or the whole + # trace when it holds none. + evidence = [ + event for event in events if start_ns <= event["timestamp_ns"] <= end_ns + ] or events + if kind == "gap": + domains = {target["clock_domain"]} + pids = {target["pid"]} + elif kind == "outlier": + domains = set(target["clock_domains"]) + pids = {target["pid"]} + else: + domains = {event.get("clock_domain") for event in evidence} + pids = {event.get("pid") for event in evidence} + if not domains or not domains <= HOST_CLOCKS: + warnings.append( + { + "code": "PYTHON_CLOCK_UNALIGNED", + "message": "the slice's timestamps are not all CLOCK_MONOTONIC; Python samples were not placed in it", + } + ) + else: + samples = load_python_samples(python_samples) + matching = [sample for sample in samples if sample.get("pid") in pids] + if len(matching) != len(samples): + warnings.append( + { + "code": "PYTHON_SAMPLES_OTHER_PROCESS", + "message": f"{len(samples) - len(matching)} Python samples come from processes other than the slice's and were left out", + } + ) + window_report["python"] = python_slice(matching, start_ns, end_ns) + if outlier_report and outlier_report["source"] == ["rank_exemplars"]: + warnings.append( + { + "code": "OUTLIERS_FROM_EXEMPLARS", + "message": "measurement has summary evidence; rerun with --evidence full to rank every pair", + } + ) + to_wall, drift = wall_clock(manifest) + if drift is not None and abs(drift) > WALL_CLOCK_DRIFT_NS: + warnings.append( + { + "code": "WALL_CLOCK_DRIFT", + "message": f"the wall clock moved {drift} ns against CLOCK_MONOTONIC during the capture; wall times carry that error", + } + ) + report = { + "analysis_version": "1.5", + "input": str(path), + "events": { + "total": len(events), + "by_type": dict( + sorted(collections.Counter(event["event_type"] for event in events).items()) + ), + "paired_activities": len(intervals), + "unmatched_activity_starts": unmatched_starts, + "unmatched_activity_ends": unmatched_ends, + }, + "capture": { + "manifest": manifest is not None, + "all_gpu_activity": bool(manifest and manifest.get("all_gpu_activity")), + "window": manifest["window"] if manifest else None, + "wall_clock_drift_ns": drift, + "communication_kernels": comm_kernel.pattern, + }, + "devices": device_budgets(intervals + partial, device_uuids(manifest), comm_kernel, top_gaps), + "gpu": { + "summed_activity_ns": summed, + "top_idle_gaps": idle_gaps, + }, + "kernels": kernel_report(intervals), + "memcpy": memcpy_report(intervals), + "memset": { + "duration": duration_summary( + [ + item["duration_ns"] + for item in intervals + if item["kind"] == "memset" + ] + ) + }, + "streams": stream_report(intervals + partial, top_gaps), + "outliers": outlier_report, + "slice": window_report, + "warnings": warnings, + } + if to_wall is not None: + clocks = {event.get("clock_domain") for event in events} + for section in ("capture", "devices", "gpu", "streams", "outliers", "slice"): + annotate_wall(report[section], to_wall, clocks) + return report + + +def compare(paths: list[pathlib.Path], *, top_gaps: int, comm_kernel: re.Pattern) -> dict: + """GPU budgets of several artifacts of one host, over the window they + share. Each artifact is one process, so its events are never paired with + another's; only their time budgets are compared.""" + inputs = [] + warnings = [] + for path in paths: + events = load_events(path) + manifest = load_manifest(path) + intervals, _, _ = pair_activities(events) + intervals += boundary_intervals(events, intervals, manifest_window(manifest)) + clocks = {item["clock_domain"] for item in intervals} + if manifest is None: + warnings.append( + { + "code": "NO_MANIFEST", + "message": f"{path} has no manifest: its window is its activity span and its GPUs have no UUIDs", + } + ) + warnings.extend(capture_warnings(path, manifest)) + _, drift = wall_clock(manifest) + if drift is not None and abs(drift) > WALL_CLOCK_DRIFT_NS: + warnings.append( + { + "code": "WALL_CLOCK_DRIFT", + "message": f"{path}: the wall clock moved {drift} ns against CLOCK_MONOTONIC during the capture; its wall times carry that error", + } + ) + if manifest is not None: + window = (manifest["window"]["start_ns"], manifest["window"]["end_ns"]) + elif intervals: + window = ( + min(item["start_ns"] for item in intervals), + max(item["end_ns"] for item in intervals), + ) + else: + window = None + inputs.append((path, intervals, manifest, clocks, window)) + host = all(clocks and clocks <= HOST_CLOCKS for _, _, _, clocks, _ in inputs) + windows = [window for *_, window in inputs if window is not None] + common = None + if host and len(windows) == len(inputs): + start = max(window[0] for window in windows) + end = min(window[1] for window in windows) + common = (start, end) if start < end else None + if not host: + warnings.append( + { + "code": "CLOCKS_NOT_COMPARABLE", + "message": "not every artifact is on CLOCK_MONOTONIC; each is budgeted over its own span", + } + ) + elif common is None: + warnings.append( + { + "code": "NO_COMMON_WINDOW", + "message": "the artifacts share no instant; each is budgeted over its own span, so compare shares, not totals", + } + ) + rows = [] + for path, intervals, manifest, _, _ in inputs: + for row in device_budgets(intervals, device_uuids(manifest), comm_kernel, top_gaps, common): + span = row["span"]["ns"] + row["input"] = str(path) + to_wall, _ = wall_clock(manifest) + if to_wall is not None: + annotate_wall(row, to_wall, set()) + row["shares"] = { + name: round(row[f"{name}_ns"] / span, 6) if span else None + for name in ("busy", "idle", "compute", "communication_only") + } + rows.append(row) + def extreme(key, pick): + candidates = [row for row in rows if row["shares"][key] is not None] + if not candidates: + return None + row = pick(candidates, key=lambda row: row["shares"][key]) + return {"input": row["input"], "pid": row["pid"], "device_id": row["device_id"], + "uuid": row["uuid"], "share": row["shares"][key]} + computes = [row["shares"]["compute"] for row in rows if row["shares"]["compute"] is not None] + return { + "analysis_version": "1.5", + "inputs": [str(path) for path in paths], + "window": {"start_ns": common[0], "end_ns": common[1]} if common else None, + "communication_kernels": comm_kernel.pattern, + "devices": rows, + "spread": { + "compute_share": round(max(computes) - min(computes), 6) if computes else None, + # On a collective, the rank that computes longest is the one its + # peers wait for; the one waiting longest computes least. + "most_compute": extreme("compute", max), + "most_communication_only": extreme("communication_only", max), + "most_idle": extreme("idle", max), + }, + "warnings": warnings, + } + + +def parse_around(value: str) -> tuple[int, int]: + start, _, end = value.partition(":") + start_ns = int(start) + end_ns = int(end) if end else start_ns + if end_ns < start_ns: + raise argparse.ArgumentTypeError("--around END_NS must not precede START_NS") + return (start_ns, end_ns) + + +def positive(value: str) -> int: + number = int(value) + if number < 1: + raise argparse.ArgumentTypeError("must be at least 1") + return number + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Summarize kernels, copies, overlap, streams, gaps, outliers, " + "and time slices in xprobe Event JSONL" + ) + parser.add_argument("trace", type=pathlib.Path, nargs="+", + help="Event JSONL artifacts; several compare per-GPU budgets across processes") + parser.add_argument("--comm-kernel", default=DEFAULT_COMM_KERNEL, metavar="REGEX", + help="kernel names counted as communication (default: nccl, which also matches mangled names)") + parser.add_argument("--top-gaps", type=positive, default=5, + help="idle gaps to rank per device and per stream") + parser.add_argument("--measurement", type=pathlib.Path, + help="measure result JSON whose slowest pairs to rank") + parser.add_argument("--outliers", type=positive, default=10, + help="slowest pairs to list from --measurement") + target = parser.add_mutually_exclusive_group() + target.add_argument("--slice-gap", type=positive, metavar="RANK", + help="list events around the RANK-th largest device idle gap") + target.add_argument("--slice-outlier", type=positive, metavar="RANK", + help="list events around the RANK-th slowest measured pair") + target.add_argument("--around", type=parse_around, metavar="START_NS[:END_NS]", + help="list events around explicit timestamps") + parser.add_argument("--window-ms", type=float, default=0.0, + help="padding before and after the slice target") + parser.add_argument("--max-slice-events", type=positive, default=200) + parser.add_argument("--python-samples", type=pathlib.Path, + help="measure --python-sample artifact whose stacks to add to the slice") + args = parser.parse_args() + try: + comm_kernel = re.compile(args.comm_kernel) + except re.error as error: + parser.error(f"--comm-kernel is not a regular expression: {error}") + if len(args.trace) > 1: + if args.measurement or args.slice_gap or args.slice_outlier or args.around or args.python_samples: + parser.error("--measurement, slices, and --python-samples take one trace") + report = compare(args.trace, top_gaps=args.top_gaps, comm_kernel=comm_kernel) + json.dump(report, sys.stdout, indent=2, sort_keys=True) + sys.stdout.write("\n") + return + if args.python_samples is not None and not ( + args.slice_gap or args.slice_outlier or args.around + ): + parser.error("--python-samples requires --slice-gap, --slice-outlier, or --around") + if args.window_ms < 0: + parser.error("--window-ms must not be negative") + window = None + if args.slice_gap is not None: + window = ("gap", args.slice_gap) + elif args.slice_outlier is not None: + window = ("outlier", args.slice_outlier) + elif args.around is not None: + window = ("timestamps", args.around) + report = analyze( + args.trace[0], + top_gaps=args.top_gaps, + comm_kernel=comm_kernel, + measurement=args.measurement, + outliers=args.outliers, + window=window, + window_ns=round(args.window_ms * 1_000_000), + max_slice_events=args.max_slice_events, + python_samples=args.python_samples, + ) + json.dump(report, sys.stdout, indent=2, sort_keys=True) + sys.stdout.write("\n") + + +if __name__ == "__main__": + main() diff --git a/tests/agent-contract/fixtures/workflow-routes.json b/tests/agent-contract/fixtures/workflow-routes.json index 6494e9d..be98f06 100644 --- a/tests/agent-contract/fixtures/workflow-routes.json +++ b/tests/agent-contract/fixtures/workflow-routes.json @@ -1,106 +1,70 @@ { "scenarios": [ { - "name": "existing_artifact", - "sources": [ - "skill" - ], + "name": "offline_recorrelate", + "sources": ["skill", "data_format"], "required": [ "measure --input", - "skip installation", - "unless a new capture is required" + "scripts/analyze_trace.py", + ".manifest.json" ] }, { - "name": "unknown_workload", - "sources": [ - "skill" - ], + "name": "scripting_and_rsi", + "sources": ["skill", "data_format"], "required": [ - "unknown live workload", - "--triage", - "next.spec", - "not_covered" + "evidence.artifact.path", + "attributes.cuda_api_name", + "rsi", + "wall_clock" ] }, { - "name": "known_selector", - "sources": [ - "skill" - ], + "name": "measurement_graph", + "sources": ["skill", "selectors"], "required": [ - "known boundary", - "skip triage", - "validate" + "measure --spec", + "1โ€“8 endpoints", + "8 cupti agent filters" ] }, { - "name": "several_boundaries", - "sources": [ - "skill", - "selectors" - ], + "name": "gpu_idle_and_trigger", + "sources": ["skill", "data_format"], "required": [ - "measurement graph", - "up to eight edges", - "at most two syscall, tracepoint, or usdt endpoints" + "--trigger-idle-ms", + "all_gpu_activity", + "--slice-gap", + "cuda_devices" ] }, { - "name": "dig_deeper", - "sources": [ - "skill", - "deep_dive" - ], - "required": [ - "dig deeper", - "split it with a measurement graph", - "rank the slowest pairs", - "not covered by this release", - "stop escalating", - "--slice-gap" - ] - }, - { - "name": "python_semantics", - "sources": [ - "skill", - "interpreting", - "selectors" - ], + "name": "python_sampling", + "sources": ["skill", "data_format", "selectors"], "required": [ + "--python-sample", + "gil_hotspots", "python_status", - "native fallback", - "-X perf", - "python:gc_start", - "check capability, not the process name" + "python:gc_start" ] }, { - "name": "multi_process", - "sources": [ - "skill", - "multi_process" - ], + "name": "cross_process_and_clocks", + "sources": ["skill", "data_format"], "required": [ - "discover --pid root", - "pid plus process start time", - "do not cancel sibling commands", - "do not concatenate artifacts" + "clock_monotonic", + "cupti_normalized_to_host_monotonic", + "discover", + "measure --input" ] }, { - "name": "container_namespace", - "sources": [ - "skill", - "setup" - ], + "name": "container_and_nvtx", + "sources": ["skill"], "required": [ - "container target", "pid and mount namespaces", - "namespace-local pid", - "do not guess a pod, container, or pid", - "does not add capabilities" + "nvtx_injection64_path", + "ptrace" ] } ] diff --git a/tests/agent-contract/test_contract.py b/tests/agent-contract/test_contract.py index 93ffcf2..df4bd02 100755 --- a/tests/agent-contract/test_contract.py +++ b/tests/agent-contract/test_contract.py @@ -15,7 +15,8 @@ "validate", "measure", } -SKILL_PATH = "skills/xprobe-measure-latency/SKILL.md" +SKILL_NAME = "xprobe-perf-profiling" +SKILL_PATH = f"skills/{SKILL_NAME}/SKILL.md" SKILL_WORD_BUDGET = 800 SKILL_TOTAL_WORD_BUDGET = 4000 @@ -49,14 +50,26 @@ def development_version(workspace: pathlib.Path) -> str: return version_match.group(1) +def version_key(version: str) -> tuple[int, int, int, float]: + """X.Y.Z or X.Y.Z-dev.N; a dev release sorts before its X.Y.Z.""" + match = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)(?:-dev\.(\d+))?", version) + assert match is not None, version + major, minor, patch, dev = match.groups() + return int(major), int(minor), int(patch), float(dev) if dev else float("inf") + + def release_version(workspace: pathlib.Path) -> str: installer = (workspace / "install.sh").read_text() - release_match = re.search(r"^version=\$\{XPROBE_VERSION:-([^}]+)\}$", installer, re.MULTILINE) + release_match = re.search( + r"^version=\$\{XPROBE_VERSION:-([^}]+)\}$", installer, re.MULTILINE + ) assert release_match is not None return release_match.group(1) -def check_documented_flags(binary: pathlib.Path, documents: list[pathlib.Path]) -> set[str]: +def check_documented_flags( + binary: pathlib.Path, documents: list[pathlib.Path] +) -> set[str]: """Require every flag in a documented `xprobe` command to exist in --help.""" help_flags: dict[str, set[str]] = {} for document in documents: @@ -74,19 +87,220 @@ def check_documented_flags(binary: pathlib.Path, documents: list[pathlib.Path]) capture_output=True, text=True, ).stdout - help_flags[subcommand] = set(re.findall(r"--[a-z][a-z0-9-]*", help_text)) + help_flags[subcommand] = set( + re.findall(r"--[a-z][a-z0-9-]*", help_text) + ) for flag in re.findall(r"(?.manifest.json`)": ["capture-manifest"], + "Python sample JSONL (`--python-sample`)": [ + "python-sample-record", + "python-sample-result", + ], + "Inventory, measurement, and trigger stdout fields": ALL_RESULT_SCHEMAS, + "Bundled analyzer (`scripts/analyze_trace.py`)": [], + "One-off script recipes & RSI loops": ALL_RESULT_SCHEMAS + ["capture-manifest"], +} + + +def schema_fields(schema: dict) -> tuple[set, dict]: + """Every property name in a schema, and its root object.""" + names = set() + + def walk(node: object) -> None: + if isinstance(node, dict): + properties = node.get("properties") + if isinstance(properties, dict): + names.update(properties) + for value in node.values(): + walk(value) + elif isinstance(node, list): + for value in node: + walk(value) + + walk(schema) + return names, schema + + +def resolve_path(schema: dict, root: dict, parts: list[str]) -> bool: + """Whether `parts` is a property path from the schema's root object.""" + definitions = root.get("$defs", {}) + + def objects(node: dict) -> list[dict]: + if "$ref" in node: + return objects(definitions[node["$ref"].rsplit("/", 1)[1]]) + found = [node] if "properties" in node else [] + for key in ("anyOf", "oneOf", "allOf"): + for option in node.get(key, []): + found += objects(option) + if "items" in node: + found += objects(node["items"]) + return found + + nodes = [schema] + for part in parts: + nodes = [ + child + for node in nodes + for candidate in objects(node) + for name, child in candidate["properties"].items() + if name == part + ] + if not nodes: + return False + return True + + +def check_json_blocks(documents: list[pathlib.Path]) -> None: + """Every ```json block in the Skill parses as valid JSON or JSONL.""" + for document in documents: + for block in re.findall(r"```json\n(.*?)```", document.read_text(), re.DOTALL): + text = block.strip() + try: + json.loads(text) + except json.JSONDecodeError: + for line in text.splitlines(): + if line.strip(): + json.loads(line) + + +def check_artifact_fields( + workspace: pathlib.Path, reference: pathlib.Path, analyzer: pathlib.Path +) -> None: + """Every field cited in data-format.md prose exists in the schemas or analyzer.""" + analyzer_text = analyzer.read_text() + event_source = (workspace / "xprobe/protocol/src/event.rs").read_text() + assert '"start_unknown"' in event_source + python = json.loads( + (workspace / "schemas/python-sample-result.schema.json").read_text() + ) + assert resolve_path(python, python, ["inventory", "gil_stack_groups"]) + assert not resolve_path(python, python, ["collection", "gil_stack_groups"]) + + sections = re.split(r"^## (.+)$", reference.read_text(), flags=re.MULTILINE) + assert set(sections[1::2]) == set(DATA_FORMAT_SECTIONS), sections[1::2] + for title, body in zip(sections[1::2], sections[2::2]): + prose = re.sub(r"```.*?```", "", body, flags=re.DOTALL) + schemas = [ + json.loads((workspace / f"schemas/{name}.schema.json").read_text()) + for name in DATA_FORMAT_SECTIONS[title] + ] + names = ( + set().union(*(schema_fields(schema)[0] for schema in schemas)) + if schemas + else set() + ) + for cited in re.findall(r"`([a-z_][a-z0-9_.\[\]]*)`", prose): + if cited.endswith(".py"): + continue + parts = [ + part + for part in re.split(r"[.\[\]]", cited) + if part and not part.isdigit() + ] + if all( + part in DATA_FORMAT_VALUES or part in EVENT_ATTRIBUTES for part in parts + ): + continue + if not schemas: + assert all(f'"{part}"' in analyzer_text for part in parts), ( + title, + cited, + ) + elif len(parts) > 1 and "." in cited: + if parts[0] == "attributes" and parts[1] in EVENT_ATTRIBUTES: + continue + if parts[0] == "details" and parts[1] in DATA_FORMAT_VALUES: + continue + assert any(resolve_path(schema, schema, parts) for schema in schemas), ( + title, + cited, + ) + else: + assert all(part in names for part in parts), (title, cited) + + def check_skill(workspace: pathlib.Path, binary: pathlib.Path) -> None: skill_path = workspace / SKILL_PATH skill_root = skill_path.parent.resolve() skill = skill_path.read_text() frontmatter = re.match(r"^---\n(.*?)\n---", skill, re.DOTALL) assert frontmatter is not None - assert re.search(r"^name: xprobe-measure-latency$", frontmatter.group(1), re.MULTILINE) + assert re.search( + rf"^name: {re.escape(SKILL_NAME)}$", frontmatter.group(1), re.MULTILINE + ) assert re.search(r"^description: .+", frontmatter.group(1), re.MULTILINE) # The entry point stays short; details live in linked references. @@ -96,51 +310,42 @@ def check_skill(workspace: pathlib.Path, binary: pathlib.Path) -> None: assert total <= SKILL_TOTAL_WORD_BUDGET, total # Every link resolves inside the Skill, and every reference is reachable. - linked = set() for document in [skill_path, *references]: for relative_link in re.findall(r"\]\(([^)]+)\)", document.read_text()): target = (document.parent / relative_link).resolve() assert target.is_relative_to(skill_root), (document, relative_link) assert target.is_file(), (document, relative_link) - linked.add(target) skill_links = { (skill_root / link).resolve() for link in re.findall(r"\]\(([^)]+)\)", skill) } assert {path.resolve() for path in references} <= skill_links, "orphaned reference" - # The entry point covers the two-command flow and its safety invariants. + # Entry point links to references, analyzer, and core entry modes. normalized_skill = re.sub(r"\s+", " ", skill) for required in ( - "--triage", "measure --spec", "measure --input", "validate", "quality.verdict", - "not_covered", - "measurement graph", - "Dig deeper", - "PID plus procfs start time", - "Bound every capture", - "leave the CUPTI shared object mapped", - "temporal correlation is not exact causality", + "references/data-format.md", + "references/selectors.md", "scripts/analyze_trace.py", - "NCU or PC sampling", ): assert required in normalized_skill, required # Every documented xprobe command uses flags its subcommand accepts. - checked = check_documented_flags(binary, [skill_path, *references]) - assert {"measure", "validate"} <= checked, sorted(checked) + check_documented_flags(binary, [skill_path, *references]) + check_json_blocks([skill_path, *references]) analyzer = skill_root / "scripts/analyze_trace.py" + check_artifact_fields(workspace, skill_root / "references/data-format.md", analyzer) assert analyzer.is_file() assert os.access(analyzer, os.X_OK) assert not list(skill_root.rglob("__pycache__")) assert not list(skill_root.rglob("*.pyc")) - # Examples are valid templates for each spec shape. + # Examples are valid templates for spec-based modes. modes = set() - policies = set() for example in sorted((skill_root / "examples").glob("*.json")): specification = json.loads(example.read_text()) if "edges" in specification: @@ -149,55 +354,28 @@ def check_skill(workspace: pathlib.Path, binary: pathlib.Path) -> None: names = set(specification["endpoints"]) for edge in specification["edges"]: assert {edge["from"], edge["to"]} <= names, example - policies.add(edge["match_policy"]) continue assert specification["schema_version"] == "2.0", example - if "sample_event" in specification: - modes.add("cpu_sample") - assert specification["frequency_hz"] > 0, example - assert specification["max_samples"] > 0, example - continue - if "max_inflight" in specification and "start_selector" not in specification: - modes.add("syscall_aggregate") - assert specification["max_groups"] > 0, example - continue mode = specification.get("measurement_mode", "exact") modes.add(mode) - if mode == "aggregate": - assert specification["max_events"] is None, example - assert specification["max_groups"] > 0, example - else: - assert specification["max_events"] > 0, example - policies.add(specification["match_policy"]) - assert modes == {"exact", "aggregate", "cpu_sample", "syscall_aggregate", "graph"} - assert {"exact", "first_after", "stack_nested", "stream_order"} <= policies + assert specification["max_events"] > 0, example + assert {"exact", "graph"} <= modes, sorted(modes) openai_yaml = (skill_root / "agents/openai.yaml").read_text() - assert 'display_name: "Xprobe Workload Profiling"' in openai_yaml - assert "$xprobe-measure-latency" in openai_yaml - - setup = re.sub(r"\s+", " ", (skill_root / "references/setup.md").read_text()) - major, minor, _ = development_version(workspace).split(".") - release = release_version(workspace) - for required in ( - f"xprobe `{major}.{minor}.x`", - f"v{release}/install.sh", - "npx skills@1 add", - "xprobe --version", - "xprobe doctor", - "PID and mount namespaces", - "namespace-local PID", - "does not add capabilities", - "CUDA/CUPTI majors other than 12 or 13 are not supported", - ): - assert required in setup, required + assert 'display_name: "Xprobe Performance Profiling"' in openai_yaml + assert f"${SKILL_NAME}" in openai_yaml def check_readme_art(workspace: pathlib.Path) -> None: """README art is generated; committed SVGs must match the renderer.""" with tempfile.TemporaryDirectory(prefix="xprobe-art-") as directory: subprocess.run( - [sys.executable, "-I", workspace / "scripts/render-readme-art.py", directory], + [ + sys.executable, + "-I", + workspace / "scripts/render-readme-art.py", + directory, + ], check=True, ) rendered = sorted(pathlib.Path(directory).glob("*.svg")) @@ -208,7 +386,10 @@ def check_readme_art(workspace: pathlib.Path) -> None: f"{committed} is stale; run scripts/render-readme-art.py docs/assets" ) readme = (workspace / "README.md").read_text() - for asset in ("docs/assets/xprobe-flow-light.svg", "docs/assets/xprobe-flow-dark.svg"): + for asset in ( + "docs/assets/xprobe-flow-light.svg", + "docs/assets/xprobe-flow-dark.svg", + ): assert asset in readme, asset @@ -226,7 +407,7 @@ def check_installation_docs(workspace: pathlib.Path) -> None: development = development_version(workspace) release = release_version(workspace) installer = (workspace / "install.sh").read_text() - assert tuple(map(int, development.split("."))) >= tuple(map(int, release.split("."))) + assert version_key(development) >= version_key(release) assert f"default: {release}" in installer for relative_path in ( @@ -235,8 +416,11 @@ def check_installation_docs(workspace: pathlib.Path) -> None: "docs/agent-integration.md", ): document = (workspace / relative_path).read_text() - assert "npx skills@1 add" in document, relative_path - assert f"/v{release}/" in document, relative_path + assert "npx skills add itdevwu/xprobe" in document, relative_path + installation = (workspace / "docs/installation.md").read_text() + assert "npx skills@1 add" in installation + assert f"/v{release}/" in installation + assert f"/skills/{SKILL_NAME}" in installation def main() -> None: @@ -310,7 +494,9 @@ def main() -> None: documented = check_documented_flags( binary, [workspace / "README.md", *sorted((workspace / "docs").glob("*.md"))] ) - assert {"doctor", "discover", "validate", "measure"} <= documented, sorted(documented) + assert {"doctor", "discover", "validate", "measure"} <= documented, sorted( + documented + ) print( json.dumps( { diff --git a/tests/agent-contract/test_skill_install.sh b/tests/agent-contract/test_skill_install.sh index a4b98b8..102efc0 100755 --- a/tests/agent-contract/test_skill_install.sh +++ b/tests/agent-contract/test_skill_install.sh @@ -12,19 +12,19 @@ install_for() { agent=$1 home=$temporary_dir/$agent HOME=$home npx --yes skills@1.5.20 add "$root" \ - --skill xprobe-measure-latency \ + --skill xprobe-perf-profiling \ --agent "$agent" \ --global \ --copy \ --yes >/dev/null case $agent in - claude-code) installed=$home/.claude/skills/xprobe-measure-latency ;; - codex|cursor) installed=$home/.agents/skills/xprobe-measure-latency ;; + claude-code) installed=$home/.claude/skills/xprobe-perf-profiling ;; + codex|cursor) installed=$home/.agents/skills/xprobe-perf-profiling ;; *) printf 'unsupported test agent: %s\n' "$agent" >&2; exit 2 ;; esac - diff -r "$root/skills/xprobe-measure-latency" "$installed" + diff -r "$root/skills/xprobe-perf-profiling" "$installed" } install_for codex diff --git a/tests/agent-contract/test_trace_analysis.py b/tests/agent-contract/test_trace_analysis.py index 306bfb8..b376b3b 100755 --- a/tests/agent-contract/test_trace_analysis.py +++ b/tests/agent-contract/test_trace_analysis.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +import hashlib import json import pathlib import subprocess @@ -54,7 +55,7 @@ def pair(sequence: int, kind: str, start: int, end: int, **kwargs: object) -> li def main() -> None: workspace = pathlib.Path(__file__).resolve().parents[2] - script = workspace / "skills/xprobe-measure-latency/scripts/analyze_trace.py" + script = workspace / "skills/xprobe-perf-profiling/scripts/analyze_trace.py" events = [ *pair( 1, @@ -122,9 +123,10 @@ def main() -> None: report = json.loads(completed.stdout) assert report["events"]["total"] == 8 assert report["events"]["paired_activities"] == 4 - assert report["gpu"]["busy_union_ns"] == 270 + device = report["devices"][0] + assert (device["busy_ns"], device["idle_ns"], device["summed_activity_ns"]) == (270, 0, 350) + assert (device["compute_ns"], device["transfer_ns"]) == (220, 50) assert report["gpu"]["summed_activity_ns"] == 350 - assert report["gpu"]["overlap_factor"] == 1.296296 assert report["kernels"]["busy_union_ns"] == 220 assert report["kernels"]["overlap_factor"] == 1.363636 vector_add = report["kernels"]["by_name"][0] @@ -136,14 +138,177 @@ def main() -> None: assert report["memcpy"]["total_bytes"] == 4096 assert report["memset"]["duration"]["count"] == 0 stream = next(item for item in report["streams"] if item["stream_id"] == 7) - assert stream["adjacent_kernel_gaps"]["count"] == 1 - assert stream["adjacent_kernel_gaps"]["p50_ns"] == 20 - assert report["warnings"] == [] + assert stream["gaps"]["count"] == 1 + assert stream["gaps"]["p50_ns"] == 20 + # Without a manifest nothing says every activity was captured. + assert [item["code"] for item in report["warnings"]] == ["GPU_ACTIVITY_COVERAGE_UNKNOWN"] assert unpaired["events"]["unmatched_activity_starts"] == 1 - assert unpaired["warnings"][0]["code"] == "UNPAIRED_ACTIVITY_BOUNDARIES" + assert "UNPAIRED_ACTIVITY_BOUNDARIES" in {item["code"] for item in unpaired["warnings"]} assert rejected.returncode != 0 assert "expected schema_version 2.0" in rejected.stderr check_gaps_outliers_and_slices(script) + check_rank_comparison(script) + check_capture_edges(script) + check_running_marker(script) + + +EPOCH_2023 = 1_700_000_000_000_000_000 + + +def write_with_manifest(path: pathlib.Path, events: list[dict], manifest: dict) -> None: + data = "".join(json.dumps(item) + "\n" for item in events).encode() + path.write_bytes(data) + manifest = { + **manifest, + "artifact": { + "format": "jsonl", + "events": len(events), + "bytes": len(data), + "sha256": hashlib.sha256(data).hexdigest(), + }, + } + path.with_name(path.name + ".manifest.json").write_text(json.dumps(manifest)) + + +def check_running_marker(script: pathlib.Path) -> None: + """A start known only as running at STOP never pairs with an earlier end + of the same key; it keeps its stream busy to the window's end.""" + host = {"clock_domain": "cupti_normalized_to_host_monotonic"} + events = [ + {**event(1, "gpu_kernel_end", 10, stream_id=7, correlation_id=5, kernel_name="k"), **host}, + { + **event(2, "gpu_kernel_start", 10, stream_id=7, correlation_id=5, kernel_name="k"), + **host, + "attributes": {"start_unknown": True}, + }, + ] + manifest = { + "target": {"pid": 1234, "process_start_time": 1}, + "window": {"start_ns": 0, "end_ns": 100}, + "all_gpu_activity": True, + "dropped_records": 0, + "unknown_records": 0, + "record_limit_reached": None, + "capture_failed": False, + } + with tempfile.TemporaryDirectory(prefix="xprobe-trace-marker-") as directory: + path = pathlib.Path(directory) / "marker.jsonl" + write_with_manifest(path, events, manifest) + report = json.loads( + subprocess.run([script, path], check=True, capture_output=True, text=True).stdout + ) + device = report["devices"][0] + assert (device["busy_ns"], device["idle_ns"]) == (100, 0), device + assert report["events"]["paired_activities"] == 0, report["events"] + + +def check_capture_edges(script: pathlib.Path) -> None: + """Activity cut by the capture edges is busy up to the manifest window, + pairs keep their identity, and recorded losses are reported.""" + host = {"clock_domain": "cupti_normalized_to_host_monotonic"} + events = [ + {**item, **host} + for item in [ + # gemm 20-50 and an NCCL kernel from 20 that runs past the end. + *pair(1, "kernel", 20, 50, stream_id=7, correlation_id=1, kernel_name="gemm"), + event(3, "gpu_kernel_start", 20, stream_id=8, correlation_id=2, + kernel_name="ncclDevKernel_AllReduce"), + # A kernel that started before the capture ends at 10. + event(4, "gpu_kernel_end", 10, stream_id=9, correlation_id=3, kernel_name="early"), + ] + ] + manifest = { + "target": {"pid": 1234, "process_start_time": 1}, + "window": {"start_ns": 0, "end_ns": 100}, + "all_gpu_activity": True, + "dropped_records": 2, + "unknown_records": 0, + "record_limit_reached": None, + "capture_failed": False, + } + reports = [] + with tempfile.TemporaryDirectory(prefix="xprobe-trace-edges-") as directory: + for order in (events, list(reversed(events))): + path = pathlib.Path(directory) / "edges.jsonl" + write_with_manifest(path, order, manifest) + reports.append(json.loads( + subprocess.run([script, path], check=True, capture_output=True, text=True).stdout + )) + for report in reports: + device = report["devices"][0] + # Busy 0-10 (early) and 20-100 (NCCL to the window's end); idle 10-20. + assert (device["busy_ns"], device["idle_ns"]) == (90, 10), device + # Compute: early 0-10 and gemm 20-50. + assert (device["compute_ns"], device["communication_ns"]) == (40, 80), device + assert device["span"] == {**device["span"], "start_ns": 0, "end_ns": 100}, device + assert "CAPTURE_INCOMPLETE" in {item["code"] for item in report["warnings"]} + + +def check_rank_comparison(script: pathlib.Path) -> None: + """Two tensor-parallel ranks over 0-100 ns: rank A computes 80 ns before + its all-reduce, rank B computes 40 ns and waits in NCCL for the rest.""" + def rank(pid: int, compute_end: int, uuid: str, drift: int = 0) -> tuple[list[dict], dict]: + events = [ + {**item, "pid": pid, "clock_domain": "cupti_normalized_to_host_monotonic"} + for item in [ + *pair(1, "kernel", 0, compute_end, stream_id=7, correlation_id=1, kernel_name="gemm"), + *pair(3, "kernel", compute_end, 100, stream_id=8, correlation_id=2, + kernel_name="_Z40ncclDevKernel_AllReduce_Sum_bf16_RING_LLP24ncclDevKernelArgsStorage"), + ] + ] + manifest = { + "target": {"pid": pid, "process_start_time": 1}, + "window": {"start_ns": 0, "end_ns": 100}, + "all_gpu_activity": True, + "cuda_devices": [{"device_id": 0, "uuid": uuid}], + # CLOCK_MONOTONIC 0 was 2023-11-14T22:13:20Z. + "wall_clock": { + "start": {"monotonic_ns": 0, "realtime_ns": EPOCH_2023, "uncertainty_ns": 5}, + "end": {"monotonic_ns": 100, "realtime_ns": EPOCH_2023 + 100 + drift, "uncertainty_ns": 5}, + }, + } + return events, manifest + + with tempfile.TemporaryDirectory(prefix="xprobe-trace-ranks-") as directory: + paths = [] + for pid, compute_end, uuid, drift in [(11, 80, "GPU-a", 0), (12, 40, "GPU-b", 2_000_000)]: + events, manifest = rank(pid, compute_end, uuid, drift) + path = pathlib.Path(directory) / f"rank-{pid}.jsonl" + write_with_manifest(path, events, manifest) + paths.append(path) + single = json.loads( + subprocess.run([script, paths[1]], check=True, capture_output=True, text=True).stdout + ) + compared = json.loads( + subprocess.run([script, *paths], check=True, capture_output=True, text=True).stdout + ) + sliced = subprocess.run( + [script, *paths, "--slice-gap", "1"], check=False, capture_output=True, text=True + ) + # An edited artifact no longer matches its manifest. + with paths[0].open("a") as artifact: + artifact.write("\n") + stale = subprocess.run([script, paths[0]], check=False, capture_output=True, text=True) + + device = single["devices"][0] + assert device["uuid"] == "GPU-b" + assert (device["compute_ns"], device["communication_ns"], device["communication_only_ns"]) == (40, 60, 60) + # Host-clock spans carry UTC wall times; rank B's wall clock moved 2 ms. + assert device["span"]["start_wall"] == "2023-11-14T22:13:20.000000000Z", device["span"] + assert [item["code"] for item in single["warnings"]] == ["WALL_CLOCK_DRIFT"], single["warnings"] + assert stale.returncode != 0 and "different artifact" in stale.stderr + assert single["capture"]["wall_clock_drift_ns"] == 2_000_000 + + assert compared["window"] == {"start_ns": 0, "end_ns": 100} + assert [item["code"] for item in compared["warnings"]] == ["WALL_CLOCK_DRIFT"], compared["warnings"] + assert all(row["span"]["start_wall"].startswith("2023-11-14T22:13:20") for row in compared["devices"]) + shares = {row["uuid"]: row["shares"] for row in compared["devices"]} + assert shares["GPU-a"]["compute"] == 0.8 and shares["GPU-b"]["compute"] == 0.4 + spread = compared["spread"] + assert spread["compute_share"] == 0.4 + assert spread["most_compute"]["uuid"] == "GPU-a" + assert spread["most_communication_only"]["uuid"] == "GPU-b" + assert sliced.returncode != 0 and "take one trace" in sliced.stderr def api_event(sequence: int, timestamp_ns: int, name: str, correlation_id: int) -> dict: @@ -171,6 +336,13 @@ def check_gaps_outliers_and_slices(script: pathlib.Path) -> None: *pair(7, "memcpy", 200, 300, stream_id=9, correlation_id=4, memcpy_kind="HtoD", bytes_count=2000), api_event(9, 450, "cudaStreamSynchronize", 5), + # Another process in the same trace has a smaller gap of its own. + *[{**item, "pid": 999} for item in pair(11, "kernel", 0, 10, stream_id=7, + correlation_id=6, kernel_name="z")], + *[{**item, "pid": 999} for item in pair(13, "kernel", 60, 70, stream_id=7, + correlation_id=7, kernel_name="z")], + # ... and a call inside 1234's gap, which that gap's slice leaves out. + {**api_event(15, 400, "cudaMemcpy", 8), "pid": 999}, ] measurement = { "schema_version": "3.0", @@ -191,6 +363,33 @@ def check_gaps_outliers_and_slices(script: pathlib.Path) -> None: trace.write_text("".join(json.dumps(item) + "\n" for item in events)) result = pathlib.Path(directory) / "measure.json" result.write_text(json.dumps(measurement)) + python = pathlib.Path(directory) / "python-samples.jsonl" + frame = lambda function: {"function": function, "file": "app.py", "first_line": 1} + python.write_text( + "".join( + json.dumps( + { + "timestamp_ns": timestamp, + "pid": pid, + "tid": tid, + "gil": gil, + "truncated": False, + "frames": [frame(leaf), frame("main")], + "native": native, + } + ) + + "\n" + for pid, timestamp, tid, gil, leaf, native in [ + (1234, 260, 1, True, "step", None), + (1234, 400, 1, True, "step", None), + (1234, 420, 1, True, "load", None), + (1234, 450, 2, False, "wait", {"syscall": "futex", "module": "libc.so.6", "symbol": None}), + (1234, 600, 1, True, "late", None), + # Another process in the trace is not the gap's. + (999, 300, 9, True, "elsewhere", None), + ] + ) + ) def run(*arguments: str) -> dict: return json.loads( @@ -203,6 +402,18 @@ def run(*arguments: str) -> dict: by_gap = run("--slice-gap", "1", "--window-ms", "0.00005") by_outlier = run("--measurement", str(result), "--slice-outlier", "2") by_time = run("--around", "440:460", "--max-slice-events", "1") + with_python = run("--slice-gap", "1", "--window-ms", "0.00005", "--python-samples", str(python)) + # The same trace on the host clock, as a normalized CUPTI capture is. + trace.write_text( + "".join( + json.dumps({**item, "clock_domain": "cupti_normalized_to_host_monotonic"}) + "\n" + for item in events + ) + ) + aligned = run("--slice-gap", "1", "--window-ms", "0.00005", "--python-samples", str(python)) + unsliced_python = subprocess.run( + [script, trace, "--python-samples", str(python)], check=False, capture_output=True, text=True + ) missing = subprocess.run( [script, trace, "--slice-outlier", "1"], check=False, capture_output=True, text=True ) @@ -212,7 +423,10 @@ def run(*arguments: str) -> dict: assert copy["avg_bytes"] == 2000.0, copy idle = report["gpu"]["top_idle_gaps"] assert [(gap["start_ns"], gap["end_ns"]) for gap in idle] == [(300, 500), (100, 200)], idle - stream = next(item for item in report["streams"] if item["stream_id"] == 7) + assert {(gap["pid"], gap["clock_domain"]) for gap in idle} == {(1234, "cupti")} + stream = next( + item for item in report["streams"] if item["stream_id"] == 7 and item["pid"] == 1234 + ) assert [gap["gap_ns"] for gap in stream["top_gaps"]] == [400, 50] assert stream["top_gaps"][0]["after"] == "a" and stream["top_gaps"][0]["before"] == "b" assert report["outliers"] is None and report["slice"] is None @@ -221,6 +435,7 @@ def run(*arguments: str) -> dict: assert sliced["around"] == {"kind": "gap", "start_ns": 300, "end_ns": 500} assert (sliced["start_ns"], sliced["end_ns"]) == (250, 550) assert [row["name"] for row in sliced["events"]] == ["HtoD", "cudaStreamSynchronize", "b"] + assert {row["pid"] for row in sliced["events"]} == {1234} assert sliced["events"][1]["tid"] == 55 outliers = by_outlier["outliers"] @@ -232,6 +447,24 @@ def run(*arguments: str) -> dict: assert by_time["slice"]["events"][0]["name"] == "cudaStreamSynchronize" assert missing.returncode != 0 and "requires --measurement" in missing.stderr + # Raw CUPTI timestamps do not line up with Python samples: no stacks are + # placed in the slice, and the result says why. + assert with_python["slice"]["python"] is None + assert "PYTHON_CLOCK_UNALIGNED" in {item["code"] for item in with_python["warnings"]} + + # Python stacks sampled inside the 250-550 window, beside the GPU events. + stacks = aligned["slice"]["python"] + assert (stacks["samples"], stacks["gil_samples"]) == (4, 3), stacks + assert stacks["gil_stacks"][0]["frames"][0] == "step (app.py:1)" + assert stacks["gil_stacks"][0]["samples"] == 2 + assert stacks["native_waits"] == [ + {"syscall": "futex", "module": "libc.so.6", "symbol": None, "samples": 1} + ] + codes = {item["code"] for item in aligned["warnings"]} + assert "PYTHON_CLOCK_UNALIGNED" not in codes + assert "PYTHON_SAMPLES_OTHER_PROCESS" in codes + assert unsliced_python.returncode != 0 and "requires --slice-gap" in unsliced_python.stderr + if __name__ == "__main__": main() diff --git a/tests/agent-contract/test_workflow_routes.py b/tests/agent-contract/test_workflow_routes.py index 48efbc1..17da303 100644 --- a/tests/agent-contract/test_workflow_routes.py +++ b/tests/agent-contract/test_workflow_routes.py @@ -10,16 +10,11 @@ def normalize(text: str) -> str: def main() -> None: workspace = pathlib.Path(__file__).resolve().parents[2] - skill_root = workspace / "skills/xprobe-measure-latency" + skill_root = workspace / "skills/xprobe-perf-profiling" sources = { "skill": normalize((skill_root / "SKILL.md").read_text()), - "setup": normalize((skill_root / "references/setup.md").read_text()), + "data_format": normalize((skill_root / "references/data-format.md").read_text()), "selectors": normalize((skill_root / "references/selectors.md").read_text()), - "interpreting": normalize((skill_root / "references/interpreting.md").read_text()), - "deep_dive": normalize((skill_root / "references/deep-dive.md").read_text()), - "multi_process": normalize( - (skill_root / "references/multi-process.md").read_text() - ), } fixture = json.loads( (workspace / "tests/agent-contract/fixtures/workflow-routes.json").read_text() @@ -31,14 +26,13 @@ def main() -> None: assert normalize(phrase) in document, (scenario["name"], phrase) covered.add(scenario["name"]) assert covered == { - "existing_artifact", - "unknown_workload", - "known_selector", - "several_boundaries", - "dig_deeper", - "python_semantics", - "multi_process", - "container_namespace", + "offline_recorrelate", + "scripting_and_rsi", + "measurement_graph", + "gpu_idle_and_trigger", + "python_sampling", + "cross_process_and_clocks", + "container_and_nvtx", } print(json.dumps({"schema_version": "2.0", "ok": True, "routes": sorted(covered)})) diff --git a/tests/install/test_install.sh b/tests/install/test_install.sh index 2862442..de72fb9 100755 --- a/tests/install/test_install.sh +++ b/tests/install/test_install.sh @@ -71,7 +71,7 @@ test -d "$prefix/share/xprobe/docs" test -d "$prefix/share/xprobe/schemas" test -d "$prefix/share/xprobe/skills" test -x \ - "$prefix/share/xprobe/skills/xprobe-measure-latency/scripts/analyze_trace.py" + "$prefix/share/xprobe/skills/xprobe-perf-profiling/scripts/analyze_trace.py" "$prefix/bin/xprobe" --version HOME=$temporary_dir/home FAKE_GLIBC_VERSION=2.34 \ diff --git a/tests/install/test_wheel.sh b/tests/install/test_wheel.sh index a0dcd62..4d83eff 100755 --- a/tests/install/test_wheel.sh +++ b/tests/install/test_wheel.sh @@ -18,7 +18,8 @@ trap 'rm -rf "${work}"' EXIT xprobe="${work}/venv/bin/xprobe" [[ -x "${xprobe}" ]] || { echo "wheel did not install an executable xprobe" >&2; exit 1; } version=$("${xprobe}" --version) -expected=$(basename "${wheel}" | sed -n 's/^xprobe-\([0-9.]*\)-.*/\1/p') +# The wheel's PEP 440 X.Y.Z.devN is the CLI's X.Y.Z-dev.N. +expected=$(basename "${wheel}" | sed -n 's/^xprobe-\([0-9]*\.[0-9]*\.[0-9]*\)\(\.dev\([0-9]*\)\)\{0,1\}-.*/\1-dev.\3/p' | sed 's/-dev\.$//') [[ "${version}" == "xprobe ${expected}" ]] || { echo "unexpected version: ${version} (expected ${expected})" >&2 exit 1 @@ -31,7 +32,7 @@ for major in 12 13; do exit 1 } done -[[ -f "${work}/venv/share/xprobe/skills/xprobe-measure-latency/SKILL.md" ]] || { +[[ -f "${work}/venv/share/xprobe/skills/xprobe-perf-profiling/SKILL.md" ]] || { echo "Skill was not installed under share/xprobe" >&2 exit 1 } diff --git a/tests/integration/python-layout/debug-offsets.c b/tests/integration/python-layout/debug-offsets.c new file mode 100644 index 0000000..717d32e --- /dev/null +++ b/tests/integration/python-layout/debug-offsets.c @@ -0,0 +1,28 @@ +#define Py_BUILD_CORE 1 +#include +#include +#include +#include +#define P(name, value) printf("\"%s\": %zu,\n", name, (size_t)(value)) +int main(void) { + printf("{\n"); + P("cookie", offsetof(_Py_DebugOffsets, cookie)); + P("version", offsetof(_Py_DebugOffsets, version)); + P("runtime_interpreters_head", offsetof(_Py_DebugOffsets, runtime_state.interpreters_head)); + P("interp_threads_head", offsetof(_Py_DebugOffsets, interpreter_state.threads_head)); + P("interp_ceval_gil", offsetof(_Py_DebugOffsets, interpreter_state.gil_runtime_state)); + P("tstate_next", offsetof(_Py_DebugOffsets, thread_state.next)); + P("tstate_native_thread_id", offsetof(_Py_DebugOffsets, thread_state.native_thread_id)); + P("tstate_current_frame", offsetof(_Py_DebugOffsets, thread_state.current_frame)); + P("frame_back", offsetof(_Py_DebugOffsets, interpreter_frame.previous)); + P("frame_code", offsetof(_Py_DebugOffsets, interpreter_frame.executable)); + P("frame_owner", offsetof(_Py_DebugOffsets, interpreter_frame.owner)); + P("code_filename", offsetof(_Py_DebugOffsets, code_object.filename)); + P("code_qualname", offsetof(_Py_DebugOffsets, code_object.qualname)); + P("code_firstlineno", offsetof(_Py_DebugOffsets, code_object.firstlineno)); + P("object_type", offsetof(_Py_DebugOffsets, pyobject.ob_type)); + P("ascii_size", offsetof(_Py_DebugOffsets, unicode_object.asciiobject_size)); + P("size", sizeof(_Py_DebugOffsets)); + printf("\"end\": 0\n}\n"); + return 0; +} diff --git a/tests/integration/python-layout/expected.json b/tests/integration/python-layout/expected.json new file mode 100644 index 0000000..7e47994 --- /dev/null +++ b/tests/integration/python-layout/expected.json @@ -0,0 +1,190 @@ +{ + "debug_offsets": { + "3.13": { + "ascii_size": 560, + "code_filename": 280, + "code_firstlineno": 312, + "code_qualname": 296, + "cookie": 0, + "frame_back": 232, + "frame_code": 240, + "frame_owner": 264, + "interp_ceval_gil": 120, + "interp_threads_head": 72, + "object_type": 360, + "runtime_interpreters_head": 40, + "size": 584, + "tstate_current_frame": 184, + "tstate_native_thread_id": 200, + "tstate_next": 168, + "version": 8 + }, + "3.14": { + "ascii_size": 640, + "code_filename": 320, + "code_firstlineno": 352, + "code_qualname": 336, + "cookie": 0, + "frame_back": 256, + "frame_code": 264, + "frame_owner": 288, + "interp_ceval_gil": 128, + "interp_threads_head": 72, + "object_type": 408, + "runtime_interpreters_head": 40, + "size": 760, + "tstate_current_frame": 208, + "tstate_native_thread_id": 224, + "tstate_next": 192, + "version": 8 + } + }, + "layouts": { + "3.10": { + "ascii_length": 16, + "ascii_size": 48, + "ascii_state": 32, + "code_filename": 104, + "code_firstlineno": 40, + "code_name": 112, + "compact_size": 72, + "frame_back": 24, + "frame_code": 32, + "interp_threads_head": 8, + "object_type": 8, + "runtime_gil_last_holder": 360, + "runtime_gil_locked": 368, + "runtime_gil_switch_number": 376, + "runtime_interpreters_head": 32, + "tstate_frame": 24, + "tstate_next": 8, + "tstate_thread_id": 176 + }, + "3.11": { + "ascii_length": 16, + "ascii_size": 48, + "ascii_state": 32, + "cframe_current_frame": 8, + "code_filename": 112, + "code_firstlineno": 72, + "code_name": 120, + "code_qualname": 128, + "compact_size": 72, + "frame_back": 48, + "frame_code": 32, + "frame_owner": 69, + "frame_owner_size": 1, + "interp_threads_head": 16, + "object_type": 8, + "runtime_gil_last_holder": 368, + "runtime_gil_locked": 376, + "runtime_gil_switch_number": 384, + "runtime_interpreters_head": 40, + "tstate_cframe": 56, + "tstate_native_thread_id": 160, + "tstate_next": 8, + "tstate_thread_id": 152 + }, + "3.12": { + "ascii_length": 16, + "ascii_size": 40, + "ascii_state": 32, + "cframe_current_frame": 0, + "code_filename": 112, + "code_firstlineno": 68, + "code_name": 120, + "code_qualname": 128, + "compact_size": 56, + "first_non_python_owner": 3, + "frame_back": 8, + "frame_code": 0, + "frame_owner": 70, + "frame_owner_size": 1, + "gil_last_holder": 8, + "gil_locked": 16, + "gil_switch_number": 24, + "interp_ceval_gil": 384, + "interp_threads_head": 72, + "object_type": 8, + "runtime_interpreters_head": 40, + "tstate_cframe": 56, + "tstate_native_thread_id": 144, + "tstate_next": 8, + "tstate_thread_id": 136 + }, + "3.13": { + "ascii_length": 16, + "ascii_size": 40, + "ascii_state": 32, + "code_filename": 112, + "code_firstlineno": 68, + "code_name": 120, + "code_qualname": 128, + "compact_size": 56, + "debug_offsets": 0, + "first_non_python_owner": 3, + "frame_back": 8, + "frame_code": 0, + "frame_owner": 70, + "frame_owner_size": 1, + "gil_last_holder": 8, + "gil_locked": 16, + "gil_switch_number": 24, + "interp_ceval_gil": 16, + "interp_threads_head": 7344, + "object_type": 8, + "runtime_interpreters_head": 632, + "tstate_current_frame": 72, + "tstate_native_thread_id": 160, + "tstate_next": 8, + "tstate_thread_id": 152 + }, + "3.14": { + "ascii_length": 16, + "ascii_size": 40, + "ascii_state": 32, + "code_filename": 112, + "code_firstlineno": 68, + "code_name": 120, + "code_qualname": 128, + "compact_size": 56, + "debug_offsets": 0, + "first_non_python_owner": 3, + "frame_back": 8, + "frame_code": 0, + "frame_owner": 74, + "frame_owner_size": 1, + "gil_last_holder": 8, + "gil_locked": 16, + "gil_switch_number": 24, + "interp_ceval_gil": 16, + "interp_threads_head": 7344, + "object_type": 8, + "runtime_interpreters_head": 808, + "tstate_current_frame": 72, + "tstate_native_thread_id": 160, + "tstate_next": 8, + "tstate_thread_id": 152 + }, + "3.9": { + "ascii_length": 16, + "ascii_size": 48, + "ascii_state": 32, + "code_filename": 104, + "code_firstlineno": 40, + "code_name": 112, + "compact_size": 72, + "frame_back": 24, + "frame_code": 32, + "interp_threads_head": 8, + "object_type": 8, + "runtime_gil_last_holder": 360, + "runtime_gil_locked": 368, + "runtime_gil_switch_number": 376, + "runtime_interpreters_head": 32, + "tstate_frame": 24, + "tstate_next": 8, + "tstate_thread_id": 176 + } + } +} diff --git a/tests/integration/python-layout/layout.c b/tests/integration/python-layout/layout.c new file mode 100644 index 0000000..86898e0 --- /dev/null +++ b/tests/integration/python-layout/layout.c @@ -0,0 +1,82 @@ +#define Py_BUILD_CORE 1 +#include +#include +#include +#include +#if PY_MINOR_VERSION >= 11 +#include +#endif +#include +#include +#if PY_MINOR_VERSION >= 12 +#include +#endif +#define P(name, value) printf("\"%s\": %zu,\n", name, (size_t)(value)) +int main(void) { + printf("{\n\"version\": \"%d.%d\",\n", PY_MAJOR_VERSION, PY_MINOR_VERSION); + P("runtime_interpreters_head", offsetof(_PyRuntimeState, interpreters.head)); +#if PY_MINOR_VERSION <= 11 + P("runtime_gil_last_holder", offsetof(_PyRuntimeState, ceval.gil.last_holder)); + P("runtime_gil_locked", offsetof(_PyRuntimeState, ceval.gil.locked)); + P("runtime_gil_switch_number", offsetof(_PyRuntimeState, ceval.gil.switch_number)); +#else + P("gil_locked", offsetof(struct _gil_runtime_state, locked)); + P("interp_ceval_gil", offsetof(PyInterpreterState, ceval.gil)); + P("gil_last_holder", offsetof(struct _gil_runtime_state, last_holder)); + P("gil_switch_number", offsetof(struct _gil_runtime_state, switch_number)); +#endif +#if PY_MINOR_VERSION <= 10 + P("interp_threads_head", offsetof(PyInterpreterState, tstate_head)); +#else + P("interp_threads_head", offsetof(PyInterpreterState, threads.head)); +#endif + P("tstate_next", offsetof(PyThreadState, next)); + P("tstate_thread_id", offsetof(PyThreadState, thread_id)); +#if PY_MINOR_VERSION >= 11 + P("tstate_native_thread_id", offsetof(PyThreadState, native_thread_id)); +#endif +#if PY_MINOR_VERSION <= 10 + P("tstate_frame", offsetof(PyThreadState, frame)); + P("frame_back", offsetof(PyFrameObject, f_back)); + P("frame_code", offsetof(PyFrameObject, f_code)); +#elif PY_MINOR_VERSION <= 12 + P("tstate_cframe", offsetof(PyThreadState, cframe)); + P("cframe_current_frame", offsetof(_PyCFrame, current_frame)); + P("frame_back", offsetof(_PyInterpreterFrame, previous)); + P("frame_code", offsetof(_PyInterpreterFrame, f_code)); + P("frame_owner", offsetof(_PyInterpreterFrame, owner)); +#if PY_MINOR_VERSION == 12 + P("frame_owner_size", sizeof(((_PyInterpreterFrame *)0)->owner)); + /* Owners from this value up are not Python frames. */ + P("first_non_python_owner", FRAME_OWNED_BY_CSTACK); +#endif +#else + P("tstate_current_frame", offsetof(PyThreadState, current_frame)); + P("frame_back", offsetof(_PyInterpreterFrame, previous)); + P("frame_code", offsetof(_PyInterpreterFrame, f_executable)); + P("frame_owner", offsetof(_PyInterpreterFrame, owner)); + P("frame_owner_size", sizeof(((_PyInterpreterFrame *)0)->owner)); +#if PY_MINOR_VERSION >= 14 + P("first_non_python_owner", FRAME_OWNED_BY_INTERPRETER); +#else + P("first_non_python_owner", FRAME_OWNED_BY_CSTACK); +#endif + P("debug_offsets", offsetof(_PyRuntimeState, debug_offsets)); +#endif +#if PY_MINOR_VERSION == 11 + P("frame_owner_size", sizeof(((_PyInterpreterFrame *)0)->owner)); +#endif + P("code_filename", offsetof(PyCodeObject, co_filename)); + P("code_name", offsetof(PyCodeObject, co_name)); +#if PY_MINOR_VERSION >= 11 + P("code_qualname", offsetof(PyCodeObject, co_qualname)); +#endif + P("code_firstlineno", offsetof(PyCodeObject, co_firstlineno)); + P("object_type", offsetof(PyObject, ob_type)); + P("ascii_length", offsetof(PyASCIIObject, length)); + P("ascii_state", offsetof(PyASCIIObject, state)); + P("ascii_size", sizeof(PyASCIIObject)); + P("compact_size", sizeof(PyCompactUnicodeObject)); + printf("\"end\": 0\n}\n"); + return 0; +} diff --git a/tests/integration/python_sample_workload.py b/tests/integration/python_sample_workload.py new file mode 100644 index 0000000..a873b1e --- /dev/null +++ b/tests/integration/python_sample_workload.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""A hot loop on the main thread and a sleeping thread, for Python sampling tests.""" +import ctypes, sys, threading, time +# Allow a non-ancestor sampler under kernel.yama.ptrace_scope=1 (test only). +ctypes.CDLL(None).prctl(0x59616d61, ctypes.c_ulong(-1), 0, 0, 0) + +def hot_inner(n): + total = 0 + for i in range(n): + total += i * i + return total + +def hot_outer(): + while True: + hot_inner(20000) + +def sleeper(): + while True: + time.sleep(0.01) + +threading.Thread(target=sleeper, name="sleeper", daemon=True).start() +print("ready", flush=True) +hot_outer() diff --git a/tests/integration/run-cupti-burst-live.sh b/tests/integration/run-cupti-burst-live.sh index 181542f..c6486f9 100755 --- a/tests/integration/run-cupti-burst-live.sh +++ b/tests/integration/run-cupti-burst-live.sh @@ -42,7 +42,7 @@ set +e /workspace/target/debug/xprobe measure --pid "${target}" --cupti-socket "${socket}" \ --from 'cuda:kernel_start:name~xprobe_burst_kernel' \ --to 'cuda:kernel_end:name~xprobe_burst_kernel' \ - --match exact --duration-ms 4000 --timeout-ms 30000 \ + --match exact --samples "$((per_stream * 4))" --timeout-ms 30000 \ --max-events $((expected * 2 + 1000)) \ --events-out "${output}/burst-events.jsonl" >"${output}/burst-measure.json" & measurement=$! diff --git a/tests/integration/run-cupti-live.sh b/tests/integration/run-cupti-live.sh index 9a328db..3743916 100755 --- a/tests/integration/run-cupti-live.sh +++ b/tests/integration/run-cupti-live.sh @@ -33,3 +33,5 @@ nvcc \ XPROBE_CUPTI_OUTPUT="$1" CUDA_INJECTION64_PATH="${agent}" "${fixture}" chmod 0644 "$1" +nvidia-smi --query-gpu=uuid --format=csv,noheader >"$(dirname "$1")/gpu-uuids.txt" +chmod 0644 "$(dirname "$1")/gpu-uuids.txt" diff --git a/tests/integration/run-multisource-live.sh b/tests/integration/run-multisource-live.sh index ab23fa4..7cf8748 100755 --- a/tests/integration/run-multisource-live.sh +++ b/tests/integration/run-multisource-live.sh @@ -21,6 +21,7 @@ spec_measurement="$1/spec-measure.json" graph="${build_dir}/measurement-graph.json" graph_validation="$1/graph-validate.json" graph_measurement="$1/graph-measure.json" +stream_order_measurement="$1/stream-order-measure.json" gpu_info="$1/gpu.txt" compute_capability=$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader | sed -n '1p') compute_arch=${compute_capability//./} @@ -92,15 +93,18 @@ printf '{"schema_version":"2.0","name":"spec_host_to_kernel","target":{"pid":%s, kernel='cuda:kernel_start:name~xprobe_multisource_kernel.*' kernel_end='cuda:kernel_end:name~xprobe_multisource_kernel.*' +auxiliary_start='cuda:kernel_start:name~xprobe_auxiliary_kernel.*' cat >"${graph}" <"${graph_validation}" @@ -109,6 +113,20 @@ GRAPH --cupti-socket "${snapshot_socket}" \ --events-out "$1/graph-events.jsonl" >"${graph_measurement}" +# The auxiliary kernel always follows the measured kernel, so stream order +# must not pair one measured kernel with the next iteration's: only a capture +# of every activity on the stream can see the kernel in between. +if /workspace/target/debug/xprobe measure \ + --pid "${target_pid}" \ + --cupti-socket "${snapshot_socket}" \ + --from "${kernel_end}" --to "${kernel}" \ + --match stream-order --samples 3 --duration-ms 1000 --timeout-ms 5000 \ + --json --non-interactive --no-color >"${stream_order_measurement}"; then + echo "stream order paired kernels that another kernel separates" >&2 + cat "${stream_order_measurement}" >&2 + exit 1 +fi + if [[ $(stat -c '%a' "${snapshot_socket}") != 600 ]]; then echo "CUPTI snapshot socket is not mode 0600" >&2 exit 1 @@ -123,4 +141,6 @@ wait "${target_pid}" trap - EXIT chmod 0644 "${live_capture}" \ "${live_measurement}" "${spec_measurement}" "${gpu_info}" \ - "${graph_validation}" "${graph_measurement}" "$1/graph-events.jsonl" + "${graph_validation}" "${graph_measurement}" "$1/graph-events.jsonl" \ + "$1/graph-events.jsonl.manifest.json" \ + "${stream_order_measurement}" diff --git a/tests/integration/run-nvtx-live.sh b/tests/integration/run-nvtx-live.sh index 82011ca..87fb537 100755 --- a/tests/integration/run-nvtx-live.sh +++ b/tests/integration/run-nvtx-live.sh @@ -22,7 +22,7 @@ printf '%s\n' nested >"${mode}" NVTX_INJECTION64_PATH="${agent}" "${fixture}" "${mode}" \ >"${output_dir}/fixture.log" 2>"${output_dir}/fixture.stderr" & pid=$! -trap 'chmod 0644 "${output_dir}"/*.jsonl 2>/dev/null || true; kill "${pid}" 2>/dev/null || true; wait "${pid}" 2>/dev/null || true' EXIT +trap 'chmod 0644 "${output_dir}"/* 2>/dev/null || true; kill "${pid}" 2>/dev/null || true; wait "${pid}" 2>/dev/null || true' EXIT attempt=0 while ! grep -q '^ready$' "${output_dir}/fixture.log"; do diff --git a/tests/integration/run-python-sample-live.sh b/tests/integration/run-python-sample-live.sh new file mode 100755 index 0000000..879928d --- /dev/null +++ b/tests/integration/run-python-sample-live.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Inside one python:3.N image: check the built-in layout against this +# version's headers, then sample a workload with xprobe. +set -euo pipefail + +output=$1 +minor=$(python3 -c 'import sys; print(sys.version_info.minor)') +include=$(python3 -c 'import sysconfig; print(sysconfig.get_paths()["include"])') +layout=/workspace/tests/integration/python-layout +gcc -I"${include}" -I"${include}/internal" "${layout}/layout.c" -o /tmp/layout +/tmp/layout >"${output}/layout.json" +if (( minor >= 13 )); then + gcc -I"${include}" -I"${include}/internal" "${layout}/debug-offsets.c" -o /tmp/debug-offsets + /tmp/debug-offsets >"${output}/debug-offsets.json" +fi + +python3 /workspace/tests/integration/python_sample_workload.py >"${output}/workload.txt" & +target=$! +trap 'kill "${target}" 2>/dev/null || true' EXIT +for _ in $(seq 1 200); do + grep -q ready "${output}/workload.txt" 2>/dev/null && break + sleep 0.05 +done +sleep 0.5 +/workspace/target/debug/xprobe measure --pid "${target}" --python-sample --duration-ms 2000 \ + --json --events-out "${output}/samples.jsonl" >"${output}/result.json" +python3 --version >"${output}/python-version.txt" +chmod -R a+rwX "${output}" diff --git a/tests/integration/run-trigger-live.sh b/tests/integration/run-trigger-live.sh new file mode 100755 index 0000000..b0b4628 --- /dev/null +++ b/tests/integration/run-trigger-live.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +# Triggered capture against a CUDA fixture with a rare 30 ms bubble. +set -euo pipefail + +if [[ $# -ne 1 ]]; then + echo "usage: run-trigger-live.sh " >&2 + exit 2 +fi + +build_dir=/tmp/xprobe-trigger-live +cuda_root=/usr/local/cuda +agent="${build_dir}/libxprobe-cupti.so" +fixture="${build_dir}/xprobe-trigger-target" +ready="${build_dir}/ready" +stop="${build_dir}/stop" +socket="${build_dir}/cupti.sock" +xprobe=/workspace/target/debug/xprobe +compute_capability=$(nvidia-smi --query-gpu=compute_cap --format=csv,noheader | sed -n '1p') +compute_arch=${compute_capability//./} + +mkdir -p "${build_dir}" +rm -f "${ready}" "${stop}" "${socket}" +gcc \ + -std=c11 -D_GNU_SOURCE -DXPROBE_HAS_CUPTI=1 \ + -fPIC -shared -pthread -O2 -Wall -Wextra -Wpedantic -Werror \ + -I/workspace/cupti/include -isystem "${cuda_root}/include" \ + /workspace/cupti/src/cupti_agent.c \ + -L"${cuda_root}/lib64" -Wl,-rpath,"${cuda_root}/lib64" -lcupti \ + -o "${agent}" +nvcc -std=c++17 -O2 \ + -gencode="arch=compute_${compute_arch},code=sm_${compute_arch}" \ + /workspace/cupti/tests/cuda_gap_fixture.cu -o "${fixture}" + +XPROBE_CUPTI_SOCKET="${socket}" CUDA_INJECTION64_PATH="${agent}" \ + "${fixture}" "${ready}" "${stop}" & +target_pid=$! +trap 'touch "${stop}"; kill "${target_pid}" 2>/dev/null || true; wait "${target_pid}" 2>/dev/null || true' EXIT +for _ in $(seq 1 500); do + [[ -e "${ready}" ]] && break + kill -0 "${target_pid}" 2>/dev/null || wait "${target_pid}" + sleep 0.01 +done +[[ -e "${ready}" ]] || { echo "timed out waiting for the CUDA fixture" >&2; exit 1; } + + +mkdir -p "$1/fired" +set +e +"${xprobe}" measure --pid "${target_pid}" --cupti-socket "${socket}" --json \ + --trigger-gap-ms 20 --pre-ms 5 --post-ms 5 --windows 2 \ + --max-events 400000 --timeout-ms 20000 --events-out "$1/fired" \ + >"$1/fired.json" 2>"$1/fired.stderr" +echo $? >"$1/fired.status" +mkdir -p "$1/idle" +"${xprobe}" measure --pid "${target_pid}" --cupti-socket "${socket}" --json \ + --trigger-idle-ms 20 --pre-ms 5 --post-ms 5 --windows 2 \ + --max-events 400000 --timeout-ms 20000 --events-out "$1/idle" \ + >"$1/idle.json" 2>"$1/idle.stderr" +echo $? >"$1/idle.status" +# The device is never idle for half a second, though a side stream is. +"${xprobe}" measure --pid "${target_pid}" --cupti-socket "${socket}" --json \ + --trigger-idle-ms 500 --max-events 400000 --timeout-ms 3000 \ + >"$1/unobserved.json" 2>"$1/unobserved.stderr" +echo $? >"$1/unobserved.status" +"${xprobe}" measure --pid "${target_pid}" --cupti-socket "${socket}" --json \ + --trigger-gap-ms 20 --max-events 2000 --timeout-ms 4000 \ + >"$1/small-ring.json" 2>"$1/small-ring.stderr" +echo $? >"$1/small-ring.status" +set -e + +touch "${stop}" +wait "${target_pid}" +trap - EXIT +chmod -R a+rwX "$1" diff --git a/tests/integration/test_cupti.py b/tests/integration/test_cupti.py index 089db29..cb12454 100755 --- a/tests/integration/test_cupti.py +++ b/tests/integration/test_cupti.py @@ -70,11 +70,20 @@ def read_capture(path: pathlib.Path) -> tuple[dict[str, int], list[dict[str, int assert header["abi_version"] == 4 assert header["header_size"] == HEADER.size assert header["record_size"] == RECORD.size - assert header["feature_flags"] in {2, 3} - assert len(data) == header["header_size"] + header["record_count"] * RECORD.size + # Transfer records (2) and the device table (128) are always present; + # host-monotonic time (1) and peer copies (32) depend on the capture. + assert header["feature_flags"] & ~(1 | 32) == 2 | 128, header + count, entry_size = struct.unpack_from("<2I", data, HEADER.size) + assert entry_size == 48 and 0 < count <= 64, (count, entry_size) + header["device_uuids"] = [ + data[HEADER.size + 8 + index * 48 + 8 : HEADER.size + 8 + index * 48 + 24].hex() + for index in range(count) + ] + start = HEADER.size + 8 + count * 48 + assert len(data) == start + header["record_count"] * RECORD.size records = [ decode_record(data[offset : offset + RECORD.size]) - for offset in range(header["header_size"], len(data), RECORD.size) + for offset in range(start, len(data), RECORD.size) ] return header, records @@ -85,6 +94,7 @@ def measure( start_selector: str, end_selector: str, samples: str, + policy: str = "exact", ) -> dict: completed = subprocess.run( [ @@ -97,7 +107,7 @@ def measure( "--to", end_selector, "--match", - "exact", + policy, "--samples", samples, "--json", @@ -219,6 +229,13 @@ def main() -> None: raise SystemExit(measured.returncode) assert measured.stderr == "" measurement = json.loads(measured.stdout) + # The Agent names each CUDA ordinal's GPU as nvidia-smi does. + visible = (pathlib.Path(output_dir) / "gpu-uuids.txt").read_text().split() + devices = measurement["collection"]["cuda_devices"] + assert [device["uuid"] for device in devices] == visible, (devices, visible) + assert [device["device_id"] for device in devices] == list(range(len(visible))) + assert all(device["uuid"].replace("GPU-", "").replace("-", "") in header["device_uuids"] + for device in devices) cross_domain = subprocess.run( [ xprobe, @@ -270,6 +287,16 @@ def main() -> None: "cuda:memset_end", "1", ) + # memset, HtoD, HtoD, then kernels on one stream: only the second + # copy is followed by a kernel. + copy_to_kernel = measure( + xprobe, + capture, + "cuda:memcpy_end:kind=HtoD", + "cuda:kernel_start:name~xprobe_test_kernel.*", + "2", + "stream-order", + ) counts = collections.Counter(record["kind"] for record in records) diagnostics = {"header": header, "counts": counts, "records": records} @@ -286,6 +313,8 @@ def main() -> None: assert header["unknown_records"] == 0 assert header["record_offset"] == 0 assert bool(header["feature_flags"] & 1) is expect_aligned + # Copies were requested, so peer copies (CUPTI MEMCPY2) are covered too. + assert header["feature_flags"] & 32, header assert all(record["timestamp_ns"] > 0 for record in records) assert all(record["pid"] > 0 and record["tid"] > 0 for record in records) @@ -446,6 +475,8 @@ def main() -> None: assert driver_measurement["measurement"]["latency_ns"]["min"] > 0 assert driver_measurement["correlation"]["confidence"] == "exact" assert memcpy_measurement["measurement"]["samples"]["matched"] == 2 + assert copy_to_kernel["measurement"]["samples"]["matched"] == 1, copy_to_kernel + assert copy_to_kernel["measurement"]["samples"]["unmatched_start"] == 1, copy_to_kernel assert memcpy_measurement["measurement"]["latency_ns"]["min"] > 0 assert memcpy_measurement["correlation"]["confidence"] == "exact" assert memset_measurement["measurement"]["samples"]["matched"] == 1 diff --git a/tests/integration/test_cupti_burst.py b/tests/integration/test_cupti_burst.py index f2c30f6..27f9a31 100644 --- a/tests/integration/test_cupti_burst.py +++ b/tests/integration/test_cupti_burst.py @@ -40,6 +40,8 @@ def main() -> None: report = { "expected": expected, "matched": matched, + "status": result["status"], + "samples": result["measurement"]["samples"], "dropped": result["collection"]["dropped_events"], "verdict": result["quality"]["verdict"], } diff --git a/tests/integration/test_multisource.py b/tests/integration/test_multisource.py index 8c62558..186c6af 100755 --- a/tests/integration/test_multisource.py +++ b/tests/integration/test_multisource.py @@ -1,4 +1,5 @@ #!/usr/bin/env python3 +import hashlib import json import pathlib import subprocess @@ -79,6 +80,32 @@ def main() -> None: graph_events = ( pathlib.Path(output_dir) / "graph-events.jsonl" ).read_text().splitlines() + stream_order_result = json.loads( + (pathlib.Path(output_dir) / "stream-order-measure.json").read_text() + ) + graph_artifact = pathlib.Path(output_dir) / "graph-events.jsonl" + graph_manifest = json.loads( + (pathlib.Path(output_dir) / "graph-events.jsonl.manifest.json").read_text() + ) + graph_artifact_sha256 = hashlib.sha256(graph_artifact.read_bytes()).hexdigest() + offline_stream_order = subprocess.run( + [ + xprobe, + "measure", + "--input", + graph_artifact, + "--from", + "cuda:kernel_end:name~xprobe_multisource_kernel.*", + "--to", + "cuda:kernel_start:name~xprobe_auxiliary_kernel.*", + "--match", + "stream-order", + "--json", + ], + check=False, + capture_output=True, + text=True, + ) trace_path = pathlib.Path(output_dir) / "trace.json" exported = subprocess.run( @@ -118,13 +145,19 @@ def main() -> None: "request_to_launch", "launch_to_kernel", "kernel_duration", + "kernel_to_auxiliary", ] assert graph_validation["requirements"]["needs_ebpf"] is True assert graph_validation["requirements"]["needs_cupti"] is True assert graph_result["schema_version"] == "3.0", graph_result assert graph_result["status"] == "completed", graph_result edges = {edge["name"]: edge for edge in graph_result["edges"]} - assert set(edges) == {"request_to_launch", "launch_to_kernel", "kernel_duration"} + assert set(edges) == { + "request_to_launch", + "launch_to_kernel", + "kernel_duration", + "kernel_to_auxiliary", + } for edge in edges.values(): assert edge["measurement"]["samples"]["matched"] >= 3, edge assert edge["measurement"]["latency_ns"]["min"] > 0, edge @@ -133,6 +166,28 @@ def main() -> None: assert edges["request_to_launch"]["correlation"]["confidence"] == "heuristic" assert edges["launch_to_kernel"]["correlation"]["confidence"] == "exact" assert edges["kernel_duration"]["correlation"]["confidence"] == "exact" + assert edges["kernel_to_auxiliary"]["correlation"]["confidence"] == "high" + # Adjacent kernels on one stream, not the 50 ms between iterations. + assert edges["kernel_to_auxiliary"]["measurement"]["latency_ns"]["max"] < 10_000_000 + # The graph's artifact carries a manifest proving it holds every GPU + # activity, so offline stream order keeps its live confidence. + assert graph_manifest["schema_version"] == "1.0", graph_manifest + assert graph_manifest["artifact"]["events"] == len(graph_events) + assert graph_manifest["artifact"]["sha256"] == graph_artifact_sha256 + assert graph_manifest["all_gpu_activity"] is True, graph_manifest + assert graph_manifest["peer_copies"] is True, graph_manifest + assert graph_manifest["dropped_records"] == 0 + assert graph_manifest["window"]["start_ns"] < graph_manifest["window"]["end_ns"] + assert offline_stream_order.returncode == 0, offline_stream_order.stdout + offline = json.loads(offline_stream_order.stdout) + assert offline["collection"]["coverage"]["source"] == "manifest", offline + assert offline["correlation"]["confidence"] == "high", offline + assert graph_result["collection"]["coverage"] == { + "source": "live", + "all_gpu_activity": True, + } + assert stream_order_result["ok"] is False, stream_order_result + assert stream_order_result["error"]["code"] == "NO_MATCHED_SAMPLES", stream_order_result assert graph_result["artifact"]["events"] == len(graph_events) assert graph_result["collection"]["host_events"] >= 3 assert export_result["format"] == "chrome" diff --git a/tests/integration/test_python_sample.py b/tests/integration/test_python_sample.py new file mode 100644 index 0000000..517889b --- /dev/null +++ b/tests/integration/test_python_sample.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""External CPython sampling across every supported minor version.""" + +import json +import pathlib +import subprocess +import sys +import tempfile + +MINORS = (9, 10, 11, 12, 13, 14) + + +def check(minor: int, output: pathlib.Path, expected: dict) -> dict: + version = f"3.{minor}" + # The built-in layout is the one this version's headers produce. + layout = json.loads((output / "layout.json").read_text()) + layout.pop("end") + assert layout.pop("version") == version + assert layout == expected["layouts"][version], (version, layout) + if minor >= 13: + debug = json.loads((output / "debug-offsets.json").read_text()) + debug.pop("end") + assert debug == expected["debug_offsets"][version], (version, debug) + + result = json.loads((output / "result.json").read_text()) + assert result["ok"] is True, result + collection = result["collection"] + assert collection["python_version"] == version, collection + assert collection["tid_source"] == ("native" if minor >= 11 else "pthread"), collection + assert collection["gil_hz_achieved"] >= 1800, collection + assert collection["threads"] == 2, collection + clock = collection["wall_clock"] + assert clock["start"]["monotonic_ns"] < clock["end"]["monotonic_ns"], clock + reads = collection["gil_samples"] + collection["thread_samples"] + assert collection["inconsistent_reads"] <= reads * 0.05, collection + hottest = result["inventory"]["gil_hotspots"][0] + assert hottest["frame"]["function"] == "hot_inner", hottest + assert hottest["exclusive_proportion"] >= 0.8, hottest + sleeper = [ + group + for group in result["inventory"]["thread_stack_groups"] + if group["frames"][0]["function"] == "sleeper" + ] + assert sleeper, result["inventory"]["thread_stack_groups"] + # time.sleep blocks in a sleep system call (select before 3.11); the + # sweep sees where. + sleeps = {"clock_nanosleep", "nanosleep", "pselect6", "select"} + waits = result["inventory"]["native_waits"] + assert any(wait["leaf"]["syscall"] in sleeps for wait in waits), waits + records = [ + json.loads(line) for line in (output / "samples.jsonl").read_text().splitlines() + ] + assert len(records) == result["artifact"]["events"] + # Samples fall between the run's wall-clock anchors. + anchors = result["collection"]["wall_clock"] + assert all( + anchors["start"]["monotonic_ns"] <= record["timestamp_ns"] <= anchors["end"]["monotonic_ns"] + for record in records + ) + assert all(record["tid"] is not None for record in records) + return { + "python": (output / "python-version.txt").read_text().split()[1], + "gil_hz": round(collection["gil_hz_achieved"]), + "hot_inner": round(hottest["exclusive_proportion"], 3), + "inconsistent": collection["inconsistent_reads"], + "read_p50_us": collection["read_latency"]["p50_ns"] // 1000, + "read_p99_us": collection["read_latency"]["p99_ns"] // 1000, + } + + +def main() -> None: + workspace = pathlib.Path(__file__).resolve().parents[2] + expected = json.loads( + (workspace / "tests/integration/python-layout/expected.json").read_text() + ) + summary = {} + for minor in MINORS: + with tempfile.TemporaryDirectory(prefix=f"xprobe-python-3{minor}-") as output_dir: + output = pathlib.Path(output_dir) + completed = subprocess.run( + [ + "docker", "run", "--rm", + "--volume", f"{workspace}:/workspace:ro", + "--volume", f"{output}:/output", + f"python:3.{minor}", + "/workspace/tests/integration/run-python-sample-live.sh", "/output", + ], + check=False, + capture_output=True, + text=True, + ) + if completed.returncode != 0: + sys.stdout.write(completed.stdout) + sys.stderr.write(completed.stderr) + result = output / "result.json" + if result.exists(): + sys.stderr.write(result.read_text()) + raise SystemExit(completed.returncode) + summary[f"3.{minor}"] = check(minor, output, expected) + print(json.dumps({"ok": True, "versions": summary}, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/tests/integration/test_triage.py b/tests/integration/test_triage.py index c72f209..175291a 100644 --- a/tests/integration/test_triage.py +++ b/tests/integration/test_triage.py @@ -16,6 +16,7 @@ "syscall_aggregate", "gpu_health", "gpu_activity", + "python_sample", } @@ -160,6 +161,9 @@ def assert_triage(triage: dict, pid: int) -> None: assert set(statuses) == EXPECTED_SOURCES, statuses collected = {name for name, status in statuses.items() if status == "collected"} assert collected >= EXPECTED_SOURCES - {"cgroup"}, statuses + # The PyTorch workload is CPython: its GIL holder is sampled externally. + assert triage["python_hotspots"], triage["python_hotspots"] + assert triage["gil_released_proportion"] is not None for source in triage["sources"]: if source["source"] in {"cpu_sample", "syscall_aggregate", "gpu_activity"}: assert pathlib.Path(source["artifact"]).name.endswith(".json"), source diff --git a/tests/integration/test_trigger.py b/tests/integration/test_trigger.py new file mode 100644 index 0000000..e77dd3e --- /dev/null +++ b/tests/integration/test_trigger.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Triggered capture against a CUDA fixture with a rare 30 ms bubble.""" + +import hashlib +import json +import pathlib +import subprocess +import sys +import tempfile +import time + +MS = 1_000_000 + + +def busy_during(output: pathlib.Path, window: dict) -> bool: + """Whether a kernel of the window ran inside its firing span.""" + artifact = output / pathlib.Path(window["artifact"]["path"]).relative_to("/output") + events = [json.loads(line) for line in artifact.read_text().splitlines()] + starts = {} + intervals = [] + for event in events: + key = (event["cuda"]["stream_id"], event["cuda"]["correlation_id"]) + if event["event_type"] == "gpu_kernel_start": + starts[key] = event["timestamp_ns"] + elif event["event_type"] == "gpu_kernel_end": + # A kernel that began before the window ran from its start. + intervals.append((starts.pop(key, window["start_ns"]), event["timestamp_ns"])) + # Kernels still running at either edge of the window count as busy too. + intervals += [(start, window["end_ns"]) for start in starts.values()] + begin = window["fired"]["start"]["timestamp_ns"] + end = window["fired"]["end"]["timestamp_ns"] + return any(start < end and stop > begin for start, stop in intervals) + + +def main() -> None: + if len(sys.argv) != 3: + raise SystemExit("usage: test_trigger.py ") + workspace = pathlib.Path(__file__).resolve().parents[2] + xprobe = workspace / sys.argv[2] + with tempfile.TemporaryDirectory(prefix="xprobe-trigger-") as output_dir: + output = pathlib.Path(output_dir) + completed = subprocess.run( + [ + "docker", "run", "--rm", "--gpus", "all", + "--volume", f"{workspace}:/workspace:ro", + "--volume", f"{output}:/output", + "--workdir", "/workspace", + sys.argv[1], + "/workspace/tests/integration/run-trigger-live.sh", "/output", + ], + check=False, + capture_output=True, + text=True, + ) + if completed.returncode != 0: + sys.stdout.write(completed.stdout) + sys.stderr.write(completed.stderr) + raise SystemExit(completed.returncode) + + def outcome(name: str) -> tuple[int, dict]: + status = int((output / f"{name}.status").read_text()) + return status, json.loads((output / f"{name}.json").read_text()) + + fired_status, fired = outcome("fired") + assert fired_status == 0, fired + windows = fired["windows"] + assert fired["collection"]["wall_clock"]["end"]["monotonic_ns"] >= windows[-1]["end_ns"] + assert fired["status"] == "completed", fired["status"] + assert len(windows) == 2, len(windows) + assert fired["collection"]["overwritten_records"] == 0, fired["collection"] + assert fired["observed"]["spans"] > 1000, fired["observed"] + offline = [] + for window in windows: + assert window["fired"]["latency_ns"] >= 20 * MS, window["fired"] + # Both windows sit well inside the capture. + assert window["truncated"] is False, window + assert window["start_ns"] <= window["fired"]["start"]["timestamp_ns"] - 5 * MS + artifact = output / pathlib.Path(window["artifact"]["path"]).relative_to("/output") + manifest = json.loads( + artifact.with_name(artifact.name + ".manifest.json").read_text() + ) + assert manifest["artifact"]["sha256"] == hashlib.sha256( + artifact.read_bytes() + ).hexdigest() + assert manifest["all_gpu_activity"] is True, manifest + # The window's wall clock is this host's UTC time. + anchor = manifest["wall_clock"]["start"] + assert abs(anchor["realtime_ns"] / 1e9 - time.time()) < 600, anchor + assert anchor["uncertainty_ns"] < 1_000_000, anchor + assert manifest["dropped_records"] == 0 + # The window re-correlates offline and keeps its coverage. + measured = subprocess.run( + [ + xprobe, "measure", "--input", artifact, + "--from", "cuda:kernel_end", "--to", "cuda:kernel_start", + "--match", "stream-order", "--json", + ], + check=False, + capture_output=True, + text=True, + ) + assert measured.returncode == 0, measured.stdout + result = json.loads(measured.stdout) + assert result["collection"]["coverage"]["source"] == "manifest", result + assert result["correlation"]["confidence"] == "high", result + assert result["measurement"]["latency_ns"]["max"] == window["fired"]["latency_ns"] + offline.append(result["measurement"]["latency_ns"]["max"]) + # The second window starts after the first ends. + assert windows[1]["start_ns"] >= windows[0]["end_ns"] + # A stream gap can sit under another stream's kernel. + assert any(busy_during(output, window) for window in windows), windows + + # Device idle fires only when no stream of the target runs anything. + idle_status, idle = outcome("idle") + assert idle_status == 0, idle + assert idle["trigger"]["kind"] == "idle", idle["trigger"] + assert len(idle["windows"]) == 2, idle["windows"] + for window in idle["windows"]: + assert window["fired"]["latency_ns"] >= 20 * MS, window["fired"] + assert not busy_during(output, window), window + + unobserved_status, unobserved = outcome("unobserved") + assert unobserved_status != 0, unobserved + error = unobserved["error"] + assert error["code"] == "TRIGGER_NOT_OBSERVED", error + assert 0 < error["details"]["longest_ns"] < 500 * MS, error + + # A ring smaller than one snapshot's records loses windows and says so. + ring_status, ring = outcome("small-ring") + if ring_status == 0: + overwritten = ring["collection"]["overwritten_records"] + assert ring["collection"]["lost_windows"] > 0, ring + else: + assert ring["error"]["code"] in {"EVENTS_DROPPED", "TRIGGER_NOT_OBSERVED"}, ring + overwritten = ring["error"]["details"]["overwritten_records"] + assert overwritten > 0, ring + + print( + json.dumps( + { + "fired_gaps_ms": [window["fired"]["latency_ns"] / MS for window in windows], + "offline_max_ms": [value / MS for value in offline], + "spans": fired["observed"]["spans"], + "unobserved_longest_ms": error["details"]["longest_ns"] / MS, + "small_ring_overwritten": overwritten, + "ok": True, + }, + sort_keys=True, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/xprobe/cli/src/args.rs b/xprobe/cli/src/args.rs index 77c4f4f..eaeac25 100644 --- a/xprobe/cli/src/args.rs +++ b/xprobe/cli/src/args.rs @@ -326,10 +326,10 @@ pub(crate) struct MeasureArgs { #[arg(long)] pub(crate) events_out: Option, - /// Triage one bounded window: thread time, cgroup throttling, CPU samples, - /// syscall totals, GPU health, and CUDA kernel activity, with ranked - /// findings and the next exact measurement. Requires --pid and - /// --duration-ms. + /// Take a broad look over one bounded window: thread time, cgroup + /// throttling, CPU and Python samples, syscall totals, GPU health, and + /// CUDA kernel activity, with rule-based hints and a possible next + /// measurement. Requires --pid and --duration-ms. #[arg( long, requires_all = ["pid", "duration_ms"], @@ -406,6 +406,29 @@ pub(crate) struct MeasureArgs { )] pub(crate) max_threads: Option, + /// Sample CPython stacks from outside the process without perf events, + /// eBPF, or injection: the GIL holder at --python-hz and every thread at + /// --python-threads-hz. Needs ptrace access to the target; requires + /// --pid and --duration-ms. + #[arg( + long, + requires_all = ["pid", "duration_ms"], + conflicts_with_all = [ + "spec", "input", "from", "to", "match_policy", "samples", "cpu_sample", + "syscall_aggregate", "aggregate", "triage", "format", "cupti_socket", "agent" + ] + )] + pub(crate) python_sample: bool, + + /// Samples per second of the thread holding the GIL; 0 samples only the + /// all-thread sweeps. + #[arg(long, requires = "python_sample", default_value_t = 2000)] + pub(crate) python_hz: u32, + + /// Sweeps per second over every Python thread. + #[arg(long, requires = "python_sample", default_value_t = 100)] + pub(crate) python_threads_hz: u32, + /// Aggregate all syscall lifecycles in bounded BPF maps. #[arg(long, conflicts_with_all = ["input", "from", "to", "match_policy", "samples", "cpu_sample", "aggregate", "events_out", "format", "cupti_socket", "agent"])] pub(crate) syscall_aggregate: bool, @@ -447,10 +470,74 @@ pub(crate) struct MeasureArgs { #[arg(long)] pub(crate) name: Option, + #[command(flatten)] + pub(crate) trigger: TriggerArgs, + + #[command(flatten)] + pub(crate) trigger_window: TriggerWindowArgs, + #[command(flatten)] pub(crate) output: CommonOutputArgs, } +/// Wait for one rare slow span and write the GPU activity around it. CUPTI +/// keeps the newest --max-events records in a ring until a span crosses the +/// threshold or --timeout-ms passes; --events-out names a directory for the +/// window artifacts. +#[derive(Debug, Clone, Args)] +#[group( + id = "trigger", + multiple = false, + requires = "pid", + conflicts_with_all = [ + "spec", "input", "samples", "duration_ms", "triage", "cpu_sample", + "syscall_aggregate", "aggregate", "format" + ] +)] +#[expect( + clippy::struct_field_names, + reason = "field names are the --trigger-* flags and avoid clashing with --duration-ms" +)] +pub(crate) struct TriggerArgs { + /// Fire on a gap of at least this many milliseconds between one + /// activity's end and the next kernel, copy, or memset on the same + /// stream, even while other streams keep the device busy. + #[arg(long)] + pub(crate) trigger_gap_ms: Option, + + /// Fire when a device runs no kernel, copy, or memset of the target on + /// any stream for at least this many milliseconds. + #[arg(long)] + pub(crate) trigger_idle_ms: Option, + + /// Fire on a kernel, copy, or memset lasting at least this many + /// milliseconds. + #[arg(long)] + pub(crate) trigger_duration_ms: Option, + + /// Fire on a --from/--to pair under --match lasting at least this many + /// milliseconds; CUDA endpoints only. + #[arg(long, requires_all = ["from", "to", "match_policy"])] + pub(crate) trigger_latency_ms: Option, +} + +/// The window a trigger writes; outside the trigger group so they combine +/// with any one trigger. +#[derive(Debug, Clone, Args)] +pub(crate) struct TriggerWindowArgs { + /// Context written before the firing span starts. + #[arg(long, requires = "trigger", default_value_t = 50.0)] + pub(crate) pre_ms: f64, + + /// Context written after the firing span ends. + #[arg(long, requires = "trigger", default_value_t = 50.0)] + pub(crate) post_ms: f64, + + /// Windows to write before stopping; each starts after the previous ends. + #[arg(long, requires = "trigger", default_value_t = 1)] + pub(crate) windows: u32, +} + #[derive(Debug, Clone, Copy, Args)] pub(crate) struct CommonOutputArgs { /// Emit only the versioned JSON result on stdout (default when stdout is diff --git a/xprobe/cli/src/coverage.rs b/xprobe/cli/src/coverage.rs new file mode 100644 index 0000000..67f5265 --- /dev/null +++ b/xprobe/cli/src/coverage.rs @@ -0,0 +1,359 @@ +//! Capture coverage: what live collection recorded, kept in a manifest beside +//! the Event JSONL artifact and read back for offline correlation. + +use std::fs; +use std::io::ErrorKind; +use std::path::Path; + +use xprobe_collector::completed::CompletedCapture; +use xprobe_protocol::{ + CaptureCoverage, CaptureManifest, CaptureWindow, CoverageSource, ErrorCode, ManifestArtifact, + ManifestVersion, TargetIdentity, manifest_path, +}; + +use crate::failure::CommandFailure; +use crate::live::{LiveCollection, monotonic_now}; + +/// How one capture was collected, independent of where its events are written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct CaptureRecord { + pub(crate) target: TargetIdentity, + pub(crate) window: CaptureWindow, + pub(crate) selectors: Vec, + pub(crate) all_gpu_activity: bool, + pub(crate) peer_copies: bool, + pub(crate) dropped_records: u64, + pub(crate) unknown_records: u64, + pub(crate) record_limit_reached: Option, + pub(crate) capture_failed: bool, + pub(crate) cuda_devices: Vec, + pub(crate) wall_clock: Option, +} + +impl CaptureRecord { + /// The record of a live collection whose sources merged into `capture`. + pub(crate) fn live( + collection: &LiveCollection, + capture: &CompletedCapture, + ) -> Result { + let peer_copies = collection + .latest_cuda + .as_ref() + .is_some_and(|cuda| cuda.peer_memcpy_captured); + Ok(Self { + target: collection.report.target.clone(), + window: CaptureWindow { + start_ns: collection.capture_plan.start_ns, + end_ns: monotonic_now()?, + }, + selectors: collection.capture_plan.selectors.clone(), + // Stream order armed unfiltered start and end filters for every + // activity family; copies cover peers only when MEMCPY2 ran. + all_gpu_activity: collection.capture_plan.stream_order && peer_copies, + peer_copies, + dropped_records: capture.dropped_records, + unknown_records: capture.unknown_records, + record_limit_reached: capture.record_limit_reached, + capture_failed: capture.capture_failed, + cuda_devices: capture.cuda_devices.clone(), + // Without an end anchor the capture keeps its evidence and only + // loses the wall-clock mapping, which then reads as absent. + wall_clock: crate::live::clock_anchor() + .ok() + .map(|end| xprobe_protocol::WallClock { + start: collection.wall_clock_start, + end, + }), + }) + } + + pub(crate) const fn live_coverage(&self) -> CaptureCoverage { + CaptureCoverage { + source: CoverageSource::Live, + all_gpu_activity: self.all_gpu_activity, + } + } + + fn manifest(&self, artifact: ManifestArtifact) -> CaptureManifest { + CaptureManifest { + schema_version: ManifestVersion::current(), + artifact, + target: self.target.clone(), + window: self.window, + selectors: self.selectors.clone(), + all_gpu_activity: self.all_gpu_activity, + peer_copies: self.peer_copies, + dropped_records: self.dropped_records, + unknown_records: self.unknown_records, + record_limit_reached: self.record_limit_reached, + capture_failed: self.capture_failed, + cuda_devices: self.cuda_devices.clone(), + wall_clock: self.wall_clock, + } + } + + /// Record a live capture's coverage and wall clock in its result. + pub(crate) fn apply_to(&self, result: &mut xprobe_protocol::MeasurementResult) { + xprobe_correlator::apply_coverage(result, self.live_coverage()); + result.collection.wall_clock = self.wall_clock; + } + + pub(crate) fn from_manifest(manifest: &CaptureManifest) -> Self { + Self { + target: manifest.target.clone(), + window: manifest.window, + selectors: manifest.selectors.clone(), + all_gpu_activity: manifest.all_gpu_activity, + peer_copies: manifest.peer_copies, + dropped_records: manifest.dropped_records, + unknown_records: manifest.unknown_records, + record_limit_reached: manifest.record_limit_reached, + capture_failed: manifest.capture_failed, + cuda_devices: manifest.cuda_devices.clone(), + wall_clock: manifest.wall_clock, + } + } +} + +/// Write `.manifest.json` for an artifact just written, or remove a +/// stale one when the artifact has no known coverage. +pub(crate) fn write_manifest( + artifact_path: &Path, + described: Option<(&CaptureRecord, ManifestArtifact)>, +) -> Result<(), CommandFailure> { + let path = manifest_path(artifact_path); + let failure = |action: &str, error: &dyn std::fmt::Display| { + CommandFailure::new( + ErrorCode::TraceExportFailed, + format!("failed to {action} {}: {error}", path.display()), + false, + ) + }; + let Some((record, artifact)) = described else { + return match fs::remove_file(&path) { + Err(error) if error.kind() != ErrorKind::NotFound => { + Err(failure("remove stale manifest", &error)) + } + _ => Ok(()), + }; + }; + let mut text = serde_json::to_string_pretty(&record.manifest(artifact)) + .map_err(|error| failure("serialize", &error))?; + text.push('\n'); + crate::dev::write_export_file(&path, text.as_bytes()).map_err(|error| failure("write", &error)) +} + +/// Read and check the manifest beside an input artifact, if there is one. +pub(crate) fn read_manifest( + artifact_path: &Path, + bytes: &[u8], +) -> Result, CommandFailure> { + let path = manifest_path(artifact_path); + let text = match fs::read(&path) { + Ok(text) => text, + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None), + Err(error) => { + return Err(CommandFailure::new( + ErrorCode::TraceExportFailed, + format!("failed to read {}: {error}", path.display()), + false, + )); + } + }; + let manifest: CaptureManifest = serde_json::from_slice(&text).map_err(|error| { + CommandFailure::new( + ErrorCode::TraceExportFailed, + format!( + "{} does not match schemas/capture-manifest.schema.json: {error}", + path.display() + ), + false, + ) + })?; + if !xprobe_exporter::artifact_matches(&manifest.artifact, bytes) { + return Err(CommandFailure::new( + ErrorCode::TraceExportFailed, + format!( + "{} describes a different artifact than {}", + path.display(), + artifact_path.display() + ), + true, + ) + .with_detail("manifest_path", path.display().to_string()) + .with_hint( + "the events changed after capture; delete the stale manifest to analyze them without coverage", + )); + } + Ok(Some(manifest)) +} + +/// Coverage of inputs read together. Manifests prove coverage only when they +/// all describe one target and their windows share an instant. +pub(crate) fn offline_coverage(manifests: &[Option]) -> CaptureCoverage { + let known = manifests.iter().flatten().collect::>(); + let unverified = CaptureCoverage { + source: if manifests.len() > 1 { + CoverageSource::UnverifiedMerge + } else { + CoverageSource::Unverified + }, + all_gpu_activity: false, + }; + if known.len() != manifests.len() || known.is_empty() { + return unverified; + } + let one_window = known.iter().all(|manifest| { + manifest.target == known[0].target + && known + .iter() + .all(|other| manifest.window.overlaps(&other.window)) + }); + if !one_window { + return unverified; + } + // A capture of every GPU activity proves adjacency for the merge only + // when its window holds every other input's. + let all_gpu_activity = known.iter().any(|wide| { + wide.all_gpu_activity + && known.iter().all(|other| { + wide.window.start_ns <= other.window.start_ns + && other.window.end_ns <= wide.window.end_ns + }) + }); + CaptureCoverage { + source: CoverageSource::Manifest, + all_gpu_activity, + } +} + +/// Check a manifest against the events decoded from its artifact. +pub(crate) fn check_manifest( + artifact_path: &Path, + manifest: &CaptureManifest, + events: &[xprobe_protocol::Event], +) -> Result<(), CommandFailure> { + let failure = |problem: String| { + Err(CommandFailure::new( + ErrorCode::TraceExportFailed, + format!("the manifest beside {} {problem}", artifact_path.display()), + false, + )) + }; + if manifest.artifact.format != xprobe_protocol::ExportFormat::Jsonl { + return failure("describes a non-JSONL artifact".to_owned()); + } + if manifest.artifact.events != events.len() as u64 { + return failure(format!( + "counts {} events but the artifact holds {}", + manifest.artifact.events, + events.len() + )); + } + if manifest.window.start_ns > manifest.window.end_ns { + return failure("has a window that ends before it starts".to_owned()); + } + // Activity running at ARM may begin before the window, but nothing on + // the window's clock can happen after the capture's final read. + let late = events.iter().find(|event| { + event.clock_domain != xprobe_protocol::ClockDomain::Cupti + && event.timestamp_ns > manifest.window.end_ns + }); + if let Some(event) = late { + return failure(format!( + "has a window ending at {} ns but holds an event at {} ns", + manifest.window.end_ns, event.timestamp_ns + )); + } + let foreign = events.iter().find(|event| { + event.pid != manifest.target.pid + || event + .process_start_time + .is_some_and(|start| start != manifest.target.process_start_time) + }); + if let Some(event) = foreign { + return failure(format!( + "names process {} started at {} but holds an event of PID {}", + manifest.target.pid, manifest.target.process_start_time, event.pid + )); + } + Ok(()) +} + +/// Apply the losses and stop state a manifest records to its decoded events. +pub(crate) fn apply_manifest(capture: &mut CompletedCapture, manifest: &CaptureManifest) { + capture.dropped_records = capture.dropped_records.max(manifest.dropped_records); + capture.unknown_records = capture.unknown_records.max(manifest.unknown_records); + capture.record_limit_reached = capture + .record_limit_reached + .max(manifest.record_limit_reached); + capture.capture_failed |= manifest.capture_failed; + if capture.cuda_devices.is_empty() { + capture.cuda_devices.clone_from(&manifest.cuda_devices); + } +} + +#[cfg(test)] +mod tests { + use xprobe_protocol::{ + CaptureManifest, CaptureWindow, CoverageSource, ExportFormat, ManifestVersion, + TargetIdentity, + }; + + use super::offline_coverage; + + fn manifest(pid: u32, window: (u64, u64), all_gpu_activity: bool) -> CaptureManifest { + CaptureManifest { + schema_version: ManifestVersion::current(), + artifact: xprobe_exporter::manifest_artifact(ExportFormat::Jsonl, 0, b""), + target: TargetIdentity { + pid, + process_start_time: 7, + }, + window: CaptureWindow { + start_ns: window.0, + end_ns: window.1, + }, + selectors: Vec::new(), + all_gpu_activity, + peer_copies: all_gpu_activity, + dropped_records: 0, + unknown_records: 0, + record_limit_reached: None, + capture_failed: false, + cuda_devices: Vec::new(), + wall_clock: None, + } + } + + #[test] + fn manifests_prove_coverage_only_for_one_window_of_one_target() { + let gpu = manifest(1, (10, 30), true); + let host = manifest(1, (12, 25), false); + let covered = offline_coverage(&[Some(gpu.clone()), Some(host.clone())]); + assert_eq!(covered.source, CoverageSource::Manifest); + assert!(covered.all_gpu_activity); + // A wide capture of 10-30 says nothing about a narrower one past it. + let past = manifest(1, (12, 40), false); + let partial = offline_coverage(&[Some(gpu.clone()), Some(past)]); + assert_eq!(partial.source, CoverageSource::Manifest); + assert!(!partial.all_gpu_activity); + + let later = manifest(1, (31, 40), false); + let other = manifest(2, (10, 20), false); + for inputs in [ + vec![Some(gpu.clone()), Some(later)], + vec![Some(gpu.clone()), Some(other)], + vec![Some(gpu.clone()), None], + ] { + let coverage = offline_coverage(&inputs); + assert_eq!(coverage.source, CoverageSource::UnverifiedMerge); + assert!(!coverage.all_gpu_activity); + } + assert_eq!(offline_coverage(&[None]).source, CoverageSource::Unverified); + assert_eq!( + offline_coverage(&[Some(host)]).source, + CoverageSource::Manifest + ); + } +} diff --git a/xprobe/cli/src/dev.rs b/xprobe/cli/src/dev.rs index d55ef53..1e3464f 100644 --- a/xprobe/cli/src/dev.rs +++ b/xprobe/cli/src/dev.rs @@ -131,6 +131,7 @@ pub(crate) fn run_trace(args: TraceArgs) -> ExitCode { timeout: Duration::from_millis(spec.timeout_ms), match_policy_text: match_policy_name(spec.match_policy), mode: MeasurementMode::Exact, + ring: false, options: MeasureOptions { session_id: format!("xp_trace_{}", std::process::id()), name: spec.name, diff --git a/xprobe/cli/src/failure.rs b/xprobe/cli/src/failure.rs index 94bb806..9bf81cc 100644 --- a/xprobe/cli/src/failure.rs +++ b/xprobe/cli/src/failure.rs @@ -1,4 +1,5 @@ use crate::clock_domain_name; +use crate::coverage::CaptureRecord; use crate::live::match_policy_name; use std::collections::BTreeMap; use std::process::ExitCode; @@ -18,6 +19,8 @@ pub(crate) struct CommandFailure { pub(crate) details: BTreeMap, pub(crate) hints: Vec, pub(crate) artifact_events: Option>, + /// How the preserved events were collected, written as their manifest. + pub(crate) artifact_capture: Option>, } impl CommandFailure { @@ -29,6 +32,7 @@ impl CommandFailure { details: BTreeMap::new(), hints: Vec::new(), artifact_events: None, + artifact_capture: None, } } @@ -50,6 +54,11 @@ impl CommandFailure { self.artifact_events = Some(events); self } + + pub(crate) fn with_artifact_capture(mut self, capture: Option) -> Self { + self.artifact_capture = capture.map(Box::new); + self + } } pub(crate) fn measurement_failure( diff --git a/xprobe/cli/src/graph.rs b/xprobe/cli/src/graph.rs index 451867b..d50d741 100644 --- a/xprobe/cli/src/graph.rs +++ b/xprobe/cli/src/graph.rs @@ -17,11 +17,13 @@ use xprobe_protocol::{ }; use crate::{ - EvidenceOutput, ExportFormatArg, export_measurement_capture, + EvidenceOutput, ExportFormatArg, + coverage::CaptureRecord, + export_measurement_capture, failure::{CommandFailure, emit_command_failure, measurement_failure}, finish_measurement_failure, live::{ - LiveCollection, LiveEvaluator, LiveMeasureRequest, LiveOutcome, LivePlan, + LiveCapture, LiveCollection, LiveEvaluator, LiveMeasureRequest, LiveOutcome, LivePlan, apply_collection_summary, checked_live_capture, collect_live, validate_live_limits, }, protocol_export_format, @@ -120,6 +122,7 @@ pub(crate) struct GraphExecution { events: Vec, /// The shared capture's summary; every edge reports the same one. collection: CollectionSummary, + capture: CaptureRecord, } impl LiveOutcome for GraphExecution { @@ -148,7 +151,7 @@ impl LiveEvaluator for GraphEdges { collection: &LiveCollection, require_complete: bool, ) -> Result { - let capture = checked_live_capture( + let LiveCapture { capture, record } = checked_live_capture( host_captures, collection, &self.session_id, @@ -157,7 +160,7 @@ impl LiveEvaluator for GraphEdges { let results = self .edges .iter() - .map(|edge| measure_edge(edge, &capture, require_complete)) + .map(|edge| measure_edge(edge, &capture, &record, require_complete)) .collect::, _>>()?; Ok(GraphExecution { session_id: self.session_id.clone(), @@ -166,6 +169,7 @@ impl LiveEvaluator for GraphEdges { status: SessionStatus::Completed, warnings: Vec::new(), events: capture.events, + capture: record, }) } @@ -185,6 +189,7 @@ impl LiveEvaluator for GraphEdges { fn measure_edge( edge: &EdgePlan, capture: &CompletedCapture, + record: &CaptureRecord, require_complete: bool, ) -> Result { let options = MeasureOptions { @@ -193,11 +198,13 @@ fn measure_edge( }; let mut result = measure(&capture.events, &options).map_err(|error| { let mut failure = measurement_failure(&error, &options, &capture.events, require_complete) - .with_detail("edge", edge.name.clone()); + .with_detail("edge", edge.name.clone()) + .with_artifact_capture(Some(record.clone())); failure.message = format!("edge {:?}: {}", edge.name, failure.message); failure })?; apply_collection_summary(&mut result, capture); + record.apply_to(&mut result); Ok(result) } @@ -289,6 +296,7 @@ fn collect_graph( timeout: Duration::from_millis(spec.timeout_ms), match_policy_text: graph::policy_text(first.match_policy), mode: MeasurementMode::Exact, + ring: false, options: MeasureOptions { session_id: session_id.clone(), name: spec.name.clone(), @@ -307,6 +315,9 @@ fn collect_graph( .map(|endpoint| endpoint.endpoint) .collect(), requirements: validation.requirements, + stream_order: edges + .iter() + .any(|edge| edge.options.match_policy == xprobe_protocol::MatchPolicy::StreamOrder), }; let execution = collect_live(plan, &request, &GraphEdges { session_id, edges })?; Ok((execution, spec, target)) @@ -326,7 +337,9 @@ fn finish_graph( let mut artifact = None; if let Some(path) = path { let format = output.format.unwrap_or(ExportFormatArg::Jsonl); - if let Err(error) = export_measurement_capture(&execution.events, &path, format) { + if let Err(error) = + export_measurement_capture(&execution.events, &path, format, Some(&execution.capture)) + { return emit_command_failure(error, json); } artifact = Some(EvidenceArtifact { diff --git a/xprobe/cli/src/live.rs b/xprobe/cli/src/live.rs index 2808a9b..dfdf47a 100644 --- a/xprobe/cli/src/live.rs +++ b/xprobe/cli/src/live.rs @@ -1,4 +1,5 @@ use crate::MeasurementExecution; +use crate::coverage::CaptureRecord; use crate::failure::CommandFailure; use crate::failure::measurement_failure; use std::collections::BTreeMap; @@ -52,6 +53,9 @@ pub(crate) struct LiveMeasureRequest { pub(crate) timeout: Duration, pub(crate) match_policy_text: &'static str, pub(crate) mode: MeasurementMode, + /// Keep the newest `max_events` CUPTI records in a ring instead of + /// stopping at the limit (triggered capture). + pub(crate) ring: bool, pub(crate) options: MeasureOptions, } @@ -60,6 +64,8 @@ pub(crate) struct LivePlan { pub(crate) report: ProcessReport, pub(crate) endpoints: Vec, pub(crate) requirements: ValidationRequirements, + /// Some edge uses stream order, so every GPU activity is captured. + pub(crate) stream_order: bool, } /// A correlated view of the capture that the live loop can finish with. @@ -182,6 +188,25 @@ pub(crate) struct LiveCollection { pub(crate) agent_major: Option, pub(crate) agent_path: Option, pub(crate) cupti_path: Option, + pub(crate) capture_plan: CapturePlan, + /// Ring records overwritten before a snapshot read them. + pub(crate) ring_overwritten: u64, + /// Wall time against `CLOCK_MONOTONIC` when the capture was armed. + pub(crate) wall_clock_start: xprobe_protocol::ClockAnchor, + /// Clock domain of the GPU activity read so far; one capture keeps one. + pub(crate) cuda_activity_clock: Option, + /// The part of `ring_overwritten` a triggered capture has accounted for. + pub(crate) ring_overwritten_seen: u64, +} + +/// What the collectors were armed to record, kept for the capture manifest. +pub(crate) struct CapturePlan { + /// `CLOCK_MONOTONIC` time just before the first collector was armed. + pub(crate) start_ns: u64, + /// Endpoint selectors the collectors were armed for. + pub(crate) selectors: Vec, + /// CUPTI recorded every GPU activity for stream order. + pub(crate) stream_order: bool, } pub(crate) fn collect_live_measurement( @@ -403,7 +428,7 @@ pub(crate) fn prepare_live_collection( } /// Validate the request's start/end pair into a capture plan. -fn single_edge_plan(request: &LiveMeasureRequest) -> Result { +pub(crate) fn single_edge_plan(request: &LiveMeasureRequest) -> Result { let report = inspect::run(request.pid).map_err(|error| { CommandFailure::new(error.code(), error.to_string(), error.recoverable()) })?; @@ -445,6 +470,7 @@ fn single_edge_plan(request: &LiveMeasureRequest) -> Result cupti::CuptiCaptureMode::Exact, + MeasurementMode::Aggregate => cupti::CuptiCaptureMode::Aggregate, + } + }, + stream_order, )?; let baseline = arm_cupti_capture( &activation, @@ -472,6 +510,8 @@ pub(crate) fn start_live_collection( requirements.needs_nvtx, request, )?; + // Host-clock activity before the ARM reply may predate the capture. + let capture_start_ns = monotonic_now()?; let socket = activation.socket; let baseline_timestamp = baseline .as_ref() @@ -500,6 +540,10 @@ pub(crate) fn start_live_collection( .and_then(|duration| started.checked_add(duration)); let collectors = start_host_collectors(&report, &endpoints, request)?; let host_captures = collectors.handles.is_empty().then(Vec::new); + let selectors = endpoints + .iter() + .map(|endpoint| endpoint.selector.clone()) + .collect(); Ok(LiveCollection { report, @@ -520,6 +564,37 @@ pub(crate) fn start_live_collection( agent_major: activation.major, agent_path: activation.agent_path, cupti_path: activation.cupti_path, + capture_plan: CapturePlan { + start_ns: capture_start_ns, + selectors, + stream_order, + }, + ring_overwritten: 0, + cuda_activity_clock: None, + wall_clock_start, + ring_overwritten_seen: 0, + }) +} + +/// `CLOCK_MONOTONIC` now, the clock capture windows are recorded in. +/// `CLOCK_REALTIME` against `CLOCK_MONOTONIC` now. +pub(crate) fn clock_anchor() -> Result { + xprobe_core::clock::clock_anchor().map_err(|error| { + CommandFailure::new( + ErrorCode::Internal, + format!("failed to read the wall clock: {error}"), + false, + ) + }) +} + +pub(crate) fn monotonic_now() -> Result { + xprobe_core::clock::monotonic_ns().map_err(|error| { + CommandFailure::new( + ErrorCode::Internal, + format!("failed to read CLOCK_MONOTONIC: {error}"), + false, + ) }) } @@ -642,7 +717,8 @@ pub(crate) fn cupti_arm_config( endpoints: &[ValidatedEndpoint], requirements: &ValidationRequirements, max_events: usize, - mode: MeasurementMode, + capture_mode: cupti::CuptiCaptureMode, + stream_order: bool, ) -> Result, CommandFailure> { if !requirements.needs_cupti { return Ok(None); @@ -659,7 +735,15 @@ pub(crate) fn cupti_arm_config( .into_iter() .flatten() .collect::>(); - if mode == MeasurementMode::Exact { + if stream_order { + // Stream order needs every activity on the stream to find successors. + // Unfiltered start and end filters for every family record both + // boundaries of every kernel, copy, and memset and cover the + // endpoints' own filters. + filters.retain(|filter| !filter.record_kind.is_activity()); + filters.extend(cupti::all_activity_filters()); + } + if capture_mode != cupti::CuptiCaptureMode::Aggregate { let mut unique = Vec::with_capacity(filters.len()); for filter in filters { if !unique.contains(&filter) { @@ -688,10 +772,7 @@ pub(crate) fn cupti_arm_config( })?; Ok(Some(cupti::CuptiArmConfig { record_capacity, - capture_mode: match mode { - MeasurementMode::Exact => cupti::CuptiCaptureMode::Exact, - MeasurementMode::Aggregate => cupti::CuptiCaptureMode::Aggregate, - }, + capture_mode, filters, })) } @@ -858,6 +939,10 @@ pub(crate) fn resolve_agent_path( }) } +/// Reads without progress before a stopped ring's unread tail is lost. +const RING_DRAIN_RETRIES: u32 = 8; +const RING_DRAIN_PAUSE: Duration = Duration::from_millis(2); + pub(crate) fn stop_cupti_agent( collection: &mut LiveCollection, request: &LiveMeasureRequest, @@ -867,30 +952,89 @@ pub(crate) fn stop_cupti_agent( } let socket = collection .socket - .as_deref() + .clone() .expect("armed CUPTI agent has a socket"); - collection.cupti_armed = false; - let capture = if collection.managed_agent { + let session = request.options.session_id.as_str(); + let failure = |error: cupti::CuptiSnapshotError| { + CommandFailure::new(ErrorCode::CleanupFailed, error.to_string(), true) + .with_detail("cleanup_phase", "stop_cupti") + .with_hint("verify the target state before starting another measurement") + }; + // A ring reply ends at its first gap, so stop without closing, read the + // rest, and close only after every record was read. + let capture = if collection.managed_agent && !request.ring { cupti::close( - socket, + &socket, request.timeout, - &request.options.session_id, + session, collection.cuda_record_offset, ) } else { cupti::stop( - socket, + &socket, request.timeout, - &request.options.session_id, + session, collection.cuda_record_offset, ) } - .map_err(|error| { - CommandFailure::new(ErrorCode::CleanupFailed, error.to_string(), true) - .with_detail("cleanup_phase", "stop_cupti") - .with_hint("verify the target state before starting another measurement") - })?; + .map_err(failure)?; append_cuda_capture(collection, capture)?; + if request.ring { + // A writer still finishing its record holds the reader back briefly; + // a record still unread after the retries is counted as lost. + let mut stalled = 0; + loop { + let taken = collection + .latest_cuda + .as_ref() + .map_or(0, |cuda| cuda.observed_records); + let before = collection.cuda_record_offset; + if before >= taken { + break; + } + if stalled == RING_DRAIN_RETRIES { + collection.ring_overwritten += taken - before; + collection.cuda_record_offset = taken; + break; + } + let rest = + cupti::snapshot(&socket, request.timeout, session, before).map_err(failure)?; + append_cuda_capture(collection, rest)?; + if collection.cuda_record_offset == before { + stalled += 1; + thread::sleep(RING_DRAIN_PAUSE); + } else { + stalled = 0; + } + } + if collection.managed_agent { + let closed = cupti::close( + &socket, + request.timeout, + session, + collection.cuda_record_offset, + ) + .map_err(failure)?; + append_cuda_capture(collection, closed)?; + } + } + // An Agent that could not disable its callbacks keeps serving; leave the + // flag set so cleanup retries CLOSE. + if collection + .latest_cuda + .as_ref() + .is_some_and(|cuda| cuda.stop_reason == cupti::CuptiStopReason::CleanupError) + { + return Err(CommandFailure::new( + ErrorCode::CleanupFailed, + "the CUPTI Agent could not disable its callbacks or activity kinds", + true, + ) + .with_detail("cleanup_phase", "stop_cupti") + .with_hint("verify the target state before starting another measurement")); + } + // Only a completed stop clears the flag; otherwise cleanup retries it. + collection.cupti_armed = false; collection.managed_agent = false; Ok(()) } @@ -1068,6 +1212,9 @@ pub(crate) fn wait_for_host_collectors( Ok(()) } +/// Shortest I/O timeout given to a snapshot that starts before the deadline. +const SNAPSHOT_IO_FLOOR: Duration = Duration::from_secs(2); + pub(crate) fn refresh_live_sources( collection: &mut LiveCollection, request: &LiveMeasureRequest, @@ -1085,9 +1232,11 @@ pub(crate) fn refresh_live_sources( collection.collectors.cancel(); return Ok(()); } + // The deadline decides whether to start a snapshot; one that starts + // near it still gets time to finish. let capture = cupti::snapshot( path, - remaining, + remaining.max(SNAPSHOT_IO_FLOOR), &request.options.session_id, collection.cuda_record_offset, ) @@ -1096,10 +1245,17 @@ pub(crate) fn refresh_live_sources( Ok(()) } +/// Append an incremental CUPTI capture. A ring capture may start past the +/// requested offset; the records in between were overwritten unread and are +/// counted in `ring_overwritten`. pub(crate) fn append_cuda_capture( collection: &mut LiveCollection, mut capture: cupti::CuptiCapture, ) -> Result<(), CommandFailure> { + if capture.ring && capture.record_offset > collection.cuda_record_offset { + collection.ring_overwritten += capture.record_offset - collection.cuda_record_offset; + collection.cuda_record_offset = capture.record_offset; + } if capture.record_offset != collection.cuda_record_offset { return Err(CommandFailure::new( ErrorCode::TraceExportFailed, @@ -1110,6 +1266,26 @@ pub(crate) fn append_cuda_capture( false, )); } + // Raw and host-clock activity in one capture cannot be compared. + for event in &capture.events { + if xprobe_protocol::activity_boundary(&event.event_type).is_none() { + continue; + } + match &collection.cuda_activity_clock { + Some(clock) if *clock != event.clock_domain => { + return Err(CommandFailure::new( + ErrorCode::ClockAlignmentFailed, + format!( + "CUPTI activity changed clock domain from {clock:?} to {:?} during capture", + event.clock_domain + ), + true, + )); + } + Some(_) => {} + None => collection.cuda_activity_clock = Some(event.clock_domain.clone()), + } + } let returned = u64::try_from(capture.events.len()).map_err(|error| { CommandFailure::new( ErrorCode::TraceExportFailed, @@ -1146,6 +1322,17 @@ pub(crate) fn append_cuda_capture( false, )); } + // The Agent reads device UUIDs once the driver can report them, so + // a later snapshot may bring the table an earlier one lacked. + if accumulated.devices.is_empty() { + accumulated.devices = std::mem::take(&mut capture.devices); + } else if !capture.devices.is_empty() && capture.devices != accumulated.devices { + return Err(CommandFailure::new( + ErrorCode::TraceExportFailed, + "the CUPTI device table changed during capture", + false, + )); + } accumulated.state = capture.state; accumulated.stop_reason = capture.stop_reason; accumulated.observed_records = capture.observed_records; @@ -1167,6 +1354,7 @@ pub(crate) fn aggregate_inventory_result( request: &LiveMeasureRequest, ) -> Result { validate_aggregate_capture(capture)?; + let cuda_devices = capture.devices.clone(); let capture = gpu_aggregate::GpuAggregateCapture { groups: capture .aggregate_groups @@ -1203,6 +1391,10 @@ pub(crate) fn aggregate_inventory_result( }, capture, ) + .map(|mut result| { + result.collection.cuda_devices = cuda_devices; + result + }) .map_err(|error| CommandFailure::new(error.code(), error.to_string(), error.recoverable())) } @@ -1368,7 +1560,7 @@ pub(crate) fn measure_live_capture( options: &MeasureOptions, require_complete: bool, ) -> Result { - let capture = checked_live_capture( + let LiveCapture { capture, record } = checked_live_capture( host_captures, collection, &options.session_id, @@ -1380,25 +1572,38 @@ pub(crate) fn measure_live_capture( }; let mut result = measure(&capture.events, &options).map_err(|error| { measurement_failure(&error, &options, &capture.events, require_complete) + .with_artifact_capture(Some(record.clone())) })?; apply_collection_summary(&mut result, &capture); + record.apply_to(&mut result); Ok(MeasurementExecution { result, events: capture.events, + capture: Some(record), }) } +/// A merged live capture and the record of how it was collected. +pub(crate) struct LiveCapture { + pub(crate) capture: completed::CompletedCapture, + pub(crate) record: CaptureRecord, +} + /// Merge the live sources into one capture and reject incomplete or unknown -/// records, preserving the events as an artifact on failure. +/// records, preserving the events and their coverage as an artifact on failure. pub(crate) fn checked_live_capture( host_captures: &[HostCaptureResult], collection: &LiveCollection, session_id: &str, require_complete: bool, -) -> Result { +) -> Result { let capture = completed_live_capture(host_captures, collection, session_id)?; - reject_incomplete_capture(&capture, true, require_complete) - .map_err(|error| error.with_artifact_events(capture.events.clone()))?; + let record = CaptureRecord::live(collection, &capture)?; + reject_incomplete_capture(&capture, true, require_complete).map_err(|error| { + error + .with_artifact_events(capture.events.clone()) + .with_artifact_capture(Some(record.clone())) + })?; if capture.unknown_records != 0 { return Err(CommandFailure::new( ErrorCode::TraceExportFailed, @@ -1410,9 +1615,10 @@ pub(crate) fn checked_live_capture( ) .with_detail("unknown_records", capture.unknown_records) .with_hint("rebuild xprobe and the CUPTI Agent from the same release") - .with_artifact_events(capture.events)); + .with_artifact_events(capture.events) + .with_artifact_capture(Some(record))); } - Ok(capture) + Ok(LiveCapture { capture, record }) } pub(crate) fn completed_live_capture( @@ -1428,6 +1634,7 @@ pub(crate) fn completed_live_capture( record_limit_reached: capture.record_limit_reached.then_some(capture.captured), capture_failed: false, cupti: None, + cuda_devices: Vec::new(), events: capture.events.clone(), }) .collect::>(); @@ -1477,16 +1684,23 @@ pub(crate) fn completed_live_capture( observed_records, dropped_records, }), - events: cuda - .events - .iter() - .filter(|event| { + cuda_devices: cuda.devices.clone(), + events: { + // Place activity running at STOP before filtering by time. + let mut events = cuda.events.clone(); + let began = collection + .baseline_timestamp + .map_or(collection.capture_plan.start_ns, |baseline| { + collection.capture_plan.start_ns.max(baseline + 1) + }); + cupti::place_unknown_starts(&mut events, &[], Some(began)); + events.retain(|event| { collection .baseline_timestamp .is_none_or(|start| event.timestamp_ns > start) - }) - .cloned() - .collect(), + }); + events + }, }); } completed::merge(captures, session_id).map_err(|error| { @@ -1518,7 +1732,9 @@ pub(crate) fn reject_incomplete_capture( true, ) .with_detail("record_capacity", capacity) - .with_hint("narrow the selectors or explicitly increase max-events"); + .with_hint( + "narrow the selectors, or shorten the capture or explicitly increase max-events; stream-order records every GPU activity, so narrowing its selectors does not help", + ); if let Some(cupti) = capture.cupti.as_ref() { failure = failure .with_detail("observed_records", cupti.observed_records) @@ -1546,6 +1762,10 @@ pub(crate) fn apply_collection_summary( result: &mut MeasurementResult, capture: &completed::CompletedCapture, ) { + result + .collection + .cuda_devices + .clone_from(&capture.cuda_devices); let Some(cupti) = capture.cupti.as_ref() else { return; }; @@ -1578,3 +1798,62 @@ pub(crate) const fn match_policy_name(policy: MatchPolicy) -> &'static str { MatchPolicy::StreamOrder => "stream-order", } } + +#[cfg(test)] +mod tests { + use xprobe_core::{graph, inspect, validate}; + + use super::{cupti, cupti_arm_config}; + + /// Graph validation predicts the filter count ARM lowers to. + #[test] + fn validation_filter_slots_match_the_armed_filters() { + let report = inspect::run(std::process::id()).expect("inspect self"); + for (from, to, policy, expected) in [ + ( + "cuda:kernel_start:name~^a", + "cuda:kernel_end:name~^a", + "exact", + 2, + ), + ("cuda:launch_api:exit", "cuda:kernel_start", "exact", 3), + ( + "cuda:kernel_end:name~^a", + "cuda:kernel_start:name~^b", + "stream-order", + xprobe_core::graph::STREAM_ORDER_FILTERS, + ), + ( + "cuda:memcpy_end:kind=HtoD", + "cuda:kernel_start", + "stream-order", + xprobe_core::graph::STREAM_ORDER_FILTERS, + ), + ] { + let validation = validate::run(&report, from, to, policy).expect("validate"); + assert!(validation.valid, "{from} -> {to}: {:?}", validation.issues); + let endpoints = [validation.start, validation.end]; + let stream_order = policy == "stream-order"; + let armed = cupti_arm_config( + &endpoints, + &validation.requirements, + 100, + cupti::CuptiCaptureMode::Exact, + stream_order, + ) + .expect("arm config") + .expect("CUDA endpoints need CUPTI"); + let predicted = + graph::cuda_filter_slots(&endpoints.iter().collect::>(), stream_order); + assert_eq!(armed.filters.len(), expected, "{from} -> {to}"); + assert_eq!(predicted, expected, "{from} -> {to}"); + if stream_order { + assert!( + cupti::all_activity_filters() + .iter() + .all(|filter| armed.filters.contains(filter)) + ); + } + } + } +} diff --git a/xprobe/cli/src/main.rs b/xprobe/cli/src/main.rs index f76f102..e42fc8c 100644 --- a/xprobe/cli/src/main.rs +++ b/xprobe/cli/src/main.rs @@ -18,17 +18,22 @@ use xprobe_exporter::{events_to_chrome_trace, events_to_jsonl}; use xprobe_protocol::{ AggregateInventoryResult, ClockDomain, CpuSamplingValidationResult, ErrorCode, Event, EvidenceArtifact, EvidenceMode, ExportFormat, MatchPolicy, MeasurementMode, MeasurementResult, - MeasurementSpec, SyscallAggregateValidationResult, + MeasurementSpec, SyscallAggregateValidationResult, TriggerCondition, TriggerKind, }; +use crate::coverage::CaptureRecord; + mod args; +mod coverage; mod dev; mod failure; mod graph; mod inventory; mod live; +mod python; mod render; mod triage; +mod trigger; use args::{ Cli, Command, CommonOutputArgs, DiscoverArgs, DoctorArgs, ExportFormatArg, MeasureArgs, @@ -87,6 +92,9 @@ fn run_measure(args: MeasureArgs) -> ExitCode { match_policy, cpu_sample, syscall_aggregate, + python_sample, + python_hz, + python_threads_hz, frequency_hz, max_samples, stack_depth, @@ -98,6 +106,8 @@ fn run_measure(args: MeasureArgs) -> ExitCode { aggregate, max_groups, name, + trigger, + trigger_window, output: CommonOutputArgs { json, @@ -159,6 +169,23 @@ fn run_measure(args: MeasureArgs) -> ExitCode { json, ); } + if python_sample { + let (Some(pid), Some(duration_ms)) = (pid, duration_ms) else { + unreachable!("clap requires --pid and --duration-ms with --python-sample"); + }; + return python::run_python_sample( + &python::PythonSampleRequest { + pid, + runtime: None, + name, + duration_ms, + gil_hz: python_hz, + threads_hz: python_threads_hz, + events_out: events_out.as_deref(), + }, + json, + ); + } if syscall_aggregate { let Some(pid) = pid else { return emit_error( @@ -187,6 +214,29 @@ fn run_measure(args: MeasureArgs) -> ExitCode { json, ); } + if let Some(condition) = match trigger_condition( + &trigger, + &trigger_window, + from.as_deref(), + to.as_deref(), + match_policy.as_deref(), + ) { + Ok(condition) => condition, + Err(error) => return emit_command_failure(error, json), + } { + let pid = pid.expect("clap requires --pid with a trigger"); + let request = trigger::trigger_request( + pid, + cupti_socket, + agent, + timeout_ms, + max_events, + format!("xp_trigger_{}", std::process::id()), + condition, + events_out.as_deref(), + ); + return trigger::run_trigger(&request, json); + } if max_groups.is_some() && !aggregate { return emit_error( ErrorCode::InvalidEventSelector, @@ -244,6 +294,7 @@ fn run_measure(args: MeasureArgs) -> ExitCode { timeout: Duration::from_millis(timeout_ms), match_policy_text: match_policy_name(match_policy), mode: MeasurementMode::Exact, + ring: false, options, }; return match collect_live_measurement(&request) { @@ -261,6 +312,55 @@ fn run_measure(args: MeasureArgs) -> ExitCode { ) } +/// The trigger requested by `--trigger-*`, if any. +fn trigger_condition( + args: &args::TriggerArgs, + window: &args::TriggerWindowArgs, + from: Option<&str>, + to: Option<&str>, + policy: Option<&str>, +) -> Result, CommandFailure> { + let (kind, threshold, flag) = match ( + args.trigger_gap_ms, + args.trigger_idle_ms, + args.trigger_duration_ms, + args.trigger_latency_ms, + ) { + (Some(ms), None, None, None) => (TriggerKind::Gap, ms, "trigger-gap-ms"), + (None, Some(ms), None, None) => (TriggerKind::Idle, ms, "trigger-idle-ms"), + (None, None, Some(ms), None) => (TriggerKind::Duration, ms, "trigger-duration-ms"), + (None, None, None, Some(ms)) => (TriggerKind::Latency, ms, "trigger-latency-ms"), + _ => return Ok(None), + }; + let latency = kind == TriggerKind::Latency; + if !latency && (from.is_some() || to.is_some() || policy.is_some()) { + return Err(CommandFailure::new( + ErrorCode::InvalidEventSelector, + format!("--{flag} watches all GPU activity and takes no --from, --to, or --match"), + true, + )); + } + let match_policy = policy.map(parse_match_policy_text).transpose()?; + Ok(Some(TriggerCondition { + kind, + threshold_ns: trigger::milliseconds_ns(flag, threshold, false)?, + start_selector: from.filter(|_| latency).map(str::to_owned), + end_selector: to.filter(|_| latency).map(str::to_owned), + match_policy: match_policy.filter(|_| latency), + pre_ns: trigger::milliseconds_ns("pre-ms", window.pre_ms, true)?, + post_ns: trigger::milliseconds_ns("post-ms", window.post_ms, true)?, + windows: if window.windows == 0 { + return Err(CommandFailure::new( + ErrorCode::SessionLimitExceeded, + "--windows must be positive", + true, + )); + } else { + window.windows + }, + })) +} + fn validate_measure_source(pid: Option, input: &[PathBuf]) -> Result<(), CommandFailure> { if pid.is_some() && !input.is_empty() { return Err(CommandFailure::new( @@ -303,6 +403,7 @@ fn direct_aggregate_request( timeout: Duration::from_millis(timeout_ms), match_policy_text: match_policy_name(options.match_policy), mode: MeasurementMode::Aggregate, + ring: false, options: MeasureOptions { duration: Some(Duration::from_millis(duration_ms)), max_events: max_groups.expect("clap supplies aggregate group capacity"), @@ -337,21 +438,22 @@ fn parse_measure_selection( true, )); }; - let policy = match policy.as_str() { - "exact" => MatchPolicy::Exact, - "first-after" | "first_after" => MatchPolicy::FirstAfter, - "nearest" => MatchPolicy::Nearest, - "stack-nested" | "stack_nested" => MatchPolicy::StackNested, - "stream-order" | "stream_order" => MatchPolicy::StreamOrder, - _ => { - return Err(CommandFailure::new( - ErrorCode::InvalidCorrelationPolicy, - "unsupported measurement correlation policy", - true, - )); - } - }; - Ok((from, to, policy)) + Ok((from, to, parse_match_policy_text(&policy)?)) +} + +fn parse_match_policy_text(policy: &str) -> Result { + match policy { + "exact" => Ok(MatchPolicy::Exact), + "first-after" | "first_after" => Ok(MatchPolicy::FirstAfter), + "nearest" => Ok(MatchPolicy::Nearest), + "stack-nested" | "stack_nested" => Ok(MatchPolicy::StackNested), + "stream-order" | "stream_order" => Ok(MatchPolicy::StreamOrder), + _ => Err(CommandFailure::new( + ErrorCode::InvalidCorrelationPolicy, + "unsupported measurement correlation policy", + true, + )), + } } fn run_completed_measurement( @@ -474,6 +576,7 @@ fn run_measure_spec( timeout: Duration::from_millis(spec.timeout_ms), match_policy_text: match_policy_name(spec.match_policy), mode: spec.measurement_mode, + ring: false, options: MeasureOptions { session_id: format!("xp_measure_{}", std::process::id()), name: spec.name, @@ -611,7 +714,9 @@ fn finish_measurement( }; if let Some(path) = path { let format = output.format.unwrap_or(ExportFormatArg::Jsonl); - if let Err(error) = export_measurement_capture(&execution.events, &path, format) { + if let Err(error) = + export_measurement_capture(&execution.events, &path, format, execution.capture.as_ref()) + { return emit_command_failure(error, json); } result.evidence.artifact = Some(EvidenceArtifact { @@ -641,7 +746,9 @@ fn finish_measurement_failure( Err(invalid) => return emit_command_failure(invalid, json), }; let format = output.format.unwrap_or(ExportFormatArg::Jsonl); - if let Err(export) = export_measurement_capture(&events, &path, format) { + if let Err(export) = + export_measurement_capture(&events, &path, format, error.artifact_capture.as_deref()) + { return emit_command_failure( export .with_detail("original_error_code", error.code.to_string()) @@ -663,10 +770,13 @@ const fn protocol_export_format(format: ExportFormatArg) -> ExportFormat { } } +/// Write the capture's events and, for Event JSONL, the coverage manifest +/// that lets `measure --input` reuse what the collectors reported. fn export_measurement_capture( events: &[Event], path: &Path, format: ExportFormatArg, + capture: Option<&CaptureRecord>, ) -> Result<(), CommandFailure> { let artifact = match format { ExportFormatArg::Jsonl => events_to_jsonl(events), @@ -679,7 +789,24 @@ fn export_measurement_capture( format!("failed to write {}: {error}", path.display()), false, ) - }) + })?; + let format = protocol_export_format(format); + // Only an Event JSONL artifact with known coverage gets a manifest; the + // digest is computed for it alone. + let record = capture.filter(|_| format == ExportFormat::Jsonl); + coverage::write_manifest( + path, + record.map(|record| { + ( + record, + xprobe_exporter::manifest_artifact( + format, + events.len() as u64, + artifact.as_bytes(), + ), + ) + }), + ) } const fn export_format_name(format: ExportFormatArg) -> &'static str { @@ -689,11 +816,54 @@ const fn export_format_name(format: ExportFormatArg) -> &'static str { } } +/// What an event records, apart from the session, ID, and sequence that a +/// re-export or re-decode assigns anew. +fn event_content(event: &xprobe_protocol::Event) -> u64 { + use std::hash::{Hash, Hasher}; + + let mut canonical = event.clone(); + canonical.session_id.clear(); + canonical.event_id.clear(); + canonical.sequence = 0; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + serde_json::to_string(&canonical) + .expect("a decoded event serializes") + .hash(&mut hasher); + hasher.finish() +} + +/// Two manifests naming one PID as different processes are two targets, +/// even when their events carry no start time. +fn reject_mixed_manifest_targets( + manifests: &[Option], +) -> Result<(), CommandFailure> { + for (index, first) in manifests.iter().flatten().enumerate() { + if let Some(other) = manifests.iter().flatten().skip(index + 1).find(|other| { + other.target.pid == first.target.pid + && other.target.process_start_time != first.target.process_start_time + }) { + return Err(CommandFailure::new( + ErrorCode::TraceExportFailed, + format!( + "inputs capture two processes with PID {}, started at {} and {}", + first.target.pid, + first.target.process_start_time, + other.target.process_start_time + ), + false, + )); + } + } + Ok(()) +} + fn measure_completed_inputs( input: &[PathBuf], options: &MeasureOptions, ) -> Result { let mut captures = Vec::with_capacity(input.len()); + let mut manifests = Vec::with_capacity(input.len()); + let mut identities = std::collections::BTreeSet::new(); for path in input { let bytes = fs::read(path).map_err(|error| { CommandFailure::new( @@ -702,20 +872,57 @@ fn measure_completed_inputs( false, ) })?; - let capture = completed::decode(&bytes, &options.session_id).map_err(|error| { + let mut capture = completed::decode(&bytes, &options.session_id).map_err(|error| { CommandFailure::new( ErrorCode::TraceExportFailed, format!("failed to decode {}: {error}", path.display()), false, ) })?; + let manifest = coverage::read_manifest(path, &bytes)?; + if let Some(manifest) = manifest.as_ref() { + coverage::check_manifest(path, manifest, &capture.events)?; + coverage::apply_manifest(&mut capture, manifest); + } + // Merging events twice would double them. Session, ID, and sequence + // change when events are re-exported or re-decoded, so an event is + // identified by everything else it records. + let repeated = input.len() > 1 && { + let own = capture + .events + .iter() + .map(event_content) + .collect::>(); + let repeated = !own.is_disjoint(&identities); + identities.extend(own); + repeated + }; + if repeated { + return Err(CommandFailure::new( + ErrorCode::TraceExportFailed, + format!("{} repeats events given in another input", path.display()), + true, + )); + } captures.push(capture); + manifests.push(manifest); } + reject_mixed_manifest_targets(&manifests)?; + let coverage = coverage::offline_coverage(&manifests); + // A re-exported artifact keeps its input's coverage only when one input + // carried a manifest. + let record = match manifests.as_slice() { + [Some(manifest)] => Some(CaptureRecord::from_manifest(manifest)), + _ => None, + }; let capture = completed::merge(captures, &options.session_id).map_err(|error| { CommandFailure::new(ErrorCode::TraceExportFailed, error.to_string(), false) })?; - reject_incomplete_capture(&capture, false, true) - .map_err(|error| error.with_artifact_events(capture.events.clone()))?; + reject_incomplete_capture(&capture, false, true).map_err(|error| { + error + .with_artifact_events(capture.events.clone()) + .with_artifact_capture(record.clone()) + })?; if capture.unknown_records != 0 { return Err(CommandFailure::new( ErrorCode::TraceExportFailed, @@ -727,18 +934,24 @@ fn measure_completed_inputs( ) .with_detail("unknown_records", capture.unknown_records) .with_hint("rebuild xprobe and the CUPTI Agent from the same release") - .with_artifact_events(capture.events)); + .with_artifact_events(capture.events) + .with_artifact_capture(record)); } let options = MeasureOptions { dropped_events: capture.dropped_records, ..options.clone() }; - let mut result = measure(&capture.events, &options) - .map_err(|error| measurement_failure(&error, &options, &capture.events, true))?; + let mut result = measure(&capture.events, &options).map_err(|error| { + measurement_failure(&error, &options, &capture.events, true) + .with_artifact_capture(record.clone()) + })?; apply_collection_summary(&mut result, &capture); + xprobe_correlator::apply_coverage(&mut result, coverage); + result.collection.wall_clock = record.as_ref().and_then(|record| record.wall_clock); Ok(MeasurementExecution { result, events: capture.events, + capture: record, }) } @@ -746,6 +959,8 @@ fn measure_completed_inputs( struct MeasurementExecution { result: MeasurementResult, events: Vec, + /// How the events were collected, when that is known. + capture: Option, } const fn clock_domain_name(domain: &ClockDomain) -> &'static str { diff --git a/xprobe/cli/src/python.rs b/xprobe/cli/src/python.rs new file mode 100644 index 0000000..3166b22 --- /dev/null +++ b/xprobe/cli/src/python.rs @@ -0,0 +1,235 @@ +//! `measure --python-sample`: external CPython stack sampling. + +use std::path::Path; +use std::process::ExitCode; +use std::time::Duration; + +use xprobe_collector::python_sampling::{ + ProcessMemory, ReadError, SamplerConfig, SamplerError, Walker, sample, +}; +use xprobe_core::cpu_sampling_analysis::symbolize_native; +use xprobe_core::inspect; +use xprobe_core::python_layout::{self, PythonLocateError}; +use xprobe_core::python_sampling::{SamplingRequest, analyze, native_addresses, records}; +use xprobe_protocol::{ErrorCode, EvidenceArtifact, ExportFormat, PythonSampleResult, ReadLatency}; + +use crate::failure::{CommandFailure, emit_command_failure}; + +/// Python frames kept per stack. +pub(crate) const STACK_DEPTH: usize = 128; +/// Threads assumed per sweep when sizing the sample capacity. +const SIZING_THREADS: u64 = 64; +/// Upper bound on kept samples. +const MAX_CAPACITY: u64 = 2_000_000; + +pub(crate) struct PythonSampleRequest<'a> { + pub(crate) pid: u32, + /// The interpreter, when the caller already located it. + pub(crate) runtime: Option, + pub(crate) name: Option, + pub(crate) duration_ms: u64, + pub(crate) gil_hz: u32, + pub(crate) threads_hz: u32, + pub(crate) events_out: Option<&'a Path>, +} + +pub(crate) fn run_python_sample(request: &PythonSampleRequest<'_>, json: bool) -> ExitCode { + match python_sample(request) { + Ok(result) => { + if json { + println!( + "{}", + serde_json::to_string_pretty(&result) + .expect("Python sample result must serialize") + ); + } else { + print_python_sample(&result); + } + ExitCode::SUCCESS + } + Err(error) => emit_command_failure(error, json), + } +} + +fn print_python_sample(result: &PythonSampleResult) { + let collection = &result.collection; + println!( + "CPython {} PID {}: {} GIL samples at {:.0} Hz, GIL released {:.0}% of ticks", + collection.python_version, + result.target.pid, + collection.gil_samples, + collection.gil_hz_achieved, + result.inventory.gil_released_proportion * 100.0 + ); + for hotspot in result.inventory.gil_hotspots.iter().take(10) { + println!( + " {:5.1}% self {:5.1}% total {} ({}:{})", + hotspot.exclusive_proportion * 100.0, + hotspot.inclusive_proportion * 100.0, + hotspot.frame.function, + hotspot.frame.file, + hotspot.frame.first_line + ); + } + if let Some(ReadLatency { p50_ns, p99_ns, .. }) = collection.read_latency { + println!(" stack read p50 {p50_ns} ns, p99 {p99_ns} ns"); + } +} + +fn locate_failure(error: &PythonLocateError) -> CommandFailure { + let code = match error { + PythonLocateError::NotPython => ErrorCode::SymbolNotFound, + PythonLocateError::UnknownVersion { .. } | PythonLocateError::UnsupportedVersion { .. } => { + ErrorCode::UnsupportedPythonVersion + } + PythonLocateError::NotMapped { .. } => ErrorCode::BinaryNotMapped, + PythonLocateError::Io { .. } | PythonLocateError::InvalidElf { .. } => { + ErrorCode::PermissionDenied + } + }; + CommandFailure::new(code, error.to_string(), true) +} + +fn sampler_failure(error: &SamplerError) -> CommandFailure { + match error { + SamplerError::Read { + error: ReadError::Permission, + .. + } => CommandFailure::new(ErrorCode::PermissionDenied, error.to_string(), true).with_hint( + "reading another process's memory needs ptrace access: the same user under kernel.yama.ptrace_scope 0, or CAP_SYS_PTRACE", + ), + SamplerError::Read { + error: ReadError::Gone, + .. + } => CommandFailure::new(ErrorCode::TargetExited, error.to_string(), true), + SamplerError::LayoutMismatch { .. } + | SamplerError::NotDebugOffsets + | SamplerError::FreeThreaded => { + CommandFailure::new(ErrorCode::UnsupportedPythonVersion, error.to_string(), true) + } + SamplerError::Read { .. } | SamplerError::NoInterpreter | SamplerError::Clock(_) => { + CommandFailure::new(ErrorCode::Internal, error.to_string(), false) + } + } +} + +/// Samples kept for this request: every GIL tick and every thread per sweep. +fn capacity(request: &PythonSampleRequest<'_>) -> u64 { + let per_second = u64::from(request.gil_hz) + u64::from(request.threads_hz) * SIZING_THREADS; + (per_second.saturating_mul(request.duration_ms) / 1000).clamp(1, MAX_CAPACITY) +} + +fn period(hz: u32) -> Option { + (hz != 0).then(|| Duration::from_secs(1) / hz) +} + +pub(crate) fn python_sample( + request: &PythonSampleRequest<'_>, +) -> Result { + if request.duration_ms == 0 || request.threads_hz == 0 { + return Err(CommandFailure::new( + ErrorCode::SessionLimitExceeded, + "--python-sample needs a positive --duration-ms and --python-threads-hz", + true, + )); + } + let report = inspect::run(request.pid).map_err(|error| { + CommandFailure::new(error.code(), error.to_string(), error.recoverable()) + })?; + let runtime = match request.runtime.clone() { + Some(runtime) => runtime, + None => python_layout::locate(&report).map_err(|error| locate_failure(&error))?, + }; + let memory = ProcessMemory::new(request.pid); + let mut walker = Walker::new(&memory, runtime.clone(), STACK_DEPTH); + let sample_capacity = capacity(request); + let duration = Duration::from_millis(request.duration_ms); + let wall_clock_start = crate::live::clock_anchor()?; + let capture = sample( + &mut walker, + request.pid, + SamplerConfig { + duration, + gil_period: period(request.gil_hz), + threads_period: period(request.threads_hz).expect("threads rate is positive"), + max_samples: usize::try_from(sample_capacity).unwrap_or(usize::MAX), + max_depth: STACK_DEPTH, + }, + ) + .map_err(|error| sampler_failure(&error))?; + let wall_clock = xprobe_protocol::WallClock { + start: wall_clock_start, + end: crate::live::clock_anchor()?, + }; + // A sample of a reused PID describes the wrong process. + inspect::verify_target(&report.target).map_err(|error| { + CommandFailure::new(error.code(), error.to_string(), error.recoverable()) + })?; + // Symbolize native leaves while the target's mappings are still live. + let native = symbolize_native(&report, &native_addresses(&capture)) + .map_err(|error| CommandFailure::new(error.code(), error.to_string(), true))?; + let mut result = analyze( + &SamplingRequest { + session_id: format!("xp_python_{}", std::process::id()), + name: request.name.clone(), + target: report.target.clone(), + python_minor: runtime.minor, + python_binary: runtime.binary.display().to_string(), + duration, + gil_hz: request.gil_hz, + threads_hz: request.threads_hz, + sample_capacity, + stack_depth: u32::try_from(STACK_DEPTH).unwrap_or(u32::MAX), + }, + &capture, + &native, + ); + result.collection.wall_clock = Some(wall_clock); + let path = match request.events_out { + Some(path) => path.to_path_buf(), + None => crate::private_artifact_dir()?.join("python-samples.jsonl"), + }; + let lines = records(&capture, request.pid, &native); + let mut text = String::new(); + for line in &lines { + text.push_str(&serde_json::to_string(line).expect("sample record must serialize")); + text.push('\n'); + } + crate::dev::write_export_file(&path, text.as_bytes()).map_err(|error| { + CommandFailure::new( + ErrorCode::TraceExportFailed, + format!("failed to write {}: {error}", path.display()), + false, + ) + })?; + result.artifact = Some(EvidenceArtifact { + path: path.display().to_string(), + format: ExportFormat::Jsonl, + events: lines.len() as u64, + }); + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::{PythonSampleRequest, capacity}; + + #[test] + fn capacity_covers_the_requested_rates_with_a_bound() { + let request = PythonSampleRequest { + pid: 1, + runtime: None, + name: None, + duration_ms: 2000, + gil_hz: 2000, + threads_hz: 100, + events_out: None, + }; + assert_eq!(capacity(&request), 2 * (2000 + 100 * 64)); + let long = PythonSampleRequest { + duration_ms: 10_000_000, + ..request + }; + assert_eq!(capacity(&long), 2_000_000); + } +} diff --git a/xprobe/cli/src/render.rs b/xprobe/cli/src/render.rs index cb648d9..62a1deb 100644 --- a/xprobe/cli/src/render.rs +++ b/xprobe/cli/src/render.rs @@ -272,6 +272,18 @@ pub(crate) fn print_triage_result(result: &TriageResult) { thread.blocked_share * 100.0 ); } + if let Some(released) = result.gil_released_proportion { + println!("Python: GIL released {:.0}% of ticks", released * 100.0); + } + for hotspot in &result.python_hotspots { + println!( + " {:>5.1}% self {} ({}:{})", + hotspot.exclusive_proportion * 100.0, + hotspot.frame.function, + hotspot.frame.file, + hotspot.frame.first_line + ); + } for source in &result.sources { println!( "Source {:?}: {:?}{}", diff --git a/xprobe/cli/src/triage.rs b/xprobe/cli/src/triage.rs index f840bd5..e12771e 100644 --- a/xprobe/cli/src/triage.rs +++ b/xprobe/cli/src/triage.rs @@ -9,7 +9,9 @@ use std::{ use serde::Serialize; use xprobe_core::{ - cgroup_cpu, gpu_health, inspect, thread_time, + cgroup_cpu, gpu_health, inspect, + python_layout::{self, PythonLocateError}, + thread_time, triage::{TriageEvidence, findings}, }; use xprobe_correlator::MeasureOptions; @@ -26,6 +28,7 @@ use crate::{ inventory::{cpu_inventory, syscall_inventory}, live::{LiveMeasureRequest, collect_live_aggregate}, private_artifact_dir, + python::{PythonSampleRequest, python_sample}, render::print_triage_result, }; @@ -96,6 +99,7 @@ fn classify(result: Result) -> Result, CommandF | ErrorCode::CuptiAgentNotLoaded | ErrorCode::CudaContextNotFound | ErrorCode::UnsupportedCudaVersion + | ErrorCode::UnsupportedPythonVersion | ErrorCode::EventRateTooHigh | ErrorCode::EventsDropped | ErrorCode::NoMatchedSamples @@ -136,7 +140,18 @@ fn triage(request: &TriageRequest) -> Result { let started = Instant::now(); let window = Duration::from_millis(request.duration_ms); - let (cpu, syscalls, gpu_activity, gpu_rounds) = thread::scope(|scope| { + let python_runtime = python_layout::locate(&report); + let python_artifact = artifacts.join("python-samples.jsonl"); + let python_request = PythonSampleRequest { + pid: request.pid, + runtime: python_runtime.as_ref().ok().cloned(), + name: None, + duration_ms: request.duration_ms, + gil_hz: 2000, + threads_hz: 100, + events_out: Some(&python_artifact), + }; + let (cpu, syscalls, gpu_activity, gpu_rounds, python) = thread::scope(|scope| { let cpu = scope.spawn(|| cpu_inventory(&cpu_spec(&report, request), Some(report.clone()))); let syscalls = scope .spawn(|| syscall_inventory(&syscall_spec(&report, request), Some(report.clone()))); @@ -145,11 +160,15 @@ fn triage(request: &TriageRequest) -> Result { .libcuda_loaded .then(|| scope.spawn(|| collect_live_aggregate(&gpu_request(request)))); let gpu_rounds = scope.spawn(|| sample_gpu_health(window)); + let python = python_runtime + .is_ok() + .then(|| scope.spawn(|| python_sample(&python_request))); ( cpu.join(), syscalls.join(), gpu_activity.map(thread::ScopedJoinHandle::join), gpu_rounds.join(), + python.map(thread::ScopedJoinHandle::join), ) }); let elapsed = started.elapsed(); @@ -175,6 +194,14 @@ fn triage(request: &TriageRequest) -> Result { None => Outcome::Skipped("the target has not loaded libcuda".to_owned()), }; let gpu_rounds = gpu_rounds.map_err(|_| panicked("GPU health"))?; + let python = match (python, &python_runtime) { + (Some(joined), _) => classify(joined.map_err(|_| panicked("Python sampling"))?)?, + (None, Err(PythonLocateError::NotPython)) => { + Outcome::Skipped("the target is not a CPython process".to_owned()) + } + (None, Err(error)) => Outcome::Unavailable(error.to_string()), + (None, Ok(_)) => unreachable!("a located CPython runtime is sampled"), + }; let window_ns = u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX); let threads = thread_time::breakdown(&threads_before, &threads_after, window_ns, TOP); @@ -231,6 +258,26 @@ fn triage(request: &TriageRequest) -> Result { outcome => sources.push(not_collected(TriageSourceKind::CpuSample, outcome)), } + let mut python_hotspots = None; + let mut gil_released_proportion = None; + match python { + Outcome::Collected(result) => { + let path = write_artifact(&artifacts, "python-sample.json", &result)?; + let mut hotspots = result.inventory.gil_hotspots; + hotspots.truncate(TOP); + python_hotspots = Some(hotspots); + gil_released_proportion = Some(result.inventory.gil_released_proportion); + warnings.extend(result.warnings); + sources.push(source( + TriageSourceKind::PythonSample, + TriageSourceStatus::Collected, + None, + Some(path), + )); + } + outcome => sources.push(not_collected(TriageSourceKind::PythonSample, outcome)), + } + let mut syscall_groups = Vec::new(); match syscalls { Outcome::Collected(result) => { @@ -250,17 +297,21 @@ fn triage(request: &TriageRequest) -> Result { } let mut activity_groups = None; + let mut cuda_devices = Vec::new(); match gpu_activity { Outcome::Collected(result) => { let path = write_artifact(&artifacts, "gpu-activity.json", &result)?; let AggregateInventoryResult { inventory, + collection, warnings: activity_warnings, .. } = result; + cuda_devices = collection.cuda_devices; let mut groups = inventory.groups; groups.sort_by_key(|group| std::cmp::Reverse(group.duration_ns.total)); - groups.truncate(TOP); + // Rules attribute every group to its GPU; only the inline list + // is cut to the top groups. activity_groups = Some(groups); warnings.extend(activity_warnings); sources.push(source( @@ -316,9 +367,11 @@ fn triage(request: &TriageRequest) -> Result { cgroup: cgroup_throttling.as_ref(), cpu_hotspots: &cpu_hotspots, python_status, + python_hotspots: python_hotspots.as_deref(), syscalls: &syscall_groups, gpu_devices: &gpu_devices, gpu_activity: activity_groups.as_deref(), + cuda_devices: &cuda_devices, }); Ok(TriageResult { schema_version: SchemaVersion3::current(), @@ -331,9 +384,17 @@ fn triage(request: &TriageRequest) -> Result { threads, cgroup: cgroup_throttling, cpu_hotspots, + python_hotspots: python_hotspots.unwrap_or_default(), + gil_released_proportion, syscalls: syscall_groups, gpu_devices, - gpu_activity: activity_groups.unwrap_or_default(), + gpu_activity: activity_groups + .map(|mut groups| { + groups.truncate(TOP); + groups + }) + .unwrap_or_default(), + cuda_devices, sources, not_covered: NOT_COVERED.iter().map(|item| (*item).to_owned()).collect(), warnings, @@ -425,6 +486,7 @@ fn gpu_request(request: &TriageRequest) -> LiveMeasureRequest { timeout: Duration::from_millis(request.timeout_ms), match_policy_text: "exact", mode: MeasurementMode::Aggregate, + ring: false, options: MeasureOptions { session_id: format!("xp_triage_gpu_{}", std::process::id()), name: Some("triage".to_owned()), diff --git a/xprobe/cli/src/trigger.rs b/xprobe/cli/src/trigger.rs new file mode 100644 index 0000000..01a48d1 --- /dev/null +++ b/xprobe/cli/src/trigger.rs @@ -0,0 +1,1965 @@ +//! Triggered capture: keep a ring of recent GPU activity and write a window +//! around each span that crosses a threshold. +//! +//! The CUPTI Agent only keeps the newest records in a ring. Deciding when to +//! fire stays here, on the same span rules `measure` uses, so the hot path is +//! unchanged and every trigger rule is deterministic Rust. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs::DirBuilder; +use std::os::unix::fs::DirBuilderExt; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::thread; +use std::time::{Duration, Instant}; + +use xprobe_correlator::{MeasureError, MeasureOptions, spans}; +use xprobe_protocol::{ + ActivityBoundary, CaptureWindow, ClockDomain, ErrorCode, Event, EventType, EvidenceArtifact, + ExportFormat, MatchPolicy, MatchedEventPair, MeasurementMode, SchemaVersion3, SessionStatus, + TriggerCollection, TriggerCondition, TriggerKind, TriggerObservation, TriggerResult, + TriggerWindow, Warning, activity_boundary, +}; + +use crate::coverage::CaptureRecord; +use crate::failure::{CommandFailure, emit_command_failure}; +use crate::live::{ + LiveCollection, LiveMeasureRequest, SNAPSHOT_QUIET_PERIOD, injection_warning, + match_policy_name, refresh_live_sources, single_edge_plan, start_live_collection, + stop_cupti_agent, +}; +use crate::{ExportFormatArg, export_measurement_capture, private_artifact_dir}; + +/// Longest spans of the trigger's kind listed per window. +const WINDOW_LONGEST: usize = 5; + +/// A span that crossed the threshold and the window kept around it. +struct Pending { + fired: MatchedEventPair, + start_ns: u64, + end_ns: u64, + fired_at: Instant, + /// The span left retention and was counted in the settled spans. + settled: bool, + /// Records the window may hold were lost: trimmed before it fired, + /// reported lost after it fired, or beyond the retention bound. + lost: bool, + /// The window's records trimmed from retention after it closed. + kept: Vec, +} + +/// Spans over the retained records at the last evaluation. +#[derive(Default)] +struct CurrentSpans { + spans: u64, + over_threshold: u64, + longest: Option, +} + +impl CurrentSpans { + fn record(&mut self, span: &spans::Span<'_>, threshold_ns: u64) { + self.spans += 1; + if span.latency_ns >= threshold_ns { + self.over_threshold += 1; + } + if self + .longest + .as_ref() + .is_none_or(|longest| span.latency_ns > longest.latency_ns) + { + self.longest = Some(pair(span)); + } + } +} + +/// What became of a closed window once the capture stopped. +enum Cut { + Written(Box), + Lost, +} + +/// One window cut from the retained events. +pub(crate) struct CutWindow { + pub(crate) fired: MatchedEventPair, + pub(crate) start_ns: u64, + pub(crate) end_ns: u64, + pub(crate) truncated: bool, + pub(crate) events: Vec, + pub(crate) longest: Vec, +} + +/// One GPU activity: process, device, context, stream, kind, correlation +/// ID, and kernel name. +type ActivityKey = ( + u32, + Option, + Option, + Option, + u8, + Option, + Option, +); + +fn activity_key(event: &Event) -> Option { + let cuda = event.cuda.as_ref()?; + let family = match event.event_type { + EventType::GpuKernelStart | EventType::GpuKernelEnd => 0, + EventType::GpuMemcpyStart | EventType::GpuMemcpyEnd => 1, + EventType::GpuMemsetStart | EventType::GpuMemsetEnd => 2, + _ => return None, + }; + Some(( + event.pid, + cuda.device_id, + cuda.context_id, + cuda.stream_id, + family, + cuda.correlation_id, + cuda.kernel_name.clone(), + )) +} + +/// One stream of one process, and whether its time is raw CUPTI time. +type StreamKey = (u32, Option, Option, Option, bool); + +fn stream_key(event: &Event) -> Option { + let cuda = event.cuda.as_ref()?; + Some(( + event.pid, + cuda.device_id, + cuda.context_id, + cuda.stream_id, + event.clock_domain == ClockDomain::Cupti, + )) +} + +/// How many of the longest settled spans to keep, so `longest` can fall back +/// to the next one when a window is revoked. +const SETTLED_TOP: usize = 16; + +/// Trigger state over the records read so far. It performs no I/O. +pub(crate) struct TriggerEngine { + condition: TriggerCondition, + capacity: usize, + retained: Vec, + /// Spans that fired a window, by the sequence numbers of their events. + seen: BTreeSet<(u64, u64)>, + /// Timestamp intervals in which records were overwritten or dropped. + losses: Vec<(u64, u64)>, + /// Latest timestamp of a record trimmed from retention. + trimmed_through_ns: Option, + last_batch_min_ns: Option, + last_dropped: u64, + /// Reads ingested so far. + reads: u64, + /// Activity starts whose end has not arrived (idle and gap triggers). + open_starts: BTreeMap>, + /// Latest activity end on each stream, kept across trimming, to place + /// starts known only as running at STOP. + last_end: BTreeMap, + /// The longest settled spans, longest first, so a revoked one can be + /// replaced as the longest. + settled_top: Vec, + /// Spans whose records left retention; their counts are final. + settled: TriggerObservation, + /// Spans over the retained records as of the last evaluation. + current: CurrentSpans, + pending: Option, + /// Windows whose post-roll has arrived. They are cut only after the + /// capture stopped, once late records and losses are known. + closed: Vec, + cooldown_until_ns: u64, + lost_windows: u32, + revoked_windows: u32, + /// `CLOCK_MONOTONIC` time once the Agent acknowledged ARM. + armed_ns: u64, + /// Earliest and latest timestamps ever read. + observed: Option<(u64, u64)>, + /// Records or window slots changed since the last evaluation. + dirty: bool, +} + +impl TriggerEngine { + pub(crate) fn new(condition: TriggerCondition, capacity: usize, armed_ns: u64) -> Self { + Self { + armed_ns, + observed: None, + dirty: false, + condition, + capacity, + retained: Vec::new(), + seen: BTreeSet::new(), + losses: Vec::new(), + trimmed_through_ns: None, + last_batch_min_ns: None, + last_dropped: 0, + reads: 0, + open_starts: BTreeMap::new(), + last_end: BTreeMap::new(), + settled_top: Vec::new(), + settled: TriggerObservation { + spans: 0, + over_threshold: 0, + longest: None, + }, + current: CurrentSpans::default(), + pending: None, + closed: Vec::new(), + cooldown_until_ns: 0, + lost_windows: 0, + revoked_windows: 0, + } + } + + /// Add newly read records. `overwritten` records were lost before this + /// read and `dropped_total` is the capture's cumulative drop count; either + /// marks the time this read covers as lost. + pub(crate) fn ingest(&mut self, mut events: Vec, overwritten: u64, dropped_total: u64) { + self.place_unknown_starts(&mut events); + events.sort_by_key(|event| (event.timestamp_ns, event.sequence)); + self.reads += 1; + let batch_min = events.first().map(|event| event.timestamp_ns); + let batch_max = events.iter().map(|event| event.timestamp_ns).max(); + if overwritten != 0 || dropped_total > self.last_dropped { + // Lost records were delivered between the previous read and this + // one; delivery is not time-ordered across streams, so the loss + // covers both reads' events. + let retained_max = self.retained.iter().map(|event| event.timestamp_ns).max(); + let from = [self.last_batch_min_ns, batch_min, retained_max] + .into_iter() + .flatten() + .min(); + let to = [batch_max, retained_max].into_iter().flatten().max(); + if let (Some(from), Some(to)) = (from, to) { + self.losses.push((from, to)); + } else { + // Nothing was ever read: everything up to now is suspect. + self.losses.push((0, u64::MAX)); + } + // A loss cannot be placed in time, so one reported after a window + // fired may belong to it. + for window in self.closed.iter_mut().chain(&mut self.pending) { + window.lost = true; + } + } + self.last_dropped = self.last_dropped.max(dropped_total); + self.revoke_by_late_records(&events); + if let (Some(low), Some(high)) = (batch_min, batch_max) { + self.last_batch_min_ns = Some(low); + self.observed = Some( + self.observed + .map_or((low, high), |(min, max)| (min.min(low), max.max(high))), + ); + self.dirty = true; + } + self.retained.extend(events); + } + + /// Place each start known only as running at STOP at its stream's latest + /// end, the earliest it can have started, remembered across trimming; + /// with none, at the earliest record read, or for host-clock records at + /// ARM. A raw-clock one with neither is dropped. + fn place_unknown_starts(&mut self, events: &mut Vec) { + for event in events.iter() { + if activity_boundary(&event.event_type) == Some(ActivityBoundary::End) + && let Some(key) = stream_key(event) + { + let end = self.last_end.entry(key).or_insert(0); + *end = (*end).max(event.timestamp_ns); + } + } + let earliest = self + .observed + .map(|(min, _)| min) + .into_iter() + .chain( + events + .iter() + .filter(|event| !xprobe_protocol::start_unknown(event)) + .map(|event| event.timestamp_ns), + ) + .min(); + events.retain_mut(|event| { + if !xprobe_protocol::start_unknown(event) { + return true; + } + let placed = stream_key(event) + .and_then(|key| self.last_end.get(&key).copied()) + .or(earliest) + .or((event.clock_domain != ClockDomain::Cupti).then_some(self.armed_ns)); + let Some(time) = placed else { + return false; + }; + event.timestamp_ns = time; + event.timestamp_raw = time; + if let Some(cuda) = event.cuda.as_mut() { + cuda.start_ns = Some(time); + } + true + }); + } + + /// Revoke idle and gap windows that records from this read show were + /// busy. Everything read before a window fired was already part of the + /// spans that fired it, so only later records can contradict it: a + /// boundary inside the span, a later activity that ran across it, or a + /// start still running at STOP that began before its end. + fn revoke_by_late_records(&mut self, batch: &[Event]) { + let kind = self.condition.kind; + if !matches!(kind, TriggerKind::Idle | TriggerKind::Gap) { + return; + } + // Pair each end with the latest open start of its activity at or + // before it: activities of one key on one stream do not overlap. + let mut arrivals = Vec::new(); + for event in batch { + let Some(key) = activity_key(event) else { + continue; + }; + let interval = match activity_boundary(&event.event_type) { + Some(ActivityBoundary::Start) => { + if !xprobe_protocol::start_unknown(event) { + self.open_starts + .entry(key.clone()) + .or_default() + .push(event.timestamp_ns); + } + None + } + _ => self.open_starts.get_mut(&key).and_then(|starts| { + let (index, _) = starts + .iter() + .enumerate() + .filter(|(_, start)| **start <= event.timestamp_ns) + .max_by_key(|(_, start)| **start)?; + Some(starts.swap_remove(index)) + }), + }; + arrivals.push((event, key, interval)); + } + self.bound_open_starts(); + let busy = |window: &Pending| { + if window.lost { + return false; + } + let Some(scope) = activity_key(&window.fired.start) else { + return false; + }; + let (from, to) = ( + window.fired.start.timestamp_ns, + window.fired.end.timestamp_ns, + ); + // A boundary inside the span, a marker of activity running from + // before its end, or an activity that ran across it. + arrivals.iter().any(|(event, key, interval)| { + let same_place = (key.0, key.1) == (scope.0, scope.1) + && (kind == TriggerKind::Idle || (key.2, key.3) == (scope.2, scope.3)); + let at = event.timestamp_ns; + same_place + && ((at < to && (from < at || xprobe_protocol::start_unknown(event))) + || interval.is_some_and(|start| start <= from && at >= to)) + }) + }; + let mut revoked = Vec::new(); + let mut index = 0; + while index < self.closed.len() { + if busy(&self.closed[index]) { + revoked.push(self.closed.remove(index)); + } else { + index += 1; + } + } + if self.pending.as_ref().is_some_and(busy) { + revoked.extend(self.pending.take()); + } + self.revoke(&revoked); + } + + /// Keep at most `capacity` open starts, dropping the oldest. An end whose + /// start was dropped pairs with nothing and only counts if it falls + /// inside a span. + fn bound_open_starts(&mut self) { + self.open_starts.retain(|_, starts| !starts.is_empty()); + let mut total = self.open_starts.values().map(Vec::len).sum::(); + while total > self.capacity { + let Some(key) = self + .open_starts + .iter() + .min_by_key(|(_, starts)| starts.iter().min().copied().unwrap_or(u64::MAX)) + .map(|(key, _)| key.clone()) + else { + break; + }; + let starts = self.open_starts.get_mut(&key).expect("key was found"); + let (oldest, _) = starts + .iter() + .enumerate() + .min_by_key(|(_, start)| **start) + .expect("an empty entry was removed"); + starts.swap_remove(oldest); + if starts.is_empty() { + self.open_starts.remove(&key); + } + total -= 1; + } + } + + /// Count the `revoked` windows, take their spans out of the settled + /// counts, and reopen their slots. + fn revoke(&mut self, revoked: &[Pending]) { + if revoked.is_empty() { + return; + } + self.revoked_windows += u32::try_from(revoked.len()).unwrap_or(u32::MAX); + for window in revoked { + let key = (window.fired.start.sequence, window.fired.end.sequence); + if window.settled { + self.settled.spans -= 1; + self.settled.over_threshold -= 1; + } + self.settled_top + .retain(|top| (top.start.sequence, top.end.sequence) != key); + } + self.settled.longest = self.settled_top.first().cloned(); + self.cooldown_until_ns = self + .closed + .iter() + .map(|window| window.end_ns) + .max() + .unwrap_or(0); + self.dirty = true; + } + + /// Evaluate the spans over the retained records once: count them, arm a + /// window on the first new span that crosses the threshold while a slot + /// is free, and trim retention to `capacity`, settling the spans of the + /// records it drops. + /// + /// # Errors + /// + /// Returns [`MeasureError`] when a latency trigger's selectors or policy + /// cannot correlate the records. + pub(crate) fn evaluate(&mut self, now: Instant) -> Result<(), MeasureError> { + if !std::mem::take(&mut self.dirty) { + return Ok(()); + } + self.retained + .sort_by_key(|event| (event.timestamp_ns, event.sequence)); + let Self { + condition, + capacity, + retained, + seen, + settled, + settled_top, + current, + pending, + closed, + cooldown_until_ns, + armed_ns, + trimmed_through_ns, + .. + } = self; + let threshold = condition.threshold_ns; + let mut reopened = false; + let mut found = trigger_spans(condition, retained)?; + found.sort_by_key(|span| (span.start.timestamp_ns, span.end.timestamp_ns)); + *current = CurrentSpans::default(); + for span in &found { + current.record(span, threshold); + } + for span in found.iter().filter(|span| span.latency_ns >= threshold) { + if pending.is_some() || (closed.len() as u64) >= u64::from(condition.windows) { + break; + } + let key = (span.start.sequence, span.end.sequence); + // A span that began before ARM has no captured pre-roll; one that + // already fired, even if later revoked, never fires again. + let before_arm = span.start.clock_domain != ClockDomain::Cupti + && span.start.timestamp_ns < *armed_ns; + let start_ns = span.start.timestamp_ns.saturating_sub(condition.pre_ns); + if before_arm || seen.contains(&key) || start_ns < *cooldown_until_ns { + continue; + } + seen.insert(key); + *pending = Some(Pending { + start_ns, + end_ns: span.end.timestamp_ns.saturating_add(condition.post_ns), + fired: pair(span), + fired_at: now, + settled: false, + lost: trimmed_through_ns.is_some_and(|through| through >= start_ns), + kept: Vec::new(), + }); + } + // Keep `capacity` records; the open window, including one just armed, + // holds its records until it closes, up to twice the bound. Past the + // bound, a window whose post-roll records already arrived closes and + // keeps its own records. + if retained.len() > capacity.saturating_mul(2) + && let Some(last) = retained.last() + && pending + .as_ref() + .is_some_and(|open| !open.lost && last.timestamp_ns > open.end_ns) + { + let open = pending.take().expect("pending window was checked"); + *cooldown_until_ns = open.end_ns; + closed.push(open); + // A span read earlier may take the next slot without new records. + reopened = true; + } + let excess = retained.len().saturating_sub(*capacity); + let removable_before = |from: u64| { + retained + .iter() + .take(excess) + .take_while(|event| event.timestamp_ns < from) + .count() + }; + let mut removable = pending + .as_ref() + .filter(|open| !open.lost) + .map_or(excess, |open| removable_before(open.start_ns)); + if retained.len() - removable > capacity.saturating_mul(2) + && let Some(open) = pending.as_mut() + { + open.lost = true; + removable = excess; + } + // Spans that touch records about to leave retention are settled. + if removable != 0 { + let leaving = retained[..removable] + .iter() + .map(|event| event.sequence) + .collect::>(); + let fired = closed.iter_mut().chain(pending.as_mut()); + settle( + settled, + settled_top, + current, + fired, + &found, + &leaving, + threshold, + ); + } + drop(found); + self.dirty |= reopened; + self.trim(removable); + Ok(()) + } + + /// Drop the oldest `removable` retained records. A closed window keeps + /// its own records, including late ones, until it is cut. + fn trim(&mut self, removable: usize) { + if removable == 0 { + return; + } + let removed = self.retained.drain(..removable).collect::>(); + for window in self.closed.iter_mut().filter(|window| !window.lost) { + window.kept.extend( + removed + .iter() + .filter(|event| (window.start_ns..=window.end_ns).contains(&event.timestamp_ns)) + .cloned(), + ); + // A window keeps at most the retention bound of its own records. + if window.kept.len() > self.capacity { + window.lost = true; + window.kept = Vec::new(); + } + } + let through = removed.iter().map(|event| event.timestamp_ns).max(); + self.trimmed_through_ns = self.trimmed_through_ns.max(through); + let oldest = self + .retained + .iter() + .map(|event| event.sequence) + .min() + .unwrap_or(u64::MAX); + self.seen.retain(|(start, _)| *start >= oldest); + } + + /// Close the pending window once its post-roll has had time to arrive. + pub(crate) fn close_window(&mut self, now: Instant, settle: Duration) { + let Some(pending) = self.pending.as_ref() else { + return; + }; + if now < pending.fired_at + Duration::from_nanos(self.condition.post_ns) + settle { + return; + } + let pending = self.pending.take().expect("pending window was checked"); + self.cooldown_until_ns = pending.end_ns; + self.closed.push(pending); + // A span read earlier may take the next slot without new records. + self.dirty = true; + } + + /// Cut every window once the capture stopped at `stopped_ns` + /// (`CLOCK_MONOTONIC`). Windows are clipped to what the capture covered. + /// A window that lost records is not written. + pub(crate) fn finish(&mut self, stopped_ns: u64) -> Vec { + let windows = std::mem::take(&mut self.closed) + .into_iter() + .chain(self.pending.take()) + .collect::>(); + let mut cut = Vec::new(); + for window in windows { + match self.cut(window, stopped_ns) { + Cut::Written(window) => cut.push(*window), + Cut::Lost => self.lost_windows += 1, + } + } + cut + } + + fn cut(&self, window: Pending, stopped_ns: u64) -> Cut { + // Host-clock events compare with the ARM and STOP times; raw CUPTI + // time only with the records read. + let host_clock = window.fired.start.clock_domain != ClockDomain::Cupti; + let (first_seen, last_seen) = self.observed.unwrap_or((window.start_ns, window.end_ns)); + let (covered_from, covered_to) = if host_clock { + (self.armed_ns, stopped_ns) + } else { + (first_seen, last_seen) + }; + let start_ns = window.start_ns.max(covered_from); + let end_ns = window.end_ns.min(covered_to); + let truncated = start_ns > window.start_ns || end_ns < window.end_ns; + let lost = window.lost + || self + .losses + .iter() + .any(|(from, to)| *from <= end_ns && start_ns <= *to); + if lost { + return Cut::Lost; + } + let mut context = window + .kept + .into_iter() + .chain(self.retained.iter().cloned()) + .collect::>(); + context.sort_by_key(|event| (event.timestamp_ns, event.sequence)); + let inside = |event: &Event| (start_ns..=end_ns).contains(&event.timestamp_ns); + // These records already passed evaluation, so this cannot fail. + let spans = trigger_spans(&self.condition, &context).unwrap_or_default(); + let mut longest = spans + .iter() + .filter(|span| inside(span.start) && inside(span.end)) + .map(pair) + .collect::>(); + longest.sort_by_key(|span| std::cmp::Reverse(span.latency_ns)); + longest.truncate(WINDOW_LONGEST); + drop(spans); + context.retain(|event| inside(event)); + Cut::Written(Box::new(CutWindow { + fired: window.fired, + start_ns, + end_ns, + truncated, + events: context, + longest, + })) + } + + pub(crate) fn done(&self) -> bool { + self.pending.is_none() && self.closed.len() as u64 >= u64::from(self.condition.windows) + } + + pub(crate) const fn lost_windows(&self) -> u32 { + self.lost_windows + } + + pub(crate) const fn revoked_windows(&self) -> u32 { + self.revoked_windows + } + + /// Spans seen so far, as the latest records describe them. + pub(crate) fn observation(&self) -> TriggerObservation { + let longest = [self.settled.longest.as_ref(), self.current.longest.as_ref()] + .into_iter() + .flatten() + .max_by_key(|span| span.latency_ns) + .cloned(); + TriggerObservation { + spans: self.settled.spans + self.current.spans, + over_threshold: self.settled.over_threshold + self.current.over_threshold, + longest, + } + } +} + +/// Move the spans that touch `leaving` records from the current counts to +/// the settled ones, marking the `fired` windows whose span settled. +fn settle<'w>( + settled: &mut TriggerObservation, + top: &mut Vec, + current: &mut CurrentSpans, + fired: impl Iterator, + found: &[spans::Span<'_>], + leaving: &BTreeSet, + threshold: u64, +) { + let mut fired = fired + .map(|window| { + ( + (window.fired.start.sequence, window.fired.end.sequence), + window, + ) + }) + .collect::>(); + for span in found.iter().filter(|span| { + leaving.contains(&span.start.sequence) || leaving.contains(&span.end.sequence) + }) { + let key = (span.start.sequence, span.end.sequence); + settled.spans += 1; + current.spans -= 1; + if span.latency_ns >= threshold { + settled.over_threshold += 1; + current.over_threshold -= 1; + } + if let Some(window) = fired.get_mut(&key) { + window.settled = true; + } + if top.len() < SETTLED_TOP + || top + .last() + .is_some_and(|shortest| span.latency_ns > shortest.latency_ns) + { + let at = top.partition_point(|kept| kept.latency_ns >= span.latency_ns); + top.insert(at, pair(span)); + top.truncate(SETTLED_TOP); + } + if current + .longest + .as_ref() + .is_some_and(|longest| (longest.start.sequence, longest.end.sequence) == key) + { + current.longest = None; + } + } + settled.longest = top.first().cloned(); +} + +/// The trigger's spans over `events`. +fn trigger_spans<'a>( + condition: &TriggerCondition, + events: &'a [Event], +) -> Result>, MeasureError> { + Ok(match condition.kind { + TriggerKind::Gap => spans::stream_gaps(events), + TriggerKind::Idle => spans::device_idle(events), + TriggerKind::Duration => spans::activity_durations(events), + TriggerKind::Latency => spans::edge_spans( + events, + condition.start_selector.as_deref().unwrap_or_default(), + condition.end_selector.as_deref().unwrap_or_default(), + condition.match_policy.unwrap_or(MatchPolicy::Exact), + )?, + }) +} + +fn pair(span: &spans::Span<'_>) -> MatchedEventPair { + MatchedEventPair { + start: span.start.clone(), + end: span.end.clone(), + latency_ns: span.latency_ns, + } +} + +/// Milliseconds from the command line as nanoseconds. +pub(crate) fn milliseconds_ns( + name: &str, + value: f64, + allow_zero: bool, +) -> Result { + let nanoseconds = (value * 1_000_000.0).round(); + if !nanoseconds.is_finite() || nanoseconds < 0.0 || (!allow_zero && nanoseconds == 0.0) { + return Err(CommandFailure::new( + ErrorCode::SessionLimitExceeded, + format!( + "--{name} must be a finite {} number of milliseconds", + if allow_zero { + "non-negative" + } else { + "positive" + } + ), + true, + )); + } + // A finite value this large is not a usable duration anyway. + if nanoseconds >= 1.8e19 { + return Err(CommandFailure::new( + ErrorCode::SessionLimitExceeded, + format!("--{name} exceeds the nanosecond range"), + true, + )); + } + #[expect( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "checked non-negative, finite, and below u64::MAX above" + )] + Ok(nanoseconds as u64) +} + +/// A request for one triggered capture. +pub(crate) struct TriggerRequest<'a> { + pub(crate) live: LiveMeasureRequest, + pub(crate) condition: TriggerCondition, + pub(crate) events_out: Option<&'a Path>, +} + +pub(crate) fn run_trigger(request: &TriggerRequest<'_>, json: bool) -> ExitCode { + match collect_trigger(request) { + Ok(result) => { + if json { + println!( + "{}", + serde_json::to_string_pretty(&result).expect("trigger result must serialize") + ); + } else { + print_trigger_result(&result); + } + ExitCode::SUCCESS + } + Err(error) => emit_command_failure(error, json), + } +} + +fn print_trigger_result(result: &TriggerResult) { + println!( + "Trigger {:?} >= {} ns: {} window(s), {} span(s) evaluated, {} over threshold", + result.trigger.kind, + result.trigger.threshold_ns, + result.windows.len(), + result.observed.spans, + result.observed.over_threshold + ); + for window in &result.windows { + println!( + " window {}: fired at {} ns for {} ns; {} events in {}", + window.index, + window.fired.start.timestamp_ns, + window.fired.latency_ns, + window.artifact.events, + window.artifact.path + ); + } +} + +fn collect_trigger(request: &TriggerRequest<'_>) -> Result { + let condition = &request.condition; + let mut plan = single_edge_plan(&request.live)?; + if plan.requirements.needs_ebpf || !plan.requirements.needs_cupti { + return Err(CommandFailure::new( + ErrorCode::InvalidEventSelector, + "triggered capture supports CUDA endpoints only", + true, + ) + .with_hint("measure host endpoints with a bounded --samples or --duration-ms capture")); + } + // Gap and duration triggers read every activity; a latency trigger reads + // every activity only when its policy needs it. + plan.stream_order = condition.kind != TriggerKind::Latency + || condition.match_policy == Some(MatchPolicy::StreamOrder); + let directory = window_directory(request.events_out)?; + let mut collection = start_live_collection(plan, &request.live)?; + let mut engine = TriggerEngine::new( + condition.clone(), + request.live.options.max_events, + collection.capture_plan.start_ns, + ); + let outcome = watch(&mut collection, request, &mut engine); + let timed_out = Instant::now() >= collection.deadline; + // Activity after this instant may miss the capture. + let stopped_ns = crate::live::monotonic_now(); + let stopped = stop_cupti_agent(&mut collection, &request.live); + let mut windows = Vec::new(); + let mut wall_clock = None; + outcome.and_then(|()| { + stopped?; + let stopped_ns = stopped_ns?; + let clock = xprobe_protocol::WallClock { + start: collection.wall_clock_start, + end: crate::live::clock_anchor()?, + }; + wall_clock = Some(clock); + check_capture(&collection)?; + // The final drain may complete windows; cut them only now. + drain_into(&mut collection, &mut engine); + engine + .evaluate(Instant::now()) + .map_err(|error| trigger_failure(&error))?; + for window in engine.finish(stopped_ns) { + windows.push(write_window( + &collection, + &directory, + window, + windows.len(), + clock, + )?); + } + Ok(()) + })?; + let observation = engine.observation(); + if windows.is_empty() { + return Err(no_window_failure(&engine, condition, &collection)); + } + let warnings = trigger_warnings(&engine, &collection); + let cuda = collection.latest_cuda.as_ref(); + Ok(TriggerResult { + schema_version: SchemaVersion3::current(), + ok: true, + session_id: request.live.options.session_id.clone(), + // Fewer windows than asked for is a timeout only if the deadline + // passed; otherwise windows were lost or revoked after closing. + status: if timed_out + && u32::try_from(windows.len()).is_ok_and(|written| written < condition.windows) + { + SessionStatus::TimedOut + } else { + SessionStatus::Completed + }, + target: collection.report.target.clone(), + trigger: condition.clone(), + observed: observation, + windows, + collection: TriggerCollection { + wall_clock, + ring_capacity: request.live.options.max_events as u64, + observed_records: cuda.map_or(0, |cuda| cuda.observed_records), + overwritten_records: collection.ring_overwritten, + dropped_records: cuda.map_or(0, |cuda| cuda.dropped_records), + lost_windows: engine.lost_windows(), + revoked_windows: engine.revoked_windows(), + }, + warnings, + }) +} + +fn trigger_warnings(engine: &TriggerEngine, collection: &LiveCollection) -> Vec { + let mut warnings = Vec::new(); + if collection.agent_injected { + warnings.push(injection_warning(collection)); + } + if engine.lost_windows() != 0 { + warnings.push(Warning { + code: "TRIGGER_WINDOWS_LOST".to_owned(), + message: format!( + "{} triggered window(s) lost records to ring overwrites or drops and were not written; raise --max-events", + engine.lost_windows() + ), + details: std::collections::BTreeMap::new(), + }); + } + if engine.revoked_windows() != 0 { + warnings.push(Warning { + code: "TRIGGER_WINDOWS_REVOKED".to_owned(), + message: format!( + "{} triggered window(s) were not written because later records showed activity in their firing span", + engine.revoked_windows() + ), + details: std::collections::BTreeMap::new(), + }); + } + warnings +} + +/// Why no window was written: nothing fired, or every fired window lost +/// records. A lost window is a loss, not an absence. +fn no_window_failure( + engine: &TriggerEngine, + condition: &TriggerCondition, + collection: &LiveCollection, +) -> CommandFailure { + let observation = engine.observation(); + let lost = engine.lost_windows() != 0; + let mut failure = if lost { + CommandFailure::new( + ErrorCode::EventsDropped, + format!( + "{} span(s) reached {} ns, but their windows lost records to ring overwrites or drops", + observation.over_threshold, condition.threshold_ns + ), + true, + ) + .with_hint("raise --max-events so the ring holds the records between snapshots") + } else if engine.revoked_windows() != 0 { + CommandFailure::new( + ErrorCode::TriggerNotObserved, + format!( + "{} window(s) fired at {} ns but later records showed activity in their spans", + engine.revoked_windows(), + condition.threshold_ns + ), + true, + ) + .with_hint("the longest span is the observed bound; lower the threshold or wait longer with --timeout-ms") + } else { + CommandFailure::new( + ErrorCode::TriggerNotObserved, + format!( + "no span reached {} ns before the timeout; {} span(s) evaluated", + condition.threshold_ns, observation.spans + ), + true, + ) + .with_hint( + "the longest span is the observed bound; lower the threshold or wait longer with --timeout-ms", + ) + } + .with_detail("spans", observation.spans) + .with_detail("over_threshold", observation.over_threshold) + .with_detail("lost_windows", engine.lost_windows()) + .with_detail("revoked_windows", engine.revoked_windows()) + .with_detail("overwritten_records", collection.ring_overwritten); + if let Some(longest) = observation.longest.as_ref() { + failure = failure + .with_detail("longest_ns", longest.latency_ns) + .with_detail("longest_start_ns", longest.start.timestamp_ns); + } + failure +} + +/// Read snapshots until every window is closed or the timeout passes. +fn watch( + collection: &mut LiveCollection, + request: &TriggerRequest<'_>, + engine: &mut TriggerEngine, +) -> Result<(), CommandFailure> { + // Two snapshot periods let the post-roll's records reach the ring. + let settle = SNAPSHOT_QUIET_PERIOD * 2; + // Once every window closed, read once more before stopping: records that + // arrive late can still revoke a window while there is time to replace it. + let mut confirming = false; + loop { + refresh_live_sources(collection, &request.live)?; + check_capture(collection)?; + drain_into(collection, engine); + let now = Instant::now(); + engine + .evaluate(now) + .map_err(|error| trigger_failure(&error))?; + engine.close_window(now, settle); + if now >= collection.deadline || (engine.done() && confirming) { + return Ok(()); + } + confirming = engine.done(); + thread::sleep(SNAPSHOT_QUIET_PERIOD); + } +} + +/// A failed capture or unknown records invalidate every window. +fn check_capture(collection: &LiveCollection) -> Result<(), CommandFailure> { + let Some(cuda) = collection.latest_cuda.as_ref() else { + return Ok(()); + }; + if matches!( + cuda.state, + xprobe_collector::cupti::CuptiCaptureState::Failed + | xprobe_collector::cupti::CuptiCaptureState::Idle + ) { + return Err(CommandFailure::new( + ErrorCode::CuptiNotAvailable, + "CUPTI capture entered a failed state during triggered capture", + true, + )); + } + // ARM resets the Agent's counters, so every unknown record, including + // any in the ARM reply, belongs to this capture. + let unknown = cuda.unknown_records; + if unknown != 0 { + return Err(CommandFailure::new( + ErrorCode::TraceExportFailed, + format!("triggered capture holds {unknown} unknown CUPTI activity records"), + false, + ) + .with_hint("rebuild xprobe and the CUPTI Agent from the same release")); + } + Ok(()) +} + +/// Move newly appended CUDA events from the collection into the engine. +fn drain_into(collection: &mut LiveCollection, engine: &mut TriggerEngine) { + let overwritten = collection.ring_overwritten; + let Some(cuda) = collection.latest_cuda.as_mut() else { + return; + }; + let events = std::mem::take(&mut cuda.events); + // Counters restart at ARM; a drop reported with ARM is a loss too. + let dropped = cuda.dropped_records; + let new_overwrites = overwritten - collection.ring_overwritten_seen; + collection.ring_overwritten_seen = overwritten; + engine.ingest(events, new_overwrites, dropped); +} + +fn trigger_failure(error: &MeasureError) -> CommandFailure { + CommandFailure::new(error.code(), error.to_string(), error.recoverable()) +} + +fn window_directory(events_out: Option<&Path>) -> Result { + let Some(directory) = events_out else { + return private_artifact_dir(); + }; + DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(directory) + .map_err(|error| { + CommandFailure::new( + ErrorCode::TraceExportFailed, + format!( + "failed to create window directory {}: {error}", + directory.display() + ), + true, + ) + })?; + Ok(directory.to_path_buf()) +} + +/// Write one window's events and manifest and describe it. +fn write_window( + collection: &LiveCollection, + directory: &Path, + window: CutWindow, + written: usize, + wall_clock: xprobe_protocol::WallClock, +) -> Result { + let index = u32::try_from(written + 1).unwrap_or(u32::MAX); + let path = directory.join(format!("window-{index}.events.jsonl")); + let clock_domain = window.fired.start.clock_domain.clone(); + let peer_copies = collection + .latest_cuda + .as_ref() + .is_some_and(|cuda| cuda.peer_memcpy_captured); + // The manifest window is CLOCK_MONOTONIC; GPU timestamps qualify only + // when CUPTI normalized them to it. + let window_bounds = match clock_domain { + ClockDomain::Cupti => CaptureWindow { + start_ns: collection.capture_plan.start_ns, + end_ns: crate::live::monotonic_now()?, + }, + ClockDomain::HostMonotonic | ClockDomain::CuptiNormalizedToHostMonotonic => CaptureWindow { + start_ns: window.start_ns, + end_ns: window.end_ns, + }, + }; + let record = CaptureRecord { + target: collection.report.target.clone(), + window: window_bounds, + selectors: collection.capture_plan.selectors.clone(), + all_gpu_activity: collection.capture_plan.stream_order && peer_copies, + peer_copies, + // A window that lost records is never written. + dropped_records: 0, + unknown_records: 0, + record_limit_reached: None, + capture_failed: false, + cuda_devices: collection + .latest_cuda + .as_ref() + .map(|cuda| cuda.devices.clone()) + .unwrap_or_default(), + wall_clock: Some(wall_clock), + }; + export_measurement_capture(&window.events, &path, ExportFormatArg::Jsonl, Some(&record))?; + Ok(TriggerWindow { + index, + fired: window.fired, + start_ns: window.start_ns, + end_ns: window.end_ns, + clock_domain, + truncated: window.truncated, + longest: window.longest, + artifact: EvidenceArtifact { + path: path.display().to_string(), + format: ExportFormat::Jsonl, + events: window.events.len() as u64, + }, + }) +} + +/// Build the request for `measure --pid ... --trigger-*`. +#[allow(clippy::too_many_arguments)] +pub(crate) fn trigger_request( + pid: u32, + cupti_socket: Option, + agent_path: Option, + timeout_ms: u64, + max_events: usize, + session_id: String, + condition: TriggerCondition, + events_out: Option<&Path>, +) -> TriggerRequest<'_> { + // Gap and duration triggers arm on activity endpoints; a latency trigger + // arms on its own edge. + let (start_selector, end_selector, match_policy) = match condition.kind { + TriggerKind::Gap | TriggerKind::Idle | TriggerKind::Duration => ( + "cuda:kernel_end".to_owned(), + "cuda:kernel_start".to_owned(), + MatchPolicy::StreamOrder, + ), + TriggerKind::Latency => ( + condition.start_selector.clone().unwrap_or_default(), + condition.end_selector.clone().unwrap_or_default(), + condition.match_policy.unwrap_or(MatchPolicy::Exact), + ), + }; + TriggerRequest { + live: LiveMeasureRequest { + pid, + expected_target: None, + cupti_socket, + agent_path, + timeout: Duration::from_millis(timeout_ms), + match_policy_text: match_policy_name(match_policy), + mode: MeasurementMode::Exact, + ring: true, + options: MeasureOptions { + session_id, + name: None, + start_selector, + end_selector, + match_policy, + samples: None, + duration: None, + max_events, + dropped_events: 0, + }, + }, + condition, + events_out, + } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + use std::time::{Duration, Instant}; + + use xprobe_protocol::{ + ClockDomain, CudaEvent, Event, EventSource, EventType, SchemaVersion, TriggerCondition, + TriggerKind, + }; + + use super::{TriggerEngine, milliseconds_ns}; + + const MS: u64 = 1_000_000; + + /// One kernel's start and end on stream 7, numbered from `sequence`. + fn kernel(start: u64, end: u64, sequence: u64) -> Vec { + [ + (EventType::GpuKernelStart, start), + (EventType::GpuKernelEnd, end), + ] + .into_iter() + .zip(sequence..) + .map(|((event_type, timestamp), sequence)| Event { + schema_version: SchemaVersion::current(), + session_id: "trigger".to_owned(), + event_id: format!("evt_{sequence}"), + sequence, + source: EventSource::CuptiActivity, + event_type, + pid: 1, + tid: 1, + cpu: None, + timestamp_raw: timestamp, + timestamp_ns: timestamp, + clock_domain: ClockDomain::CuptiNormalizedToHostMonotonic, + timestamp_error_ns: None, + process_start_time: None, + host: None, + cuda: Some(CudaEvent { + device_id: Some(0), + context_id: Some(1), + stream_id: Some(7), + correlation_id: u32::try_from(sequence / 2 + 1).ok(), + runtime_correlation_id: None, + callback_domain: None, + callback_id: None, + kernel_name: Some("k".to_owned()), + kernel_name_mangled: None, + start_ns: None, + end_ns: None, + grid: None, + block: None, + bytes: None, + memcpy_kind: None, + }), + nvtx: None, + attributes: BTreeMap::new(), + }) + .collect() + } + + fn condition(kind: TriggerKind, threshold_ms: u64, windows: u32) -> TriggerCondition { + TriggerCondition { + kind, + threshold_ns: threshold_ms * MS, + start_selector: None, + end_selector: None, + match_policy: None, + pre_ns: MS, + post_ns: MS, + windows, + } + } + + /// Close the open window as if its post-roll had arrived. + fn close(engine: &mut TriggerEngine) { + engine.close_window(Instant::now() + Duration::from_secs(3600), Duration::ZERO); + } + + #[test] + fn a_gap_over_the_threshold_writes_the_window_around_it() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 100, 0); + // Kernels at 0โ€“10, 10.5โ€“11, and 30โ€“31 ms: one 19 ms gap. + let events = [kernel(0, 10 * MS, 0), kernel(10 * MS + MS / 2, 11 * MS, 2)].concat(); + engine.ingest(events, 0, 0); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + assert!(!engine.done()); + + engine.ingest(kernel(30 * MS, 31 * MS, 4), 0, 0); + engine.evaluate(Instant::now()).unwrap(); + // The post-roll has not had time to arrive yet. + engine.close_window(Instant::now(), Duration::from_secs(60)); + assert!(!engine.done()); + close(&mut engine); + assert!(engine.done()); + let windows = engine.finish(u64::MAX); + assert_eq!(windows.len(), 1); + let window = &windows[0]; + assert_eq!(window.fired.latency_ns, 19 * MS); + assert_eq!((window.start_ns, window.end_ns), (10 * MS, 31 * MS)); + // Every record from 10 ms through 31 ms: A's end, B, and C. + assert_eq!(window.events.len(), 5); + assert_eq!(window.longest[0].latency_ns, 19 * MS); + + let observation = engine.observation(); + assert_eq!(observation.spans, 2); + assert_eq!(observation.over_threshold, 1); + } + + #[test] + fn windows_are_clipped_to_what_the_capture_covered() { + // Armed at 9.5 ms, stopped at 30.5 ms: the 1 ms pre- and post-roll + // around the 10-30 ms gap are only partly captured. + let mut engine = + TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 100, 9 * MS + MS / 2); + engine.ingest( + [ + kernel(9 * MS + MS / 2, 10 * MS, 0), + kernel(30 * MS, 30 * MS + MS / 4, 2), + ] + .concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + let windows = engine.finish(30 * MS + MS / 2); + assert!(windows[0].truncated); + assert_eq!( + (windows[0].start_ns, windows[0].end_ns), + (9 * MS + MS / 2, 30 * MS + MS / 2) + ); + } + + #[test] + fn a_span_that_began_before_arm_does_not_fire() { + // A 19 ms gap from 1 ms, but the Agent acknowledged ARM at 5 ms. + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 100, 5 * MS); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.observation().over_threshold, 1); + assert_eq!(engine.finish(u64::MAX).len(), 0); + } + + #[test] + fn spans_fire_once_and_later_windows_follow_the_previous_one() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 2), 100, 0); + // The second window, 22-41 ms, starts after the first ends at 21 ms. + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 23 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + // Re-evaluating the same records does not fire again. + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + assert!(!engine.done()); + + engine.ingest(kernel(40 * MS, 41 * MS, 4), 0, 0); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + assert!(engine.done()); + let windows = engine.finish(u64::MAX); + assert_eq!(windows.len(), 2); + assert_eq!(windows[1].fired.start.timestamp_ns, 23 * MS); + } + + #[test] + fn a_window_that_lost_records_is_not_written() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 100, 0); + engine.ingest(kernel(0, MS, 0), 0, 0); + // The ring overwrote records between the two reads. + engine.ingest(kernel(20 * MS, 21 * MS, 10), 3, 0); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + assert!(engine.done()); + assert_eq!(engine.finish(u64::MAX).len(), 0); + assert_eq!(engine.lost_windows(), 1); + + // Drops count the same way. + let mut dropped = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 100, 0); + dropped.ingest(kernel(0, MS, 0), 0, 0); + dropped.ingest(kernel(20 * MS, 21 * MS, 2), 0, 1); + dropped.evaluate(Instant::now()).unwrap(); + assert_eq!(dropped.finish(u64::MAX).len(), 0); + assert_eq!(dropped.lost_windows(), 1); + + // A loss reported after the window closed still invalidates it. + let mut late = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 100, 0); + late.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + late.evaluate(Instant::now()).unwrap(); + close(&mut late); + late.ingest(kernel(10 * MS, 11 * MS, 4), 0, 1); + assert_eq!(late.finish(u64::MAX).len(), 0); + assert_eq!(late.lost_windows(), 1); + } + + #[test] + fn a_window_revoked_while_watching_frees_its_slot() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 100, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + assert!(engine.done()); + assert_eq!(engine.observation().longest.unwrap().latency_ns, 19 * MS); + // A late kernel from 9 to 12 ms splits the 19 ms gap. + engine.ingest(kernel(9 * MS, 12 * MS, 4), 0, 0); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.revoked_windows(), 1); + assert!(!engine.done(), "the slot is free to wait for a real gap"); + // The observation describes the records as they now stand. + let observation = engine.observation(); + assert_eq!(observation.over_threshold, 0); + assert_eq!(observation.longest.unwrap().latency_ns, 8 * MS); + // A later real gap fires the window again. + engine.ingest(kernel(40 * MS, 41 * MS, 6), 0, 0); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + assert!(engine.done()); + let windows = engine.finish(u64::MAX); + assert_eq!(windows.len(), 1); + assert_eq!(windows[0].fired.start.timestamp_ns, 21 * MS); + } + + #[test] + fn a_slot_freed_by_revocation_takes_a_span_from_the_same_batch() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 100, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + // One read brings both the kernel that splits the 19 ms gap and a + // later real gap from 21 to 40 ms. + engine.ingest( + [kernel(9 * MS, 12 * MS, 4), kernel(40 * MS, 41 * MS, 6)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.revoked_windows(), 1); + close(&mut engine); + let windows = engine.finish(u64::MAX); + assert_eq!(windows.len(), 1); + assert_eq!(windows[0].fired.start.timestamp_ns, 21 * MS); + } + + #[test] + fn trimming_a_closed_windows_context_does_not_revoke_it() { + // Room for five records: the first kernel's start is trimmed after + // its gap's window closed. + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 5, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + engine.ingest(kernel(40 * MS, 41 * MS, 4), 0, 0); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.revoked_windows(), 0); + assert_eq!(engine.finish(u64::MAX).len(), 1); + assert_eq!(engine.revoked_windows(), 0); + } + + #[test] + fn activity_across_an_idle_span_on_another_stream_revokes_it() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Idle, 10, 1), 100, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + // A kernel on stream 8 ran from before the gap to after it. + let mut across = kernel(MS / 2, 25 * MS, 4); + for event in &mut across { + event.cuda.as_mut().unwrap().stream_id = Some(8); + } + engine.ingest(across, 0, 0); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.revoked_windows(), 1); + assert_eq!(engine.observation().over_threshold, 0); + } + + #[test] + fn a_settled_span_stays_the_longest_after_later_ones_split() { + // Room for six records. Gaps of 19 ms (1-20) and 49 ms (21-70). + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 100, 1), 6, 0); + engine.ingest( + [ + kernel(0, MS, 0), + kernel(20 * MS, 21 * MS, 2), + kernel(70 * MS, 71 * MS, 4), + ] + .concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + // The next read trims the first kernel, settling the 19 ms gap, and + // splits the 49 ms one. + engine.ingest(kernel(30 * MS, 60 * MS, 6), 0, 0); + engine.evaluate(Instant::now()).unwrap(); + let observation = engine.observation(); + assert_eq!(observation.longest.unwrap().latency_ns, 19 * MS); + // 1-20 settled; 21-30 and 60-70 remain. + assert_eq!(observation.spans, 3); + } + + /// Give a kernel's records one correlation ID, as CUDA Graph nodes do. + fn graph_node(mut events: Vec) -> Vec { + for event in &mut events { + event.cuda.as_mut().unwrap().correlation_id = Some(99); + } + events + } + + #[test] + fn a_late_graph_node_with_a_shared_key_still_revokes_the_gap() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 5, 1), 100, 0); + engine.ingest( + graph_node([kernel(MS, 10 * MS, 0), kernel(20 * MS, 30 * MS, 2)].concat()), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + // Another node of the graph ran from 5 to 25 ms on the stream. + engine.ingest(graph_node(kernel(5 * MS, 25 * MS, 4)), 0, 0); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.revoked_windows(), 1); + } + + #[test] + fn a_kernel_running_at_stop_from_before_the_span_revokes_idle() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Idle, 10, 1), 100, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + // STOP's flush brings a kernel on stream 8 still running, placed at + // its stream's previous end, 2 ms. + let mut running = kernel(2 * MS, 3 * MS, 4); + running.truncate(1); + running[0].cuda.as_mut().unwrap().stream_id = Some(8); + running[0].attributes.insert( + xprobe_protocol::START_UNKNOWN_ATTRIBUTE.to_owned(), + true.into(), + ); + engine.ingest(running, 0, 0); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.finish(u64::MAX).len(), 0); + assert_eq!(engine.revoked_windows(), 1); + } + + #[test] + fn a_second_window_fires_from_records_already_read() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 2), 100, 0); + // Two gaps in one read: 1-20 and 23-40 ms. + engine.ingest( + [ + kernel(0, MS, 0), + kernel(20 * MS, 23 * MS, 2), + kernel(40 * MS, 41 * MS, 4), + ] + .concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + // No new records: the second gap fires once the first window closes. + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + assert!(engine.done()); + assert_eq!(engine.finish(u64::MAX).len(), 2); + } + + #[test] + fn settled_spans_keep_counting_after_their_records_leave() { + // Room for four records; each kernel adds two. + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 100, 1), 4, 0); + for (index, start) in [0, 20, 40, 60].into_iter().enumerate() { + engine.ingest(kernel(start * MS, start * MS + MS, index as u64 * 2), 0, 0); + engine.evaluate(Instant::now()).unwrap(); + } + let observation = engine.observation(); + assert_eq!(observation.spans, 3); + assert_eq!(observation.longest.unwrap().latency_ns, 19 * MS); + } + + #[test] + fn a_late_record_inside_the_gap_revokes_its_window() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 100, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + // A kernel from 9 to 12 ms arrives after the window closed. + engine.ingest(kernel(9 * MS, 12 * MS, 4), 0, 0); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.finish(u64::MAX).len(), 0); + assert_eq!(engine.revoked_windows(), 1); + } + + #[test] + fn retention_keeps_the_records_of_windows_not_yet_cut() { + // Room for four records: each kernel adds two. + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 4, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + // While the window is open, later records exceed retention. + engine.ingest(kernel(22 * MS, 23 * MS, 4), 0, 0); + close(&mut engine); + // After it closes, trimming moves its records aside. + engine.ingest( + [kernel(40 * MS, 41 * MS, 6), kernel(60 * MS, 61 * MS, 8)].concat(), + 0, + 0, + ); + let windows = engine.finish(u64::MAX); + assert_eq!(engine.lost_windows(), 0); + assert_eq!(windows.len(), 1); + // 0 to 21 ms: both records of A and of B. + assert_eq!(windows[0].events.len(), 4); + } + + #[test] + fn a_window_without_pre_roll_keeps_its_span() { + // With no pre-roll the window starts at A's end, so A's start lies + // outside it; the gap is still re-checked in context. + let mut gap = condition(TriggerKind::Gap, 10, 1); + gap.pre_ns = 0; + let mut engine = TriggerEngine::new(gap, 100, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + let windows = engine.finish(u64::MAX); + assert_eq!(engine.revoked_windows(), 0); + assert_eq!(windows[0].start_ns, MS); + assert_eq!(windows[0].longest[0].latency_ns, 19 * MS); + } + + #[test] + fn an_open_window_beyond_twice_retention_is_lost() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 4, 0); + // A 10 ms post-roll: the window runs to 30 ms. + engine.condition.post_ns = 10 * MS; + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + // Five more kernels arrive inside the window before it closes. + for index in 0..5 { + engine.ingest( + kernel( + 22 * MS + index * MS, + 22 * MS + index * MS + 1, + 4 + index * 2, + ), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + } + assert!(engine.retained.len() <= 2 * 4 + 2); + assert_eq!(engine.finish(u64::MAX).len(), 0); + assert_eq!(engine.lost_windows(), 1); + } + + #[test] + fn a_late_end_revokes_a_gap_its_earlier_start_spans() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 2, 0); + // A kernel from 0.5 to 25 ms whose start is read, then trimmed by a + // kernel on another stream, before the 2-20 ms gap fires. + let across = kernel(MS / 2, 25 * MS, 10); + engine.ingest(vec![across[0].clone()], 0, 0); + engine.evaluate(Instant::now()).unwrap(); + let mut other = kernel(MS * 6 / 10, MS * 7 / 10, 20); + for event in &mut other { + event.cuda.as_mut().unwrap().stream_id = Some(9); + } + engine.ingest(other, 0, 0); + engine.evaluate(Instant::now()).unwrap(); + engine.ingest( + [kernel(MS, 2 * MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + assert_eq!(engine.closed.len(), 1); + engine.ingest(vec![across[1].clone()], 0, 0); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.revoked_windows(), 1); + assert_eq!(engine.finish(u64::MAX).len(), 0); + } + + #[test] + fn a_marker_on_a_new_stream_is_placed_before_trimmed_windows() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Idle, 10, 1), 4, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + // Later reads trim the window's records out of retention. + engine.ingest( + [kernel(30 * MS, 31 * MS, 4), kernel(40 * MS, 41 * MS, 6)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + // A kernel still running at STOP on a stream with no earlier end may + // have run since the first record read, across the idle span. + let mut running = kernel(50 * MS, 51 * MS, 8); + running.truncate(1); + running[0].cuda.as_mut().unwrap().stream_id = Some(8); + running[0].attributes.insert( + xprobe_protocol::START_UNKNOWN_ATTRIBUTE.to_owned(), + true.into(), + ); + engine.ingest(running, 0, 0); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.revoked_windows(), 1); + } + + #[test] + fn an_end_pairs_with_the_latest_start_of_its_key() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 100, 0); + engine.ingest( + [kernel(0, 10 * MS, 0), kernel(30 * MS, 31 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + // Graph nodes 2-5 and 35-40 ms share a key and arrive out of order: + // the first start, the whole second node, then the first end. + let first = graph_node(kernel(2 * MS, 5 * MS, 10)); + engine.ingest(vec![first[0].clone()], 0, 0); + engine.ingest(graph_node(kernel(35 * MS, 40 * MS, 12)), 0, 0); + engine.ingest(vec![first[1].clone()], 0, 0); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.revoked_windows(), 0); + assert_eq!(engine.finish(u64::MAX).len(), 1); + } + + #[test] + fn a_revoked_settled_span_leaves_the_counts() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 4, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + // Trimming settles the 19 ms gap; a kernel across it then arrives. + engine.ingest( + [kernel(30 * MS, 31 * MS, 4), kernel(40 * MS, 41 * MS, 6)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.observation().over_threshold, 1); + engine.ingest(kernel(MS / 2, 25 * MS, 8), 0, 0); + engine.evaluate(Instant::now()).unwrap(); + assert_eq!(engine.revoked_windows(), 1); + let observation = engine.observation(); + assert_eq!(observation.over_threshold, 0); + assert!(observation.longest.unwrap().latency_ns < 10 * MS); + } + + #[test] + fn a_new_window_that_fits_after_trimming_is_not_lost() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 2), 4, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + // Ten records retained before trimming; the 33-50 ms gap's window + // needs only the last four. + engine.ingest( + [ + kernel(30 * MS, 31 * MS, 4), + kernel(32 * MS, 33 * MS, 6), + kernel(50 * MS, 51 * MS, 8), + ] + .concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + assert!(engine.done()); + assert_eq!(engine.finish(u64::MAX).len(), 2); + assert_eq!(engine.lost_windows(), 0); + } + + #[test] + fn open_starts_stay_within_retention() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 4, 0); + let starts = (0..10) + .map(|index| kernel(index * MS, index * MS + 1, index * 2).remove(0)) + .collect(); + engine.ingest(starts, 0, 0); + assert!(engine.open_starts.values().map(Vec::len).sum::() <= 4); + let mut latency = TriggerEngine::new(condition(TriggerKind::Duration, 10, 1), 4, 0); + latency.ingest(kernel(0, MS, 0), 0, 0); + assert!(latency.open_starts.is_empty()); + } + + #[test] + fn a_window_closed_by_later_traffic_lets_the_next_span_fire() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 2), 4, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + // One read past the first window holds a 28-40 ms gap. + engine.ingest( + [ + kernel(23 * MS, 24 * MS, 4), + kernel(25 * MS, 26 * MS, 6), + kernel(27 * MS, 28 * MS, 8), + kernel(40 * MS, 41 * MS, 10), + ] + .concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + engine.evaluate(Instant::now()).unwrap(); + close(&mut engine); + assert!(engine.done()); + assert_eq!(engine.finish(u64::MAX).len(), 2); + } + + #[test] + fn records_after_an_open_window_close_it_instead_of_losing_it() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Gap, 10, 1), 4, 0); + engine.ingest( + [kernel(0, MS, 0), kernel(20 * MS, 21 * MS, 2)].concat(), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + // The window runs to 22 ms; five kernels after it arrive before the + // settle time has passed. + for index in 0..5 { + engine.ingest( + kernel( + 23 * MS + index * MS, + 23 * MS + index * MS + 1, + 4 + index * 2, + ), + 0, + 0, + ); + engine.evaluate(Instant::now()).unwrap(); + } + assert!(engine.retained.len() <= 2 * 4 + 2); + assert!(engine.done()); + assert_eq!(engine.finish(u64::MAX).len(), 1); + assert_eq!(engine.lost_windows(), 0); + } + + #[test] + fn a_duration_trigger_fires_on_a_long_activity() { + let mut engine = TriggerEngine::new(condition(TriggerKind::Duration, 5, 1), 100, 0); + engine.ingest([kernel(0, MS, 0), kernel(2 * MS, 9 * MS, 2)].concat(), 0, 0); + engine.evaluate(Instant::now()).unwrap(); + let windows = engine.finish(u64::MAX); + assert_eq!(windows[0].fired.latency_ns, 7 * MS); + assert_eq!(windows[0].fired.start.timestamp_ns, 2 * MS); + } + + #[test] + fn millisecond_bounds_are_finite_and_positive() { + assert_eq!(milliseconds_ns("x", 0.5, false).unwrap(), 500_000); + assert_eq!(milliseconds_ns("x", 0.0, true).unwrap(), 0); + for invalid in [0.0, -1.0, f64::NAN, f64::INFINITY, 1e30] { + assert!(milliseconds_ns("x", invalid, false).is_err(), "{invalid}"); + } + } +} diff --git a/xprobe/cli/tests/manifest.rs b/xprobe/cli/tests/manifest.rs new file mode 100644 index 0000000..1820de6 --- /dev/null +++ b/xprobe/cli/tests/manifest.rs @@ -0,0 +1,330 @@ +//! Offline correlation trusts what a capture manifest records about the +//! events beside it, and nothing more. + +use std::{ + collections::BTreeMap, + fs, + path::{Path, PathBuf}, + process::Command, +}; + +use xprobe_protocol::{ + CaptureManifest, CaptureWindow, ClockDomain, CorrelationConfidence, CoverageSource, CudaEvent, + ErrorCode, ErrorResponse, Event, EventSource, EventType, ExportFormat, ManifestVersion, + MeasurementResult, QualityVerdict, SchemaVersion, TargetIdentity, manifest_path, +}; + +const PID: u32 = 1234; + +/// A fresh directory for one test's artifacts. +fn workdir(name: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!("xprobe-manifest-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("test directory must be created"); + path +} + +fn kernel(event_type: EventType, timestamp: u64, correlation_id: u32, name: &str) -> Event { + Event { + schema_version: SchemaVersion::current(), + session_id: "capture".to_owned(), + event_id: format!("evt_{timestamp}_{correlation_id}"), + sequence: timestamp, + source: EventSource::CuptiActivity, + event_type, + pid: PID, + tid: PID, + cpu: None, + timestamp_raw: timestamp, + timestamp_ns: timestamp, + clock_domain: ClockDomain::Cupti, + timestamp_error_ns: None, + process_start_time: None, + host: None, + cuda: Some(CudaEvent { + device_id: Some(0), + context_id: Some(1), + stream_id: Some(7), + correlation_id: Some(correlation_id), + runtime_correlation_id: None, + callback_domain: None, + callback_id: None, + kernel_name: Some(name.to_owned()), + kernel_name_mangled: None, + start_ns: None, + end_ns: None, + grid: None, + block: None, + bytes: None, + memcpy_kind: None, + }), + nvtx: None, + attributes: BTreeMap::new(), + } +} + +/// Kernels A, B, and C back to back on one stream: two end-to-start gaps. +fn write_events(path: &Path) -> Vec { + let events = [(0, 10, "A"), (12, 20, "B"), (25, 30, "C")] + .iter() + .zip(1..) + .flat_map(|(&(start, end, name), id)| { + [ + kernel(EventType::GpuKernelStart, start, id, name), + kernel(EventType::GpuKernelEnd, end, id, name), + ] + }) + .collect::>(); + let bytes = events + .iter() + .map(|event| serde_json::to_string(event).expect("event serializes") + "\n") + .collect::() + .into_bytes(); + fs::write(path, &bytes).expect("events must be written"); + bytes +} + +fn manifest(bytes: &[u8], all_gpu_activity: bool) -> CaptureManifest { + CaptureManifest { + schema_version: ManifestVersion::current(), + artifact: xprobe_exporter::manifest_artifact(ExportFormat::Jsonl, 6, bytes), + target: TargetIdentity { + pid: PID, + process_start_time: 99, + }, + window: CaptureWindow { + start_ns: 0, + end_ns: 100, + }, + selectors: vec!["cuda:kernel_end".to_owned(), "cuda:kernel_start".to_owned()], + all_gpu_activity, + peer_copies: all_gpu_activity, + dropped_records: 0, + unknown_records: 0, + record_limit_reached: None, + capture_failed: false, + cuda_devices: Vec::new(), + wall_clock: None, + } +} + +fn write_manifest(events: &Path, manifest: &CaptureManifest) { + fs::write( + manifest_path(events), + serde_json::to_vec(manifest).expect("manifest serializes"), + ) + .expect("manifest must be written"); +} + +fn measure(inputs: &[&Path], extra: &[&str]) -> std::process::Output { + let mut command = Command::new(env!("CARGO_BIN_EXE_xprobe")); + command.arg("measure"); + for input in inputs { + command.arg("--input").arg(input); + } + command + .args([ + "--from", + "cuda:kernel_end", + "--to", + "cuda:kernel_start", + "--match", + "stream-order", + "--json", + ]) + .args(extra) + .output() + .expect("xprobe measure must run") +} + +fn result(output: &std::process::Output) -> MeasurementResult { + assert_eq!( + output.status.code(), + Some(0), + "{}", + String::from_utf8_lossy(&output.stdout) + ); + serde_json::from_slice(&output.stdout).expect("measurement result parses") +} + +fn issue_codes(result: &MeasurementResult) -> Vec<&str> { + result + .quality + .issues + .iter() + .map(|issue| issue.code.as_str()) + .collect() +} + +#[test] +fn stream_order_without_a_manifest_is_heuristic() { + let dir = workdir("none"); + let events = dir.join("events.jsonl"); + write_events(&events); + + let result = result(&measure(&[&events], &[])); + assert_eq!(result.measurement.samples.matched, 2); + assert_eq!( + result.collection.coverage.source, + CoverageSource::Unverified + ); + assert_eq!( + result.correlation.confidence, + CorrelationConfidence::Heuristic + ); + assert_eq!(result.quality.verdict, QualityVerdict::Caution); + assert!(issue_codes(&result).contains(&"STREAM_COVERAGE_UNVERIFIED")); +} + +#[test] +fn a_manifest_of_every_gpu_activity_keeps_stream_order_high() { + let dir = workdir("all"); + let events = dir.join("events.jsonl"); + let bytes = write_events(&events); + write_manifest(&events, &manifest(&bytes, true)); + + let result = result(&measure(&[&events], &[])); + assert_eq!(result.collection.coverage.source, CoverageSource::Manifest); + assert!(result.collection.coverage.all_gpu_activity); + assert_eq!(result.correlation.confidence, CorrelationConfidence::High); + assert!(!issue_codes(&result).contains(&"STREAM_COVERAGE_UNVERIFIED")); + + // A narrower capture's manifest proves its own losses, not adjacency. + write_manifest(&events, &manifest(&bytes, false)); + let narrow = self::result(&measure(&[&events], &[])); + assert_eq!( + narrow.correlation.confidence, + CorrelationConfidence::Heuristic + ); +} + +#[test] +fn a_manifest_keeps_losses_the_live_capture_reported() { + let dir = workdir("drops"); + let events = dir.join("events.jsonl"); + let bytes = write_events(&events); + let mut lossy = manifest(&bytes, true); + lossy.dropped_records = 3; + write_manifest(&events, &lossy); + + let output = measure(&[&events], &[]); + assert_eq!(output.status.code(), Some(1)); + let error: ErrorResponse = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(error.error.code, ErrorCode::EventsDropped); +} + +#[test] +fn a_stale_manifest_is_an_error() { + let dir = workdir("stale"); + let events = dir.join("events.jsonl"); + let bytes = write_events(&events); + write_manifest(&events, &manifest(&bytes, true)); + // Trim the events after capture, as a hand-filtered artifact would. + let trimmed = String::from_utf8(bytes) + .unwrap() + .split_inclusive('\n') + .take(4) + .collect::(); + fs::write(&events, trimmed).unwrap(); + + let output = measure(&[&events], &[]); + assert_eq!(output.status.code(), Some(1)); + let error: ErrorResponse = serde_json::from_slice(&output.stdout).unwrap(); + assert_eq!(error.error.code, ErrorCode::TraceExportFailed); + assert!( + error + .error + .message + .contains("describes a different artifact") + ); +} + +#[test] +fn merging_inputs_without_manifests_is_a_caution() { + let dir = workdir("merge"); + let first = dir.join("first.jsonl"); + let second = dir.join("second.jsonl"); + let bytes = write_events(&first); + // A later capture of the same process. + let text = String::from_utf8(bytes).unwrap(); + let later = text + .lines() + .map(|line| { + let mut event: Event = serde_json::from_str(line).unwrap(); + event.timestamp_ns += 1000; + event.timestamp_raw += 1000; + serde_json::to_string(&event).unwrap() + "\n" + }) + .collect::(); + fs::write(&second, later).unwrap(); + + let output = Command::new(env!("CARGO_BIN_EXE_xprobe")) + .args(["measure", "--input"]) + .arg(&first) + .arg("--input") + .arg(&second) + .args([ + "--from", + "cuda:kernel_start", + "--to", + "cuda:kernel_end", + "--match", + "nearest", + "--json", + ]) + .output() + .unwrap(); + let result = result(&output); + assert_eq!( + result.collection.coverage.source, + CoverageSource::UnverifiedMerge + ); + assert!(issue_codes(&result).contains(&"CAPTURE_COVERAGE_UNKNOWN")); + + // The same events twice would double them, even renumbered or as a + // subset of another input. + let subset = dir.join("subset.jsonl"); + let lines = text.split_inclusive('\n').collect::>(); + fs::write(&subset, lines[..lines.len() - 1].concat()).unwrap(); + let renumbered = dir.join("renumbered.jsonl"); + fs::write(&renumbered, text.replace("\"capture\"", "\"other\"")).unwrap(); + for inputs in [[&first, &first], [&first, &subset], [&first, &renumbered]] { + let twice = measure(&inputs.map(PathBuf::as_path), &[]); + assert_eq!(twice.status.code(), Some(1)); + let error: ErrorResponse = serde_json::from_slice(&twice.stdout).unwrap(); + assert!( + error.error.message.contains("repeats events"), + "{}", + error.error.message + ); + } +} + +#[test] +fn re_exported_artifacts_keep_or_drop_their_manifest() { + let dir = workdir("export"); + let events = dir.join("events.jsonl"); + let bytes = write_events(&events); + write_manifest(&events, &manifest(&bytes, true)); + let copy = dir.join("copy.jsonl"); + + result(&measure( + &[&events], + &["--events-out", copy.to_str().unwrap()], + )); + let written: CaptureManifest = + serde_json::from_slice(&fs::read(manifest_path(©)).unwrap()).unwrap(); + assert!(xprobe_exporter::artifact_matches( + &written.artifact, + &fs::read(©).unwrap() + )); + assert!(written.all_gpu_activity); + + // Without a manifest on the input, a stale one at the output goes away. + fs::remove_file(manifest_path(&events)).unwrap(); + result(&measure( + &[&events], + &["--events-out", copy.to_str().unwrap()], + )); + assert!(!manifest_path(©).exists()); +} diff --git a/xprobe/collector/Cargo.toml b/xprobe/collector/Cargo.toml index adcf9b1..1ac6fdc 100644 --- a/xprobe/collector/Cargo.toml +++ b/xprobe/collector/Cargo.toml @@ -8,8 +8,10 @@ rust-version.workspace = true [dependencies] libbpf-rs.workspace = true +nix.workspace = true perf-event-open.workspace = true serde_json.workspace = true +xprobe-core.workspace = true xprobe-protocol.workspace = true [lints] diff --git a/xprobe/collector/src/completed.rs b/xprobe/collector/src/completed.rs index c347ff5..4ebec24 100644 --- a/xprobe/collector/src/completed.rs +++ b/xprobe/collector/src/completed.rs @@ -20,6 +20,8 @@ pub struct CompletedCapture { pub record_limit_reached: Option, pub capture_failed: bool, pub cupti: Option, + /// The UUID behind each CUDA device ordinal in the events. + pub cuda_devices: Vec, pub events: Vec, } @@ -31,7 +33,20 @@ pub enum CompletedCaptureError { HostCaptureFollowedByAnotherDocument, HostCaptureInsideEventStream, CounterOverflow, - TargetMismatch { expected: u32, actual: u32 }, + TargetMismatch { + expected: u32, + actual: u32, + }, + /// Inputs disagree on which GPU a CUDA device ordinal names. + DeviceMismatch { + device_id: u32, + }, + /// One PID names two process instances, so the PID was reused. + ProcessInstanceMismatch { + pid: u32, + expected: u64, + actual: u64, + }, } impl fmt::Display for CompletedCaptureError { @@ -51,6 +66,18 @@ impl fmt::Display for CompletedCaptureError { formatter, "completed capture mixes target PIDs {expected} and {actual}" ), + Self::DeviceMismatch { device_id } => write!( + formatter, + "completed capture inputs name different GPUs as CUDA device {device_id}" + ), + Self::ProcessInstanceMismatch { + pid, + expected, + actual, + } => write!( + formatter, + "completed capture mixes two processes with PID {pid}, started at {expected} and {actual}" + ), } } } @@ -64,7 +91,9 @@ impl Error for CompletedCaptureError { | Self::HostCaptureFollowedByAnotherDocument | Self::HostCaptureInsideEventStream | Self::CounterOverflow - | Self::TargetMismatch { .. } => None, + | Self::TargetMismatch { .. } + | Self::DeviceMismatch { .. } + | Self::ProcessInstanceMismatch { .. } => None, } } } @@ -96,9 +125,23 @@ pub fn decode(bytes: &[u8], session_id: &str) -> Result Result Result record_limit_reached: capture.record_limit_reached.then_some(capture.captured), capture_failed: false, cupti: None, + cuda_devices: Vec::new(), events: capture.events, }); } @@ -151,6 +196,7 @@ fn decode_json(bytes: &[u8]) -> Result record_limit_reached: None, capture_failed: false, cupti: None, + cuda_devices: Vec::new(), events, }) } @@ -171,9 +217,11 @@ pub fn merge( record_limit_reached: None, capture_failed: false, cupti: None, + cuda_devices: Vec::new(), events: Vec::new(), }; let mut target_pid = None; + let mut started = None; for capture in captures { merged.dropped_records = merged .dropped_records @@ -187,6 +235,23 @@ pub fn merge( .record_limit_reached .max(capture.record_limit_reached); merged.capture_failed |= capture.capture_failed; + // One process sees one ordinal-to-UUID mapping. + for device in capture.cuda_devices { + match merged + .cuda_devices + .iter() + .find(|known| known.device_id == device.device_id) + { + Some(known) if known.uuid != device.uuid => { + return Err(CompletedCaptureError::DeviceMismatch { + device_id: device.device_id, + }); + } + Some(_) => {} + None => merged.cuda_devices.push(device), + } + } + merged.cuda_devices.sort(); if let Some(cupti) = capture.cupti { if let Some(existing) = merged.cupti.as_mut() { existing.complete &= cupti.complete; @@ -217,6 +282,18 @@ pub fn merge( } else { target_pid = Some(event.pid); } + if let Some(actual) = event.process_start_time { + match started { + Some(expected) if expected != actual => { + return Err(CompletedCaptureError::ProcessInstanceMismatch { + pid: event.pid, + expected, + actual, + }); + } + _ => started = Some(actual), + } + } merged.events.push(event); } } @@ -264,6 +341,37 @@ mod tests { } } + #[test] + fn merging_two_processes_behind_one_pid_fails() { + let capture = |started: u64| CompletedCapture { + dropped_records: 0, + unknown_records: 0, + record_limit_reached: None, + capture_failed: false, + cupti: None, + cuda_devices: Vec::new(), + events: vec![Event { + process_start_time: Some(started), + ..event(12, started) + }], + }; + assert!(matches!( + merge(vec![capture(10), capture(11)], "merged"), + Err(CompletedCaptureError::ProcessInstanceMismatch { + pid: 12, + expected: 10, + actual: 11 + }) + )); + assert_eq!( + merge(vec![capture(10), capture(10)], "merged") + .unwrap() + .events + .len(), + 2 + ); + } + #[test] fn decodes_event_json_stream() { let input = format!( @@ -309,6 +417,7 @@ mod tests { record_limit_reached: None, capture_failed: false, cupti: None, + cuda_devices: Vec::new(), events: vec![event(12, 30)], }, CompletedCapture { @@ -317,6 +426,7 @@ mod tests { record_limit_reached: None, capture_failed: false, cupti: None, + cuda_devices: Vec::new(), events: vec![event(12, 20)], }, ], @@ -338,6 +448,7 @@ mod tests { record_limit_reached: None, capture_failed: false, cupti: None, + cuda_devices: Vec::new(), events: vec![event(12, 20), event(13, 30)], }], "merged", diff --git a/xprobe/collector/src/cupti.rs b/xprobe/collector/src/cupti.rs index 5bdf5e3..275adbc 100644 --- a/xprobe/collector/src/cupti.rs +++ b/xprobe/collector/src/cupti.rs @@ -18,11 +18,13 @@ use xprobe_protocol::{ mod filter; -pub use filter::{CuptiFilterError, bounded_name_filter, event_filter, event_filters}; +pub use filter::{ + CuptiFilterError, all_activity_filters, bounded_name_filter, event_filter, event_filters, +}; const OUTPUT_MAGIC: &[u8; 8] = b"XPCUPTI\0"; const CONTROL_MAGIC: &[u8; 8] = b"XPCTRL\0\0"; -const CONTROL_VERSION: u32 = 5; +const CONTROL_VERSION: u32 = 6; const ABI_VERSION: u32 = 4; const HEADER_SIZE: usize = 88; const HEADER_SIZE_U32: u32 = 88; @@ -33,16 +35,99 @@ const FILTER_SIZE: usize = 144; /// Endpoint filters one ARM can carry; matches `XPROBE_CUPTI_FILTER_COUNT`. pub const CUPTI_FILTER_COUNT: usize = 8; pub const CUPTI_NAME_CAPACITY: usize = 128; +const _: () = assert!(CUPTI_NAME_CAPACITY == xprobe_protocol::CUDA_RECORD_NAME_MAX_BYTES + 1); const FEATURE_HOST_MONOTONIC_TIMESTAMPS: u32 = 1 << 0; const FEATURE_TRANSFER_RECORDS: u32 = 1 << 1; const FEATURE_AGGREGATE_RECORDS: u32 = 1 << 2; const FEATURE_NVTX_RECORDS: u32 = 1 << 3; const FEATURE_MEMORY_KINDS: u32 = 1 << 4; -const SUPPORTED_FEATURES: u32 = FEATURE_HOST_MONOTONIC_TIMESTAMPS +const FEATURE_PEER_MEMCPY: u32 = 1 << 5; +const FEATURE_RING_RECORDS: u32 = 1 << 6; +const FEATURE_DEVICE_TABLE: u32 = 1 << 7; +/// Device table: count and entry size, then 32-byte entries. +const DEVICE_TABLE_HEADER: usize = 8; +const DEVICE_ENTRY_SIZE: usize = 48; +const DEVICE_MIG: u32 = 1; +/// `callback_domain` of an activity start whose time CUPTI did not report. +const START_UNKNOWN: u32 = 1; +use xprobe_protocol::{START_UNKNOWN_ATTRIBUTE, start_unknown}; + +/// Give each activity that was running at STOP with an unknown start the +/// latest end on its stream in `events` or `earlier`, the earliest it can +/// have started; without one, the earliest activity time of its clock, or +/// for host-clock records `floor`, where the capture began. One with nothing +/// to place it by is dropped. +pub fn place_unknown_starts(events: &mut Vec, earlier: &[Event], floor: Option) { + let stream = |event: &Event| { + event.cuda.as_ref().map(|cuda| { + ( + event.pid, + cuda.device_id, + cuda.context_id, + cuda.stream_id, + event.clock_domain.clone(), + ) + }) + }; + let known = |event: &&Event| { + xprobe_protocol::activity_boundary(&event.event_type).is_some() && !start_unknown(event) + }; + let mut placed = Vec::new(); + for (index, event) in events.iter().enumerate() { + if !start_unknown(event) { + continue; + } + let key = stream(event); + let previous_end = earlier + .iter() + .chain(events.iter()) + .filter(known) + .filter(|other| { + xprobe_protocol::activity_boundary(&other.event_type) + == Some(xprobe_protocol::ActivityBoundary::End) + && stream(other) == key + }) + .map(|other| other.timestamp_ns) + .max(); + let earliest = || { + earlier + .iter() + .chain(events.iter()) + .filter(known) + .filter(|other| other.clock_domain == event.clock_domain) + .map(|other| other.timestamp_ns) + .min() + }; + let floor = floor.filter(|_| event.clock_domain != ClockDomain::Cupti); + placed.push((index, previous_end.or_else(earliest).or(floor))); + } + let mut dropped = Vec::new(); + for (index, time) in placed { + match time { + Some(time) => { + events[index].timestamp_ns = time; + events[index].timestamp_raw = time; + if let Some(cuda) = events[index].cuda.as_mut() { + cuda.start_ns = Some(time); + } + } + None => dropped.push(index), + } + } + for index in dropped.into_iter().rev() { + events.remove(index); + } + events.sort_by_key(|event| event.timestamp_ns); +} +const MAX_DEVICES: usize = 64; +const SUPPORTED_FEATURES: u32 = FEATURE_DEVICE_TABLE + | FEATURE_HOST_MONOTONIC_TIMESTAMPS | FEATURE_TRANSFER_RECORDS | FEATURE_AGGREGATE_RECORDS | FEATURE_NVTX_RECORDS - | FEATURE_MEMORY_KINDS; + | FEATURE_MEMORY_KINDS + | FEATURE_PEER_MEMCPY + | FEATURE_RING_RECORDS; const UNKNOWN_U32: u32 = u32::MAX; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -60,6 +145,22 @@ pub enum CuptiRecordKind { NvtxRangeEnd = 10, } +impl CuptiRecordKind { + /// Whether the kind is a kernel, copy, or memset boundary. + #[must_use] + pub const fn is_activity(self) -> bool { + matches!( + self, + Self::GpuKernelStart + | Self::GpuKernelEnd + | Self::GpuMemcpyStart + | Self::GpuMemcpyEnd + | Self::GpuMemsetStart + | Self::GpuMemsetEnd + ) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u32)] pub enum CuptiApiDomain { @@ -84,6 +185,8 @@ pub enum CuptiMemcpyKind { pub enum CuptiCaptureMode { Exact = 0, Aggregate = 1, + /// Exact records kept in a ring of the newest `record_capacity`. + Ring = 2, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -136,6 +239,11 @@ pub struct CuptiAggregateGroup { #[derive(Debug, Clone, PartialEq)] pub struct CuptiCapture { pub nvtx_callbacks_active: bool, + /// Peer-to-peer copies (CUPTI `MEMCPY2`) were captured with other copies. + pub peer_memcpy_captured: bool, + /// Records came from a ring; a larger `record_offset` than requested + /// means the records in between were overwritten unread. + pub ring: bool, pub record_offset: u64, pub state: CuptiCaptureState, pub stop_reason: CuptiStopReason, @@ -145,6 +253,9 @@ pub struct CuptiCapture { pub cupti_dropped_records: u64, pub dropped_records: u64, pub unknown_records: u64, + /// The UUID behind each CUDA device ordinal; empty when the Agent's + /// driver did not report them. + pub devices: Vec, pub events: Vec, pub aggregate_groups: Vec, } @@ -165,6 +276,8 @@ pub enum CuptiStopReason { RecordLimit, CuptiError, OutputError, + /// STOP could not disable every callback or activity kind. + CleanupError, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -181,6 +294,7 @@ pub enum CuptiDecodeError { expected: u32, }, InvalidRecordSize(u32), + InvalidDeviceTable(&'static str), CaptureLengthOverflow, InvalidCaptureLength { expected: usize, @@ -243,6 +357,12 @@ impl fmt::Display for CuptiDecodeError { "CUPTI capture ABI {version} header size is {actual}, expected {expected}" ) } + Self::InvalidDeviceTable(problem) => { + write!( + formatter, + "CUPTI capture device table is invalid: {problem}" + ) + } Self::InvalidRecordSize(size) => { write!( formatter, @@ -519,62 +639,32 @@ fn read_snapshot(reader: &mut impl Read, bytes: &mut Vec) -> Result<(), Cupt /// Returns [`CuptiDecodeError`] when the capture header, size, record kind, or /// bounded name does not match a supported ABI. pub fn decode_capture(bytes: &[u8], session_id: &str) -> Result { - if bytes.len() < HEADER_SIZE { - return Err(CuptiDecodeError::HeaderTooShort { - actual: bytes.len(), - }); - } - if &bytes[0..8] != OUTPUT_MAGIC { - return Err(CuptiDecodeError::InvalidMagic); - } - - let abi_version = read_u32(bytes, 8); - if abi_version != ABI_VERSION { - return Err(CuptiDecodeError::UnsupportedAbi(abi_version)); - } - let header_size = read_u32(bytes, 12); - if header_size != HEADER_SIZE_U32 { - return Err(CuptiDecodeError::InvalidHeaderSize { - version: abi_version, - actual: header_size, - expected: HEADER_SIZE_U32, - }); - } - let record_size = read_u32(bytes, 16); - if record_size != RECORD_SIZE_U32 { - return Err(CuptiDecodeError::InvalidRecordSize(record_size)); - } - let feature_flags = read_u32(bytes, 20); - let unsupported_features = feature_flags & !SUPPORTED_FEATURES; - if unsupported_features != 0 { - return Err(CuptiDecodeError::UnsupportedFeatureFlags( - unsupported_features, - )); - } - + let feature_flags = check_header(bytes)?; let state = decode_capture_state(read_u32(bytes, 24))?; let stop_reason = decode_stop_reason(read_u32(bytes, 28))?; let record_count_raw = read_u64(bytes, 32); let record_capacity = read_u64(bytes, 40); let observed_records = read_u64(bytes, 48); let record_offset = read_u64(bytes, 80); - let committed_records = record_offset - .checked_add(record_count_raw) - .ok_or(CuptiDecodeError::CounterOverflow)?; - if committed_records > record_capacity || observed_records < committed_records { - return Err(CuptiDecodeError::InvalidCounters { - offset: record_offset, - records: record_count_raw, - capacity: record_capacity, - observed: observed_records, - }); - } + let ring = feature_flags & FEATURE_RING_RECORDS != 0; + check_record_counters( + record_offset, + record_count_raw, + record_capacity, + observed_records, + ring, + )?; let record_count = usize::try_from(record_count_raw).map_err(|_| CuptiDecodeError::CaptureLengthOverflow)?; + let (devices, payload_start) = if feature_flags & FEATURE_DEVICE_TABLE != 0 { + decode_device_table(bytes)? + } else { + (Vec::new(), HEADER_SIZE) + }; let payload_size = record_count .checked_mul(RECORD_SIZE) .ok_or(CuptiDecodeError::CaptureLengthOverflow)?; - let expected_size = HEADER_SIZE + let expected_size = payload_start .checked_add(payload_size) .ok_or(CuptiDecodeError::CaptureLengthOverflow)?; if bytes.len() != expected_size { @@ -594,7 +684,7 @@ pub fn decode_capture(bytes: &[u8], session_id: &str) -> Result Result Result String { + let hex = |range: std::ops::Range| { + use std::fmt::Write; + bytes[range].iter().fold(String::new(), |mut text, byte| { + write!(text, "{byte:02x}").expect("writing to a String cannot fail"); + text + }) + }; + format!( + "{prefix}-{}-{}-{}-{}-{}", + hex(0..4), + hex(4..6), + hex(6..8), + hex(8..10), + hex(10..16) + ) +} + +/// The device table after the header, and where the records begin. +fn decode_device_table( bytes: &[u8], +) -> Result<(Vec, usize), CuptiDecodeError> { + let table = bytes + .get(HEADER_SIZE..HEADER_SIZE + DEVICE_TABLE_HEADER) + .ok_or(CuptiDecodeError::InvalidDeviceTable( + "truncated table header", + ))?; + let count = usize::try_from(read_u32(table, 0)) + .map_err(|_| CuptiDecodeError::InvalidDeviceTable("device count overflows"))?; + if read_u32(table, 4) as usize != DEVICE_ENTRY_SIZE { + return Err(CuptiDecodeError::InvalidDeviceTable( + "unexpected entry size", + )); + } + if count == 0 || count > MAX_DEVICES { + return Err(CuptiDecodeError::InvalidDeviceTable( + "device count out of range", + )); + } + let start = HEADER_SIZE + DEVICE_TABLE_HEADER; + let end = start + count * DEVICE_ENTRY_SIZE; + let entries = bytes + .get(start..end) + .ok_or(CuptiDecodeError::InvalidDeviceTable("truncated entries"))?; + let mut devices = Vec::with_capacity(count); + for entry in entries.chunks_exact(DEVICE_ENTRY_SIZE) { + let mig = read_u32(entry, 4) & DEVICE_MIG != 0; + devices.push(xprobe_protocol::CudaDevice { + device_id: read_u32(entry, 0), + uuid: format_uuid(if mig { "MIG" } else { "GPU" }, &entry[8..24]), + gpu_uuid: mig.then(|| format_uuid("GPU", &entry[24..40])), + }); + } + if devices + .iter() + .zip(0..) + .any(|(device, ordinal)| device.device_id != ordinal) + { + return Err(CuptiDecodeError::InvalidDeviceTable( + "ordinals are not 0..count", + )); + } + Ok((devices, end)) +} + +/// The magic, ABI, sizes, and feature flags of a capture header. +fn check_header(bytes: &[u8]) -> Result { + if bytes.len() < HEADER_SIZE { + return Err(CuptiDecodeError::HeaderTooShort { + actual: bytes.len(), + }); + } + if &bytes[0..8] != OUTPUT_MAGIC { + return Err(CuptiDecodeError::InvalidMagic); + } + + let abi_version = read_u32(bytes, 8); + if abi_version != ABI_VERSION { + return Err(CuptiDecodeError::UnsupportedAbi(abi_version)); + } + let header_size = read_u32(bytes, 12); + if header_size != HEADER_SIZE_U32 { + return Err(CuptiDecodeError::InvalidHeaderSize { + version: abi_version, + actual: header_size, + expected: HEADER_SIZE_U32, + }); + } + let record_size = read_u32(bytes, 16); + if record_size != RECORD_SIZE_U32 { + return Err(CuptiDecodeError::InvalidRecordSize(record_size)); + } + let feature_flags = read_u32(bytes, 20); + let unsupported_features = feature_flags & !SUPPORTED_FEATURES; + if unsupported_features != 0 { + return Err(CuptiDecodeError::UnsupportedFeatureFlags( + unsupported_features, + )); + } + Ok(feature_flags) +} + +/// Retained records fit the capacity and never exceed what was observed. A +/// ring returns at most its capacity, from any logical offset. +fn check_record_counters( + offset: u64, + records: u64, + capacity: u64, + observed: u64, + ring: bool, +) -> Result<(), CuptiDecodeError> { + let committed = offset + .checked_add(records) + .ok_or(CuptiDecodeError::CounterOverflow)?; + let retained = if ring { records } else { committed }; + if retained > capacity || observed < committed { + return Err(CuptiDecodeError::InvalidCounters { + offset, + records, + capacity, + observed, + }); + } + Ok(()) +} + +fn decode_payload( + records: &[u8], record_count: usize, record_offset: u64, session_id: &str, @@ -631,14 +851,14 @@ fn decode_payload( ) -> Result<(Vec, Vec), CuptiDecodeError> { if feature_flags & FEATURE_AGGREGATE_RECORDS != 0 { let mut groups = Vec::with_capacity(record_count); - for (index, record) in bytes[HEADER_SIZE..].chunks_exact(RECORD_SIZE).enumerate() { + for (index, record) in records.chunks_exact(RECORD_SIZE).enumerate() { groups.push(decode_aggregate_record(record, index, feature_flags)?); } return Ok((Vec::new(), groups)); } let mut events = Vec::with_capacity(record_count); - for (index, record) in bytes[HEADER_SIZE..].chunks_exact(RECORD_SIZE).enumerate() { + for (index, record) in records.chunks_exact(RECORD_SIZE).enumerate() { events.push(decode_record(record, index, session_id, feature_flags)?); } events.sort_by_key(|event| event.timestamp_ns); @@ -765,6 +985,7 @@ fn decode_stop_reason(value: u32) -> Result { 2 => Ok(CuptiStopReason::RecordLimit), 3 => Ok(CuptiStopReason::CuptiError), 4 => Ok(CuptiStopReason::OutputError), + 5 => Ok(CuptiStopReason::CleanupError), _ => Err(CuptiDecodeError::InvalidStopReason(value)), } } @@ -778,7 +999,9 @@ fn decode_record( let kind = read_u32(record, 8); let (source, event_type) = decode_record_kind(kind, index, feature_flags)?; let timestamp_raw = read_u64(record, 0); - if timestamp_raw == 0 { + // Only a start flagged as running at STOP may lack its time. + let unknown_start = matches!(kind, 3 | 5 | 7) && read_u32(record, 36) == START_UNKNOWN; + if timestamp_raw == 0 && !unknown_start { return Err(CuptiDecodeError::InvalidTimestamp { index, kind }); } let name_bytes = &record[72..200]; @@ -822,6 +1045,12 @@ fn decode_record( if matches!(kind, 7 | 8) { attributes.insert("memset_value".to_owned(), Value::from(read_u32(record, 56))); } + // An activity still running at STOP whose start CUPTI did not report; + // `place_unknown_starts` gives it a conservative time. + let start_unknown = unknown_start; + if start_unknown { + attributes.insert(START_UNKNOWN_ATTRIBUTE.to_owned(), Value::Bool(true)); + } let nvtx = decode_nvtx_event(record, index, is_nvtx, name)?; Ok(Event { @@ -846,7 +1075,9 @@ fn decode_record( stream_id: optional_unknown(read_u32(record, 28)).map(u64::from), correlation_id: optional_nonzero(read_u32(record, 32)), runtime_correlation_id: optional_nonzero(read_u32(record, 68)), - callback_domain: optional_nonzero(read_u32(record, 36)), + // On GPU activity the field only marks activity running at STOP. + callback_domain: optional_nonzero(read_u32(record, 36)) + .filter(|_| !matches!(kind, 3..=8)), callback_id: optional_nonzero(read_u32(record, 40)), kernel_name: is_kernel.then(|| name.to_owned()), kernel_name_mangled: None, @@ -1304,16 +1535,132 @@ mod tests { assert_eq!(memset_event.attributes["memset_value"], 0xab); } + #[test] + fn decodes_peer_copies_reported_with_the_peer_feature() { + // A MEMCPY2 record carries CUPTI copy kind PTOP and no runtime + // correlation ID. + let peer = transfer_record(5, 10_500, 45, 1 << 20, 10); + let mut bytes = transfer_capture(&[peer]); + let features = super::FEATURE_TRANSFER_RECORDS | super::FEATURE_PEER_MEMCPY; + bytes[20..24].copy_from_slice(&features.to_le_bytes()); + let decoded = decode_capture(&bytes, "xp_test").expect("peer capture must decode"); + + assert!(decoded.peer_memcpy_captured); + let payload = decoded.events[0].cuda.as_ref().expect("CUDA payload"); + assert_eq!(payload.memcpy_kind, Some(MemcpyKind::PeerToPeer)); + assert_eq!(payload.runtime_correlation_id, None); + assert!( + !decode_capture(&transfer_capture(&[peer]), "xp_test") + .expect("capture must decode") + .peer_memcpy_captured + ); + } + + #[test] + fn places_activity_running_at_stop_after_its_streams_last_end() { + let event = |stream: u64, kind: EventType, timestamp: u64, unknown: bool| { + let mut event = decode_capture(&capture(&[record(3, 1, 1, "k")]), "xp_test") + .unwrap() + .events + .remove(0); + event.event_type = kind; + event.timestamp_ns = timestamp; + event.cuda.as_mut().unwrap().stream_id = Some(stream); + if unknown { + event.attributes.insert( + xprobe_protocol::START_UNKNOWN_ATTRIBUTE.to_owned(), + true.into(), + ); + } + event + }; + let earlier = [ + event(7, EventType::GpuKernelStart, 100, false), + event(7, EventType::GpuKernelEnd, 200, false), + ]; + let mut events = vec![ + event(7, EventType::GpuKernelStart, 0, true), + // A stream with no earlier activity starts at the capture's first. + event(9, EventType::GpuKernelStart, 0, true), + ]; + super::place_unknown_starts(&mut events, &earlier, None); + let placed = events + .iter() + .map(|event| (event.cuda.as_ref().unwrap().stream_id, event.timestamp_ns)) + .collect::>(); + assert_eq!(placed, [(Some(9), 100), (Some(7), 200)]); + // A flagged start record with no time decodes; an unflagged one does not. + let mut flagged = record(3, 0, 1, "k"); + flagged[36..40].copy_from_slice(&1_u32.to_le_bytes()); + let decoded = decode_capture(&capture(&[flagged]), "xp_test").unwrap(); + assert!(xprobe_protocol::start_unknown(&decoded.events[0])); + assert_eq!( + decoded.events[0].cuda.as_ref().unwrap().callback_domain, + None + ); + // Alone, it starts where the capture began. + let mut lonely = vec![event(7, EventType::GpuKernelStart, 0, true)]; + lonely[0].clock_domain = ClockDomain::CuptiNormalizedToHostMonotonic; + super::place_unknown_starts(&mut lonely, &[], Some(50)); + assert_eq!(lonely[0].timestamp_ns, 50); + // Raw CUPTI time has no capture start to place it by. + let mut lonely = vec![event(7, EventType::GpuKernelStart, 0, true)]; + super::place_unknown_starts(&mut lonely, &[], Some(50)); + assert_eq!(lonely.len(), 0); + } + #[test] fn rejects_unknown_feature_flags() { let mut bytes = capture(&[]); - bytes[20..24].copy_from_slice(&32_u32.to_le_bytes()); + bytes[20..24].copy_from_slice(&256_u32.to_le_bytes()); assert_eq!( decode_capture(&bytes, "xp_test"), - Err(CuptiDecodeError::UnsupportedFeatureFlags(32)) + Err(CuptiDecodeError::UnsupportedFeatureFlags(256)) ); } + #[test] + fn decodes_the_device_table_before_the_records() { + let plain = capture(&[record(1, 100, 1, "cudaLaunchKernel")]); + let mut bytes = plain[..HEADER_SIZE].to_vec(); + let flags = + u32::from_le_bytes(bytes[20..24].try_into().unwrap()) | super::FEATURE_DEVICE_TABLE; + bytes[20..24].copy_from_slice(&flags.to_le_bytes()); + bytes.extend_from_slice(&2_u32.to_le_bytes()); + bytes.extend_from_slice(&48_u32.to_le_bytes()); + for ordinal in 0_u32..2 { + // Device 1 is a MIG instance of the GPU whose UUID bytes are 0xff. + bytes.extend_from_slice(&ordinal.to_le_bytes()); + bytes.extend_from_slice(&ordinal.to_le_bytes()); + bytes.extend((0..16).map(|byte| byte + u8::try_from(ordinal).unwrap() * 16)); + bytes.extend_from_slice(&[if ordinal == 1 { 0xff } else { 0 }; 16]); + bytes.extend_from_slice(&[0; 8]); + } + bytes.extend_from_slice(&plain[HEADER_SIZE..]); + let decoded = decode_capture(&bytes, "xp_test").unwrap(); + assert_eq!(decoded.events.len(), 1); + assert_eq!( + decoded.devices[0].uuid, + "GPU-00010203-0405-0607-0809-0a0b0c0d0e0f" + ); + assert_eq!(decoded.devices[0].gpu_uuid, None); + assert_eq!( + decoded.devices[1], + xprobe_protocol::CudaDevice { + device_id: 1, + uuid: "MIG-10111213-1415-1617-1819-1a1b1c1d1e1f".to_owned(), + gpu_uuid: Some("GPU-ffffffff-ffff-ffff-ffff-ffffffffffff".to_owned()), + } + ); + // A table whose ordinals skip one is malformed. + let mut skipped = bytes.clone(); + skipped[HEADER_SIZE + 8 + 48..HEADER_SIZE + 8 + 52].copy_from_slice(&5_u32.to_le_bytes()); + assert!(matches!( + decode_capture(&skipped, "xp_test"), + Err(CuptiDecodeError::InvalidDeviceTable(_)) + )); + } + #[test] fn rejects_truncated_capture() { let mut bytes = capture(&[record(1, 100, 1, "cudaLaunchKernel")]); @@ -1362,6 +1709,26 @@ mod tests { assert_eq!(decoded.events[0].event_type, EventType::GpuKernelStart); } + #[test] + fn ring_captures_may_start_past_their_capacity() { + // Record 100 of a 4-record ring: only a ring header may say so. + let mut bytes = normalized_capture(&[record(3, 100, 7, "test_kernel")]); + bytes[40..48].copy_from_slice(&4_u64.to_le_bytes()); + bytes[48..56].copy_from_slice(&101_u64.to_le_bytes()); + bytes[80..88].copy_from_slice(&100_u64.to_le_bytes()); + assert!(matches!( + decode_capture(&bytes, "xp_ring"), + Err(CuptiDecodeError::InvalidCounters { .. }) + )); + + let features = super::FEATURE_HOST_MONOTONIC_TIMESTAMPS | super::FEATURE_RING_RECORDS; + bytes[20..24].copy_from_slice(&features.to_le_bytes()); + let decoded = decode_capture(&bytes, "xp_ring").expect("ring capture must decode"); + assert!(decoded.ring); + assert_eq!(decoded.record_offset, 100); + assert_eq!(decoded.events[0].sequence, 100); + } + #[test] fn decodes_incremental_capture_offsets() { let mut bytes = normalized_capture(&[record(3, 100, 7, "test_kernel")]); diff --git a/xprobe/collector/src/cupti/filter.rs b/xprobe/collector/src/cupti/filter.rs index 464622b..3c05326 100644 --- a/xprobe/collector/src/cupti/filter.rs +++ b/xprobe/collector/src/cupti/filter.rs @@ -35,6 +35,27 @@ impl fmt::Display for CuptiFilterError { impl Error for CuptiFilterError {} +/// Unfiltered start and end filters for every activity family. The Agent +/// checks each record against the filters, so these capture both boundaries +/// of every kernel, copy (including peer copies), and memset. +#[must_use] +pub fn all_activity_filters() -> [CuptiEventFilter; 6] { + [ + CuptiRecordKind::GpuKernelStart, + CuptiRecordKind::GpuKernelEnd, + CuptiRecordKind::GpuMemcpyStart, + CuptiRecordKind::GpuMemcpyEnd, + CuptiRecordKind::GpuMemsetStart, + CuptiRecordKind::GpuMemsetEnd, + ] + .map(|record_kind| CuptiEventFilter { + record_kind, + api_domain: CuptiApiDomain::Any, + memcpy_kind: CuptiMemcpyKind::Any, + name: CuptiNameFilter::Any, + }) +} + /// Lower one validated CUDA endpoint into Agent filters. /// /// `cuda:launch_api` needs one prefix filter per API domain; every other diff --git a/xprobe/collector/src/lib.rs b/xprobe/collector/src/lib.rs index 758daff..52d0a7f 100644 --- a/xprobe/collector/src/lib.rs +++ b/xprobe/collector/src/lib.rs @@ -4,5 +4,6 @@ pub mod completed; pub mod cpu_sampling; pub mod cupti; pub mod linux; +pub mod python_sampling; pub mod syscall_aggregate; pub mod uprobe; diff --git a/xprobe/collector/src/python_sampling.rs b/xprobe/collector/src/python_sampling.rs new file mode 100644 index 0000000..39faf20 --- /dev/null +++ b/xprobe/collector/src/python_sampling.rs @@ -0,0 +1,1364 @@ +//! External, read-only CPython stack sampling. +//! +//! The sampler reads interpreter state with `process_vm_readv` and never stops +//! or injects into the target. Without stopping, a stack can change while it +//! is read; every frame's code object is type-checked and the innermost frame +//! is read again afterwards, so a torn read is discarded and counted rather +//! than reported. The GIL holder is sampled at a high rate, because only it +//! runs Python code; every thread is sampled at a lower rate. + +use std::collections::{BTreeSet, HashMap}; +use std::error::Error; +use std::fmt; +use std::fs; +use std::io::IoSliceMut; +use std::thread; +use std::time::{Duration, Instant}; + +use nix::errno::Errno; +use nix::sys::uio::{RemoteIoVec, process_vm_readv}; +use nix::time::{ClockId, clock_gettime}; +use nix::unistd::Pid; +use xprobe_core::python_layout::{FramePath, GilPath, PythonLayout, PythonRuntime}; +pub use xprobe_core::python_sampling::{ + Code, NativeLeaf, PythonCapture, PythonSample, SamplerCounters, Stack, TidSource, + parse_task_syscall, +}; + +/// Longest string read from an interpreter object, in code points. +const MAX_STRING_CHARS: u64 = 4096; +/// Bound on threads walked per interpreter. +const MAX_THREADS: usize = 4096; +/// Bytes of `struct pthread` searched for its TID (CPython before 3.11). +const PTHREAD_SEARCH_BYTES: usize = 2048; +/// Bytes below the innermost frame read at once (3.11+): frames of one +/// thread sit together on its data stack, so most of a stack is one read. +const FRAME_WINDOW_BYTES: u64 = 16 * 1024; +/// Segments per `process_vm_readv` call (`IOV_MAX`). +const MAX_SEGMENTS: usize = 1024; + +/// Why a remote read failed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReadError { + /// The address is not mapped, or the read was partial. + Fault, + /// ptrace access to the target is denied. + Permission, + /// The target exited. + Gone, + /// Any other `process_vm_readv` failure, by errno. + Other(i32), +} + +/// Read-only access to a target's memory. +pub trait RemoteMemory { + /// Fill `out` from `address`. + /// + /// # Errors + /// + /// Returns [`ReadError`] when the range cannot be read completely. + fn read(&self, address: u64, out: &mut [u8]) -> Result<(), ReadError>; + + /// Fill several buffers, each from its own address, in as few system + /// calls as possible. + /// + /// # Errors + /// + /// Returns [`ReadError`] when any range cannot be read completely. + fn read_many(&self, reads: &mut [(u64, &mut [u8])]) -> Result<(), ReadError> { + for (address, out) in reads { + self.read(*address, out)?; + } + Ok(()) + } +} + +/// A live process read through `process_vm_readv`. +pub struct ProcessMemory { + pid: Pid, +} + +impl ProcessMemory { + #[must_use] + pub fn new(pid: u32) -> Self { + Self { + pid: Pid::from_raw(i32::try_from(pid).unwrap_or(i32::MAX)), + } + } +} + +impl RemoteMemory for ProcessMemory { + fn read(&self, address: u64, out: &mut [u8]) -> Result<(), ReadError> { + let base = usize::try_from(address).map_err(|_| ReadError::Fault)?; + let remote = [RemoteIoVec { + base, + len: out.len(), + }]; + let expected = out.len(); + let mut local = [IoSliceMut::new(out)]; + transfer(process_vm_readv(self.pid, &mut local, &remote), expected) + } + + fn read_many(&self, reads: &mut [(u64, &mut [u8])]) -> Result<(), ReadError> { + for chunk in reads.chunks_mut(MAX_SEGMENTS) { + let remote = chunk + .iter() + .map(|(address, out)| { + Ok(RemoteIoVec { + base: usize::try_from(*address).map_err(|_| ReadError::Fault)?, + len: out.len(), + }) + }) + .collect::, ReadError>>()?; + let expected = remote.iter().map(|segment| segment.len).sum::(); + let mut local = chunk + .iter_mut() + .map(|(_, out)| IoSliceMut::new(out)) + .collect::>(); + transfer(process_vm_readv(self.pid, &mut local, &remote), expected)?; + } + Ok(()) + } +} + +/// A complete transfer, or why it failed; a partial one is a fault. +fn transfer(result: nix::Result, expected: usize) -> Result<(), ReadError> { + match result { + Ok(read) if read == expected => Ok(()), + Err(Errno::EPERM | Errno::EACCES) => Err(ReadError::Permission), + Err(Errno::ESRCH) => Err(ReadError::Gone), + Ok(_) | Err(Errno::EFAULT) => Err(ReadError::Fault), + Err(errno) => Err(ReadError::Other(errno as i32)), + } +} + +/// Why sampling stopped or could not start. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SamplerError { + Read { + what: &'static str, + error: ReadError, + }, + /// `_Py_DebugOffsets` disagrees with the built-in layout. + LayoutMismatch { + field: &'static str, + expected: u64, + found: u64, + }, + NotDebugOffsets, + FreeThreaded, + NoInterpreter, + Clock(String), +} + +impl fmt::Display for SamplerError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Read { what, error } => write!(formatter, "failed to read {what}: {error:?}"), + Self::LayoutMismatch { + field, + expected, + found, + } => write!( + formatter, + "the interpreter's _Py_DebugOffsets reports {field} = {found}, expected {expected}; this CPython build has an unsupported layout" + ), + Self::NotDebugOffsets => write!( + formatter, + "_PyRuntime does not start with _Py_DebugOffsets; this CPython build has an unsupported layout" + ), + Self::FreeThreaded => write!( + formatter, + "free-threaded CPython builds have a different object layout and are not supported" + ), + Self::NoInterpreter => write!(formatter, "the CPython runtime has no interpreter"), + Self::Clock(error) => write!(formatter, "failed to read CLOCK_MONOTONIC: {error}"), + } + } +} + +impl Error for SamplerError {} + +/// Why one stack read was discarded. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Discard { + /// The stack changed while it was read. + Inconsistent, + Fatal(ReadError), +} + +impl From for Discard { + fn from(error: ReadError) -> Self { + match error { + // Frames are freed while a running thread is read. + ReadError::Fault => Self::Inconsistent, + ReadError::Permission | ReadError::Gone | ReadError::Other(_) => Self::Fatal(error), + } + } +} + +/// The GIL at one instant. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct GilState { + /// The thread state holding it, or `None` while it is released. + pub holder: Option, + /// The thread state that took it last, even while it is released. + pub last_holder: u64, + /// Handoffs so far; it changes whenever another thread takes the GIL. + pub switches: u64, +} + +/// Walks interpreter state; resolved code objects are cached and shared by +/// every sample. +pub struct Walker<'m, M: RemoteMemory> { + memory: &'m M, + runtime: PythonRuntime, + max_depth: usize, + codes: Vec, + /// Code address to (its identifying header fields, index into `codes`). + by_address: HashMap, +} + +impl<'m, M: RemoteMemory> Walker<'m, M> { + #[must_use] + pub fn new(memory: &'m M, runtime: PythonRuntime, max_depth: usize) -> Self { + Self { + memory, + runtime, + max_depth, + codes: Vec::new(), + by_address: HashMap::new(), + } + } + + const fn layout(&self) -> &'static PythonLayout { + self.runtime.layout + } + + fn u64_at(&self, address: u64) -> Result { + let mut buffer = [0_u8; 8]; + self.memory.read(address, &mut buffer)?; + Ok(u64::from_le_bytes(buffer)) + } + + fn u32_at(&self, address: u64) -> Result { + let mut buffer = [0_u8; 4]; + self.memory.read(address, &mut buffer)?; + Ok(u32::from_le_bytes(buffer)) + } + + /// Check `_Py_DebugOffsets` (3.13+) against the built-in layout. + /// + /// # Errors + /// + /// Returns [`SamplerError`] when the runtime is unreadable, free-threaded, + /// or laid out differently. + pub fn verify(&self) -> Result<(), SamplerError> { + let layout = self.layout(); + let Some(debug) = layout.debug else { + return Ok(()); + }; + let base = self.runtime.runtime_address; + let read = |offset: u64, what| { + self.u64_at(base + offset) + .map_err(|error| SamplerError::Read { what, error }) + }; + let mut cookie = [0_u8; 8]; + self.memory + .read(base, &mut cookie) + .map_err(|error| SamplerError::Read { + what: "the _Py_DebugOffsets cookie", + error, + })?; + if &cookie != b"xdebugpy" { + return Err(SamplerError::NotDebugOffsets); + } + if read(16, "the free-threaded flag")? != 0 { + return Err(SamplerError::FreeThreaded); + } + let current_frame = match layout.frame { + FramePath::Direct { tstate_frame } => tstate_frame, + FramePath::CFrame { .. } => return Err(SamplerError::NotDebugOffsets), + }; + for (field, position, expected) in [ + ( + "runtime_state.interpreters_head", + debug.runtime_interpreters_head, + layout.runtime_interpreters_head, + ), + ( + "interpreter_state.threads_head", + debug.interp_threads_head, + layout.interp_threads_head, + ), + ("thread_state.next", debug.tstate_next, layout.tstate_next), + ( + "thread_state.native_thread_id", + debug.tstate_native_thread_id, + layout.tstate_native_thread_id.unwrap_or(u64::MAX), + ), + ( + "thread_state.current_frame", + debug.tstate_current_frame, + current_frame, + ), + ( + "interpreter_frame.previous", + debug.frame_back, + layout.frame_back, + ), + ( + "interpreter_frame.executable", + debug.frame_code, + layout.frame_code, + ), + ( + "interpreter_frame.owner", + debug.frame_owner, + layout.frame_owner.unwrap_or(u64::MAX), + ), + ( + "code_object.filename", + debug.code_filename, + layout.code_filename, + ), + ( + "code_object.qualname", + debug.code_qualname, + layout.code_qualname.unwrap_or(u64::MAX), + ), + ( + "code_object.firstlineno", + debug.code_firstlineno, + layout.code_firstlineno, + ), + ("pyobject.ob_type", debug.object_type, layout.object_type), + ] { + let found = read(position, field)?; + if found != expected { + return Err(SamplerError::LayoutMismatch { + field, + expected, + found, + }); + } + } + Ok(()) + } + + /// The main interpreter. + /// + /// # Errors + /// + /// Returns [`SamplerError`] when the runtime is unreadable or empty. + pub fn interpreter(&self) -> Result { + let interpreter = self + .u64_at(self.runtime.runtime_address + self.layout().runtime_interpreters_head) + .map_err(|error| SamplerError::Read { + what: "the interpreter list", + error, + })?; + if interpreter == 0 { + return Err(SamplerError::NoInterpreter); + } + Ok(interpreter) + } + + /// Thread states of an interpreter. + /// + /// # Errors + /// + /// Returns [`ReadError`] when the thread list is unreadable. + pub fn threads(&self, interpreter: u64) -> Result, ReadError> { + let mut threads = Vec::new(); + let mut thread = self.u64_at(interpreter + self.layout().interp_threads_head)?; + while thread != 0 && threads.len() < MAX_THREADS && !threads.contains(&thread) { + threads.push(thread); + thread = self.u64_at(thread + self.layout().tstate_next)?; + } + Ok(threads) + } + + /// The GIL's holder and handoff count, read at once. + /// + /// # Errors + /// + /// Returns [`ReadError`] when the GIL state is unreadable. + pub fn gil_state(&self, interpreter: u64) -> Result { + let (gil, last_holder, locked, switch_number) = match self.layout().gil { + GilPath::Runtime { + last_holder, + locked, + switch_number, + } => ( + self.runtime.runtime_address, + last_holder, + locked, + switch_number, + ), + GilPath::Interpreter { + interp_gil, + last_holder, + locked, + switch_number, + } => ( + self.u64_at(interpreter + interp_gil)?, + last_holder, + locked, + switch_number, + ), + }; + if gil == 0 { + return Ok(GilState { + holder: None, + last_holder: 0, + switches: 0, + }); + } + // The three fields sit together at the start of the GIL state. + let first = last_holder.min(locked).min(switch_number); + let end = last_holder.max(locked).max(switch_number) + 8; + let mut block = [0_u8; 64]; + let block = block + .get_mut(..usize::try_from(end - first).map_err(|_| ReadError::Fault)?) + .ok_or(ReadError::Fault)?; + self.memory.read(gil + first, block)?; + let field = |offset: u64, width: usize| -> Result { + let start = usize::try_from(offset - first).map_err(|_| ReadError::Fault)?; + let mut bytes = [0_u8; 8]; + bytes[..width] + .copy_from_slice(block.get(start..start + width).ok_or(ReadError::Fault)?); + Ok(u64::from_le_bytes(bytes)) + }; + let holder = field(last_holder, 8)?; + Ok(GilState { + holder: (field(locked, 4)? != 0 && holder != 0).then_some(holder), + last_holder: holder, + switches: field(switch_number, 8)?, + }) + } + + /// The thread state holding the GIL, or `None` while it is released. + /// + /// # Errors + /// + /// Returns [`ReadError`] when the GIL state is unreadable. + pub fn gil_holder(&self, interpreter: u64) -> Result, ReadError> { + Ok(self.gil_state(interpreter)?.holder) + } + + /// What identifies the OS thread behind a thread state: its TID from + /// 3.11, its `pthread_t` before. + fn identity(&self, thread: u64) -> Result { + match self.layout().tstate_native_thread_id { + Some(offset) => self.u64_at(thread + offset), + None => self.pthread(thread), + } + } + + /// The Linux TID a thread state records (3.11+). + /// + /// # Errors + /// + /// Returns [`ReadError`] when the thread state is unreadable. + pub fn native_thread_id(&self, thread: u64) -> Result, ReadError> { + let Some(offset) = self.layout().tstate_native_thread_id else { + return Ok(None); + }; + Ok(u32::try_from(self.u64_at(thread + offset)?).ok()) + } + + /// The `pthread_t` a thread state records. + /// + /// # Errors + /// + /// Returns [`ReadError`] when the thread state is unreadable. + pub fn pthread(&self, thread: u64) -> Result { + self.u64_at(thread + self.layout().tstate_thread_id) + } + + fn top_frame(&self, thread: u64) -> Result { + match self.layout().frame { + FramePath::Direct { tstate_frame } => self.u64_at(thread + tstate_frame), + FramePath::CFrame { + tstate_cframe, + cframe_current_frame, + } => { + let cframe = self.u64_at(thread + tstate_cframe)?; + if cframe == 0 { + return Ok(0); + } + self.u64_at(cframe + cframe_current_frame) + } + } + } + + /// Bytes of a frame the walker reads. + fn frame_bytes(&self) -> u64 { + let layout = self.layout(); + [ + Some(layout.frame_back), + Some(layout.frame_code), + layout.frame_owner, + ] + .into_iter() + .flatten() + .max() + .unwrap_or(0) + + 8 + } + + /// Bytes of a code object the walker reads. + fn code_header_bytes(&self) -> u64 { + let layout = self.layout(); + [ + layout.object_type, + layout.code_filename, + layout.code_name, + layout.code_qualname.unwrap_or(layout.code_name), + ] + .into_iter() + .max() + .unwrap_or(0) + .max(layout.code_firstlineno) + + 8 + } + + /// Read one thread's stack: walk the frames, then read every frame's + /// code object in one batch. + fn stack(&mut self, thread: u64) -> Result { + let layout = self.layout(); + let top = self.top_frame(thread)?; + let frame_bytes = self.frame_bytes(); + // 3.11+ frames sit together on the thread's data stack; read the + // span below the innermost one at once and fall back per frame. + let window = if layout.frame_owner.is_some() && top != 0 { + let start = top.saturating_sub(FRAME_WINDOW_BYTES); + let mut bytes = vec![0_u8; usize::try_from(top - start + frame_bytes).unwrap_or(0)]; + // The window may reach below the data stack's mapping; only a + // fault falls back to per-frame reads. + match self.memory.read(start, &mut bytes) { + Ok(()) => Some((start, bytes)), + Err(ReadError::Fault) => None, + Err(error) => return Err(Discard::Fatal(error)), + } + } else { + None + }; + let mut single = vec![0_u8; usize::try_from(frame_bytes).unwrap_or(usize::MAX)]; + let mut codes = Vec::new(); + let mut frame = top; + let mut visited = 0_usize; + let mut truncated = false; + while frame != 0 { + if codes.len() == self.max_depth || visited > self.max_depth * 2 { + truncated = true; + break; + } + visited += 1; + let bytes: &[u8] = match window.as_ref() { + Some((start, bytes)) + if frame >= *start && frame - start + frame_bytes <= bytes.len() as u64 => + { + let offset = usize::try_from(frame - start).unwrap_or(usize::MAX); + &bytes[offset..] + } + _ => { + self.memory.read(frame, &mut single)?; + &single + } + }; + let field = |offset: u64| { + let start = usize::try_from(offset).unwrap_or(usize::MAX); + u64::from_le_bytes(bytes[start..start + 8].try_into().expect("eight bytes")) + }; + let back = field(layout.frame_back); + // Interpreter entry frames and C-stack shims are not Python code. + let shim = layout + .frame_owner + .zip(layout.first_non_python_owner) + .is_some_and(|(offset, first)| { + bytes[usize::try_from(offset).unwrap_or(usize::MAX)] >= first + }); + if !shim { + let mut code = field(layout.frame_code); + if layout.code_tagged { + code &= !1; + } + codes.push(code); + } + frame = back; + } + let frames = self.codes(&codes)?; + if self.top_frame(thread)? != top { + return Err(Discard::Inconsistent); + } + Ok(Stack { frames, truncated }) + } + + /// Resolve code objects with one batched header read, reusing cached + /// ones whose identifying fields are unchanged. + fn codes(&mut self, addresses: &[u64]) -> Result, Discard> { + let layout = self.layout(); + let mut unique = addresses.to_vec(); + unique.sort_unstable(); + unique.dedup(); + let length = usize::try_from(self.code_header_bytes()).unwrap_or(usize::MAX); + let mut headers = vec![vec![0_u8; length]; unique.len()]; + let mut reads = unique + .iter() + .zip(headers.iter_mut()) + .map(|(address, header)| (*address, header.as_mut_slice())) + .collect::>(); + self.memory.read_many(&mut reads)?; + let mut resolved = HashMap::with_capacity(unique.len()); + for (address, header) in unique.iter().zip(&headers) { + let pointer = |offset: u64| { + let start = usize::try_from(offset).unwrap_or(usize::MAX); + u64::from_le_bytes(header[start..start + 8].try_into().expect("eight bytes")) + }; + if pointer(layout.object_type) != self.runtime.code_type_address { + return Err(Discard::Inconsistent); + } + let start = usize::try_from(layout.code_firstlineno).unwrap_or(usize::MAX); + let first_line = + i32::from_le_bytes(header[start..start + 4].try_into().expect("four bytes")); + let filename = pointer(layout.code_filename); + let name = pointer(layout.code_qualname.unwrap_or(layout.code_name)); + let mut identity = [0_u8; 32]; + identity[0..8].copy_from_slice(&filename.to_le_bytes()); + identity[8..16].copy_from_slice(&name.to_le_bytes()); + identity[16..20].copy_from_slice(&first_line.to_le_bytes()); + let index = match self.by_address.get(address) { + Some((cached, index)) if *cached == identity => *index, + _ => { + let code = Code { + function: self.string(name)?, + file: self.string(filename)?, + first_line: u32::try_from(first_line).unwrap_or(0), + }; + let index = u32::try_from(self.codes.len()).unwrap_or(u32::MAX); + self.codes.push(code); + self.by_address.insert(*address, (identity, index)); + index + } + }; + resolved.insert(*address, index); + } + Ok(addresses.iter().map(|address| resolved[address]).collect()) + } + + /// Decode a compact `str` object. + fn string(&self, address: u64) -> Result { + let layout = self.layout(); + let mut header = vec![0_u8; usize::try_from(layout.compact_size).unwrap_or(usize::MAX)]; + self.memory.read(address, &mut header)?; + let at = |offset: u64, width: usize| { + let start = usize::try_from(offset).unwrap_or(usize::MAX); + header[start..start + width].to_vec() + }; + let state = u32::from_le_bytes(at(layout.ascii_state, 4).try_into().expect("four bytes")); + let length = + u64::from_le_bytes(at(layout.ascii_length, 8).try_into().expect("eight bytes")); + let kind = (state >> 2) & 0b111; + let compact = (state >> 5) & 1 == 1; + let ascii = (state >> 6) & 1 == 1; + if !compact || !matches!(kind, 1 | 2 | 4) || length > MAX_STRING_CHARS { + return Err(Discard::Inconsistent); + } + let data = if ascii { + layout.ascii_size + } else { + layout.compact_size + }; + let width = u64::from(kind); + let mut bytes = vec![0_u8; usize::try_from(length * width).unwrap_or(usize::MAX)]; + self.memory.read(address + data, &mut bytes)?; + let characters: Option = match kind { + 1 => Some(bytes.iter().map(|byte| char::from(*byte)).collect()), + 2 => bytes + .chunks_exact(2) + .map(|unit| char::from_u32(u32::from(u16::from_le_bytes([unit[0], unit[1]])))) + .collect(), + _ => bytes + .chunks_exact(4) + .map(|unit| { + char::from_u32(u32::from_le_bytes([unit[0], unit[1], unit[2], unit[3]])) + }) + .collect(), + }; + characters.ok_or(Discard::Inconsistent) + } + + /// The functions referenced by sample frames. + #[must_use] + pub fn into_codes(self) -> Vec { + self.codes + } +} + +/// Find where `struct pthread` stores its TID (CPython before 3.11 records +/// only `pthread_t`). Every thread state must agree on one offset that maps +/// it to a distinct TID of the target; otherwise threads stay unmapped. +/// +/// A thread that exits during the search leaves it undecided for this sweep. +fn pthread_tid_offset( + walker: &Walker<'_, M>, + threads: &[u64], + tids: &BTreeSet, +) -> Result, ReadError> { + match search_pthread_tid_offset(walker, threads, tids) { + Err(ReadError::Fault) => Ok(None), + other => other, + } +} + +fn search_pthread_tid_offset( + walker: &Walker<'_, M>, + threads: &[u64], + tids: &BTreeSet, +) -> Result, ReadError> { + let mut candidates: Option> = None; + for thread in threads { + let pthread = walker.pthread(*thread)?; + let mut bytes = vec![0_u8; PTHREAD_SEARCH_BYTES]; + walker.memory.read(pthread, &mut bytes)?; + let found = bytes + .chunks_exact(4) + .zip((0_u64..).step_by(4)) + .filter(|(word, _)| { + tids.contains(&u32::from_le_bytes([word[0], word[1], word[2], word[3]])) + }) + .map(|(_, offset)| offset) + .collect::>(); + candidates = Some(match candidates { + None => found, + Some(previous) => previous.intersection(&found).copied().collect(), + }); + } + // Keep offsets that map every thread to a distinct TID; several are + // acceptable only when they agree on every thread. + let mut chosen: Option<(u64, Vec)> = None; + for offset in candidates.unwrap_or_default() { + let mapped = threads + .iter() + .map(|thread| walker.u32_at(walker.pthread(*thread)? + offset)) + .collect::, _>>()?; + if mapped.iter().collect::>().len() != threads.len() { + continue; + } + match &chosen { + None => chosen = Some((offset, mapped)), + Some((_, previous)) if *previous == mapped => {} + Some(_) => return Ok(None), + } + } + Ok(chosen.map(|(offset, _)| offset)) +} + +/// When and how much to sample. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SamplerConfig { + pub duration: Duration, + /// Period of GIL-holder samples, or `None` to sample only all threads. + pub gil_period: Option, + /// Period of samples of every thread. + pub threads_period: Duration, + pub max_samples: usize, + pub max_depth: usize, +} + +fn monotonic_ns() -> Result { + let now = clock_gettime(ClockId::CLOCK_MONOTONIC) + .map_err(|error| SamplerError::Clock(error.to_string()))?; + let seconds = + u64::try_from(now.tv_sec()).map_err(|error| SamplerError::Clock(error.to_string()))?; + let nanoseconds = + u64::try_from(now.tv_nsec()).map_err(|error| SamplerError::Clock(error.to_string()))?; + Ok(seconds * 1_000_000_000 + nanoseconds) +} + +/// The target's TIDs. A thread that exits mid-listing is skipped; a target +/// that is gone or unreadable is an error. +fn task_ids(pid: u32) -> Result, SamplerError> { + let failure = |error: &std::io::Error| SamplerError::Read { + what: "the target's thread list", + error: match error.kind() { + std::io::ErrorKind::NotFound => ReadError::Gone, + std::io::ErrorKind::PermissionDenied => ReadError::Permission, + _ => ReadError::Other(error.raw_os_error().unwrap_or(0)), + }, + }; + let mut tids = BTreeSet::new(); + for entry in fs::read_dir(format!("/proc/{pid}/task")).map_err(|error| failure(&error))? { + let entry = entry.map_err(|error| failure(&error))?; + if let Some(tid) = entry + .file_name() + .to_str() + .and_then(|name| name.parse().ok()) + { + tids.insert(tid); + } + } + Ok(tids) +} + +struct Run<'w, 'm, M: RemoteMemory> { + walker: &'w mut Walker<'m, M>, + pid: u32, + interpreter: u64, + config: SamplerConfig, + capture: PythonCapture, + /// Where `struct pthread` stores the TID, once found (before 3.11). + pthread_offset: Option, +} + +impl Run<'_, '_, M> { + /// Sample one thread's stack. A GIL sample passes the GIL state it saw; + /// the sample is kept only if no other thread took the GIL meanwhile, + /// and any sample only if its thread state named one OS thread + /// throughout, since an exited thread's state can be reused. + fn read(&mut self, thread: u64, gil: Option) -> Result<(), SamplerError> { + if self.capture.samples.len() >= self.config.max_samples { + self.capture.counters.over_capacity += 1; + return Ok(()); + } + let timestamp_ns = monotonic_ns()?; + let started = Instant::now(); + let outcome = self.consistent_stack(thread, gil); + let (stack, tid) = match outcome { + Ok(read) => read, + Err(Discard::Inconsistent) => { + self.capture.counters.inconsistent += 1; + return Ok(()); + } + Err(Discard::Fatal(error)) => { + return Err(SamplerError::Read { + what: "a thread stack", + error, + }); + } + }; + self.capture + .read_ns + .push(u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX)); + self.capture.threads.extend(tid); + // The GIL holder runs Python; a swept thread may be blocked. + let native = match tid.filter(|_| gil.is_none()) { + Some(tid) => self.native_leaf(tid), + None => None, + }; + self.capture.samples.push(PythonSample { + timestamp_ns, + tid, + gil: gil.is_some(), + stack, + native, + }); + Ok(()) + } + + fn consistent_stack( + &mut self, + thread: u64, + gil: Option, + ) -> Result<(Stack, Option), Discard> { + let identity = self.identity(thread)?; + let stack = self.walker.stack(thread)?; + if let Some(before) = gil { + // Another thread taking the GIL during the read, even if it came + // back, makes part of it that thread's time. The holder dropping + // and retaking it does not count as a switch. + let after = self.walker.gil_state(self.interpreter)?; + if after.last_holder != thread || after.switches != before.switches { + return Err(Discard::Inconsistent); + } + } + if self.identity(thread)? != identity { + return Err(Discard::Inconsistent); + } + Ok((stack, identity.1)) + } + + /// The OS thread behind a thread state: what the thread state records + /// (its TID from 3.11, its `pthread_t` before) and the TID it maps to. + /// Before 3.11 the TID is read through the `pthread_t` each time, since + /// an exited thread's `struct pthread` can be reused. + fn identity(&self, thread: u64) -> Result<(u64, Option), Discard> { + let recorded = self.walker.identity(thread)?; + if self.walker.layout().tstate_native_thread_id.is_some() { + return Ok(( + recorded, + u32::try_from(recorded).ok().filter(|tid| *tid != 0), + )); + } + match self.pthread_offset { + Some(offset) => Ok((recorded, Some(self.walker.u32_at(recorded + offset)?))), + None => Ok((recorded, None)), + } + } + + /// Where a blocked thread waits; an unreadable or unparsable state is + /// counted rather than mistaken for a running thread. + fn native_leaf(&mut self, tid: u32) -> Option { + let Ok(text) = fs::read_to_string(format!("/proc/{}/task/{tid}/syscall", self.pid)) else { + self.capture.counters.native_unreadable += 1; + return None; + }; + let leaf = parse_task_syscall(&text); + if leaf.is_none() && text.trim() != "running" { + self.capture.counters.native_unreadable += 1; + } + leaf + } + + /// Refresh the thread list and its TIDs, then sample every thread. + fn sweep(&mut self) -> Result<(), SamplerError> { + let threads = + self.walker + .threads(self.interpreter) + .map_err(|error| SamplerError::Read { + what: "the thread list", + error, + })?; + // Until an offset is found, every sweep searches again. + if self.walker.layout().tstate_native_thread_id.is_none() && self.pthread_offset.is_none() { + self.pthread_offset = pthread_tid_offset(self.walker, &threads, &task_ids(self.pid)?) + .map_err(|error| SamplerError::Read { + what: "a thread's pthread", + error, + })?; + self.capture.tid_source = self + .pthread_offset + .map_or(TidSource::Unmapped, TidSource::Pthread); + } + self.capture.counters.thread_sweeps += 1; + for thread in threads { + self.read(thread, None)?; + } + Ok(()) + } +} + +/// Sample a CPython process for `config.duration`. +/// +/// # Errors +/// +/// Returns [`SamplerError`] when the runtime cannot be read or verified, the +/// target denies access, or it exits. +pub fn sample( + walker: &mut Walker<'_, M>, + pid: u32, + config: SamplerConfig, +) -> Result { + walker.verify()?; + let interpreter = walker.interpreter()?; + let native_tids = walker.layout().tstate_native_thread_id.is_some(); + let mut run = Run { + walker, + pid, + interpreter, + config, + capture: PythonCapture { + samples: Vec::new(), + codes: Vec::new(), + counters: SamplerCounters::default(), + read_ns: Vec::new(), + elapsed: Duration::ZERO, + tid_source: if native_tids { + TidSource::Native + } else { + TidSource::Unmapped + }, + threads: BTreeSet::new(), + }, + pthread_offset: None, + }; + let start = Instant::now(); + let end = start + config.duration; + let mut next_sweep = start; + let mut next_gil = start; + loop { + let now = Instant::now(); + if now >= end { + break; + } + if now >= next_sweep { + run.sweep()?; + next_sweep = advance( + next_sweep, + config.threads_period, + now, + &mut run.capture.counters, + ); + } + if let Some(period) = config.gil_period + && now >= next_gil + { + run.capture.counters.gil_ticks += 1; + match run.walker.gil_state(interpreter) { + Ok( + state @ GilState { + holder: Some(holder), + .. + }, + ) => run.read(holder, Some(state))?, + Ok(GilState { holder: None, .. }) => run.capture.counters.gil_idle += 1, + Err(ReadError::Fault) => run.capture.counters.inconsistent += 1, + Err(error) => { + return Err(SamplerError::Read { + what: "the GIL", + error, + }); + } + } + next_gil = advance(next_gil, period, now, &mut run.capture.counters); + } + let wake = config + .gil_period + .map_or(next_sweep, |_| next_gil.min(next_sweep)) + .min(end); + let now = Instant::now(); + if wake > now { + thread::sleep(wake - now); + } + } + let mut capture = run.capture; + capture.elapsed = start.elapsed(); + capture.codes = std::mem::take(&mut run.walker.codes); + Ok(capture) +} + +/// The next deadline after `deadline`; a missed one restarts from now +/// instead of bursting to catch up. +fn advance( + deadline: Instant, + period: Duration, + now: Instant, + counters: &mut SamplerCounters, +) -> Instant { + let next = deadline + period; + if next <= now { + counters.late_ticks += 1; + now + period + } else { + next + } +} + +#[cfg(test)] +mod tests { + use std::cell::RefCell; + use std::collections::BTreeMap; + use std::path::PathBuf; + + use xprobe_core::python_layout::{PythonRuntime, layout}; + + use super::{Code, Discard, ReadError, RemoteMemory, Walker}; + + /// Sparse little-endian memory; unmapped reads fault. + #[derive(Default)] + struct Memory { + bytes: RefCell>, + } + + impl Memory { + fn put(&self, address: u64, bytes: &[u8]) { + let mut memory = self.bytes.borrow_mut(); + for (offset, byte) in bytes.iter().enumerate() { + memory.insert(address + offset as u64, *byte); + } + } + + fn u64(&self, address: u64, value: u64) { + self.put(address, &value.to_le_bytes()); + } + + /// A compact string object with CPython's narrowest kind. + fn string(&self, address: u64, minor: u8, text: &str) { + let layout = layout(minor).unwrap(); + let ascii = text.is_ascii(); + let widest = text.chars().map(u32::from).max().unwrap_or(0); + let kind: u32 = match widest { + 0..=0xff => 1, + 0x100..=0xffff => 2, + _ => 4, + }; + let state = (kind << 2) | (1 << 5) | (u32::from(ascii) << 6); + self.put( + address, + &vec![0; usize::try_from(layout.compact_size).unwrap()], + ); + self.u64(address + layout.ascii_length, text.chars().count() as u64); + self.put(address + layout.ascii_state, &state.to_le_bytes()); + let data = if ascii { + layout.ascii_size + } else { + layout.compact_size + }; + let encoded: Vec = match kind { + 1 => text + .chars() + .map(|c| u8::try_from(u32::from(c)).unwrap()) + .collect(), + 2 => text.encode_utf16().flat_map(u16::to_le_bytes).collect(), + _ => text + .chars() + .flat_map(|c| u32::from(c).to_le_bytes()) + .collect(), + }; + self.put(address + data, &encoded); + } + + /// A code object with zeroed fields up to its qualname. + fn code( + &self, + address: u64, + minor: u8, + names: (u64, u64), + first_line: i32, + code_type: u64, + ) { + let layout = layout(minor).unwrap(); + self.put(address, &[0; 144]); + self.u64(address + layout.object_type, code_type); + self.u64(address + layout.code_filename, names.0); + self.u64(address + layout.code_name, names.1); + if let Some(qualname) = layout.code_qualname { + self.u64(address + qualname, names.1); + } + self.put(address + layout.code_firstlineno, &first_line.to_le_bytes()); + } + } + + impl RemoteMemory for Memory { + fn read(&self, address: u64, out: &mut [u8]) -> Result<(), ReadError> { + let memory = self.bytes.borrow(); + for (offset, byte) in out.iter_mut().enumerate() { + *byte = *memory + .get(&(address + offset as u64)) + .ok_or(ReadError::Fault)?; + } + Ok(()) + } + } + + const CODE_TYPE: u64 = 0x9000; + + fn runtime(minor: u8) -> PythonRuntime { + PythonRuntime { + binary: PathBuf::from("/usr/bin/python3"), + minor, + layout: layout(minor).unwrap(), + runtime_address: 0x1000, + code_type_address: CODE_TYPE, + } + } + + /// A 3.12 interpreter whose one thread holds the GIL and runs + /// `outer -> -> inner`. + fn python_312() -> Memory { + let layout = layout(12).unwrap(); + let memory = Memory::default(); + memory.u64(0x1000 + layout.runtime_interpreters_head, 0x2000); + memory.u64(0x2000 + layout.interp_threads_head, 0x3000); + memory.u64(0x3000 + layout.tstate_next, 0); + memory.u64(0x3000 + layout.tstate_native_thread_id.unwrap(), 4242); + memory.u64(0x3000 + 56, 0x3100); + memory.u64(0x3100, 0x4000); + memory.u64(0x2000 + 384, 0x7000); + memory.u64(0x7000 + 8, 0x3000); + memory.put(0x7000 + 16, &[1, 0, 0, 0, 0, 0, 0, 0]); + memory.u64(0x7000 + 24, 5); + for (frame, code, back, owner) in [ + (0x4000, 0x5000, 0x4100, 0_u8), + (0x4100, 0, 0x4200, 3), + (0x4200, 0x5100, 0, 0), + ] { + memory.put(frame, &[0; 80]); + memory.u64(frame + layout.frame_code, code); + memory.u64(frame + layout.frame_back, back); + memory.put(frame + layout.frame_owner.unwrap(), &[owner]); + } + memory.code(0x5000, 12, (0x6000, 0x6100), 10, CODE_TYPE); + memory.code(0x5100, 12, (0x6000, 0x6200), 3, CODE_TYPE); + memory.string(0x6000, 12, "app.py"); + memory.string(0x6100, 12, "inner"); + memory.string(0x6200, 12, "Model.forward"); + memory + } + + #[test] + fn walks_a_312_stack_and_skips_shim_frames() { + let memory = python_312(); + let mut walker = Walker::new(&memory, runtime(12), 64); + let interpreter = walker.interpreter().unwrap(); + assert_eq!(walker.threads(interpreter).unwrap(), [0x3000]); + assert_eq!(walker.gil_holder(interpreter).unwrap(), Some(0x3000)); + assert_eq!(walker.native_thread_id(0x3000).unwrap(), Some(4242)); + + let stack = walker.stack(0x3000).unwrap(); + assert_eq!(stack.frames.len(), 2); + assert!(!stack.truncated); + // Reading again reuses the resolved code objects. + assert_eq!(walker.stack(0x3000).unwrap(), stack); + let codes = walker.into_codes(); + assert_eq!( + codes, + [ + Code { + function: "inner".to_owned(), + file: "app.py".to_owned(), + first_line: 10 + }, + Code { + function: "Model.forward".to_owned(), + file: "app.py".to_owned(), + first_line: 3 + }, + ] + ); + } + + #[test] + fn reads_data_stack_frames_in_one_window() { + // Frames grow upward on a thread's data stack: the innermost frame + // is highest and its callers sit below it inside one window. + let layout = layout(12).unwrap(); + let memory = python_312(); + memory.put(0x10000 - super::FRAME_WINDOW_BYTES, &vec![0; 0x4100]); + memory.u64(0x3100, 0x10000); + for (frame, code, back) in [(0x10000, 0x5000, 0xff00), (0xff00, 0x5100, 0)] { + memory.u64(frame + layout.frame_code, code); + memory.u64(frame + layout.frame_back, back); + } + let mut walker = Walker::new(&memory, runtime(12), 64); + assert_eq!(walker.stack(0x3000).unwrap().frames, [0, 1]); + } + + #[test] + fn a_released_gil_has_no_holder() { + let memory = python_312(); + memory.put(0x7000 + 16, &0_u32.to_le_bytes()); + let walker = Walker::new(&memory, runtime(12), 64); + assert_eq!(walker.gil_holder(0x2000).unwrap(), None); + } + + fn run<'w, 'm>(walker: &'w mut Walker<'m, Memory>) -> super::Run<'w, 'm, Memory> { + let interpreter = walker.interpreter().unwrap(); + super::Run { + walker, + pid: 1, + interpreter, + config: super::SamplerConfig { + duration: std::time::Duration::from_secs(1), + gil_period: None, + threads_period: std::time::Duration::from_secs(1), + max_samples: 16, + max_depth: 64, + }, + capture: xprobe_core::python_sampling::PythonCapture { + samples: Vec::new(), + codes: Vec::new(), + counters: xprobe_core::python_sampling::SamplerCounters::default(), + read_ns: Vec::new(), + elapsed: std::time::Duration::ZERO, + tid_source: xprobe_core::python_sampling::TidSource::Native, + threads: std::collections::BTreeSet::new(), + }, + pthread_offset: None, + } + } + + #[test] + fn a_gil_sample_needs_the_same_holder_throughout() { + let memory = python_312(); + let mut walker = Walker::new(&memory, runtime(12), 64); + let before = walker.gil_state(0x2000).unwrap(); + assert_eq!((before.holder, before.switches), (Some(0x3000), 5)); + let mut run = run(&mut walker); + run.read(0x3000, Some(before)).unwrap(); + assert_eq!(run.capture.samples.len(), 1); + assert_eq!(run.capture.samples[0].tid, Some(4242)); + + // The holder released the GIL during the read without a switch. + memory.put(0x7000 + 16, &[0, 0, 0, 0, 0, 0, 0, 0]); + run.read(0x3000, Some(before)).unwrap(); + assert_eq!(run.capture.samples.len(), 2); + + // The GIL went to another thread and came back during the read. + run.read( + 0x3000, + Some(super::GilState { + switches: 3, + ..before + }), + ) + .unwrap(); + assert_eq!(run.capture.samples.len(), 2); + assert_eq!(run.capture.counters.inconsistent, 1); + } + + #[test] + fn torn_stacks_are_discarded() { + // A frame whose code pointer no longer points at a code object. + let memory = python_312(); + memory.u64(0x5100 + 8, 0xdead); + let mut walker = Walker::new(&memory, runtime(12), 64); + assert_eq!(walker.stack(0x3000), Err(Discard::Inconsistent)); + + // A frame freed while it was read. + let memory = python_312(); + memory.u64(0x4200 + layout(12).unwrap().frame_back, 0xbad0); + let mut walker = Walker::new(&memory, runtime(12), 64); + assert_eq!(walker.stack(0x3000), Err(Discard::Inconsistent)); + } + + #[test] + fn deep_stacks_are_truncated_at_the_depth_bound() { + let memory = python_312(); + let mut walker = Walker::new(&memory, runtime(12), 1); + let stack = walker.stack(0x3000).unwrap(); + assert_eq!(stack.frames.len(), 1); + assert!(stack.truncated); + } + + #[test] + fn decodes_every_string_kind() { + // Latin-1 (one byte but not ASCII), UCS-2, and UCS-4. + let memory = Memory::default(); + memory.string(0x6000, 10, "naรฏve_step"); + memory.string(0x7000, 12, "ๆŽจ็†"); + memory.string(0x8000, 13, "step_๐Ÿš€"); + for (address, minor, text) in [ + (0x6000, 10, "naรฏve_step"), + (0x7000, 12, "ๆŽจ็†"), + (0x8000, 13, "step_๐Ÿš€"), + ] { + let walker = Walker::new(&memory, runtime(minor), 1); + assert_eq!(walker.string(address).unwrap(), text); + } + } + + #[test] + fn walks_a_310_frame_chain() { + let layout = layout(10).unwrap(); + let memory = Memory::default(); + memory.u64(0x3000 + 24, 0x4000); + for (frame, code, back) in [(0x4000, 0x5000, 0x4100), (0x4100, 0x5100, 0)] { + memory.put(frame, &[0; 48]); + memory.u64(frame + layout.frame_code, code); + memory.u64(frame + layout.frame_back, back); + } + memory.code(0x5000, 10, (0x6000, 0x6100), 7, CODE_TYPE); + memory.code(0x5100, 10, (0x6000, 0x6200), 1, CODE_TYPE); + memory.string(0x6000, 10, "train.py"); + memory.string(0x6100, 10, "step"); + memory.string(0x6200, 10, ""); + let mut walker = Walker::new(&memory, runtime(10), 64); + assert_eq!(walker.stack(0x3000).unwrap().frames, [0, 1]); + let codes = walker.into_codes(); + assert_eq!(codes[0].function, "step"); + assert_eq!(codes[1].function, ""); + } +} diff --git a/xprobe/core/src/clock.rs b/xprobe/core/src/clock.rs new file mode 100644 index 0000000..9b7934e --- /dev/null +++ b/xprobe/core/src/clock.rs @@ -0,0 +1,80 @@ +//! Host clock readings shared with captured event timestamps. + +use nix::time::{ClockId, clock_gettime}; + +/// Current `CLOCK_MONOTONIC` time in nanoseconds, the clock host events and +/// normalized CUPTI timestamps use. +/// +/// # Errors +/// +/// Returns the `clock_gettime` failure. +pub fn monotonic_ns() -> Result { + let now = clock_gettime(ClockId::CLOCK_MONOTONIC)?; + // CLOCK_MONOTONIC is non-negative and fits u64 nanoseconds for centuries. + let seconds = u64::try_from(now.tv_sec()).map_err(|_| nix::Error::EOVERFLOW)?; + let nanoseconds = u64::try_from(now.tv_nsec()).map_err(|_| nix::Error::EOVERFLOW)?; + seconds + .checked_mul(1_000_000_000) + .and_then(|value| value.checked_add(nanoseconds)) + .ok_or(nix::Error::EOVERFLOW) +} + +/// Reads of each clock pair; the tightest bracket is kept. +const ANCHOR_READS: usize = 5; + +fn realtime_ns() -> Result { + let now = clock_gettime(ClockId::CLOCK_REALTIME)?; + let seconds = u64::try_from(now.tv_sec()).map_err(|_| nix::Error::EOVERFLOW)?; + let nanoseconds = u64::try_from(now.tv_nsec()).map_err(|_| nix::Error::EOVERFLOW)?; + seconds + .checked_mul(1_000_000_000) + .and_then(|value| value.checked_add(nanoseconds)) + .ok_or(nix::Error::EOVERFLOW) +} + +/// `CLOCK_REALTIME` against `CLOCK_MONOTONIC`: the wall clock is read between +/// two monotonic reads, and the tightest of a few brackets is kept. +/// +/// # Errors +/// +/// Returns the `clock_gettime` failure. +pub fn clock_anchor() -> Result { + let read = || -> Result { + let before = monotonic_ns()?; + let realtime = realtime_ns()?; + let after = monotonic_ns()?; + Ok(xprobe_protocol::ClockAnchor { + monotonic_ns: before + (after - before) / 2, + realtime_ns: realtime, + uncertainty_ns: (after - before).div_ceil(2), + }) + }; + let mut best = read()?; + for _ in 1..ANCHOR_READS { + let anchor = read()?; + if anchor.uncertainty_ns < best.uncertainty_ns { + best = anchor; + } + } + Ok(best) +} + +#[cfg(test)] +mod tests { + #[test] + fn anchors_pair_wall_time_with_monotonic_time() { + let anchor = super::clock_anchor().unwrap(); + let later = super::monotonic_ns().unwrap(); + assert!(anchor.monotonic_ns <= later); + // Some time after 2020 and a bracket well under a millisecond. + assert!(anchor.realtime_ns > 1_577_836_800_000_000_000); + assert!(anchor.uncertainty_ns < 1_000_000); + } + + #[test] + fn monotonic_time_advances() { + let first = super::monotonic_ns().unwrap(); + let second = super::monotonic_ns().unwrap(); + assert!(first > 0 && second >= first); + } +} diff --git a/xprobe/core/src/cpu_sampling_analysis.rs b/xprobe/core/src/cpu_sampling_analysis.rs index 515b108..32354c2 100644 --- a/xprobe/core/src/cpu_sampling_analysis.rs +++ b/xprobe/core/src/cpu_sampling_analysis.rs @@ -174,6 +174,22 @@ struct Symbolizer { warnings: Vec, } +/// Resolve native addresses of a live process to their module and symbol. +/// +/// # Errors +/// +/// Returns [`CpuAnalysisError`] when the process mappings are unreadable. +pub fn symbolize_native( + report: &ProcessReport, + addresses: &BTreeSet, +) -> Result, CpuAnalysisError> { + let symbolizer = Symbolizer::load(report, PythonSymbolizationStatus::NotDetected, addresses)?; + Ok(addresses + .iter() + .map(|address| (*address, symbolizer.symbolize(*address))) + .collect()) +} + /// Aggregate and symbolize one completed bounded CPU capture. /// /// # Errors diff --git a/xprobe/core/src/gpu_aggregate.rs b/xprobe/core/src/gpu_aggregate.rs index a4a7613..5e7115d 100644 --- a/xprobe/core/src/gpu_aggregate.rs +++ b/xprobe/core/src/gpu_aggregate.rs @@ -128,6 +128,7 @@ pub fn analyze( groups, }, collection: AggregateCollectionSummary { + cuda_devices: Vec::new(), completeness: CaptureCompleteness::Complete, observed_activities: capture.observed_activities, grouped_activities, diff --git a/xprobe/core/src/graph.rs b/xprobe/core/src/graph.rs index 286dfcc..2c0a931 100644 --- a/xprobe/core/src/graph.rs +++ b/xprobe/core/src/graph.rs @@ -1,12 +1,16 @@ //! Read-only validation of multi-edge measurement graphs. -use std::{collections::BTreeSet, error::Error, fmt}; +use std::{ + collections::{BTreeMap, BTreeSet}, + error::Error, + fmt, +}; use xprobe_protocol::{ AgentActivation, ErrorCode, GRAPH_MAX_CUDA_FILTERS, GRAPH_MAX_EDGES, GRAPH_MAX_ENDPOINTS, GRAPH_MAX_LINUX_ENDPOINTS, GraphEdgeValidation, GraphEndpointValidation, GraphIssueScope, GraphValidationIssue, MatchPolicy, MeasurementGraphSpec, MeasurementGraphValidationResult, - ProcessReport, SchemaVersion3, ValidatedEndpoint, ValidationRequirements, + ProcessReport, SchemaVersion3, ValidatedEndpoint, ValidationRequirements, activity_boundary, }; use crate::{ @@ -148,7 +152,11 @@ pub fn run( .iter() .map(|endpoint| &endpoint.endpoint) .collect::>(); - issues.extend(slot_issues(&public)); + let stream_order = spec + .edges + .iter() + .any(|edge| edge.match_policy == MatchPolicy::StreamOrder); + issues.extend(slot_issues(&public, stream_order)); warnings.dedup_by(|left, right| left.code == right.code && left.message == right.message); inspect::verify_target(&report.target)?; Ok(MeasurementGraphValidationResult { @@ -258,7 +266,44 @@ fn structural_issues( } /// Syscall, tracepoint, and USDT endpoints share the Linux collector's slots. -fn slot_issues(endpoints: &[&ValidatedEndpoint]) -> Vec { +/// Agent filters stream order uses to record every kernel, copy, and memset. +pub const STREAM_ORDER_FILTERS: usize = 6; + +/// Agent filters a capture of these endpoints needs. Identical selectors share +/// a filter, `cuda:launch_api` needs two, and stream order replaces every +/// activity endpoint with unfiltered start and end filters for each of the +/// three activity families. +#[must_use] +pub fn cuda_filter_slots(endpoints: &[&ValidatedEndpoint], stream_order: bool) -> usize { + let selectors = endpoints + .iter() + .filter_map(|endpoint| { + endpoint + .cuda + .as_ref() + .map(|cuda| (endpoint.selector.as_str(), cuda)) + }) + .collect::>(); + let endpoint_filters = selectors + .values() + .filter(|cuda| !stream_order || activity_boundary(&cuda.event_type).is_none()) + .map(|cuda| { + if cuda.api_domain.as_deref() == Some("launch_api") { + 2 + } else { + 1 + } + }) + .sum::(); + endpoint_filters + + if stream_order { + STREAM_ORDER_FILTERS + } else { + 0 + } +} + +fn slot_issues(endpoints: &[&ValidatedEndpoint], stream_order: bool) -> Vec { let slot_issue = |message| GraphValidationIssue { scope: GraphIssueScope::Graph, name: None, @@ -277,20 +322,10 @@ fn slot_issues(endpoints: &[&ValidatedEndpoint]) -> Vec { linux.len() ))); } - let cuda_filters = endpoints - .iter() - .filter_map(|endpoint| endpoint.cuda.as_ref()) - .map(|cuda| { - if cuda.api_domain.as_deref() == Some("launch_api") { - 2 - } else { - 1 - } - }) - .sum::(); + let cuda_filters = cuda_filter_slots(endpoints, stream_order); if cuda_filters > GRAPH_MAX_CUDA_FILTERS { issues.push(slot_issue(format!( - "CUDA endpoints need {cuda_filters} Agent filters; a graph supports at most {GRAPH_MAX_CUDA_FILTERS} (cuda:launch_api uses two)" + "CUDA endpoints need {cuda_filters} Agent filters; a graph supports at most {GRAPH_MAX_CUDA_FILTERS} (cuda:launch_api uses two, and stream order uses {STREAM_ORDER_FILTERS} for all activity)" ))); } issues diff --git a/xprobe/core/src/lib.rs b/xprobe/core/src/lib.rs index 2c691ec..cfe7dc7 100644 --- a/xprobe/core/src/lib.rs +++ b/xprobe/core/src/lib.rs @@ -1,6 +1,7 @@ //! Measurement orchestration and domain logic for xprobe. pub mod cgroup_cpu; +pub mod clock; pub mod cpu_sampling; pub mod cpu_sampling_analysis; pub mod cupti_compat; @@ -11,6 +12,8 @@ pub mod gpu_health; pub mod graph; pub mod inject; pub mod inspect; +pub mod python_layout; +pub mod python_sampling; pub mod resolve; pub mod syscall_aggregate; pub mod thread_time; diff --git a/xprobe/core/src/python_layout.rs b/xprobe/core/src/python_layout.rs new file mode 100644 index 0000000..e05288a --- /dev/null +++ b/xprobe/core/src/python_layout.rs @@ -0,0 +1,707 @@ +//! CPython interpreter layouts and where they live in a target process. +//! +//! An external sampler reads interpreter state with `process_vm_readv`. The +//! offsets below come from compiling `tests/integration/python-layout/layout.c` +//! against each minor version's internal headers; a unit test pins this table +//! to that fixture and a live test regenerates the fixture from real headers. +//! CPython 3.13 and newer also describe their own layout in +//! `_Py_DebugOffsets`, which the sampler checks against this table at runtime. + +use std::{ + error::Error, + fmt, fs, + path::{Path, PathBuf}, +}; + +use object::{Object, ObjectSegment, ObjectSymbol}; +use xprobe_protocol::ProcessReport; + +/// How a thread state reaches its innermost frame. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FramePath { + /// `tstate->frame` (3.9, 3.10) or `tstate->current_frame` (3.13+). + Direct { tstate_frame: u64 }, + /// `tstate->cframe->current_frame` (3.11, 3.12). + CFrame { + tstate_cframe: u64, + cframe_current_frame: u64, + }, +} + +/// Where the GIL records its holder. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GilPath { + /// Inside `_PyRuntime` (3.9โ€“3.11). + Runtime { + last_holder: u64, + locked: u64, + /// Counts GIL handoffs; a change during a read means another thread + /// held the GIL in between. + switch_number: u64, + }, + /// Behind `interp->ceval.gil` (3.12+). + Interpreter { + interp_gil: u64, + last_holder: u64, + locked: u64, + switch_number: u64, + }, +} + +/// Positions of checked fields inside `_Py_DebugOffsets` (3.13+). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DebugOffsetsLayout { + pub version: u64, + pub runtime_interpreters_head: u64, + pub interp_threads_head: u64, + pub tstate_next: u64, + pub tstate_native_thread_id: u64, + pub tstate_current_frame: u64, + pub frame_back: u64, + pub frame_code: u64, + pub frame_owner: u64, + pub code_filename: u64, + pub code_qualname: u64, + pub code_firstlineno: u64, + pub object_type: u64, +} + +/// Offsets the sampler reads for one CPython minor version (release builds, +/// 64-bit, with the GIL). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PythonLayout { + pub minor: u8, + pub runtime_interpreters_head: u64, + pub gil: GilPath, + pub interp_threads_head: u64, + pub tstate_next: u64, + pub tstate_thread_id: u64, + /// Present from 3.11; older versions map `pthread_t` to a TID. + pub tstate_native_thread_id: Option, + pub frame: FramePath, + pub frame_back: u64, + pub frame_code: u64, + /// `_PyInterpreterFrame.owner` (3.11+), one byte. + pub frame_owner: Option, + /// Frames owned by this value or above are interpreter entry or C-stack + /// shims, not Python frames (3.12+). + pub first_non_python_owner: Option, + /// The code reference is a tagged `_PyStackRef` (3.14+). + pub code_tagged: bool, + pub code_filename: u64, + pub code_name: u64, + pub code_qualname: Option, + pub code_firstlineno: u64, + pub object_type: u64, + pub ascii_length: u64, + pub ascii_state: u64, + pub ascii_size: u64, + pub compact_size: u64, + pub debug: Option, +} + +const PRE_311_STRINGS: (u64, u64, u64, u64) = (16, 32, 48, 72); +const POST_312_STRINGS: (u64, u64, u64, u64) = (16, 32, 40, 56); + +const LAYOUTS: [PythonLayout; 6] = [ + PythonLayout { + minor: 9, + runtime_interpreters_head: 32, + gil: GilPath::Runtime { + last_holder: 360, + locked: 368, + switch_number: 376, + }, + interp_threads_head: 8, + tstate_next: 8, + tstate_thread_id: 176, + tstate_native_thread_id: None, + frame: FramePath::Direct { tstate_frame: 24 }, + frame_back: 24, + frame_code: 32, + frame_owner: None, + first_non_python_owner: None, + code_tagged: false, + code_filename: 104, + code_name: 112, + code_qualname: None, + code_firstlineno: 40, + object_type: 8, + ascii_length: PRE_311_STRINGS.0, + ascii_state: PRE_311_STRINGS.1, + ascii_size: PRE_311_STRINGS.2, + compact_size: PRE_311_STRINGS.3, + debug: None, + }, + PythonLayout { + minor: 10, + runtime_interpreters_head: 32, + gil: GilPath::Runtime { + last_holder: 360, + locked: 368, + switch_number: 376, + }, + interp_threads_head: 8, + tstate_next: 8, + tstate_thread_id: 176, + tstate_native_thread_id: None, + frame: FramePath::Direct { tstate_frame: 24 }, + frame_back: 24, + frame_code: 32, + frame_owner: None, + first_non_python_owner: None, + code_tagged: false, + code_filename: 104, + code_name: 112, + code_qualname: None, + code_firstlineno: 40, + object_type: 8, + ascii_length: PRE_311_STRINGS.0, + ascii_state: PRE_311_STRINGS.1, + ascii_size: PRE_311_STRINGS.2, + compact_size: PRE_311_STRINGS.3, + debug: None, + }, + PythonLayout { + minor: 11, + runtime_interpreters_head: 40, + gil: GilPath::Runtime { + last_holder: 368, + locked: 376, + switch_number: 384, + }, + interp_threads_head: 16, + tstate_next: 8, + tstate_thread_id: 152, + tstate_native_thread_id: Some(160), + frame: FramePath::CFrame { + tstate_cframe: 56, + cframe_current_frame: 8, + }, + frame_back: 48, + frame_code: 32, + frame_owner: Some(69), + first_non_python_owner: None, + code_tagged: false, + code_filename: 112, + code_name: 120, + code_qualname: Some(128), + code_firstlineno: 72, + object_type: 8, + ascii_length: PRE_311_STRINGS.0, + ascii_state: PRE_311_STRINGS.1, + ascii_size: PRE_311_STRINGS.2, + compact_size: PRE_311_STRINGS.3, + debug: None, + }, + PythonLayout { + minor: 12, + runtime_interpreters_head: 40, + gil: GilPath::Interpreter { + interp_gil: 384, + last_holder: 8, + locked: 16, + switch_number: 24, + }, + interp_threads_head: 72, + tstate_next: 8, + tstate_thread_id: 136, + tstate_native_thread_id: Some(144), + frame: FramePath::CFrame { + tstate_cframe: 56, + cframe_current_frame: 0, + }, + frame_back: 8, + frame_code: 0, + frame_owner: Some(70), + first_non_python_owner: Some(3), + code_tagged: false, + code_filename: 112, + code_name: 120, + code_qualname: Some(128), + code_firstlineno: 68, + object_type: 8, + ascii_length: POST_312_STRINGS.0, + ascii_state: POST_312_STRINGS.1, + ascii_size: POST_312_STRINGS.2, + compact_size: POST_312_STRINGS.3, + debug: None, + }, + PythonLayout { + minor: 13, + runtime_interpreters_head: 632, + gil: GilPath::Interpreter { + interp_gil: 16, + last_holder: 8, + locked: 16, + switch_number: 24, + }, + interp_threads_head: 7344, + tstate_next: 8, + tstate_thread_id: 152, + tstate_native_thread_id: Some(160), + frame: FramePath::Direct { tstate_frame: 72 }, + frame_back: 8, + frame_code: 0, + frame_owner: Some(70), + first_non_python_owner: Some(3), + code_tagged: false, + code_filename: 112, + code_name: 120, + code_qualname: Some(128), + code_firstlineno: 68, + object_type: 8, + ascii_length: POST_312_STRINGS.0, + ascii_state: POST_312_STRINGS.1, + ascii_size: POST_312_STRINGS.2, + compact_size: POST_312_STRINGS.3, + debug: Some(DebugOffsetsLayout { + version: 8, + runtime_interpreters_head: 40, + interp_threads_head: 72, + tstate_next: 168, + tstate_native_thread_id: 200, + tstate_current_frame: 184, + frame_back: 232, + frame_code: 240, + frame_owner: 264, + code_filename: 280, + code_qualname: 296, + code_firstlineno: 312, + object_type: 360, + }), + }, + PythonLayout { + minor: 14, + runtime_interpreters_head: 808, + gil: GilPath::Interpreter { + interp_gil: 16, + last_holder: 8, + locked: 16, + switch_number: 24, + }, + interp_threads_head: 7344, + tstate_next: 8, + tstate_thread_id: 152, + tstate_native_thread_id: Some(160), + frame: FramePath::Direct { tstate_frame: 72 }, + frame_back: 8, + frame_code: 0, + frame_owner: Some(74), + first_non_python_owner: Some(3), + code_tagged: true, + code_filename: 112, + code_name: 120, + code_qualname: Some(128), + code_firstlineno: 68, + object_type: 8, + ascii_length: POST_312_STRINGS.0, + ascii_state: POST_312_STRINGS.1, + ascii_size: POST_312_STRINGS.2, + compact_size: POST_312_STRINGS.3, + debug: Some(DebugOffsetsLayout { + version: 8, + runtime_interpreters_head: 40, + interp_threads_head: 72, + tstate_next: 192, + tstate_native_thread_id: 224, + tstate_current_frame: 208, + frame_back: 256, + frame_code: 264, + frame_owner: 288, + code_filename: 320, + code_qualname: 336, + code_firstlineno: 352, + object_type: 408, + }), + }, +]; + +/// The layout of CPython `3.minor`, if xprobe supports it. +#[must_use] +pub fn layout(minor: u8) -> Option<&'static PythonLayout> { + LAYOUTS.iter().find(|layout| layout.minor == minor) +} + +/// Minor versions with a known layout. +#[must_use] +pub fn supported_minors() -> Vec { + LAYOUTS.iter().map(|layout| layout.minor).collect() +} + +/// A CPython interpreter found in a target's mappings. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PythonRuntime { + /// The executable or libpython that defines `_PyRuntime`. + pub binary: PathBuf, + pub minor: u8, + pub layout: &'static PythonLayout, + /// Runtime addresses in the target. + pub runtime_address: u64, + pub code_type_address: u64, +} + +#[derive(Debug)] +pub enum PythonLocateError { + Io { + path: PathBuf, + source: std::io::Error, + }, + InvalidElf { + path: PathBuf, + reason: String, + }, + /// No mapped object defines `_PyRuntime`. + NotPython, + UnknownVersion { + path: PathBuf, + }, + UnsupportedVersion { + path: PathBuf, + minor: u8, + }, + NotMapped { + path: PathBuf, + }, +} + +impl fmt::Display for PythonLocateError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Io { path, source } => { + write!(formatter, "failed to read {}: {source}", path.display()) + } + Self::InvalidElf { path, reason } => { + write!( + formatter, + "{} is not a readable ELF object: {reason}", + path.display() + ) + } + Self::NotPython => write!( + formatter, + "no mapped executable or libpython defines the CPython runtime (_PyRuntime)" + ), + Self::UnknownVersion { path } => write!( + formatter, + "cannot tell which CPython version {} is", + path.display() + ), + Self::UnsupportedVersion { path, minor } => write!( + formatter, + "{} is CPython 3.{minor}; external sampling supports 3.{}", + path.display(), + supported_minors() + .iter() + .map(u8::to_string) + .collect::>() + .join(", 3.") + ), + Self::NotMapped { path } => write!( + formatter, + "{} is not mapped from file offset zero in the target", + path.display() + ), + } + } +} + +impl Error for PythonLocateError {} + +/// Find the CPython runtime of an inspected process. +/// +/// # Errors +/// +/// Returns [`PythonLocateError`] when no mapped object is CPython, its +/// version is unknown or unsupported, or its files or mappings are unreadable. +pub fn locate(report: &ProcessReport) -> Result { + let maps_path = PathBuf::from(format!("/proc/{}/maps", report.target.pid)); + let maps = fs::read_to_string(&maps_path).map_err(|source| PythonLocateError::Io { + path: maps_path, + source, + })?; + let mut candidates = vec![PathBuf::from(&report.executable)]; + candidates.extend( + report + .loaded_libraries + .iter() + .map(PathBuf::from) + .filter(|path| { + path.file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("libpython")) + }), + ); + for path in candidates { + let bytes = fs::read(&path).map_err(|source| PythonLocateError::Io { + path: path.clone(), + source, + })?; + let Some(symbols) = runtime_symbols(&path, &bytes)? else { + continue; + }; + let minor = symbols + .version_hex + .map(|hex| u8::try_from((hex >> 16) & 0xff).unwrap_or(u8::MAX)) + .or_else(|| minor_from_name(&path)) + .ok_or_else(|| PythonLocateError::UnknownVersion { path: path.clone() })?; + let layout = layout(minor).ok_or_else(|| PythonLocateError::UnsupportedVersion { + path: path.clone(), + minor, + })?; + let base = load_base(&maps, &path) + .ok_or_else(|| PythonLocateError::NotMapped { path: path.clone() })?; + let bias = base.wrapping_sub(symbols.first_load_address); + return Ok(PythonRuntime { + binary: path, + minor, + layout, + runtime_address: bias.wrapping_add(symbols.runtime), + code_type_address: bias.wrapping_add(symbols.code_type), + }); + } + Err(PythonLocateError::NotPython) +} + +struct RuntimeSymbols { + runtime: u64, + code_type: u64, + /// `Py_Version` (3.11+), read from the file. + version_hex: Option, + /// Page-aligned address of the segment loaded from file offset zero. + first_load_address: u64, +} + +fn runtime_symbols(path: &Path, bytes: &[u8]) -> Result, PythonLocateError> { + let file = object::File::parse(bytes).map_err(|error| PythonLocateError::InvalidElf { + path: path.to_owned(), + reason: error.to_string(), + })?; + let address = |wanted: &str| { + file.dynamic_symbols() + .chain(file.symbols()) + .find(|symbol| symbol.name() == Ok(wanted) && symbol.address() != 0) + .map(|symbol| symbol.address()) + }; + let (Some(runtime), Some(code_type)) = (address("_PyRuntime"), address("PyCode_Type")) else { + return Ok(None); + }; + let first_load_address = file + .segments() + .find(|segment| segment.file_range().0 == 0) + .map(|segment| segment.address() & !0xfff) + .ok_or_else(|| PythonLocateError::InvalidElf { + path: path.to_owned(), + reason: "no segment loads from file offset zero".to_owned(), + })?; + let version_hex = address("Py_Version").and_then(|symbol| { + file.segments().find_map(|segment| { + let (offset, size) = segment.file_range(); + let start = segment.address(); + (symbol >= start && symbol + 8 <= start + size).then(|| { + let at = usize::try_from(offset + (symbol - start)).ok()?; + let raw = bytes.get(at..at + 8)?; + Some(u64::from_le_bytes(raw.try_into().ok()?)) + })? + }) + }); + Ok(Some(RuntimeSymbols { + runtime, + code_type, + version_hex, + first_load_address, + })) +} + +/// `3.minor` from a `python3.N` or `libpython3.N` file name. +fn minor_from_name(path: &Path) -> Option { + let name = path.file_name()?.to_str()?; + let rest = name + .strip_prefix("libpython3.") + .or_else(|| name.strip_prefix("python3."))?; + let digits = rest + .chars() + .take_while(char::is_ascii_digit) + .collect::(); + digits.parse().ok() +} + +/// Start address of the mapping of `path` at file offset zero. +fn load_base(maps: &str, path: &Path) -> Option { + maps.lines().find_map(|line| { + // address perms offset dev inode path, where the path may hold spaces. + let mut rest = line; + let mut fields = [""; 5]; + for field in &mut fields { + rest = rest.trim_start(); + let end = rest.find(char::is_whitespace)?; + *field = &rest[..end]; + rest = &rest[end..]; + } + let mapped = rest.trim(); + let mapped = mapped.strip_suffix(" (deleted)").unwrap_or(mapped); + if u64::from_str_radix(fields[2], 16).ok()? != 0 || Path::new(mapped) != path { + return None; + } + u64::from_str_radix(fields[0].split_once('-')?.0, 16).ok() + }) +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use super::{FramePath, GilPath, LAYOUTS, PythonLayout, load_base, minor_from_name}; + + /// The fields `layout.c` prints, from this table. + fn printed(layout: &PythonLayout) -> BTreeMap { + let mut fields = BTreeMap::from([ + ( + "runtime_interpreters_head", + layout.runtime_interpreters_head, + ), + ("interp_threads_head", layout.interp_threads_head), + ("tstate_next", layout.tstate_next), + ("tstate_thread_id", layout.tstate_thread_id), + ("frame_back", layout.frame_back), + ("frame_code", layout.frame_code), + ("code_filename", layout.code_filename), + ("code_name", layout.code_name), + ("code_firstlineno", layout.code_firstlineno), + ("object_type", layout.object_type), + ("ascii_length", layout.ascii_length), + ("ascii_state", layout.ascii_state), + ("ascii_size", layout.ascii_size), + ("compact_size", layout.compact_size), + ]); + match layout.gil { + GilPath::Runtime { + last_holder, + locked, + switch_number, + } => { + fields.insert("runtime_gil_last_holder", last_holder); + fields.insert("runtime_gil_locked", locked); + fields.insert("runtime_gil_switch_number", switch_number); + } + GilPath::Interpreter { + interp_gil, + last_holder, + locked, + switch_number, + } => { + fields.insert("interp_ceval_gil", interp_gil); + fields.insert("gil_last_holder", last_holder); + fields.insert("gil_locked", locked); + fields.insert("gil_switch_number", switch_number); + } + } + match layout.frame { + FramePath::Direct { tstate_frame } if layout.minor >= 13 => { + fields.insert("tstate_current_frame", tstate_frame); + } + FramePath::Direct { tstate_frame } => { + fields.insert("tstate_frame", tstate_frame); + } + FramePath::CFrame { + tstate_cframe, + cframe_current_frame, + } => { + fields.insert("tstate_cframe", tstate_cframe); + fields.insert("cframe_current_frame", cframe_current_frame); + } + } + let optional = [ + ("tstate_native_thread_id", layout.tstate_native_thread_id), + ("frame_owner", layout.frame_owner), + ("code_qualname", layout.code_qualname), + ( + "first_non_python_owner", + layout.first_non_python_owner.map(u64::from), + ), + ]; + for (name, value) in optional { + if let Some(value) = value { + fields.insert(name, value); + } + } + if layout.frame_owner.is_some() { + fields.insert("frame_owner_size", 1); + } + if layout.debug.is_some() { + fields.insert("debug_offsets", 0); + } + fields + .into_iter() + .map(|(name, value)| (name.to_owned(), value)) + .collect() + } + + #[test] + fn layouts_match_the_header_fixture() { + let fixture: serde_json::Value = serde_json::from_str(include_str!( + "../../../tests/integration/python-layout/expected.json" + )) + .unwrap(); + for layout in &LAYOUTS { + let version = format!("3.{}", layout.minor); + let expected: BTreeMap = + serde_json::from_value(fixture["layouts"][&version].clone()).unwrap(); + assert_eq!(printed(layout), expected, "CPython {version}"); + if let Some(debug) = layout.debug { + let expected: BTreeMap = + serde_json::from_value(fixture["debug_offsets"][&version].clone()).unwrap(); + for (name, value) in [ + ("version", debug.version), + ("runtime_interpreters_head", debug.runtime_interpreters_head), + ("interp_threads_head", debug.interp_threads_head), + ("tstate_next", debug.tstate_next), + ("tstate_native_thread_id", debug.tstate_native_thread_id), + ("tstate_current_frame", debug.tstate_current_frame), + ("frame_back", debug.frame_back), + ("frame_code", debug.frame_code), + ("frame_owner", debug.frame_owner), + ("code_filename", debug.code_filename), + ("code_qualname", debug.code_qualname), + ("code_firstlineno", debug.code_firstlineno), + ("object_type", debug.object_type), + ] { + assert_eq!(expected[name], value, "CPython {version} debug {name}"); + } + } + } + } + + #[test] + fn reads_minor_versions_from_file_names() { + for (name, minor) in [ + ("/usr/lib/libpython3.10.so.1.0", Some(10)), + ("/usr/local/bin/python3.12", Some(12)), + ("/opt/conda/bin/python3.9", Some(9)), + ("/usr/bin/python3", None), + ] { + assert_eq!(minor_from_name(std::path::Path::new(name)), minor, "{name}"); + } + } + + #[test] + fn finds_the_mapping_at_file_offset_zero() { + let maps = "\ +55d0c0000000-55d0c0001000 r--p 00000000 08:01 12 /usr/bin/python3.12 +55d0c0001000-55d0c0200000 r-xp 00001000 08:01 12 /usr/bin/python3.12 +7f0000000000-7f0000010000 r--p 00000000 08:01 13 /usr/lib/lib with space.so +"; + assert_eq!( + load_base(maps, std::path::Path::new("/usr/bin/python3.12")), + Some(0x55d0_c000_0000) + ); + assert_eq!( + load_base(maps, std::path::Path::new("/usr/lib/lib with space.so")), + Some(0x7f00_0000_0000) + ); + assert_eq!( + load_base(maps, std::path::Path::new("/usr/bin/other")), + None + ); + } +} diff --git a/xprobe/core/src/python_sampling.rs b/xprobe/core/src/python_sampling.rs new file mode 100644 index 0000000..03004bd --- /dev/null +++ b/xprobe/core/src/python_sampling.rs @@ -0,0 +1,574 @@ +//! CPython stack samples and their aggregation. +//! +//! The collector reads samples from a live interpreter; this module holds +//! their data and turns a finished capture into a `PythonSampleResult`. + +use std::collections::{BTreeMap, BTreeSet}; +use std::time::Duration; + +use xprobe_protocol::{ + CpuStackFrame, PythonFrame, PythonHotspot, PythonNativeLeaf, PythonNativeWait, + PythonSampleCollection, PythonSampleInventory, PythonSampleRecord, PythonSampleResult, + PythonStackGroup, PythonTidSource, ReadLatency, SchemaVersion3, SessionStatus, TargetIdentity, + Warning, +}; + +/// A function in a sampled stack. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Code { + /// `co_qualname` (3.11+) or `co_name`. + pub function: String, + pub file: String, + /// `co_firstlineno`: the line where the function starts. + pub first_line: u32, +} + +/// One stack, innermost frame first. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Stack { + pub frames: Vec, + pub truncated: bool, +} + +/// One stack read. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PythonSample { + /// `CLOCK_MONOTONIC` time just before the read. + pub timestamp_ns: u64, + pub tid: Option, + /// Taken as the GIL holder rather than in an all-thread sweep. + pub gil: bool, + pub stack: Stack, + /// Where a blocked thread waits in native code (sweep samples only). + pub native: Option, +} + +/// A blocked thread's system call and user-space program counter. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NativeLeaf { + pub syscall: Option, + pub pc: u64, +} + +/// Parse `/proc//task//syscall`: `running`, `-1 sp pc` for a +/// thread blocked outside a system call, or `nr args... sp pc`. +#[must_use] +pub fn parse_task_syscall(text: &str) -> Option { + let fields = text.split_whitespace().collect::>(); + let first = *fields.first()?; + if first == "running" || fields.len() < 3 { + return None; + } + let pc = u64::from_str_radix(fields.last()?.trim_start_matches("0x"), 16).ok()?; + let syscall = if first == "-1" { + None + } else { + Some(first.parse().ok()?) + }; + Some(NativeLeaf { syscall, pc }) +} + +/// How many reads of each kind happened. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct SamplerCounters { + pub gil_ticks: u64, + /// GIL ticks on which no thread held the GIL. + pub gil_idle: u64, + pub thread_sweeps: u64, + /// Stacks that changed while they were read. + pub inconsistent: u64, + /// Samples not kept because `max_samples` was reached. + pub over_capacity: u64, + /// Ticks that started after their deadline had passed. + pub late_ticks: u64, + /// Swept threads whose native state could not be read or parsed. + pub native_unreadable: u64, +} + +/// How thread states were mapped to Linux TIDs. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TidSource { + /// `PyThreadState.native_thread_id` (3.11+). + Native, + /// A TID found in `struct pthread` at this offset. + Pthread(u64), + Unmapped, +} + +/// A finished sampling run. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PythonCapture { + pub samples: Vec, + pub codes: Vec, + pub counters: SamplerCounters, + /// Wall time of each kept stack read, in nanoseconds. + pub read_ns: Vec, + pub elapsed: Duration, + pub tid_source: TidSource, + /// Every TID seen in the interpreter's thread list. + pub threads: BTreeSet, +} + +/// Stack groups and hotspots kept per list. +const LIST_LIMIT: usize = 50; +/// Share of discarded reads above which the result warns. +const INCONSISTENT_WARNING_SHARE: f64 = 0.05; +/// Share of the requested rate below which the result warns. +const RATE_WARNING_SHARE: f64 = 0.9; + +/// What the sampler was asked to do and where it ran. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SamplingRequest { + pub session_id: String, + pub name: Option, + pub target: TargetIdentity, + pub python_minor: u8, + pub python_binary: String, + pub duration: Duration, + pub gil_hz: u32, + pub threads_hz: u32, + pub sample_capacity: u64, + pub stack_depth: u32, +} + +fn frame(codes: &[Code], index: u32) -> PythonFrame { + codes.get(index as usize).map_or_else( + || PythonFrame { + function: "".to_owned(), + file: String::new(), + first_line: 0, + }, + |code| PythonFrame { + function: code.function.clone(), + file: code.file.clone(), + first_line: code.first_line, + }, + ) +} + +#[allow( + clippy::cast_precision_loss, + reason = "sample counts stay far below 2^52" +)] +fn ratio(numerator: u64, denominator: u64) -> f64 { + if denominator == 0 { + 0.0 + } else { + numerator as f64 / denominator as f64 + } +} + +fn groups<'a>( + samples: impl Iterator, + codes: &[Code], + total: u64, +) -> Vec { + let mut counts = BTreeMap::<&[u32], u64>::new(); + for sample in samples { + *counts.entry(sample.stack.frames.as_slice()).or_default() += 1; + } + let mut groups = counts + .into_iter() + .map(|(frames, samples)| PythonStackGroup { + frames: frames.iter().map(|index| frame(codes, *index)).collect(), + samples, + proportion: ratio(samples, total), + }) + .collect::>(); + groups.sort_by(|left, right| { + right + .samples + .cmp(&left.samples) + .then_with(|| left.frames.cmp(&right.frames)) + }); + groups.truncate(LIST_LIMIT); + groups +} + +fn hotspots<'a>( + samples: impl Iterator, + codes: &[Code], + total: u64, +) -> Vec { + let mut inclusive = BTreeMap::::new(); + let mut exclusive = BTreeMap::::new(); + for sample in samples { + // A recursive function counts once per sample. + for index in sample.stack.frames.iter().collect::>() { + *inclusive.entry(*index).or_default() += 1; + } + if let Some(leaf) = sample.stack.frames.first() { + *exclusive.entry(*leaf).or_default() += 1; + } + } + let mut hotspots = inclusive + .into_iter() + .map(|(index, inclusive_samples)| { + let exclusive_samples = exclusive.get(&index).copied().unwrap_or(0); + PythonHotspot { + frame: frame(codes, index), + inclusive_samples, + exclusive_samples, + inclusive_proportion: ratio(inclusive_samples, total), + exclusive_proportion: ratio(exclusive_samples, total), + } + }) + .collect::>(); + hotspots.sort_by(|left, right| { + right + .exclusive_samples + .cmp(&left.exclusive_samples) + .then(right.inclusive_samples.cmp(&left.inclusive_samples)) + .then_with(|| left.frame.cmp(&right.frame)) + }); + hotspots.truncate(LIST_LIMIT); + hotspots +} + +fn latency(read_ns: &[u64]) -> Option { + let mut sorted = read_ns.to_vec(); + sorted.sort_unstable(); + let rank = + |percentile: usize| sorted[(percentile * sorted.len()).div_ceil(100).saturating_sub(1)]; + (!sorted.is_empty()).then(|| ReadLatency { + p50_ns: rank(50), + p99_ns: rank(99), + max_ns: sorted[sorted.len() - 1], + }) +} + +fn warning(code: &str, message: String) -> Warning { + Warning { + code: code.to_owned(), + message, + details: BTreeMap::new(), + } +} + +/// Warnings for discarded reads, missed rates, unmapped TIDs, and samples +/// over capacity. +fn quality_warnings( + request: &SamplingRequest, + capture: &PythonCapture, + gil_hz_achieved: f64, + threads_hz_achieved: f64, +) -> Vec { + let counters = capture.counters; + let mut warnings = Vec::new(); + let attempted = capture.samples.len() as u64 + counters.inconsistent; + if ratio(counters.inconsistent, attempted) > INCONSISTENT_WARNING_SHARE { + warnings.push(warning( + "PYTHON_READS_INCONSISTENT", + format!( + "{} of {attempted} stack reads changed while they were read and were discarded", + counters.inconsistent + ), + )); + } + for (what, requested, achieved) in [ + ("GIL", request.gil_hz, gil_hz_achieved), + ("thread", request.threads_hz, threads_hz_achieved), + ] { + if requested != 0 && achieved < f64::from(requested) * RATE_WARNING_SHARE { + warnings.push(warning( + "PYTHON_RATE_BELOW_REQUEST", + format!("{what} sampling reached {achieved:.0} Hz of the requested {requested} Hz"), + )); + } + } + if capture.tid_source == TidSource::Unmapped { + warnings.push(warning( + "PYTHON_TIDS_UNMAPPED", + "thread states could not be mapped to Linux TIDs; samples carry no TID".to_owned(), + )); + } + if counters.over_capacity != 0 { + warnings.push(warning( + "PYTHON_SAMPLES_OVER_CAPACITY", + format!( + "{} samples were not kept after the capacity of {} was reached", + counters.over_capacity, request.sample_capacity + ), + )); + } + warnings +} + +/// Aggregate a finished capture. +#[must_use] +pub fn analyze( + request: &SamplingRequest, + capture: &PythonCapture, + native: &BTreeMap, +) -> PythonSampleResult { + let counters = capture.counters; + let gil = || capture.samples.iter().filter(|sample| sample.gil); + let threads = || capture.samples.iter().filter(|sample| !sample.gil); + let gil_samples = gil().count() as u64; + let thread_samples = threads().count() as u64; + let seconds = capture.elapsed.as_secs_f64(); + #[allow( + clippy::cast_precision_loss, + reason = "tick counts stay far below 2^52" + )] + let per_second = |count: u64| { + if seconds > 0.0 { + count as f64 / seconds + } else { + 0.0 + } + }; + let gil_hz_achieved = per_second(counters.gil_ticks); + let threads_hz_achieved = per_second(counters.thread_sweeps); + + let warnings = quality_warnings(request, capture, gil_hz_achieved, threads_hz_achieved); + let truncated_stacks = capture + .samples + .iter() + .filter(|sample| sample.stack.truncated) + .count() as u64; + PythonSampleResult { + schema_version: SchemaVersion3::current(), + ok: true, + session_id: request.session_id.clone(), + status: SessionStatus::Completed, + target: request.target.clone(), + inventory: PythonSampleInventory { + name: request.name.clone(), + duration_ms: u64::try_from(request.duration.as_millis()).unwrap_or(u64::MAX), + gil_stack_groups: groups(gil(), &capture.codes, counters.gil_ticks), + gil_hotspots: hotspots(gil(), &capture.codes, counters.gil_ticks), + gil_released_proportion: ratio(counters.gil_idle, counters.gil_ticks), + thread_stack_groups: groups(threads(), &capture.codes, thread_samples), + native_waits: native_waits(threads(), native, thread_samples), + }, + collection: PythonSampleCollection { + wall_clock: None, + python_version: format!("3.{}", request.python_minor), + python_binary: request.python_binary.clone(), + tid_source: match capture.tid_source { + TidSource::Native => PythonTidSource::Native, + TidSource::Pthread(_) => PythonTidSource::Pthread, + TidSource::Unmapped => PythonTidSource::Unmapped, + }, + elapsed_ns: u64::try_from(capture.elapsed.as_nanos()).unwrap_or(u64::MAX), + gil_hz_requested: request.gil_hz, + gil_hz_achieved, + threads_hz_requested: request.threads_hz, + threads_hz_achieved, + gil_ticks: counters.gil_ticks, + gil_samples, + gil_released_ticks: counters.gil_idle, + thread_sweeps: counters.thread_sweeps, + thread_samples, + threads: u32::try_from(capture.threads.len()).unwrap_or(u32::MAX), + inconsistent_reads: counters.inconsistent, + native_unreadable: counters.native_unreadable, + late_ticks: counters.late_ticks, + sample_capacity: request.sample_capacity, + over_capacity: counters.over_capacity, + stack_depth: request.stack_depth, + truncated_stacks, + read_latency: latency(&capture.read_ns), + }, + artifact: None, + warnings, + } +} + +/// The program counters of every native leaf, to symbolize while the +/// target's mappings are still live. +#[must_use] +pub fn native_addresses(capture: &PythonCapture) -> BTreeSet { + capture + .samples + .iter() + .filter_map(|sample| sample.native.map(|leaf| leaf.pc)) + .collect() +} + +fn native_leaf(leaf: NativeLeaf, native: &BTreeMap) -> PythonNativeLeaf { + let frame = native.get(&leaf.pc); + PythonNativeLeaf { + syscall: leaf.syscall.map(|number| { + crate::syscall_aggregate::syscall_name(number) + .map_or_else(|| format!("syscall {number}"), str::to_owned) + }), + module: frame.and_then(|frame| frame.module_path.clone()), + symbol: frame.and_then(|frame| frame.symbol.clone()), + } +} + +fn native_waits<'a>( + samples: impl Iterator, + native: &BTreeMap, + total: u64, +) -> Vec { + let mut counts = BTreeMap::::new(); + for leaf in samples.filter_map(|sample| sample.native) { + *counts.entry(native_leaf(leaf, native)).or_default() += 1; + } + let mut waits = counts + .into_iter() + .map(|(leaf, samples)| PythonNativeWait { + leaf, + samples, + proportion: ratio(samples, total), + }) + .collect::>(); + waits.sort_by(|left, right| { + right + .samples + .cmp(&left.samples) + .then_with(|| left.leaf.cmp(&right.leaf)) + }); + waits.truncate(LIST_LIMIT); + waits +} + +/// Every sample as an artifact record. +#[must_use] +pub fn records( + capture: &PythonCapture, + pid: u32, + native: &BTreeMap, +) -> Vec { + capture + .samples + .iter() + .map(|sample| PythonSampleRecord { + timestamp_ns: sample.timestamp_ns, + pid, + tid: sample.tid, + gil: sample.gil, + truncated: sample.stack.truncated, + frames: sample + .stack + .frames + .iter() + .map(|index| frame(&capture.codes, *index)) + .collect(), + native: sample.native.map(|leaf| native_leaf(leaf, native)), + }) + .collect() +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeSet; + use std::time::Duration; + + use xprobe_protocol::TargetIdentity; + + use super::{ + Code, NativeLeaf, PythonCapture, PythonSample, SamplerCounters, SamplingRequest, Stack, + TidSource, analyze, parse_task_syscall, records, + }; + + fn sample(gil: bool, frames: &[u32]) -> PythonSample { + PythonSample { + timestamp_ns: 1, + tid: Some(7), + gil, + stack: Stack { + frames: frames.to_vec(), + truncated: false, + }, + native: None, + } + } + + #[test] + fn parses_task_syscall_states() { + assert_eq!(parse_task_syscall("running\n"), None); + assert_eq!( + parse_task_syscall("-1 0x7ffc1234 0x7f00aa\n"), + Some(NativeLeaf { + syscall: None, + pc: 0x7f_00aa + }) + ); + assert_eq!( + parse_task_syscall("202 0x1 0x80 0x0 0x0 0x0 0x0 0x7ffc1234 0x7f00bb\n"), + Some(NativeLeaf { + syscall: Some(202), + pc: 0x7f_00bb + }) + ); + } + + #[test] + fn aggregates_gil_and_thread_samples_separately() { + let code = |function: &str| Code { + function: function.to_owned(), + file: "app.py".to_owned(), + first_line: 1, + }; + let capture = PythonCapture { + // Three GIL samples in `step` under `main`, one in `load`; the + // fifth GIL tick found the GIL released. + samples: vec![ + sample(true, &[0, 2]), + sample(true, &[0, 2]), + sample(true, &[0, 2]), + sample(true, &[1, 2]), + sample(false, &[1, 2]), + ], + codes: vec![code("step"), code("load"), code("main")], + counters: SamplerCounters { + gil_ticks: 5, + gil_idle: 1, + thread_sweeps: 1, + ..SamplerCounters::default() + }, + read_ns: vec![10, 20, 30, 40, 1000], + elapsed: Duration::from_millis(2), + tid_source: TidSource::Native, + threads: BTreeSet::from([7]), + }; + let request = SamplingRequest { + session_id: "xp".to_owned(), + name: None, + target: TargetIdentity { + pid: 1, + process_start_time: 2, + }, + python_minor: 12, + python_binary: "/usr/bin/python3.12".to_owned(), + duration: Duration::from_millis(2), + gil_hz: 2500, + threads_hz: 500, + sample_capacity: 100, + stack_depth: 128, + }; + let result = analyze(&request, &capture, &std::collections::BTreeMap::new()); + let inventory = &result.inventory; + assert_eq!(inventory.gil_stack_groups[0].samples, 3); + assert!((inventory.gil_stack_groups[0].proportion - 0.6).abs() < 1e-9); + assert!((inventory.gil_released_proportion - 0.2).abs() < 1e-9); + let step = &inventory.gil_hotspots[0]; + assert_eq!(step.frame.function, "step"); + assert_eq!((step.exclusive_samples, step.inclusive_samples), (3, 3)); + let main = inventory + .gil_hotspots + .iter() + .find(|hotspot| hotspot.frame.function == "main") + .unwrap(); + assert_eq!((main.exclusive_samples, main.inclusive_samples), (0, 4)); + assert_eq!(inventory.thread_stack_groups[0].frames[0].function, "load"); + let collection = &result.collection; + assert_eq!((collection.gil_samples, collection.thread_samples), (4, 1)); + assert!((collection.gil_hz_achieved - 2500.0).abs() < 1e-6); + let latency = collection.read_latency.unwrap(); + assert_eq!( + (latency.p50_ns, latency.p99_ns, latency.max_ns), + (30, 1000, 1000) + ); + assert!(result.warnings.is_empty(), "{:?}", result.warnings); + + let lines = records(&capture, 1, &std::collections::BTreeMap::new()); + assert_eq!(lines.len(), 5); + assert_eq!(lines[0].frames[0].function, "step"); + assert_eq!(lines[0].frames[1].function, "main"); + } +} diff --git a/xprobe/core/src/syscall_aggregate.rs b/xprobe/core/src/syscall_aggregate.rs index c428c24..5cc0321 100644 --- a/xprobe/core/src/syscall_aggregate.rs +++ b/xprobe/core/src/syscall_aggregate.rs @@ -232,106 +232,114 @@ fn normalize_group(group: &RawSyscallGroup) -> SyscallAggregateGroup { } } -fn syscall_name(number: u32) -> Option<&'static str> { - Some(match number { - 0 => "read", - 1 => "write", - 3 => "close", - 5 => "fstat", - 7 => "poll", - 8 => "lseek", - 9 => "mmap", - 10 => "mprotect", - 11 => "munmap", - 12 => "brk", - 16 => "ioctl", - 17 => "pread64", - 18 => "pwrite64", - 19 => "readv", - 20 => "writev", - 24 => "sched_yield", - 25 => "mremap", - 26 => "msync", - 27 => "mincore", - 28 => "madvise", - 35 => "nanosleep", - 39 => "getpid", - 41 => "socket", - 42 => "connect", - 43 => "accept", - 44 => "sendto", - 45 => "recvfrom", - 46 => "sendmsg", - 47 => "recvmsg", - 56 => "clone", - 57 => "fork", - 58 => "vfork", - 59 => "execve", - 60 => "exit", - 61 => "wait4", - 72 => "fcntl", - 73 => "flock", - 74 => "fsync", - 75 => "fdatasync", - 78 => "getdents", - 186 => "gettid", - 202 => "futex", - 203 => "sched_setaffinity", - 204 => "sched_getaffinity", - 232 => "epoll_wait", - 233 => "epoll_ctl", - 234 => "tgkill", - 257 => "openat", - 262 => "newfstatat", - 270 => "pselect6", - 271 => "ppoll", - 272 => "unshare", - 275 => "splice", - 281 => "epoll_pwait", - 288 => "accept4", - 290 => "eventfd2", - 291 => "epoll_create1", - 292 => "dup3", - 293 => "pipe2", - 295 => "preadv", - 296 => "pwritev", - 298 => "perf_event_open", - 299 => "recvmmsg", - 302 => "prlimit64", - 307 => "sendmmsg", - 309 => "getcpu", - 310 => "process_vm_readv", - 311 => "process_vm_writev", - 314 => "sched_setattr", - 315 => "sched_getattr", - 317 => "seccomp", - 318 => "getrandom", - 319 => "memfd_create", - 321 => "bpf", - 322 => "execveat", - 323 => "userfaultfd", - 324 => "membarrier", - 325 => "mlock2", - 326 => "copy_file_range", - 327 => "preadv2", - 328 => "pwritev2", - 332 => "statx", - 334 => "rseq", - 424 => "pidfd_send_signal", - 425 => "io_uring_setup", - 426 => "io_uring_enter", - 427 => "io_uring_register", - 434 => "pidfd_open", - 435 => "clone3", - 436 => "close_range", - 437 => "openat2", - 438 => "pidfd_getfd", - 439 => "faccessat2", - 440 => "process_madvise", - 441 => "epoll_pwait2", - 449 => "futex_waitv", - _ => return None, - }) +/// `x86_64` system call numbers xprobe names in results. +const SYSCALL_NAMES: &[(u32, &str)] = &[ + (0, "read"), + (1, "write"), + (3, "close"), + (5, "fstat"), + (7, "poll"), + (8, "lseek"), + (9, "mmap"), + (10, "mprotect"), + (11, "munmap"), + (12, "brk"), + (16, "ioctl"), + (17, "pread64"), + (18, "pwrite64"), + (19, "readv"), + (20, "writev"), + (23, "select"), + (24, "sched_yield"), + (25, "mremap"), + (26, "msync"), + (27, "mincore"), + (28, "madvise"), + (35, "nanosleep"), + (39, "getpid"), + (41, "socket"), + (42, "connect"), + (43, "accept"), + (44, "sendto"), + (45, "recvfrom"), + (46, "sendmsg"), + (47, "recvmsg"), + (56, "clone"), + (57, "fork"), + (58, "vfork"), + (59, "execve"), + (60, "exit"), + (61, "wait4"), + (72, "fcntl"), + (73, "flock"), + (74, "fsync"), + (75, "fdatasync"), + (78, "getdents"), + (186, "gettid"), + (202, "futex"), + (203, "sched_setaffinity"), + (204, "sched_getaffinity"), + (230, "clock_nanosleep"), + (232, "epoll_wait"), + (233, "epoll_ctl"), + (234, "tgkill"), + (247, "waitid"), + (257, "openat"), + (262, "newfstatat"), + (270, "pselect6"), + (271, "ppoll"), + (272, "unshare"), + (275, "splice"), + (281, "epoll_pwait"), + (288, "accept4"), + (290, "eventfd2"), + (291, "epoll_create1"), + (292, "dup3"), + (293, "pipe2"), + (295, "preadv"), + (296, "pwritev"), + (298, "perf_event_open"), + (299, "recvmmsg"), + (302, "prlimit64"), + (307, "sendmmsg"), + (309, "getcpu"), + (310, "process_vm_readv"), + (311, "process_vm_writev"), + (314, "sched_setattr"), + (315, "sched_getattr"), + (317, "seccomp"), + (318, "getrandom"), + (319, "memfd_create"), + (321, "bpf"), + (322, "execveat"), + (323, "userfaultfd"), + (324, "membarrier"), + (325, "mlock2"), + (326, "copy_file_range"), + (327, "preadv2"), + (328, "pwritev2"), + (332, "statx"), + (334, "rseq"), + (424, "pidfd_send_signal"), + (425, "io_uring_setup"), + (426, "io_uring_enter"), + (427, "io_uring_register"), + (434, "pidfd_open"), + (435, "clone3"), + (436, "close_range"), + (437, "openat2"), + (438, "pidfd_getfd"), + (439, "faccessat2"), + (440, "process_madvise"), + (441, "epoll_pwait2"), + (449, "futex_waitv"), +]; + +pub(crate) fn syscall_name(number: u32) -> Option<&'static str> { + SYSCALL_NAMES + .iter() + .find(|(known, _)| *known == number) + .map(|(_, name)| *name) } fn warning(code: &str, message: &str) -> Warning { diff --git a/xprobe/core/src/thread_time.rs b/xprobe/core/src/thread_time.rs index 05e5306..046420c 100644 --- a/xprobe/core/src/thread_time.rs +++ b/xprobe/core/src/thread_time.rs @@ -67,7 +67,14 @@ fn read_thread(dir: &Path, tid: u32) -> Result, InspectEr let path = dir.join(entry); match fs::read_to_string(&path) { Ok(text) => Ok(Some(text)), - Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(None), + // A thread that exits after the listing is gone: its entry + // disappears, or reads fail with ESRCH while it is reaped. + Err(source) + if source.kind() == io::ErrorKind::NotFound + || source.raw_os_error() == Some(nix::errno::Errno::ESRCH as i32) => + { + Ok(None) + } Err(source) => Err(InspectError::Io { path, source }), } }; diff --git a/xprobe/core/src/triage.rs b/xprobe/core/src/triage.rs index a32c0b0..0b05ad2 100644 --- a/xprobe/core/src/triage.rs +++ b/xprobe/core/src/triage.rs @@ -5,10 +5,10 @@ //! environment action. Shares are estimates; findings never claim causality. use xprobe_protocol::{ - AggregateActivity, AggregateGroup, CgroupCpuThrottling, CpuHotspot, GpuDeviceHealth, - MatchPolicy, MeasurementMode, MeasurementSpec, PythonSymbolizationStatus, SchemaVersion, - SyscallAggregateGroup, TargetIdentity, ThreadTimeBreakdown, TriageFinding, TriageNextKind, - TriageNextStep, + AggregateActivity, AggregateGroup, CgroupCpuThrottling, CpuHotspot, CudaDevice, + GpuDeviceHealth, MatchPolicy, MeasurementMode, MeasurementSpec, PythonHotspot, + PythonSymbolizationStatus, SchemaVersion, SyscallAggregateGroup, TargetIdentity, + ThreadTimeBreakdown, TriageFinding, TriageNextKind, TriageNextStep, }; /// Throttled time at or above this share of the window is reported. @@ -51,10 +51,41 @@ pub struct TriageEvidence<'a> { pub cpu_hotspots: &'a [CpuHotspot], /// Python perf-map status of the CPU sample, when one was collected. pub python_status: Option, + /// GIL-holder hotspots, when external CPython sampling ran. + pub python_hotspots: Option<&'a [PythonHotspot]>, pub syscalls: &'a [SyscallAggregateGroup], pub gpu_devices: &'a [GpuDeviceHealth], /// Present when CUDA activity was collected for the target. pub gpu_activity: Option<&'a [AggregateGroup]>, + /// The UUID behind each CUDA ordinal in `gpu_activity`. + pub cuda_devices: &'a [CudaDevice], +} + +/// The target's activity on one NVML device, or `None` when the device +/// cannot be tied to the target: its activity names devices by CUDA ordinal, +/// and only the ordinal's UUID says which physical GPU that is. +fn device_activity<'a>( + evidence: &TriageEvidence<'a>, + device: &GpuDeviceHealth, +) -> Option> { + let groups = evidence.gpu_activity?; + if evidence.cuda_devices.is_empty() { + // Without UUIDs only a single visible GPU is unambiguous. + return (evidence.gpu_devices.len() == 1 && !groups.is_empty()) + .then(|| groups.iter().collect()); + } + // NVML lists physical GPUs; a MIG instance belongs to its GPU. + let ordinals = evidence + .cuda_devices + .iter() + .filter(|cuda| cuda.gpu_uuid.as_ref().unwrap_or(&cuda.uuid) == &device.uuid) + .map(|cuda| cuda.device_id) + .collect::>(); + let on_device = groups + .iter() + .filter(|group| group.device_id.is_some_and(|id| ordinals.contains(&id))) + .collect::>(); + (!on_device.is_empty()).then_some(on_device) } /// Evaluate every rule and rank findings by estimated impact. @@ -63,6 +94,7 @@ pub fn findings(evidence: &TriageEvidence<'_>) -> Vec { let mut found = Vec::new(); cgroup_throttled(evidence, &mut found); thread_rules(evidence, &mut found); + python_hotspot(evidence, &mut found); syscall_time(evidence, &mut found); gpu_rules(evidence, &mut found); found.sort_by(|left, right| { @@ -292,6 +324,55 @@ fn thread_rules(evidence: &TriageEvidence<'_>, found: &mut Vec) { } } +/// The Python function that held the GIL longest. GIL ticks are uniform in +/// wall time, so its exclusive share estimates its share of the window. +fn python_hotspot(evidence: &TriageEvidence<'_>, found: &mut Vec) { + let Some(hotspots) = evidence.python_hotspots else { + return; + }; + let Some(top) = hotspots + .iter() + .filter(|hotspot| hotspot.exclusive_proportion >= HOTSPOT_SHARE) + .max_by(|left, right| { + left.exclusive_proportion + .total_cmp(&right.exclusive_proportion) + }) + else { + return; + }; + let callers = hotspots + .iter() + .filter(|hotspot| { + hotspot.frame != top.frame && hotspot.inclusive_proportion > top.exclusive_proportion + }) + .take(2) + .map(|hotspot| { + format!( + "{} {}", + hotspot.frame.function, + percent(hotspot.inclusive_proportion) + ) + }) + .collect::>(); + found.push(finding( + "PYTHON_HOTSPOT", + top.exclusive_proportion, + format!( + "Python function {} ({}:{}) held the GIL {} of the window{}; Python functions have no attachable boundary, so read gil_stack_groups in the python-sample artifact for its callers", + top.frame.function, + top.frame.file, + top.frame.first_line, + percent(top.exclusive_proportion), + if callers.is_empty() { + String::new() + } else { + format!(" under {}", callers.join(", ")) + } + ), + None, + )); +} + /// The busiest thread is on CPU but no single frame crosses the hotspot share. fn cpu_bound(evidence: &TriageEvidence<'_>, tid: u32, on_cpu_share: f64) -> TriageFinding { let frames = evidence @@ -306,13 +387,15 @@ fn cpu_bound(evidence: &TriageEvidence<'_>, tid: u32, on_cpu_share: f64) -> Tria ) }) .collect::>(); + // Python samples name the functions themselves; without them, point at + // the sampler, which needs no interpreter restart. let python_inactive = matches!( evidence.python_status, Some(PythonSymbolizationStatus::Inactive) - ); + ) && evidence.python_hotspots.is_none(); let next = python_inactive.then(|| { environment( - "restart the interpreter with -X perf (CPython 3.12+) so samples resolve to Python functions" + "run measure --python-sample to name the Python functions without restarting the interpreter" .to_owned(), ) }); @@ -394,26 +477,27 @@ fn syscall_time(evidence: &TriageEvidence<'_>, found: &mut Vec) { #[allow(clippy::cast_precision_loss)] fn gpu_rules(evidence: &TriageEvidence<'_>, found: &mut Vec) { - let activity = evidence.gpu_activity; for device in evidence.gpu_devices { + // Only GPUs the target ran work on say anything about the target. + let Some(activity) = device_activity(evidence, device) else { + continue; + }; let Some(mean) = device.utilization_mean_pct else { continue; }; let loaded = device.utilization_max_pct.is_some_and(|max| max > 0); - let uses_gpu = activity.is_some_and(|groups| !groups.is_empty()); let launches = activity - .unwrap_or_default() .iter() .filter(|group| group.activity == AggregateActivity::Kernel) .map(|group| group.count) .sum::(); - if uses_gpu && mean < GPU_BUSY_PCT { + if mean < GPU_BUSY_PCT { found.push(finding( "GPU_UNDERUTILIZED", 1.0 - mean / 100.0, format!( - "GPU {} was busy {mean:.0}% of sampled time (device-wide NVML estimate) while the target submitted work; CPU-side or launch-bound time likely limits it", - device.index + "GPU {} ({}) was busy {mean:.0}% of sampled time (device-wide NVML estimate) while the target submitted work there; CPU-side or launch-bound time likely limits it", + device.index, device.uuid ), Some(measure( evidence.target, @@ -425,9 +509,8 @@ fn gpu_rules(evidence: &TriageEvidence<'_>, found: &mut Vec) { "measure launch-to-kernel latency for each launch".to_owned(), )), )); - } - if uses_gpu && mean >= GPU_BUSY_PCT { - kernel_dominant(evidence, device, mean, activity.unwrap_or_default(), found); + } else { + kernel_dominant(evidence, device, mean, &activity, found); } let slowdowns = device .clock_event_reasons @@ -472,7 +555,7 @@ fn kernel_dominant( evidence: &TriageEvidence<'_>, device: &GpuDeviceHealth, mean: f64, - groups: &[AggregateGroup], + groups: &[&AggregateGroup], found: &mut Vec, ) { let kernels = groups @@ -495,8 +578,9 @@ fn kernel_dominant( "GPU_KERNEL_DOMINANT", mean / 100.0 * kernel_share, format!( - "GPU {} was busy {mean:.0}% of sampled time; {name} is {} of summed kernel time over {} launches", + "GPU {} ({}) was busy {mean:.0}% of sampled time; {name} is {} of the target's summed kernel time there over {} launches", device.index, + device.uuid, percent(kernel_share), top.count ), @@ -516,8 +600,8 @@ fn kernel_dominant( mod tests { use xprobe_protocol::{ AggregateActivity, AggregateDuration, AggregateGroup, CgroupCpuThrottling, CgroupVersion, - CpuFrameLanguage, CpuHotspot, CpuStackFrame, GpuDeviceHealth, MatchPolicy, PcieLink, - PythonSymbolizationStatus, SyscallAggregateGroup, TargetIdentity, ThreadTime, + CpuFrameLanguage, CpuHotspot, CpuStackFrame, CudaDevice, GpuDeviceHealth, MatchPolicy, + PcieLink, PythonSymbolizationStatus, SyscallAggregateGroup, TargetIdentity, ThreadTime, ThreadTimeBreakdown, TriageNextKind, }; @@ -595,6 +679,61 @@ mod tests { } } + #[test] + fn gpu_findings_cover_only_gpus_the_target_used() { + let target = TargetIdentity { + pid: 42, + process_start_time: 7, + }; + let threads = threads(thread(0.1, 0.0)); + // Two idle GPUs; the target's CUDA device 0 is the second one. + let mut other = gpu(10.0, &[]); + other.uuid = "GPU-other".to_owned(); + let mut mine = gpu(20.0, &[]); + mine.index = 1; + mine.uuid = "GPU-mine".to_owned(); + let devices = [other, mine]; + let kernels = [kernel("gemm", 900)]; + let mapping = [CudaDevice { + device_id: 0, + uuid: "GPU-mine".to_owned(), + gpu_uuid: None, + }]; + let evidence = TriageEvidence { + target: &target, + threads: &threads, + collection_window_ns: WINDOW, + cgroup: None, + cpu_hotspots: &[], + python_status: None, + python_hotspots: None, + syscalls: &[], + gpu_devices: &devices, + gpu_activity: Some(&kernels), + cuda_devices: &mapping, + }; + let gpu_findings = findings(&evidence) + .into_iter() + .filter(|finding| finding.code.starts_with("GPU")) + .collect::>(); + assert_eq!(gpu_findings.len(), 1, "{gpu_findings:?}"); + assert!( + gpu_findings[0].summary.contains("GPU-mine"), + "{gpu_findings:?}" + ); + + // Without UUIDs, several GPUs cannot be told apart. + let unmapped = TriageEvidence { + cuda_devices: &[], + ..evidence + }; + assert!( + findings(&unmapped) + .iter() + .all(|finding| !finding.code.starts_with("GPU")) + ); + } + fn kernel(name: &str, total: u64) -> AggregateGroup { AggregateGroup { activity: AggregateActivity::Kernel, @@ -636,9 +775,11 @@ mod tests { cgroup: None, cpu_hotspots: &hotspots, python_status: None, + python_hotspots: None, syscalls: &[], gpu_devices: &[], gpu_activity: None, + cuda_devices: &[], }; let found = findings(&evidence); assert_eq!(found.len(), 1); @@ -686,9 +827,11 @@ mod tests { cgroup: None, cpu_hotspots: &[], python_status: None, + python_hotspots: None, syscalls: &[], gpu_devices: &busy_gpu, gpu_activity: Some(&kernels), + cuda_devices: &[], }; let found = findings(&evidence) .into_iter() @@ -716,9 +859,11 @@ mod tests { cgroup: None, cpu_hotspots: &hotspots, python_status: Some(PythonSymbolizationStatus::Inactive), + python_hotspots: None, syscalls: &[], gpu_devices: &[], gpu_activity: None, + cuda_devices: &[], }; let found = findings(&evidence); assert_eq!(found.len(), 1); @@ -730,6 +875,56 @@ mod tests { ); } + #[test] + fn the_python_function_holding_the_gil_longest_is_a_finding() { + let target = target(); + let threads = threads(thread(0.95, 0.0)); + let python = + |function: &str, exclusive: f64, inclusive: f64| xprobe_protocol::PythonHotspot { + frame: xprobe_protocol::PythonFrame { + function: function.to_owned(), + file: "train.py".to_owned(), + first_line: 10, + }, + inclusive_samples: 0, + exclusive_samples: 0, + inclusive_proportion: inclusive, + exclusive_proportion: exclusive, + }; + let hotspots = [ + python("collate", 0.62, 0.62), + python("Loader.next", 0.0, 0.8), + ]; + let evidence = TriageEvidence { + target: &target, + threads: &threads, + collection_window_ns: WINDOW, + cgroup: None, + cpu_hotspots: &[], + python_status: Some(PythonSymbolizationStatus::Inactive), + python_hotspots: Some(&hotspots), + syscalls: &[], + gpu_devices: &[], + gpu_activity: None, + cuda_devices: &[], + }; + let found = findings(&evidence); + let python = found + .iter() + .find(|finding| finding.code == "PYTHON_HOTSPOT") + .expect("the GIL hotspot is a finding"); + assert_eq!(python.impact_share, Some(0.62)); + assert!(python.summary.contains("collate (train.py:10)")); + assert!(python.summary.contains("under Loader.next 80%")); + // Python samples already name the functions, so CPU_BOUND does not + // point at the sampler again. + let cpu = found + .iter() + .find(|finding| finding.code == "CPU_BOUND") + .unwrap(); + assert!(cpu.next.is_none()); + } + #[test] fn ranks_throttling_runqueue_and_blocked_syscalls() { let target = target(); @@ -763,9 +958,11 @@ mod tests { cgroup: Some(&cgroup), cpu_hotspots: &[], python_status: None, + python_hotspots: None, syscalls: &syscalls, gpu_devices: &[], gpu_activity: None, + cuda_devices: &[], }; let codes = findings(&evidence) .into_iter() @@ -801,9 +998,11 @@ mod tests { cgroup: None, cpu_hotspots: &[], python_status: None, + python_hotspots: None, syscalls: &[], gpu_devices: &idle_gpu, gpu_activity: None, + cuda_devices: &[], }; assert!( findings(&base) @@ -813,6 +1012,7 @@ mod tests { let underfed = TriageEvidence { gpu_activity: Some(&kernels), + cuda_devices: &[], ..base }; let found = findings(&underfed); @@ -826,6 +1026,7 @@ mod tests { let busy = TriageEvidence { gpu_devices: &busy_gpu, gpu_activity: Some(&kernels), + cuda_devices: &[], ..base }; let found = findings(&busy); diff --git a/xprobe/core/src/validate.rs b/xprobe/core/src/validate.rs index b089e15..d78a98a 100644 --- a/xprobe/core/src/validate.rs +++ b/xprobe/core/src/validate.rs @@ -2,9 +2,9 @@ use std::{collections::BTreeMap, error::Error, fmt}; use regex::Regex; use xprobe_protocol::{ - AgentActivation, EndpointSource, ErrorCode, EventType, HostProbeKind, MatchPolicy, MemcpyKind, - PolicyRecommendation, PolicyRecommendationReason, ProcessReport, ResolvedCudaSelector, - ResolvedLinuxSelector, SchemaVersion, ValidatedEndpoint, ValidationIssue, + ActivityBoundary, AgentActivation, EndpointSource, ErrorCode, EventType, HostProbeKind, + MatchPolicy, MemcpyKind, PolicyRecommendation, PolicyRecommendationReason, ProcessReport, + ResolvedCudaSelector, ResolvedLinuxSelector, SchemaVersion, ValidatedEndpoint, ValidationIssue, ValidationRequirements, ValidationResult, Warning, }; @@ -234,7 +234,7 @@ fn recommend_policy(start: &Endpoint, end: &Endpoint) -> PolicyRecommendation { if supports_exact(&start.kind, &end.kind) { compatible_policies.push(MatchPolicy::Exact); } - if supports_stream_order(&start.kind, &end.kind) { + if supports_stream_order(start, end) { compatible_policies.push(MatchPolicy::StreamOrder); } compatible_policies.push(MatchPolicy::FirstAfter); @@ -995,13 +995,17 @@ fn check_policy( "stack-nested matching requires entry and return probes for the same host function" .to_owned(), )), - MatchPolicy::StreamOrder if !supports_stream_order(&start.kind, &end.kind) => { + MatchPolicy::StreamOrder if !supports_stream_order(start, end) => { issues.push(issue( ErrorCode::InvalidCorrelationPolicy, - "stream-order matching requires two GPU activity endpoints".to_owned(), + "stream-order matching pairs a GPU activity end with the next activity start on its stream; use exact for an activity's own duration".to_owned(), )); } - MatchPolicy::Exact | MatchPolicy::StackNested | MatchPolicy::StreamOrder => {} + MatchPolicy::StreamOrder => warnings.push(warning( + "STREAM_ORDER_CAPTURES_ALL_ACTIVITY", + "stream-order records every kernel, copy, and memset to find each end's successor; size max-events for the whole GPU activity rate", + )), + MatchPolicy::Exact | MatchPolicy::StackNested => {} } } @@ -1060,8 +1064,20 @@ fn supports_stack_nested(start: &Endpoint, end: &Endpoint) -> bool { start.binary_path == end.binary_path && start.file_offset == end.file_offset } -fn supports_stream_order(start: &EndpointKind, end: &EndpointKind) -> bool { - start.needs_activity() && end.needs_activity() +/// Stream order measures the gap from one activity's end to the start of the +/// next activity on its stream, across kernels, copies, and memsets. +fn supports_stream_order(start: &Endpoint, end: &Endpoint) -> bool { + let boundary = |endpoint: &Endpoint| { + endpoint + .public + .cuda + .as_ref() + .and_then(|cuda| xprobe_protocol::activity_boundary(&cuda.event_type)) + }; + start.kind.needs_activity() + && end.kind.needs_activity() + && boundary(start) == Some(ActivityBoundary::End) + && boundary(end) == Some(ActivityBoundary::Start) } fn check_selector_breadth(endpoint: &Endpoint, name: &str, warnings: &mut Vec) { diff --git a/xprobe/correlator/src/lib.rs b/xprobe/correlator/src/lib.rs index a4219fc..a9d1ce0 100644 --- a/xprobe/correlator/src/lib.rs +++ b/xprobe/correlator/src/lib.rs @@ -3,21 +3,24 @@ use std::{ collections::{BTreeMap, BTreeSet}, error::Error, - fmt, + fmt, ptr, time::Duration, }; use regex::Regex; use xprobe_protocol::{ - CaptureCompleteness, ClockDomain, ClockQuality, CollectionSummary, CorrelationConfidence, - CorrelationSummary, ErrorCode, Event, EventSource, EventType, HostProbeKind, LatencyStatistics, + ActivityBoundary, CUDA_RECORD_NAME_MAX_BYTES, CaptureCompleteness, CaptureCoverage, + ClockDomain, ClockQuality, CollectionSummary, CorrelationConfidence, CorrelationSummary, + CoverageSource, ErrorCode, Event, EventSource, EventType, HostProbeKind, LatencyStatistics, MatchPolicy, MatchedEventPair, Measurement, MeasurementResult, MemcpyKind, NvtxRangeKind, QualityVerdict, ResultQuality, SampleSummary, SchemaVersion3, SessionStatus, Warning, + activity_boundary, }; mod quality; +pub mod spans; -pub use quality::{assess as assess_quality, finalize}; +pub use quality::{apply_coverage, assess as assess_quality, finalize}; #[derive(Debug, Clone)] pub struct MeasureOptions { @@ -663,11 +666,13 @@ impl Selector { } } - const fn is_gpu_activity(&self) -> bool { - matches!( - self, - Self::Kernel { .. } | Self::Memcpy { .. } | Self::Memset { .. } - ) + const fn activity_boundary(&self) -> Option { + match self { + Self::Kernel { event_type, .. } + | Self::Memcpy { event_type, .. } + | Self::Memset { event_type } => activity_boundary(event_type), + _ => None, + } } } @@ -763,6 +768,17 @@ struct Outcome<'a> { unmatched_start: u64, unmatched_end: u64, ambiguous: u64, + /// Matched pairs beyond the samples limit; counted in the score only. + beyond_limit: u64, +} + +/// The capture and the endpoints selected from it. +struct Selected<'s, 'a> { + events: &'a [Event], + starts: &'s [&'a Event], + ends: &'s [&'a Event], + /// The end selector, when names in the ends came from one. + end_selector: Option<&'s Selector>, } #[derive(Debug, Clone, Copy)] @@ -797,23 +813,8 @@ pub fn measure( let start_selector = Selector::parse(&options.start_selector)?; let end_selector = Selector::parse(&options.end_selector)?; validate_policy(&start_selector, &end_selector, options.match_policy)?; - let mut starts: Vec<&Event> = events - .iter() - .filter(|event| start_selector.matches(event)) - .collect(); - let mut ends: Vec<&Event> = events - .iter() - .filter(|event| end_selector.matches(event)) - .collect(); - for (selector, events) in [(&start_selector, &mut starts), (&end_selector, &mut ends)] { - if matches!(selector, Selector::LaunchApi { .. }) { - drop_nested_driver_launches(events); - } - } - starts.sort_by_key(|event| event.timestamp_ns); - ends.sort_by_key(|event| event.timestamp_ns); - let clock_domain = common_clock_domain(&starts, &ends)?; - apply_duration_window(&mut starts, &mut ends, options.duration)?; + let (starts, ends, clock_domain) = + select_endpoints(events, &start_selector, &end_selector, options.duration)?; let lifecycles = LifecycleKinds { syscall: start_selector.is_syscall_lifecycle(&end_selector), @@ -821,8 +822,12 @@ pub fn measure( python_gc: start_selector.is_python_gc_lifecycle(&end_selector), }; let outcome = correlate_selected( - &starts, - &ends, + &Selected { + events, + starts: &starts, + ends: &ends, + end_selector: Some(&end_selector), + }, options.match_policy, options.samples, lifecycles, @@ -837,7 +842,11 @@ pub fn measure( .iter() .map(|pair| pair.latency_ns) .collect::>(); - let denominator = matched + outcome.unmatched_start + outcome.unmatched_end + outcome.ambiguous; + let denominator = matched + + outcome.beyond_limit + + outcome.unmatched_start + + outcome.unmatched_end + + outcome.ambiguous; let (method, confidence) = correlation_metadata(options.match_policy, lifecycles); let warnings = measurement_warnings(options, &starts, &ends); @@ -867,14 +876,21 @@ pub fn measure( correlation: CorrelationSummary { method: method.to_owned(), confidence, - score: ratio(matched, denominator), + score: ratio(matched + outcome.beyond_limit, denominator), }, clock: ClockQuality { alignment: clock_alignment(&clock_domain).to_owned(), estimated_error_ns, }, collection: CollectionSummary { + cuda_devices: Vec::new(), + wall_clock: None, completeness: CaptureCompleteness::Complete, + // The caller knows how the events were collected and replaces this. + coverage: CaptureCoverage { + source: CoverageSource::Unverified, + all_gpu_activity: false, + }, host_events, cuda_events, dropped_events: options.dropped_events, @@ -887,6 +903,34 @@ pub fn measure( Ok(result) } +/// The start and end events each selector picks, in time order and within +/// the duration window, with the clock domain they share. +fn select_endpoints<'a>( + events: &'a [Event], + start_selector: &Selector, + end_selector: &Selector, + duration: Option, +) -> Result<(Vec<&'a Event>, Vec<&'a Event>, ClockDomain), MeasureError> { + let select = |selector: &Selector| { + // A start known only as running at STOP marks its stream busy; it + // is never a measured endpoint. + let mut selected = events + .iter() + .filter(|event| selector.matches(event) && !xprobe_protocol::start_unknown(event)) + .collect::>(); + if matches!(selector, Selector::LaunchApi { .. }) { + drop_nested_driver_launches(&mut selected); + } + selected.sort_by_key(|event| event.timestamp_ns); + selected + }; + let mut starts = select(start_selector); + let mut ends = select(end_selector); + let clock_domain = common_clock_domain(&starts, &ends)?; + apply_duration_window(&mut starts, &mut ends, duration)?; + Ok((starts, ends, clock_domain)) +} + fn matched_pairs(pairs: Vec>) -> Vec { pairs .into_iter() @@ -914,24 +958,32 @@ fn collection_event_counts(events: &[Event]) -> (u64, u64) { (host, events.len() as u64 - host) } +/// Correlate the whole window, then keep the earliest `limit` pairs so the +/// unmatched counts and the score describe the same window for every policy. fn correlate_selected<'a>( - starts: &[&'a Event], - ends: &[&'a Event], + selected: &Selected<'_, 'a>, policy: MatchPolicy, limit: Option, lifecycles: LifecycleKinds, ) -> Outcome<'a> { - match policy { + let (starts, ends) = (selected.starts, selected.ends); + let mut outcome = match policy { MatchPolicy::Exact if lifecycles.syscall || lifecycles.python_gc => { - correlate_thread_lifecycle(starts, ends, limit) + correlate_thread_lifecycle(starts, ends) } - MatchPolicy::Exact if lifecycles.nvtx => correlate_nvtx_lifecycle(starts, ends, limit), - MatchPolicy::Exact => correlate_exact(starts, ends, limit), - MatchPolicy::FirstAfter => correlate_first_after(starts, ends, limit), - MatchPolicy::Nearest => correlate_nearest(starts, ends, limit), - MatchPolicy::StackNested => correlate_stack_nested(starts, ends, limit), - MatchPolicy::StreamOrder => correlate_stream_order(starts, ends, limit), + MatchPolicy::Exact if lifecycles.nvtx => correlate_nvtx_lifecycle(starts, ends), + MatchPolicy::Exact => correlate_exact(starts, ends), + MatchPolicy::FirstAfter => correlate_first_after(starts, ends), + MatchPolicy::Nearest => correlate_nearest(starts, ends), + MatchPolicy::StackNested => correlate_stack_nested(starts, ends), + MatchPolicy::StreamOrder => correlate_stream_order(selected), + }; + outcome.pairs.sort_by_key(|pair| pair.start.timestamp_ns); + if let Some(limit) = limit.filter(|limit| outcome.pairs.len() > *limit) { + outcome.beyond_limit = (outcome.pairs.len() - limit) as u64; + outcome.pairs.truncate(limit); } + outcome } fn validate_policy( @@ -946,8 +998,13 @@ fn validate_policy( MatchPolicy::StackNested if !start.supports_stack_nested(end) => { Some("stack-nested requires entry and return selectors for the same host function") } - MatchPolicy::StreamOrder if !start.is_gpu_activity() || !end.is_gpu_activity() => { - Some("stream-order requires two GPU activity selectors") + MatchPolicy::StreamOrder + if start.activity_boundary() != Some(ActivityBoundary::End) + || end.activity_boundary() != Some(ActivityBoundary::Start) => + { + Some( + "stream-order pairs a GPU activity end with the next activity start on its stream; use exact for an activity's own duration", + ) } _ => None, }; @@ -976,15 +1033,11 @@ const fn correlation_metadata( MatchPolicy::FirstAfter => ("first_after", CorrelationConfidence::Heuristic), MatchPolicy::Nearest => ("nearest", CorrelationConfidence::Heuristic), MatchPolicy::StackNested => ("stack_nested_tid_lifo", CorrelationConfidence::High), - MatchPolicy::StreamOrder => ("cuda_stream_order", CorrelationConfidence::High), + MatchPolicy::StreamOrder => (quality::STREAM_ORDER_METHOD, CorrelationConfidence::High), } } -fn correlate_thread_lifecycle<'a>( - starts: &[&'a Event], - ends: &[&'a Event], - limit: Option, -) -> Outcome<'a> { +fn correlate_thread_lifecycle<'a>(starts: &[&'a Event], ends: &[&'a Event]) -> Outcome<'a> { let mut timeline = starts .iter() .map(|event| (event.timestamp_ns, 0_u8, *event)) @@ -1017,22 +1070,16 @@ fn correlate_thread_lifecycle<'a>( } } pairs.sort_by_key(|pair| pair.start.timestamp_ns); - if let Some(limit) = limit { - pairs.truncate(limit); - } Outcome { pairs, unmatched_start: pending.len() as u64, unmatched_end, ambiguous, + beyond_limit: 0, } } -fn correlate_nvtx_lifecycle<'a>( - starts: &[&'a Event], - ends: &[&'a Event], - limit: Option, -) -> Outcome<'a> { +fn correlate_nvtx_lifecycle<'a>(starts: &[&'a Event], ends: &[&'a Event]) -> Outcome<'a> { let mut timeline = starts .iter() .map(|event| (event.timestamp_ns, 0_u8, *event)) @@ -1074,14 +1121,12 @@ fn correlate_nvtx_lifecycle<'a>( } unmatched_start += pending.len() as u64; pairs.sort_by_key(|pair| pair.start.timestamp_ns); - if let Some(limit) = limit { - pairs.truncate(limit); - } Outcome { pairs, unmatched_start, unmatched_end, ambiguous, + beyond_limit: 0, } } @@ -1198,11 +1243,7 @@ const fn clock_group(domain: &ClockDomain) -> u8 { } } -fn correlate_exact<'a>( - starts: &[&'a Event], - ends: &[&'a Event], - limit: Option, -) -> Outcome<'a> { +fn correlate_exact<'a>(starts: &[&'a Event], ends: &[&'a Event]) -> Outcome<'a> { let mut start_groups: BTreeMap> = BTreeMap::new(); let mut end_groups: BTreeMap> = BTreeMap::new(); let mut unmatched_start = 0_u64; @@ -1248,31 +1289,21 @@ fn correlate_exact<'a>( } unmatched_end += end_groups.values().map(Vec::len).sum::() as u64; pairs.sort_by_key(|pair| pair.start.timestamp_ns); - if let Some(limit) = limit { - pairs.truncate(limit); - } Outcome { pairs, unmatched_start, unmatched_end, ambiguous, + beyond_limit: 0, } } -fn correlate_first_after<'a>( - starts: &[&'a Event], - ends: &[&'a Event], - limit: Option, -) -> Outcome<'a> { - let limit = limit.unwrap_or(usize::MAX); +fn correlate_first_after<'a>(starts: &[&'a Event], ends: &[&'a Event]) -> Outcome<'a> { let mut pairs = Vec::new(); let mut unmatched_start = 0_u64; let mut unmatched_end = 0_u64; let mut end_index = 0; for (start_index, start) in starts.iter().enumerate() { - if pairs.len() == limit { - break; - } while end_index < ends.len() && ends[end_index].timestamp_ns < start.timestamp_ns { unmatched_end += 1; end_index += 1; @@ -1289,35 +1320,24 @@ fn correlate_first_after<'a>( break; } } - if pairs.len() < limit { - unmatched_end += (ends.len() - end_index) as u64; - } + unmatched_end += (ends.len() - end_index) as u64; Outcome { pairs, unmatched_start, unmatched_end, ambiguous: 0, + beyond_limit: 0, } } -fn correlate_nearest<'a>( - starts: &[&'a Event], - ends: &[&'a Event], - limit: Option, -) -> Outcome<'a> { - let limit = limit.unwrap_or(usize::MAX); +fn correlate_nearest<'a>(starts: &[&'a Event], ends: &[&'a Event]) -> Outcome<'a> { let mut available = BTreeMap::>::new(); for end in ends { available.entry(end.timestamp_ns).or_default().push(end); } let mut pairs = Vec::new(); let mut unmatched_start = 0_u64; - let mut reached_limit = false; for (index, start) in starts.iter().enumerate() { - if pairs.len() == limit { - reached_limit = true; - break; - } let before = available .range(..=start.timestamp_ns) .next_back() @@ -1356,21 +1376,13 @@ fn correlate_nearest<'a>( Outcome { pairs, unmatched_start, - unmatched_end: if reached_limit { - 0 - } else { - available.values().map(Vec::len).sum::() as u64 - }, + unmatched_end: available.values().map(Vec::len).sum::() as u64, ambiguous: 0, + beyond_limit: 0, } } -fn correlate_stack_nested<'a>( - starts: &[&'a Event], - ends: &[&'a Event], - limit: Option, -) -> Outcome<'a> { - let limit = limit.unwrap_or(usize::MAX); +fn correlate_stack_nested<'a>(starts: &[&'a Event], ends: &[&'a Event]) -> Outcome<'a> { let mut timeline = starts .iter() .map(|event| (event.timestamp_ns, 0_u8, *event)) @@ -1385,13 +1397,11 @@ fn correlate_stack_nested<'a>( if boundary == 0 { stacks.entry(key).or_default().push(event); } else if let Some(start) = stacks.get_mut(&key).and_then(Vec::pop) { - if pairs.len() < limit { - pairs.push(Pair { - start, - end: event, - latency_ns: event.timestamp_ns - start.timestamp_ns, - }); - } + pairs.push(Pair { + start, + end: event, + latency_ns: event.timestamp_ns - start.timestamp_ns, + }); } else { unmatched_end += 1; } @@ -1402,82 +1412,243 @@ fn correlate_stack_nested<'a>( unmatched_start: stacks.values().map(Vec::len).sum::() as u64, unmatched_end, ambiguous: 0, + beyond_limit: 0, } } type StreamKey = (u32, u32, u32, u64); -fn correlate_stream_order<'a>( - starts: &[&'a Event], - ends: &[&'a Event], - limit: Option, -) -> Outcome<'a> { - let mut start_groups = BTreeMap::>::new(); - let mut end_groups = BTreeMap::>::new(); - let mut unmatched_start = group_by_stream(starts, &mut start_groups); - let mut unmatched_end = group_by_stream(ends, &mut end_groups); +/// Pair an activity end with the start of the next activity on its stream. +/// +/// Successors come from every kernel, copy, and memset on the stream in the +/// capture, not only the selected endpoints, so a narrower end selector never +/// skips over activity that ran in between. An end that overlaps other +/// activity on its stream (CUDA Graph nodes or programmatic dependent launch), +/// whose successor ties with another start, or whose successor's truncated +/// kernel name cannot decide the end selector is ambiguous. An end whose +/// successor is not selected, or that has no successor in the capture, is an +/// unmatched start. +fn correlate_stream_order<'a>(selected: &Selected<'_, 'a>) -> Outcome<'a> { + let chosen = |events: &[&Event]| { + events + .iter() + .map(|event| ptr::from_ref(*event)) + .collect::>() + }; + let from = chosen(selected.starts); + let to = chosen(selected.ends); + let mut timelines = BTreeMap::>::new(); + for event in selected.events { + if activity_boundary(&event.event_type).is_some() + && let Some(key) = stream_key(event) + { + timelines.entry(key).or_default().push(event); + } + } let mut pairs = Vec::new(); - for (key, group) in start_groups { - let Some(end_group) = end_groups.remove(&key) else { - unmatched_start += group.len() as u64; - continue; - }; - let mut end_index = 0; - for start in group { - while end_index < end_group.len() - && end_group[end_index].timestamp_ns < start.timestamp_ns - { - unmatched_end += 1; - end_index += 1; - } - if let Some(end) = end_group.get(end_index) { - pairs.push(Pair { - start, - end, - latency_ns: end.timestamp_ns - start.timestamp_ns, - }); - end_index += 1; + let mut unmatched_start = selected + .starts + .iter() + .filter(|event| stream_key(event).is_none()) + .count() as u64; + let mut ambiguous = 0_u64; + for timeline in timelines.values_mut() { + sort_timeline(timeline); + // Track running activity by identity. An end whose start is not in + // the capture began earlier and ran until then, so no gap before the + // latest such end can be shown idle. + let mut open = BTreeMap::::new(); + let mut orphan_horizon = None::; + for event in timeline.iter() { + let key = activity_key(event); + if activity_boundary(&event.event_type) == Some(ActivityBoundary::Start) { + *open.entry(key).or_default() += 1; + } else if let Some(count) = open.get_mut(&key).filter(|count| **count > 0) { + *count -= 1; } else { - unmatched_start += 1; + orphan_horizon = orphan_horizon.max(Some(event.timestamp_ns)); + } + } + open.clear(); + let mut running = 0_u64; + for (index, event) in timeline.iter().enumerate() { + let key = activity_key(event); + if activity_boundary(&event.event_type) == Some(ActivityBoundary::Start) { + *open.entry(key).or_default() += 1; + running += 1; + continue; + } + let started = open.get_mut(&key).filter(|count| **count > 0).map(|count| { + *count -= 1; + running -= 1; + }); + if !from.contains(&ptr::from_ref(*event)) { + continue; + } + let overlapped = orphan_horizon.is_some_and(|horizon| event.timestamp_ns < horizon); + let alone = started.is_some() && running == 0 && !overlapped; + match stream_successor(timeline, index, alone) { + Successor::Next(next) if to.contains(&ptr::from_ref(next)) => pairs.push(Pair { + start: event, + end: next, + latency_ns: next.timestamp_ns - event.timestamp_ns, + }), + Successor::Next(next) if name_undecidable(selected.end_selector, next) => { + ambiguous += 1; + } + Successor::Next(_) | Successor::None => unmatched_start += 1, + Successor::Ambiguous => ambiguous += 1, } } - unmatched_end += (end_group.len() - end_index) as u64; - } - unmatched_end += end_groups.values().map(Vec::len).sum::() as u64; - pairs.sort_by_key(|pair| pair.start.timestamp_ns); - if let Some(limit) = limit { - pairs.truncate(limit); } + let paired = pairs + .iter() + .map(|pair| ptr::from_ref(pair.end)) + .collect::>(); Outcome { + unmatched_end: to.difference(&paired).count() as u64, pairs, unmatched_start, - unmatched_end, - ambiguous: 0, + ambiguous, + beyond_limit: 0, } } -fn group_by_stream<'a>( - events: &[&'a Event], - groups: &mut BTreeMap>, -) -> u64 { - let mut unmatched = 0; - for event in events { - let Some(cuda) = event.cuda.as_ref() else { - unmatched += 1; - continue; +/// Order one stream's boundaries in time. At one timestamp, ends come before +/// starts, so A.end == B.start is a valid zero gap rather than an overlap. A +/// zero-duration activity's own start and end sit together between them: the +/// Agent records an activity's start before its end, so a start that shares +/// an end's timestamp and key and precedes it in sequence is that end's own. +fn sort_timeline(timeline: &mut [&Event]) { + let is_start = + |event: &Event| activity_boundary(&event.event_type) == Some(ActivityBoundary::Start); + // Per timestamp and key: the earliest start and the latest end sequence. + let mut boundaries = BTreeMap::<(u64, ActivityKey<'_>), (u64, u64)>::new(); + for event in timeline.iter() { + let seen = boundaries + .entry((event.timestamp_ns, activity_key(event))) + .or_insert((u64::MAX, 0)); + if is_start(event) { + seen.0 = seen.0.min(event.sequence); + } else { + seen.1 = seen.1.max(event.sequence); + } + } + timeline.sort_by_cached_key(|event| { + let key = activity_key(event); + let (first_start, last_end) = boundaries[&(event.timestamp_ns, key)]; + let instant = if is_start(event) { + last_end > event.sequence + } else { + first_start < event.sequence }; - let (Some(device), Some(context), Some(stream)) = - (cuda.device_id, cuda.context_id, cuda.stream_id) - else { - unmatched += 1; - continue; + let rank = match (instant, is_start(event)) { + (false, false) => 0_u8, + (true, _) => 1, + (false, true) => 2, }; - groups - .entry((event.pid, device, context, stream)) - .or_default() - .push(event); + ( + event.timestamp_ns, + rank, + instant.then_some(key), + event.sequence, + ) + }); +} + +/// An activity's family, correlation ID, and kernel name. Graph nodes can +/// share one correlation ID, so running activity is counted per key. +type ActivityKey<'a> = (u8, u32, Option<&'a str>); + +fn activity_key(event: &Event) -> ActivityKey<'_> { + let family = match event.event_type { + EventType::GpuKernelStart | EventType::GpuKernelEnd => 0, + EventType::GpuMemcpyStart | EventType::GpuMemcpyEnd => 1, + _ => 2, + }; + let correlation = event + .cuda + .as_ref() + .and_then(|cuda| cuda.correlation_id) + .unwrap_or(0); + let name = event + .cuda + .as_ref() + .and_then(|cuda| cuda.kernel_name.as_deref()); + (family, correlation, name) +} + +enum Successor<'a> { + Next(&'a Event), + None, + Ambiguous, +} + +/// The activity start that follows the end at `index` on one stream timeline. +fn stream_successor<'a>(timeline: &[&'a Event], index: usize, alone: bool) -> Successor<'a> { + if !alone { + return Successor::Ambiguous; } - unmatched + let Some(next) = timeline.get(index + 1) else { + return Successor::None; + }; + let is_start = + |event: &Event| activity_boundary(&event.event_type) == Some(ActivityBoundary::Start); + // A start known only as a lower bound gives no measurable gap. + if !is_start(next) || xprobe_protocol::start_unknown(next) { + return Successor::Ambiguous; + } + // A zero-duration activity's start is followed by its own end at the + // same instant. Two zero-duration activities at one instant, or two + // starts that are not, could be in either order; a zero-duration one + // still precedes an activity that starts then and runs on. + let same_instant = timeline[index + 2..] + .iter() + .take_while(|after| after.timestamp_ns == next.timestamp_ns) + .collect::>(); + let instant = |start: &Event, rest: &[&&Event]| { + rest.iter().any(|after| { + !is_start(after) + && activity_key(after) == activity_key(start) + && after.sequence > start.sequence + }) + }; + let next_instant = instant(next, &same_instant); + let rival = same_instant.iter().enumerate().any(|(offset, after)| { + is_start(after) && instant(after, &same_instant[offset + 1..]) == next_instant + }); + if rival { + return Successor::Ambiguous; + } + Successor::Next(next) +} + +/// Whether a kernel's name may have been truncated past what the selector's +/// regex needs, so a non-match does not prove the kernel is not selected. +fn name_undecidable(selector: Option<&Selector>, event: &Event) -> bool { + let Some(Selector::Kernel { + event_type, + name: Some(pattern), + }) = selector + else { + return false; + }; + event.event_type == *event_type + && event + .cuda + .as_ref() + .and_then(|cuda| cuda.kernel_name.as_deref()) + .is_some_and(|name| name.len() >= CUDA_RECORD_NAME_MAX_BYTES && !pattern.is_match(name)) +} + +fn stream_key(event: &Event) -> Option { + let cuda = event.cuda.as_ref()?; + Some(( + event.pid, + cuda.device_id?, + cuda.context_id?, + cuda.stream_id?, + )) } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] @@ -2158,22 +2329,296 @@ mod tests { assert_eq!(result.measurement.latency_ns.min, 60); } + /// One activity's start and end on `stream`, as the Agent records them. + fn activity( + kinds: (EventType, EventType), + span: (u64, u64), + stream: u64, + name: &str, + correlation_id: u32, + ) -> [Event; 2] { + [(kinds.0, span.0), (kinds.1, span.1)].map(|(kind, timestamp)| { + let mut event = event(kind, timestamp, correlation_id); + let cuda = event.cuda.as_mut().expect("CUDA payload"); + cuda.stream_id = Some(stream); + cuda.kernel_name = Some(name.to_owned()); + event + }) + } + + fn kernel(start: u64, end: u64, stream: u64, name: &str, correlation_id: u32) -> [Event; 2] { + activity( + (EventType::GpuKernelStart, EventType::GpuKernelEnd), + (start, end), + stream, + name, + correlation_id, + ) + } + + fn stream_order(from: &str, to: &str) -> MeasureOptions { + let mut options = options(MatchPolicy::StreamOrder); + options.start_selector = from.to_owned(); + options.end_selector = to.to_owned(); + options.samples = None; + options.duration = Some(Duration::from_secs(1)); + options + } + + fn gaps(result: &xprobe_protocol::MeasurementResult) -> Vec<(String, String, u64)> { + let name = |event: &Event| { + event + .cuda + .as_ref() + .and_then(|cuda| cuda.kernel_name.clone()) + .unwrap_or_default() + }; + result + .evidence + .pairs + .as_ref() + .expect("full evidence") + .iter() + .map(|pair| (name(&pair.start), name(&pair.end), pair.latency_ns)) + .collect() + } + #[test] - fn stream_order_never_pairs_across_cuda_streams() { - let mut events = vec![ - event(EventType::GpuKernelStart, 100, 1), - event(EventType::GpuKernelStart, 110, 2), - event(EventType::GpuKernelEnd, 150, 9), - event(EventType::GpuKernelEnd, 170, 8), - ]; - events[1].cuda.as_mut().expect("CUDA payload").stream_id = Some(3); - events[2].cuda.as_mut().expect("CUDA payload").stream_id = Some(3); + fn stream_order_pairs_each_end_with_the_next_activity_on_its_stream() { + // A B flash1 C D flash2 on one stream, 2 ns apart: a narrower end + // selector must not skip over the kernels in between. + let events = [ + kernel(0, 10, 2, "A", 1), + kernel(12, 20, 2, "B", 2), + kernel(22, 30, 2, "flash1", 3), + kernel(32, 40, 2, "C", 4), + kernel(42, 50, 2, "D", 5), + kernel(52, 60, 2, "flash2", 6), + ] + .concat(); + let result = measure( + &events, + &stream_order("cuda:kernel_end", "cuda:kernel_start:name~^flash"), + ) + .unwrap(); - let result = measure(&events, &options(MatchPolicy::StreamOrder)).unwrap(); - assert_eq!(result.measurement.samples.matched, 2); - assert_eq!(result.measurement.latency_ns.min, 40); - assert_eq!(result.measurement.latency_ns.max, 70); + assert_eq!( + gaps(&result), + [ + ("B".to_owned(), "flash1".to_owned(), 2), + ("D".to_owned(), "flash2".to_owned(), 2) + ] + ); + assert_eq!(result.measurement.samples.unmatched_start, 4); + assert_eq!(result.measurement.samples.unmatched_end, 0); assert_eq!(result.correlation.method, "cuda_stream_order"); assert_eq!(result.correlation.confidence, CorrelationConfidence::High); } + + #[test] + fn stream_order_keeps_zero_duration_activity_between_its_neighbours() { + // B starts and ends at 10 ns, exactly when A ends and C starts. + let events = [ + kernel(0, 10, 2, "A", 1), + kernel(10, 10, 2, "B", 2), + kernel(10, 20, 2, "C", 3), + kernel(30, 40, 2, "D", 4), + ] + .concat(); + // Sequences follow the Agent's write order: each start, then its end. + let events = events + .into_iter() + .zip(0..) + .map(|(event, sequence)| Event { sequence, ..event }) + .collect::>(); + let result = measure( + &events, + &stream_order("cuda:kernel_end", "cuda:kernel_start"), + ) + .unwrap(); + + assert_eq!( + gaps(&result), + [ + ("A".to_owned(), "B".to_owned(), 0), + ("B".to_owned(), "C".to_owned(), 0), + ("C".to_owned(), "D".to_owned(), 10) + ] + ); + assert_eq!(result.measurement.samples.ambiguous, 0); + } + + #[test] + fn stream_order_keeps_back_to_back_runs_of_one_graph_kernel() { + // One graph node runs twice back to back under one correlation ID. + let events = [ + kernel(0, 10, 2, "node", 7), + kernel(10, 20, 2, "node", 7), + kernel(25, 30, 2, "node", 7), + ] + .concat(); + let result = measure( + &events, + &stream_order("cuda:kernel_end", "cuda:kernel_start"), + ) + .unwrap(); + assert_eq!( + gaps(&result), + [ + ("node".to_owned(), "node".to_owned(), 0), + ("node".to_owned(), "node".to_owned(), 5) + ] + ); + } + + #[test] + fn stream_order_successors_include_unselected_copies_but_not_other_streams() { + let mut events = [ + kernel(0, 10, 2, "A", 1), + activity( + (EventType::GpuMemcpyStart, EventType::GpuMemcpyEnd), + (12, 20), + 2, + "", + 2, + ), + kernel(22, 30, 2, "B", 3), + // A kernel on another stream between A and the copy is not A's + // successor. + kernel(11, 11, 3, "other", 4), + ] + .concat(); + events.sort_by_key(|event| event.timestamp_ns); + + // A is followed by the copy, not by B. + assert!(matches!( + measure( + &events, + &stream_order("cuda:kernel_end", "cuda:kernel_start") + ), + Err(MeasureError::NoMatchedSamples) + )); + let to_copy = measure( + &events, + &stream_order("cuda:kernel_end", "cuda:memcpy_start"), + ) + .unwrap(); + assert_eq!(to_copy.measurement.samples.matched, 1); + assert_eq!(to_copy.measurement.latency_ns.min, 2); + let from_copy = measure( + &events, + &stream_order("cuda:memcpy_end", "cuda:kernel_start"), + ) + .unwrap(); + assert_eq!(gaps(&from_copy), [(String::new(), "B".to_owned(), 2)]); + } + + #[test] + fn stream_order_counts_overlap_ties_and_truncated_names() { + let long = "k".repeat(xprobe_protocol::CUDA_RECORD_NAME_MAX_BYTES); + let events = [ + kernel(0, 10, 2, "A", 1), + kernel(5, 15, 2, "B", 2), + kernel(20, 30, 2, "C", 3), + kernel(20, 25, 2, "D", 4), + kernel(40, 50, 2, "E", 5), + kernel(50, 60, 2, "flash", 6), + kernel(70, 80, 2, "F", 7), + kernel(85, 90, 2, &long, 8), + ] + .concat(); + let result = measure( + &events, + &stream_order("cuda:kernel_end", "cuda:kernel_start:name~flash$"), + ) + .unwrap(); + // E.end == flash.start is a valid zero gap. + assert_eq!(gaps(&result), [("E".to_owned(), "flash".to_owned(), 0)]); + let samples = &result.measurement.samples; + // A and D end while another kernel runs, B is followed by tied C and + // D, and F's successor name is truncated and may still end in "flash". + assert_eq!(samples.ambiguous, 4); + // C and flash are followed by unselected kernels; the long kernel + // ends the capture. + assert_eq!(samples.unmatched_start, 3); + } + + #[test] + fn activity_without_a_captured_start_hides_the_gaps_it_overlaps() { + let boundary = |kind, timestamp, correlation_id| { + let mut event = event(kind, timestamp, correlation_id); + event.cuda.as_mut().expect("CUDA payload").stream_id = Some(2); + event + }; + // B runs 5-30; A's start was trimmed, so A.end at 10 is no gap. + let trimmed = [ + boundary(EventType::GpuKernelStart, 5, 2), + boundary(EventType::GpuKernelEnd, 10, 1), + boundary(EventType::GpuKernelStart, 15, 3), + boundary(EventType::GpuKernelEnd, 30, 2), + ]; + assert_eq!(super::spans::stream_gaps(&trimmed).len(), 0); + + // B started before the capture and ended at 30: every gap before 30 + // may overlap it; only the 35-40 gap after it is idle. + let started_earlier = [ + boundary(EventType::GpuKernelStart, 0, 1), + boundary(EventType::GpuKernelEnd, 10, 1), + boundary(EventType::GpuKernelStart, 15, 3), + boundary(EventType::GpuKernelEnd, 20, 3), + boundary(EventType::GpuKernelEnd, 30, 2), + boundary(EventType::GpuKernelStart, 32, 4), + boundary(EventType::GpuKernelEnd, 35, 4), + boundary(EventType::GpuKernelStart, 40, 5), + ]; + let gaps = super::spans::stream_gaps(&started_earlier) + .iter() + .map(|span| (span.start.timestamp_ns, span.end.timestamp_ns)) + .collect::>(); + assert_eq!(gaps, [(35, 40)]); + } + + #[test] + fn stream_order_rejects_anything_but_an_end_followed_by_a_start() { + let events = kernel(0, 10, 2, "A", 1); + for (from, to) in [ + ("cuda:kernel_start", "cuda:kernel_end"), + ("cuda:kernel_start", "cuda:kernel_start"), + ("cuda:kernel_end", "cuda:kernel_end"), + ] { + assert!( + matches!( + measure(&events, &stream_order(from, to)), + Err(MeasureError::InvalidPolicy(_)) + ), + "{from} -> {to}" + ); + } + } + + #[test] + fn samples_limit_keeps_the_earliest_pairs_and_scores_the_whole_window() { + let events = (0_u32..4) + .flat_map(|index| { + let start = u64::from(index) * 20; + kernel(start, start + 10, 2, "k", index + 1) + }) + .collect::>(); + let mut options = stream_order("cuda:kernel_end", "cuda:kernel_start"); + options.samples = Some(2); + let result = measure(&events, &options).unwrap(); + + assert_eq!(result.measurement.samples.matched, 2); + // Three gaps matched in the window; the last end has no successor + // and the first start no predecessor. + assert_eq!(result.measurement.samples.unmatched_start, 1); + assert_eq!(result.measurement.samples.unmatched_end, 1); + assert!((result.correlation.score - 3.0 / 5.0).abs() < f64::EPSILON); + assert_eq!( + result.evidence.pairs.as_ref().unwrap()[0] + .start + .timestamp_ns, + 10 + ); + } } diff --git a/xprobe/correlator/src/quality.rs b/xprobe/correlator/src/quality.rs index c53c94d..e4c2318 100644 --- a/xprobe/correlator/src/quality.rs +++ b/xprobe/correlator/src/quality.rs @@ -1,8 +1,9 @@ //! Evidence summarization and deterministic result-quality assessment. use xprobe_protocol::{ - CorrelationConfidence, Evidence, EvidenceExemplar, EvidenceMode, LatencyRank, MatchedEventPair, - MeasurementResult, QualityIssue, QualitySeverity, QualityVerdict, ResultQuality, SessionStatus, + CaptureCoverage, CorrelationConfidence, CoverageSource, Evidence, EvidenceExemplar, + EvidenceMode, LatencyRank, MatchedEventPair, MeasurementResult, QualityIssue, QualitySeverity, + QualityVerdict, ResultQuality, SessionStatus, }; /// Clock error at or above this share of the p50 latency is a caution. @@ -59,6 +60,16 @@ pub(crate) fn exemplars(pairs: &[MatchedEventPair]) -> Vec { /// /// Call this after every caller-side change to status, collection, or /// warnings so the verdict describes the emitted result. +/// Record what the capture covered. Stream order without a capture of every +/// activity cannot prove adjacency, so its pairs become heuristic. +pub fn apply_coverage(result: &mut MeasurementResult, coverage: CaptureCoverage) { + result.collection.coverage = coverage; + if result.correlation.method == STREAM_ORDER_METHOD && !coverage.all_gpu_activity { + result.correlation.confidence = CorrelationConfidence::Heuristic; + } + result.quality = assess(result); +} + pub fn finalize(result: &mut MeasurementResult, mode: EvidenceMode) { result.quality = assess(result); result.evidence.mode = mode; @@ -67,6 +78,26 @@ pub fn finalize(result: &mut MeasurementResult, mode: EvidenceMode) { } } +/// Method name of stream-order correlation, whose successors need every +/// activity on the stream. +pub(crate) const STREAM_ORDER_METHOD: &str = "cuda_stream_order"; + +fn coverage_issues(result: &MeasurementResult, issues: &mut Vec) { + let coverage = result.collection.coverage; + if coverage.source == CoverageSource::UnverifiedMerge { + issues.push(caution( + "CAPTURE_COVERAGE_UNKNOWN", + "inputs were merged without capture manifests placing them in one window of one target; pairs may span gaps between them".to_owned(), + )); + } + if result.correlation.method == STREAM_ORDER_METHOD && !coverage.all_gpu_activity { + issues.push(caution( + "STREAM_COVERAGE_UNVERIFIED", + "nothing shows the capture recorded every activity on each stream; an unrecorded activity between two pairs would hide inside the gap".to_owned(), + )); + } +} + /// Interpret status, correlation, sample, and clock fields deterministically. #[must_use] pub fn assess(result: &MeasurementResult) -> ResultQuality { @@ -95,6 +126,7 @@ pub fn assess(result: &MeasurementResult) -> ResultQuality { "the correlation method cannot uniquely pair events".to_owned(), )), } + coverage_issues(result, &mut issues); if samples.ambiguous != 0 { issues.push(caution( "AMBIGUOUS_PAIRS", @@ -252,7 +284,13 @@ mod tests { estimated_error_ns: Some(0), }, collection: CollectionSummary { + cuda_devices: Vec::new(), + wall_clock: None, completeness: CaptureCompleteness::Complete, + coverage: xprobe_protocol::CaptureCoverage { + source: xprobe_protocol::CoverageSource::Live, + all_gpu_activity: false, + }, host_events: 0, cuda_events: 0, dropped_events: 0, diff --git a/xprobe/correlator/src/spans.rs b/xprobe/correlator/src/spans.rs new file mode 100644 index 0000000..61303d9 --- /dev/null +++ b/xprobe/correlator/src/spans.rs @@ -0,0 +1,328 @@ +//! Spans between events of one capture, for thresholds such as triggers. +//! +//! Each span uses the same pairing rules as `measure`: stream gaps follow +//! stream-order adjacency, activity durations follow exact correlation, and +//! edge spans follow the requested policy. + +use std::collections::{BTreeMap, BTreeSet}; +use std::ptr; + +use xprobe_protocol::{ActivityBoundary, Event, EventType, MatchPolicy, activity_boundary}; + +use super::{ + LifecycleKinds, MeasureError, Pair, Selected, Selector, correlate_exact, correlate_selected, + correlate_stream_order, select_endpoints, validate_policy, +}; + +/// Two events of one capture and the time between them. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Span<'a> { + pub start: &'a Event, + pub end: &'a Event, + pub latency_ns: u64, +} + +impl<'a> From> for Span<'a> { + fn from(pair: Pair<'a>) -> Self { + Self { + start: pair.start, + end: pair.end, + latency_ns: pair.latency_ns, + } + } +} + +/// Gaps on each stream: every activity end paired with the start of the +/// next kernel, copy, or memset on its stream. Overlapping activity and tied +/// starts give no gap. Another stream may keep the device busy meanwhile; +/// [`device_idle`] is the time a device had nothing to run. +#[must_use] +pub fn stream_gaps(events: &[Event]) -> Vec> { + let boundary = |wanted| { + events + .iter() + .filter(|event| activity_boundary(&event.event_type) == Some(wanted)) + .collect::>() + }; + let ends = boundary(ActivityBoundary::End); + let starts = boundary(ActivityBoundary::Start); + correlate_stream_order(&Selected { + events, + starts: &ends, + ends: &starts, + end_selector: None, + }) + .pairs + .into_iter() + .map(Span::from) + .collect() +} + +/// Idle time on each device: from the end of the activity that ended last to +/// the start of the next kernel, copy, or memset on any stream of that device +/// in the same process. An activity whose start the capture missed may have +/// run since before it, so no idle time is claimed before its end; one still +/// running at the end keeps the device busy from its start on. +#[must_use] +pub fn device_idle(events: &[Event]) -> Vec> { + let durations = activity_durations(events); + let paired = durations + .iter() + .flat_map(|span| [ptr::from_ref(span.start), ptr::from_ref(span.end)]) + .collect::>(); + // Per process and device: activity intervals. A missing start began + // before the capture; a missing end ran past it. + let mut devices = BTreeMap::<(u32, u32), Vec<(Option<&Event>, Option<&Event>)>>::new(); + let device = |event: &Event| { + event + .cuda + .as_ref() + .and_then(|cuda| cuda.device_id) + .map(|id| (event.pid, id)) + }; + for span in &durations { + if let Some(key) = device(span.start) { + devices + .entry(key) + .or_default() + .push((Some(span.start), Some(span.end))); + } + } + for event in events { + let Some(boundary) = activity_boundary(&event.event_type) else { + continue; + }; + if paired.contains(&ptr::from_ref(event)) { + continue; + } + let Some(key) = device(event) else { + continue; + }; + devices.entry(key).or_default().push(match boundary { + ActivityBoundary::Start => (Some(event), None), + ActivityBoundary::End => (None, Some(event)), + }); + } + let mut idle = Vec::new(); + for mut intervals in devices.into_values() { + intervals.sort_by_key(|(start, end)| { + ( + start.map_or(0, |start| start.timestamp_ns), + end.map_or(u64::MAX, |end| end.timestamp_ns), + ) + }); + // The end that keeps the device busy longest so far; `None` once an + // activity runs past the capture. + let mut busy: Option> = None; + for (start, end) in intervals { + if let (Some(Some(until)), Some(start)) = (busy, start) + && start.timestamp_ns > until.timestamp_ns + { + idle.push(Span { + start: until, + end: start, + latency_ns: start.timestamp_ns - until.timestamp_ns, + }); + } + busy = Some(match (busy, end) { + (Some(None), _) | (_, None) => None, + (Some(Some(until)), Some(end)) if until.timestamp_ns >= end.timestamp_ns => { + Some(until) + } + (_, Some(end)) => Some(end), + }); + } + } + idle.sort_by_key(|span| (span.start.timestamp_ns, span.end.timestamp_ns)); + idle +} + +/// The duration of every kernel, copy, and memset, paired by correlation ID. +#[must_use] +pub fn activity_durations(events: &[Event]) -> Vec> { + [ + (EventType::GpuKernelStart, EventType::GpuKernelEnd), + (EventType::GpuMemcpyStart, EventType::GpuMemcpyEnd), + (EventType::GpuMemsetStart, EventType::GpuMemsetEnd), + ] + .iter() + .flat_map(|(start, end)| { + // A start known only as running at STOP has no duration. + let pick = |kind: &EventType| { + let mut picked = events + .iter() + .filter(|event| event.event_type == *kind && !xprobe_protocol::start_unknown(event)) + .collect::>(); + picked.sort_by_key(|event| event.timestamp_ns); + picked + }; + correlate_exact(&pick(start), &pick(end)).pairs + }) + .map(Span::from) + .collect() +} + +/// Every pair of one edge under `policy`, without samples or duration bounds. +/// +/// # Errors +/// +/// Returns [`MeasureError`] for invalid selectors, a policy the selectors do +/// not support, or events in clocks that cannot be subtracted. +pub fn edge_spans<'a>( + events: &'a [Event], + start_selector: &str, + end_selector: &str, + policy: MatchPolicy, +) -> Result>, MeasureError> { + let start = Selector::parse(start_selector)?; + let end = Selector::parse(end_selector)?; + validate_policy(&start, &end, policy)?; + let (starts, ends, _) = select_endpoints(events, &start, &end, None)?; + let lifecycles = LifecycleKinds { + syscall: start.is_syscall_lifecycle(&end), + nvtx: start.is_nvtx_lifecycle(&end), + python_gc: start.is_python_gc_lifecycle(&end), + }; + Ok(correlate_selected( + &Selected { + events, + starts: &starts, + ends: &ends, + end_selector: Some(&end), + }, + policy, + None, + lifecycles, + ) + .pairs + .into_iter() + .map(Span::from) + .collect()) +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use xprobe_protocol::{ClockDomain, CudaEvent, Event, EventSource, EventType, SchemaVersion}; + + use super::{device_idle, stream_gaps}; + + /// A kernel's start and end on `stream` of device 0, numbered from + /// `sequence`; `None` leaves out that boundary. + fn kernel(span: (Option, Option), stream: u64, correlation: u32) -> Vec { + [ + (EventType::GpuKernelStart, span.0), + (EventType::GpuKernelEnd, span.1), + ] + .into_iter() + .filter_map(|(event_type, timestamp)| Some((event_type, timestamp?))) + .map(|(event_type, timestamp)| Event { + schema_version: SchemaVersion::current(), + session_id: "idle".to_owned(), + event_id: format!("evt_{correlation}_{timestamp}"), + sequence: u64::from(correlation) * 2 + u64::from(event_type == EventType::GpuKernelEnd), + source: EventSource::CuptiActivity, + event_type, + pid: 1, + tid: 1, + cpu: None, + timestamp_raw: timestamp, + timestamp_ns: timestamp, + clock_domain: ClockDomain::CuptiNormalizedToHostMonotonic, + timestamp_error_ns: None, + process_start_time: None, + host: None, + cuda: Some(CudaEvent { + device_id: Some(0), + context_id: Some(1), + stream_id: Some(stream), + correlation_id: Some(correlation), + runtime_correlation_id: None, + callback_domain: None, + callback_id: None, + kernel_name: Some("k".to_owned()), + kernel_name_mangled: None, + start_ns: None, + end_ns: None, + grid: None, + block: None, + bytes: None, + memcpy_kind: None, + }), + nvtx: None, + attributes: BTreeMap::new(), + }) + .collect() + } + + fn latencies(spans: &[super::Span<'_>]) -> Vec { + spans.iter().map(|span| span.latency_ns).collect() + } + + #[test] + fn a_stream_gap_is_not_idle_while_another_stream_runs() { + // Stream 1: 0-10 and 40-50. Stream 2 runs 5-30 in between. + let events = [ + kernel((Some(0), Some(10)), 1, 1), + kernel((Some(5), Some(30)), 2, 2), + kernel((Some(40), Some(50)), 1, 3), + ] + .concat(); + assert_eq!(latencies(&stream_gaps(&events)), [30]); + assert_eq!(latencies(&device_idle(&events)), [10]); + } + + #[test] + fn a_kernel_running_at_stop_keeps_its_device_busy() { + // Stream 1: 0-10 and 30-40. Stream 2 ran a kernel through STOP whose + // start CUPTI did not report; it was placed at its stream's last end. + let mut running = kernel((Some(5), None), 2, 3); + running[0].attributes.insert( + xprobe_protocol::START_UNKNOWN_ATTRIBUTE.to_owned(), + true.into(), + ); + let events = [ + kernel((Some(0), Some(10)), 1, 1), + kernel((Some(30), Some(40)), 1, 2), + running, + ] + .concat(); + assert_eq!(latencies(&device_idle(&events)), Vec::::new()); + // Its stream has no measurable gap before it. + assert_eq!(latencies(&stream_gaps(&events)), [20]); + } + + #[test] + fn a_marker_sharing_a_kernels_key_does_not_break_its_duration() { + let mut running = kernel((Some(5), None), 1, 1); + running[0].attributes.insert( + xprobe_protocol::START_UNKNOWN_ATTRIBUTE.to_owned(), + true.into(), + ); + let events = [kernel((Some(0), Some(10)), 1, 1), running].concat(); + assert_eq!(latencies(&super::activity_durations(&events)), [10]); + } + + #[test] + fn activity_across_the_capture_bounds_hides_idle_time() { + // A kernel that started before the capture ends at 30, so the 10-20 + // gap before it cannot be shown idle; 30-40 can. + let before = [ + kernel((Some(0), Some(10)), 1, 1), + kernel((Some(20), Some(25)), 1, 2), + kernel((None, Some(30)), 2, 3), + kernel((Some(40), Some(50)), 1, 4), + ] + .concat(); + assert_eq!(latencies(&device_idle(&before)), [10]); + // A kernel still running at the end keeps the device busy after 15. + let after = [ + kernel((Some(0), Some(10)), 1, 1), + kernel((Some(15), None), 2, 2), + kernel((Some(40), Some(50)), 1, 3), + ] + .concat(); + assert_eq!(latencies(&device_idle(&after)), [5]); + } +} diff --git a/xprobe/exporter/Cargo.toml b/xprobe/exporter/Cargo.toml index be6032c..82d48c7 100644 --- a/xprobe/exporter/Cargo.toml +++ b/xprobe/exporter/Cargo.toml @@ -11,4 +11,5 @@ workspace = true [dependencies] serde_json.workspace = true +sha2.workspace = true xprobe-protocol.workspace = true diff --git a/xprobe/exporter/src/lib.rs b/xprobe/exporter/src/lib.rs index fa4f63b..a87259e 100644 --- a/xprobe/exporter/src/lib.rs +++ b/xprobe/exporter/src/lib.rs @@ -1,7 +1,38 @@ //! Structured result and trace exporters. use serde_json::{Value, json}; -use xprobe_protocol::{Event, EventSource, EventType}; +use sha2::{Digest, Sha256}; +use xprobe_protocol::{Event, EventSource, EventType, ExportFormat, ManifestArtifact}; + +/// Lowercase hexadecimal SHA-256 of artifact bytes. +#[must_use] +pub fn artifact_sha256(bytes: &[u8]) -> String { + use std::fmt::Write; + + Sha256::digest(bytes) + .iter() + .fold(String::with_capacity(64), |mut hex, byte| { + write!(hex, "{byte:02x}").expect("writing to a String cannot fail"); + hex + }) +} + +/// Describe artifact bytes holding `events` events for their manifest. +#[must_use] +pub fn manifest_artifact(format: ExportFormat, events: u64, bytes: &[u8]) -> ManifestArtifact { + ManifestArtifact { + format, + events, + bytes: bytes.len() as u64, + sha256: artifact_sha256(bytes), + } +} + +/// Whether `bytes` are the artifact a manifest describes. +#[must_use] +pub fn artifact_matches(artifact: &ManifestArtifact, bytes: &[u8]) -> bool { + artifact.bytes == bytes.len() as u64 && artifact.sha256 == artifact_sha256(bytes) +} /// Serialize events as one compact, versioned JSON object per line. /// @@ -182,3 +213,22 @@ mod tests { assert_eq!(document["traceEvents"][0]["args"]["timestamp_ns"], 10_999); } } + +#[cfg(test)] +mod digest_tests { + use xprobe_protocol::ExportFormat; + + use super::{artifact_matches, manifest_artifact}; + + #[test] + fn describes_artifact_bytes_by_length_and_sha256() { + let artifact = manifest_artifact(ExportFormat::Jsonl, 0, b"abc"); + assert_eq!( + artifact.sha256, + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert!(artifact_matches(&artifact, b"abc")); + assert!(!artifact_matches(&artifact, b"abd")); + assert!(!artifact_matches(&artifact, b"abcd")); + } +} diff --git a/xprobe/protocol/src/error.rs b/xprobe/protocol/src/error.rs index f4b3f6a..71613d4 100644 --- a/xprobe/protocol/src/error.rs +++ b/xprobe/protocol/src/error.rs @@ -22,11 +22,13 @@ pub enum ErrorCode { CuptiAgentNotLoaded, CudaContextNotFound, UnsupportedCudaVersion, + UnsupportedPythonVersion, EventRateTooHigh, SessionLimitExceeded, NoMatchedSamples, HighUnmatchedRate, EventsDropped, + TriggerNotObserved, ClockAlignmentFailed, TraceExportFailed, CleanupFailed, @@ -50,11 +52,13 @@ impl ErrorCode { Self::CuptiAgentNotLoaded => "CUPTI_AGENT_NOT_LOADED", Self::CudaContextNotFound => "CUDA_CONTEXT_NOT_FOUND", Self::UnsupportedCudaVersion => "UNSUPPORTED_CUDA_VERSION", + Self::UnsupportedPythonVersion => "UNSUPPORTED_PYTHON_VERSION", Self::EventRateTooHigh => "EVENT_RATE_TOO_HIGH", Self::SessionLimitExceeded => "SESSION_LIMIT_EXCEEDED", Self::NoMatchedSamples => "NO_MATCHED_SAMPLES", Self::HighUnmatchedRate => "HIGH_UNMATCHED_RATE", Self::EventsDropped => "EVENTS_DROPPED", + Self::TriggerNotObserved => "TRIGGER_NOT_OBSERVED", Self::ClockAlignmentFailed => "CLOCK_ALIGNMENT_FAILED", Self::TraceExportFailed => "TRACE_EXPORT_FAILED", Self::CleanupFailed => "CLEANUP_FAILED", diff --git a/xprobe/protocol/src/event.rs b/xprobe/protocol/src/event.rs index 4992996..dc6fd97 100644 --- a/xprobe/protocol/src/event.rs +++ b/xprobe/protocol/src/event.rs @@ -213,3 +213,43 @@ pub fn is_cuda_launch_api(domain: &str, name: &str) -> bool { .iter() .any(|(launch_domain, launch_name)| *launch_domain == domain && *launch_name == name) } + +/// Which end of a GPU activity (kernel, copy, or memset) an event marks. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ActivityBoundary { + Start, + End, +} + +/// The activity boundary an event type marks, if it is GPU activity. +#[must_use] +pub const fn activity_boundary(event_type: &EventType) -> Option { + match event_type { + EventType::GpuKernelStart | EventType::GpuMemcpyStart | EventType::GpuMemsetStart => { + Some(ActivityBoundary::Start) + } + EventType::GpuKernelEnd | EventType::GpuMemcpyEnd | EventType::GpuMemsetEnd => { + Some(ActivityBoundary::End) + } + _ => None, + } +} + +/// Longest CUDA kernel name a CUPTI Agent record holds, in bytes. A name of +/// this length may have been truncated. +pub const CUDA_RECORD_NAME_MAX_BYTES: usize = 127; + +/// Event attribute of a GPU activity start that was still running when the +/// capture stopped and whose start CUPTI did not report. Its timestamp is a +/// lower bound: the end of the previous activity on its stream. +pub const START_UNKNOWN_ATTRIBUTE: &str = "start_unknown"; + +/// Whether an activity start's time is only a lower bound; see +/// [`START_UNKNOWN_ATTRIBUTE`]. +#[must_use] +pub fn start_unknown(event: &Event) -> bool { + event + .attributes + .get(START_UNKNOWN_ATTRIBUTE) + .is_some_and(|value| value == &serde_json::Value::Bool(true)) +} diff --git a/xprobe/protocol/src/lib.rs b/xprobe/protocol/src/lib.rs index df68a4a..bea89ae 100644 --- a/xprobe/protocol/src/lib.rs +++ b/xprobe/protocol/src/lib.rs @@ -8,12 +8,15 @@ mod error; mod event; mod export; mod graph; +mod manifest; mod measurement; mod process; +mod python_sampling; mod resolve; pub mod schema; mod syscall_aggregate; mod triage; +mod trigger; mod validate; mod version; @@ -30,8 +33,10 @@ pub use cpu_sampling::{ pub use discover::{CudaProcessCandidate, DiscoveryResult}; pub use error::{ErrorCode, ErrorResponse, XprobeError}; pub use event::{ - ArgumentValue, CUDA_LAUNCH_APIS, ClockDomain, CudaEvent, Dim3, Event, EventSource, EventType, - HostEvent, HostProbeKind, MemcpyKind, MemoryKind, NvtxEvent, NvtxRangeKind, is_cuda_launch_api, + ActivityBoundary, ArgumentValue, CUDA_LAUNCH_APIS, CUDA_RECORD_NAME_MAX_BYTES, ClockDomain, + CudaEvent, Dim3, Event, EventSource, EventType, HostEvent, HostProbeKind, MemcpyKind, + MemoryKind, NvtxEvent, NvtxRangeKind, START_UNKNOWN_ATTRIBUTE, activity_boundary, + is_cuda_launch_api, start_unknown, }; pub use export::{ExportFormat, TraceExportResult}; pub use graph::{ @@ -40,16 +45,25 @@ pub use graph::{ GraphTarget, GraphValidationIssue, MeasurementGraphResult, MeasurementGraphSpec, MeasurementGraphValidationResult, }; +pub use manifest::{ + CaptureManifest, CaptureWindow, ManifestArtifact, ManifestVersion, manifest_path, +}; pub use measurement::{ AggregateActivity, AggregateCollectionSummary, AggregateDuration, AggregateGroup, - AggregateInventory, AggregateInventoryResult, CaptureCompleteness, ClockQuality, - CollectionSummary, CorrelationConfidence, CorrelationSummary, CuptiCollectionSummary, Evidence, - EvidenceArtifact, EvidenceExemplar, EvidenceMode, LatencyRank, LatencyStatistics, MatchPolicy, - MatchedEventPair, Measurement, MeasurementMode, MeasurementResult, MeasurementSpec, - QualityIssue, QualitySeverity, QualityVerdict, ResultQuality, SampleSummary, SessionStatus, - TargetIdentity, + AggregateInventory, AggregateInventoryResult, CaptureCompleteness, CaptureCoverage, + ClockAnchor, ClockQuality, CollectionSummary, CorrelationConfidence, CorrelationSummary, + CoverageSource, CudaDevice, CuptiCollectionSummary, Evidence, EvidenceArtifact, + EvidenceExemplar, EvidenceMode, LatencyRank, LatencyStatistics, MatchPolicy, MatchedEventPair, + Measurement, MeasurementMode, MeasurementResult, MeasurementSpec, QualityIssue, + QualitySeverity, QualityVerdict, ResultQuality, SampleSummary, SessionStatus, TargetIdentity, + WallClock, }; pub use process::{CgroupEntry, ProcessCredentials, ProcessCudaState, ProcessReport}; +pub use python_sampling::{ + PythonFrame, PythonHotspot, PythonNativeLeaf, PythonNativeWait, PythonSampleCollection, + PythonSampleInventory, PythonSampleRecord, PythonSampleResult, PythonStackGroup, + PythonTidSource, ReadLatency, +}; pub use resolve::{ElfObjectKind, ProcessMapping, ResolvedProbe}; pub use syscall_aggregate::{ SyscallAggregateCollectionSummary, SyscallAggregateCompleteness, SyscallAggregateGroup, @@ -61,6 +75,10 @@ pub use triage::{ TriageFinding, TriageNextKind, TriageNextStep, TriageResult, TriageSource, TriageSourceKind, TriageSourceStatus, }; +pub use trigger::{ + TriggerCollection, TriggerCondition, TriggerKind, TriggerObservation, TriggerResult, + TriggerWindow, +}; pub use validate::{ AgentActivation, EndpointSource, PolicyRecommendation, PolicyRecommendationReason, ResolvedCudaSelector, ResolvedLinuxSelector, ValidatedEndpoint, ValidationIssue, diff --git a/xprobe/protocol/src/manifest.rs b/xprobe/protocol/src/manifest.rs new file mode 100644 index 0000000..f7f8715 --- /dev/null +++ b/xprobe/protocol/src/manifest.rs @@ -0,0 +1,121 @@ +//! Coverage manifests written beside Event JSONL artifacts. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::{ExportFormat, TargetIdentity}; + +/// Version of the capture manifest contract. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub enum ManifestVersion { + #[serde(rename = "1.0")] + V1, +} + +impl ManifestVersion { + #[must_use] + pub const fn current() -> Self { + Self::V1 + } +} + +/// What one bounded capture covered, written to `.manifest.json`. +/// +/// Event JSONL records only events. The manifest records how they were +/// collected, so offline correlation can tell "not observed" from "not +/// captured" and keep losses that the live command reported. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CaptureManifest { + pub schema_version: ManifestVersion, + /// The artifact this manifest describes; a mismatch makes it stale. + pub artifact: ManifestArtifact, + pub target: TargetIdentity, + /// `CLOCK_MONOTONIC` nanoseconds from the first collector armed to the + /// final collection. + pub window: CaptureWindow, + /// Endpoint selectors the collectors were armed for. + pub selectors: Vec, + /// Every kernel, copy, and memset on the target was recorded, not only + /// the selected endpoints. + pub all_gpu_activity: bool, + /// Peer-to-peer copies were recorded with other copies. + pub peer_copies: bool, + pub dropped_records: u64, + pub unknown_records: u64, + /// The configured record limit that stopped the capture, if any. + pub record_limit_reached: Option, + /// A collector entered a failed state. + pub capture_failed: bool, + /// The UUID behind each CUDA device ordinal in the events. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub cuda_devices: Vec, + /// Maps the events' host-clock timestamps to wall time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wall_clock: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ManifestArtifact { + pub format: ExportFormat, + pub events: u64, + pub bytes: u64, + /// Lowercase hexadecimal SHA-256 of the artifact bytes. + pub sha256: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +/// `CLOCK_MONOTONIC` interval the capture's coverage holds for: from the +/// collector's ARM acknowledgment until after its final read. Activity that +/// was already running at ARM may begin before `start_ns`. +pub struct CaptureWindow { + pub start_ns: u64, + pub end_ns: u64, +} + +impl CaptureWindow { + /// Whether two windows share any instant. + #[must_use] + pub const fn overlaps(&self, other: &Self) -> bool { + self.start_ns <= other.end_ns && other.start_ns <= self.end_ns + } +} + +/// The sidecar manifest path for an artifact path. +#[must_use] +pub fn manifest_path(artifact: &std::path::Path) -> std::path::PathBuf { + let mut path = artifact.as_os_str().to_owned(); + path.push(".manifest.json"); + path.into() +} + +#[cfg(test)] +mod tests { + use super::{CaptureWindow, manifest_path}; + + #[test] + fn windows_overlap_when_they_share_an_instant() { + let window = CaptureWindow { + start_ns: 10, + end_ns: 20, + }; + assert!(window.overlaps(&CaptureWindow { + start_ns: 20, + end_ns: 30 + })); + assert!(!window.overlaps(&CaptureWindow { + start_ns: 21, + end_ns: 30 + })); + } + + #[test] + fn manifests_sit_beside_their_artifact() { + assert_eq!( + manifest_path(std::path::Path::new("/tmp/run/events.jsonl")), + std::path::Path::new("/tmp/run/events.jsonl.manifest.json") + ); + } +} diff --git a/xprobe/protocol/src/measurement.rs b/xprobe/protocol/src/measurement.rs index e0c2d83..ab3089a 100644 --- a/xprobe/protocol/src/measurement.rs +++ b/xprobe/protocol/src/measurement.rs @@ -222,6 +222,17 @@ pub struct ClockQuality { #[serde(deny_unknown_fields)] pub struct CollectionSummary { pub completeness: CaptureCompleteness, + /// The UUID behind each CUDA device ordinal in the events; empty when the + /// capture had no CUDA source or the driver did not report UUIDs. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub cuda_devices: Vec, + /// Maps the events' host-clock timestamps to wall time, for live + /// captures and inputs whose manifest recorded it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wall_clock: Option, + /// Results written before xprobe recorded coverage read as unverified. + #[serde(default)] + pub coverage: CaptureCoverage, pub host_events: u64, pub cuda_events: u64, pub dropped_events: u64, @@ -234,6 +245,67 @@ pub enum CaptureCompleteness { Complete, } +/// The wall clock read against `CLOCK_MONOTONIC`: `realtime_ns` is +/// `CLOCK_REALTIME` (nanoseconds since the Unix epoch, UTC) when +/// `CLOCK_MONOTONIC` was `monotonic_ns`, to within `uncertainty_ns`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ClockAnchor { + pub monotonic_ns: u64, + pub realtime_ns: u64, + pub uncertainty_ns: u64, +} + +/// Wall-clock anchors at the start and end of a capture. A host-clock +/// timestamp `t` is `realtime_ns + (t - monotonic_ns)` from the nearer +/// anchor; when the two anchors' offsets differ, the wall clock was stepped +/// or slewed during the capture and wall times carry that error. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct WallClock { + pub start: ClockAnchor, + pub end: ClockAnchor, +} + +/// One CUDA device as the target saw it. `device_id` is the process's CUDA +/// ordinal, which `CUDA_VISIBLE_DEVICES` renumbers; the UUID names the +/// physical GPU across processes and in `nvidia-smi`. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CudaDevice { + pub device_id: u32, + /// `GPU-โ€ฆ`, or `MIG-โ€ฆ` for a MIG instance, as `nvidia-smi -L` prints. + pub uuid: String, + /// The physical GPU's `GPU-โ€ฆ` UUID when `uuid` names a MIG instance. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub gpu_uuid: Option, +} + +/// What is known about which events the capture could have recorded. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CaptureCoverage { + pub source: CoverageSource, + /// Every kernel, copy, and memset on the target was recorded, so stream + /// order can see each activity's true successor. + pub all_gpu_activity: bool, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum CoverageSource { + /// Collected live by this command. + Live, + /// Read from one artifact without a manifest. + #[default] + Unverified, + /// Read from artifacts whose capture manifests match them. + Manifest, + /// Merged from artifacts without manifests that place them in one window + /// of one target. + UnverifiedMerge, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct CuptiCollectionSummary { @@ -306,6 +378,9 @@ pub struct AggregateDuration { #[serde(deny_unknown_fields)] pub struct AggregateCollectionSummary { pub completeness: CaptureCompleteness, + /// The UUID behind each CUDA device ordinal in the groups. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub cuda_devices: Vec, pub observed_activities: u64, pub grouped_activities: u64, pub dropped_activities: u64, diff --git a/xprobe/protocol/src/python_sampling.rs b/xprobe/protocol/src/python_sampling.rs new file mode 100644 index 0000000..ceb33cc --- /dev/null +++ b/xprobe/protocol/src/python_sampling.rs @@ -0,0 +1,173 @@ +//! External CPython stack sampling results. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::{EvidenceArtifact, SchemaVersion3, SessionStatus, TargetIdentity, Warning}; + +/// One Python function in a sampled stack. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PythonFrame { + /// `co_qualname` (3.11+) or `co_name`. + pub function: String, + pub file: String, + /// The line where the function starts, not the line that was running. + pub first_line: u32, +} + +/// Where a blocked thread waits in native code, from +/// `/proc//task//syscall`. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PythonNativeLeaf { + /// The system call it is blocked in, if any. + pub syscall: Option, + /// The mapped object and symbol of its user-space program counter. + pub module: Option, + pub symbol: Option, +} + +/// Thread samples blocked at one native leaf. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PythonNativeWait { + pub leaf: PythonNativeLeaf, + pub samples: u64, + /// Share of thread samples. + pub proportion: f64, +} + +/// Identical stacks, innermost frame first. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PythonStackGroup { + pub frames: Vec, + pub samples: u64, + /// Share of the samples this group was drawn from. + pub proportion: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PythonHotspot { + pub frame: PythonFrame, + pub inclusive_samples: u64, + pub exclusive_samples: u64, + pub inclusive_proportion: f64, + pub exclusive_proportion: f64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PythonSampleInventory { + pub name: Option, + pub duration_ms: u64, + /// Stacks of the GIL holder; proportions are of GIL ticks, so they sum + /// with `gil_released_proportion` to one. + pub gil_stack_groups: Vec, + pub gil_hotspots: Vec, + /// Share of GIL ticks on which no thread held the GIL: native code that + /// released it, I/O, or idle waiting. + pub gil_released_proportion: f64, + /// Stacks of every thread from the slower sweeps; proportions are of + /// thread samples. + pub thread_stack_groups: Vec, + /// Native leaves of blocked threads in the sweeps; a running thread has + /// none. + pub native_waits: Vec, +} + +/// How a sample's thread was mapped to a Linux TID. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum PythonTidSource { + /// `PyThreadState.native_thread_id` (3.11+). + Native, + /// The TID glibc stores in `struct pthread` (before 3.11). + Pthread, + /// No consistent TID mapping; samples carry no TID. + Unmapped, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ReadLatency { + pub p50_ns: u64, + pub p99_ns: u64, + pub max_ns: u64, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PythonSampleCollection { + /// Maps sample timestamps to wall time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wall_clock: Option, + /// `3.N` of the target interpreter. + pub python_version: String, + pub python_binary: String, + pub tid_source: PythonTidSource, + pub elapsed_ns: u64, + pub gil_hz_requested: u32, + /// GIL ticks per second actually reached. + pub gil_hz_achieved: f64, + pub threads_hz_requested: u32, + pub threads_hz_achieved: f64, + pub gil_ticks: u64, + pub gil_samples: u64, + pub gil_released_ticks: u64, + pub thread_sweeps: u64, + pub thread_samples: u64, + pub threads: u32, + /// Reads discarded because the innermost frame, a code object, a frame + /// mapping, or the GIL holder changed while they were read. + pub inconsistent_reads: u64, + /// Swept threads whose `/proc//task//syscall` could not be + /// read or parsed. + pub native_unreadable: u64, + /// Ticks that started after their deadline. + pub late_ticks: u64, + pub sample_capacity: u64, + /// Samples not kept because the capacity was reached. + pub over_capacity: u64, + pub stack_depth: u32, + pub truncated_stacks: u64, + /// Wall time of one kept stack read. + pub read_latency: Option, +} + +/// Result of `measure --python-sample`, schema `3.0`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PythonSampleResult { + pub schema_version: SchemaVersion3, + pub ok: bool, + pub session_id: String, + pub status: SessionStatus, + pub target: TargetIdentity, + pub inventory: PythonSampleInventory, + pub collection: PythonSampleCollection, + /// Every sample with its timestamp, one `PythonSampleRecord` per line. + pub artifact: Option, + #[serde(default)] + pub warnings: Vec, +} + +/// One line of a Python sample artifact. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct PythonSampleRecord { + /// `CLOCK_MONOTONIC` time just before the stack was read. + pub timestamp_ns: u64, + pub pid: u32, + pub tid: Option, + /// Taken as the GIL holder rather than in a sweep of every thread. + pub gil: bool, + pub truncated: bool, + /// Innermost frame first. + pub frames: Vec, + /// Where the thread was blocked in native code, for sweep samples of a + /// thread that was not running. + pub native: Option, +} diff --git a/xprobe/protocol/src/schema.rs b/xprobe/protocol/src/schema.rs index ff57259..b736f6c 100644 --- a/xprobe/protocol/src/schema.rs +++ b/xprobe/protocol/src/schema.rs @@ -1,18 +1,20 @@ use schemars::{Schema, schema_for}; use crate::{ - AggregateInventoryResult, CapabilityReport, CpuSampleInventoryResult, CpuSamplingSpec, - CpuSamplingValidationResult, DiscoveryResult, ErrorResponse, Event, HostCaptureResult, - MeasurementGraphResult, MeasurementGraphSpec, MeasurementGraphValidationResult, - MeasurementResult, MeasurementSpec, ProcessReport, ResolvedProbe, SyscallAggregateResult, + AggregateInventoryResult, CapabilityReport, CaptureManifest, CpuSampleInventoryResult, + CpuSamplingSpec, CpuSamplingValidationResult, DiscoveryResult, ErrorResponse, Event, + HostCaptureResult, MeasurementGraphResult, MeasurementGraphSpec, + MeasurementGraphValidationResult, MeasurementResult, MeasurementSpec, ProcessReport, + PythonSampleRecord, PythonSampleResult, ResolvedProbe, SyscallAggregateResult, SyscallAggregateSpec, SyscallAggregateValidationResult, TraceExportResult, TriageResult, - ValidationResult, + TriggerResult, ValidationResult, }; #[must_use] -pub fn generated_schemas() -> [(&'static str, Schema); 22] { +pub fn generated_schemas() -> [(&'static str, Schema); 26] { [ ("event.schema.json", schema_for!(Event)), + ("capture-manifest.schema.json", schema_for!(CaptureManifest)), ("error.schema.json", schema_for!(ErrorResponse)), ("measurement-spec.schema.json", schema_for!(MeasurementSpec)), ( @@ -54,7 +56,16 @@ pub fn generated_schemas() -> [(&'static str, Schema); 22] { ("resolve.schema.json", schema_for!(ResolvedProbe)), ("validate.schema.json", schema_for!(ValidationResult)), ("trace-export.schema.json", schema_for!(TraceExportResult)), + ( + "python-sample-result.schema.json", + schema_for!(PythonSampleResult), + ), + ( + "python-sample-record.schema.json", + schema_for!(PythonSampleRecord), + ), ("triage-result.schema.json", schema_for!(TriageResult)), + ("trigger-result.schema.json", schema_for!(TriggerResult)), ( "measurement-graph-spec.schema.json", schema_for!(MeasurementGraphSpec), diff --git a/xprobe/protocol/src/triage.rs b/xprobe/protocol/src/triage.rs index d55e5dc..81ac44f 100644 --- a/xprobe/protocol/src/triage.rs +++ b/xprobe/protocol/src/triage.rs @@ -100,9 +100,18 @@ pub struct TriageResult { pub threads: ThreadTimeBreakdown, pub cgroup: Option, pub cpu_hotspots: Vec, + /// Python functions holding the GIL, from external CPython sampling. + pub python_hotspots: Vec, + /// Share of GIL ticks with no thread running Python, when sampled. + pub gil_released_proportion: Option, pub syscalls: Vec, + /// NVML health of every GPU on the host; `uuid` ties it to `cuda_devices`. pub gpu_devices: Vec, pub gpu_activity: Vec, + /// The UUID behind each CUDA ordinal in `gpu_activity`; GPU findings + /// cover only GPUs the target ran work on. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub cuda_devices: Vec, pub sources: Vec, /// Questions this triage cannot answer; do not infer them from silence. pub not_covered: Vec, @@ -159,6 +168,7 @@ pub enum TriageSourceKind { SyscallAggregate, GpuHealth, GpuActivity, + PythonSample, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] diff --git a/xprobe/protocol/src/trigger.rs b/xprobe/protocol/src/trigger.rs new file mode 100644 index 0000000..170715a --- /dev/null +++ b/xprobe/protocol/src/trigger.rs @@ -0,0 +1,110 @@ +//! Triggered capture: keep a ring of recent GPU activity and write a window +//! around each span that crosses a threshold. + +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::{ + ClockDomain, EvidenceArtifact, MatchPolicy, MatchedEventPair, SchemaVersion3, SessionStatus, + TargetIdentity, Warning, +}; + +/// What a trigger measures on each span it evaluates. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum TriggerKind { + /// A gap on one stream: an activity end to the next kernel, copy, or + /// memset start on that stream, even while other streams keep the + /// device busy. + Gap, + /// Idle time on one device: no kernel, copy, or memset of the target on + /// any of its streams. + Idle, + /// One kernel, copy, or memset from start to end. + Duration, + /// One edge between two selectors under a correlation policy. + Latency, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct TriggerCondition { + pub kind: TriggerKind, + /// A span fires when it lasts at least this long. + pub threshold_ns: u64, + /// Edge selectors and policy of a latency trigger. + pub start_selector: Option, + pub end_selector: Option, + pub match_policy: Option, + /// Context kept before the firing span's start and after its end. + pub pre_ns: u64, + pub post_ns: u64, + /// Windows to write before stopping; later windows start after the + /// previous one ends. + pub windows: u32, +} + +/// Result of `measure --trigger-*`, schema `3.0`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct TriggerResult { + pub schema_version: SchemaVersion3, + pub ok: bool, + pub session_id: String, + /// `timed_out` when the deadline passed with fewer windows than requested; + /// otherwise `completed`, even when windows were lost or revoked. + pub status: SessionStatus, + pub target: TargetIdentity, + pub trigger: TriggerCondition, + pub observed: TriggerObservation, + pub windows: Vec, + pub collection: TriggerCollection, + pub warnings: Vec, +} + +/// Every span evaluated while waiting, fired or not. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct TriggerObservation { + pub spans: u64, + pub over_threshold: u64, + /// The longest span seen, whether or not its window could be written. + pub longest: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct TriggerWindow { + pub index: u32, + /// The span that crossed the threshold. + pub fired: MatchedEventPair, + /// Window bounds in the events' clock, clipped to what was captured. + pub start_ns: u64, + pub end_ns: u64, + pub clock_domain: ClockDomain, + /// The capture began after `pre_ns` before the span or ended before + /// `post_ns` after it, so the window is shorter than requested. + pub truncated: bool, + /// The longest spans of the trigger's kind inside the window. + pub longest: Vec, + pub artifact: EvidenceArtifact, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct TriggerCollection { + /// Maps window timestamps to wall time. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wall_clock: Option, + /// Agent ring and CLI retention bound, in records. + pub ring_capacity: u64, + pub observed_records: u64, + /// Records the ring overwrote before they were read. + pub overwritten_records: u64, + pub dropped_records: u64, + /// Windows discarded because records inside them were lost. + pub lost_windows: u32, + /// Windows discarded because their firing span no longer crossed the + /// threshold once every record had arrived. + pub revoked_windows: u32, +} diff --git a/xprobe/protocol/tests/contracts.rs b/xprobe/protocol/tests/contracts.rs index 2640543..452aca2 100644 --- a/xprobe/protocol/tests/contracts.rs +++ b/xprobe/protocol/tests/contracts.rs @@ -457,6 +457,7 @@ fn measurement_result_contract_round_trips() { }, "collection": { "completeness": "complete", + "coverage": {"source": "live", "all_gpu_activity": false}, "host_events": 1, "cuda_events": 1, "dropped_events": 0, @@ -492,7 +493,7 @@ fn measurement_results_require_schema_three() { "quality": {"verdict": "good", "issues": []}, "correlation": {"method": "exact", "confidence": "exact", "score": 1.0}, "clock": {"alignment": "host_monotonic", "estimated_error_ns": 0}, - "collection": {"completeness": "complete", "host_events": 2, "cuda_events": 0, "dropped_events": 0, "cupti": null}, + "collection": {"completeness": "complete", "coverage": {"source": "unverified", "all_gpu_activity": false}, "host_events": 2, "cuda_events": 0, "dropped_events": 0, "cupti": null}, "evidence": {"mode": "full", "exemplars": [], "pairs": [], "artifact": null}, "warnings": [] })) @@ -795,6 +796,8 @@ fn triage_result_contract_round_trips() { "throttled_ns": 0 }, "cpu_hotspots": [], + "python_hotspots": [], + "gil_released_proportion": null, "syscalls": [], "gpu_devices": [{ "index": 0,