From 837c27a36e1c0eda80c0183186cd5dfeebdea42e Mon Sep 17 00:00:00 2001 From: itdevwu Date: Tue, 1 Dec 2026 22:39:58 +0800 Subject: [PATCH 01/22] =?UTF-8?q?=F0=9F=90=9B=20fix:=20keep=20a=20second?= =?UTF-8?q?=20session=20from=20taking=20over=20a=20running=20CUPTI=20captu?= =?UTF-8?q?re?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A second measure on the same target used to restart the Agent or re-ARM it, dropping the first session's capture without an error. The session that sends ARM now owns the capture, identified by the peer PID and start time on the control socket. While it runs, agent start returns BUSY and commands from other processes get stop reason 6; the CLI reports CUPTI_AGENT_BUSY. An owner that exited without STOP gives way. A CUPTI subscriber held by another tool (torch.profiler, Nsight, cuda-gdb) now reports stop reason 7, and the CLI names those tools in its hint. --- cupti/include/xprobe/cupti_agent.h | 12 +- cupti/src/cupti_agent.c | 137 ++++++++++++++++++ docs/cli-reference.md | 3 +- docs/cupti-agent.md | 13 +- schemas/cpu-sampling-validate.schema.json | 1 + schemas/error.schema.json | 1 + .../measurement-graph-validate.schema.json | 1 + .../syscall-aggregate-validate.schema.json | 1 + schemas/validate.schema.json | 1 + tests/integration/run-inject-live.sh | 28 ++++ tests/integration/test_inject.py | 9 ++ xprobe/cli/src/live.rs | 26 ++++ xprobe/collector/src/cupti.rs | 71 ++++++++- xprobe/core/src/inject.rs | 14 +- xprobe/protocol/src/error.rs | 2 + 15 files changed, 312 insertions(+), 8 deletions(-) diff --git a/cupti/include/xprobe/cupti_agent.h b/cupti/include/xprobe/cupti_agent.h index fcc8414..6fef988 100644 --- a/cupti/include/xprobe/cupti_agent.h +++ b/cupti/include/xprobe/cupti_agent.h @@ -45,7 +45,9 @@ enum xprobe_cupti_agent_status { XPROBE_CUPTI_AGENT_READY = 0, XPROBE_CUPTI_AGENT_UNAVAILABLE = 1, XPROBE_CUPTI_AGENT_CUPTI_ERROR = 2, - XPROBE_CUPTI_AGENT_OUTPUT_ERROR = 3 + XPROBE_CUPTI_AGENT_OUTPUT_ERROR = 3, + /* Another xprobe session owns the capture and is still running. */ + XPROBE_CUPTI_AGENT_BUSY = 4 }; enum xprobe_cupti_capture_state { @@ -64,7 +66,13 @@ enum xprobe_cupti_stop_reason { 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 + XPROBE_CUPTI_STOP_CLEANUP_ERROR = 5, + /* Reply to a command from a session that does not own the capture: the + * Agent did nothing and sends a header without records. */ + XPROBE_CUPTI_STOP_SESSION_BUSY = 6, + /* Another CUPTI client, such as torch.profiler, Nsight Systems, Nsight + * Compute, or cuda-gdb, holds the process's CUPTI subscriber. */ + XPROBE_CUPTI_STOP_SUBSCRIBER_CONFLICT = 7 }; enum xprobe_cupti_control_command { diff --git a/cupti/src/cupti_agent.c b/cupti/src/cupti_agent.c index 23b9f14..0dc1ba3 100644 --- a/cupti/src/cupti_agent.c +++ b/cupti/src/cupti_agent.c @@ -186,6 +186,11 @@ static int agent_initialized; static uint32_t enabled_activity_mask; static char output_path[PATH_MAX]; static char snapshot_socket_path[sizeof(((struct sockaddr_un *)0)->sun_path)]; +/* The xprobe process that armed the current capture, by PID and start time, + * as seen through the control socket. 0 when no session owns it, or when the + * owner's PID is not visible from the target. Guarded by flush_mutex. */ +static pid_t owner_pid; +static unsigned long long owner_start_time; static pthread_mutex_t flush_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t subscriber_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_t snapshot_thread; @@ -2345,6 +2350,98 @@ static int stop_capture(void) return status; } +/* Field 22 of /proc//stat, after the parenthesized command name. */ +static int process_start_time(pid_t pid, unsigned long long *start_time) +{ + char path[64]; + char buffer[1024]; + ssize_t length; + int descriptor; + const char *field; + + (void)snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid); + descriptor = open(path, O_RDONLY | O_CLOEXEC); + if (descriptor < 0) { + return -1; + } + length = read(descriptor, buffer, sizeof(buffer) - 1U); + (void)close(descriptor); + if (length <= 0) { + return -1; + } + buffer[length] = '\0'; + field = strrchr(buffer, ')'); + if (field == NULL) { + return -1; + } + /* Field 3 starts two bytes after ')'; skip to field 22. */ + field += 2; + for (int index = 3; index < 22; ++index) { + field = strchr(field, ' '); + if (field == NULL) { + return -1; + } + ++field; + } + *start_time = strtoull(field, NULL, 10); + return 0; +} + +/* The process on the other end of a control connection; PID 0 when the + * kernel cannot name it in the target's PID namespace. */ +static void peer_identity(int client, pid_t *pid, unsigned long long *start_time) +{ + struct ucred credentials; + socklen_t length = sizeof(credentials); + + *pid = 0; + *start_time = 0U; + if (getsockopt(client, SOL_SOCKET, SO_PEERCRED, &credentials, &length) == 0 && + credentials.pid > 0 && + process_start_time(credentials.pid, start_time) == 0) { + *pid = credentials.pid; + } +} + +/* Whether a session other than `pid` owns the capture and is still running. + * An owner that exited without STOP gives way. Called with flush_mutex. */ +static int owned_by_another_session(pid_t pid, unsigned long long start_time) +{ + unsigned long long current; + + if (owner_pid == 0 || (owner_pid == pid && owner_start_time == start_time)) { + return 0; + } + if (process_start_time(owner_pid, ¤t) == 0 && + current == owner_start_time) { + return 1; + } + fprintf(stderr, + "xprobe CUPTI: session of PID %d exited without STOP; " + "another session takes over\n", + (int)owner_pid); + owner_pid = 0; + owner_start_time = 0U; + return 0; +} + +/* A header without records telling a session that another one owns the + * capture. Nothing in the capture changes. */ +static int write_busy_reply(int descriptor) +{ + struct xprobe_cupti_output_header header; + + memset(&header, 0, sizeof(header)); + memcpy(header.magic, XPROBE_CUPTI_OUTPUT_MAGIC, sizeof(header.magic)); + header.abi_version = XPROBE_CUPTI_AGENT_ABI_VERSION; + header.header_size = sizeof(header); + header.record_size = sizeof(records[0]); + header.capture_state = + (uint32_t)atomic_load_explicit(&capture_state, memory_order_acquire); + header.stop_reason = XPROBE_CUPTI_STOP_SESSION_BUSY; + return send_all(descriptor, &header, sizeof(header)); +} + static void *serve_snapshots(void *unused) { (void)unused; @@ -2383,6 +2480,10 @@ static void *serve_snapshots(void *unused) continue; } + pid_t peer_pid; + unsigned long long peer_start_time; + + peer_identity(client, &peer_pid, &peer_start_time); if (receive_all(client, &request, sizeof(request)) != 0 || memcmp(request.magic, XPROBE_CUPTI_CONTROL_MAGIC, sizeof(request.magic)) != 0 || @@ -2397,6 +2498,14 @@ static void *serve_snapshots(void *unused) /* 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 if (owned_by_another_session(peer_pid, peer_start_time) != 0) { + if (write_busy_reply(client) != 0) { + fprintf(stderr, "xprobe CUPTI: failed to send busy reply: %s\n", + strerror(errno)); + } + if (pthread_mutex_unlock(&flush_mutex) != 0) { + fprintf(stderr, "xprobe CUPTI: failed to unlock snapshot flush mutex\n"); + } } else { int command_status = XPROBE_CUPTI_AGENT_READY; @@ -2407,6 +2516,11 @@ static void *serve_snapshots(void *unused) command_status = XPROBE_CUPTI_AGENT_OUTPUT_ERROR; } else if (request.command == XPROBE_CUPTI_CONTROL_ARM) { command_status = arm_capture(&request); + if (atomic_load_explicit(&capture_state, memory_order_acquire) == + XPROBE_CUPTI_CAPTURE_ACTIVE) { + owner_pid = peer_pid; + owner_start_time = peer_start_time; + } } else if (request.command == XPROBE_CUPTI_CONTROL_SNAPSHOT) { if (atomic_load_explicit(&capture_state, memory_order_acquire) == XPROBE_CUPTI_CAPTURE_ACTIVE) { @@ -2414,6 +2528,8 @@ static void *serve_snapshots(void *unused) } } else { command_status = stop_capture(); + owner_pid = 0; + owner_start_time = 0U; /* Keep serving after a failed cleanup so CLOSE can retry. */ close_requested = request.command == XPROBE_CUPTI_CONTROL_CLOSE && @@ -2607,6 +2723,11 @@ static int ensure_subscriber(void) result = cuptiSubscribe(&subscriber, api_callback, NULL); if (result != CUPTI_SUCCESS) { report_cupti_error("cuptiSubscribe", result); + if (result == CUPTI_ERROR_MULTIPLE_SUBSCRIBERS_NOT_SUPPORTED) { + atomic_store_explicit(&stop_reason, + XPROBE_CUPTI_STOP_SUBSCRIBER_CONFLICT, + memory_order_relaxed); + } status = XPROBE_CUPTI_AGENT_CUPTI_ERROR; } else { subscriber_active = 1; @@ -3013,7 +3134,23 @@ static void finalize_agent(void) int xprobe_cupti_agent_start(const char *configured_socket, uint64_t capacity) { size_t length; + int busy; + /* Restarting would close the socket and drop the capture of a session + * that is still running. The caller is not a socket peer, so any live + * owner makes the Agent busy. */ + if (pthread_mutex_lock(&flush_mutex) != 0) { + remember_output_error(); + return XPROBE_CUPTI_AGENT_OUTPUT_ERROR; + } + busy = owned_by_another_session(0, 0U); + if (pthread_mutex_unlock(&flush_mutex) != 0) { + remember_output_error(); + return XPROBE_CUPTI_AGENT_OUTPUT_ERROR; + } + if (busy != 0) { + return XPROBE_CUPTI_AGENT_BUSY; + } stop_snapshot_server(); if (shutdown_agent() != XPROBE_CUPTI_AGENT_READY) { return xprobe_cupti_agent_status(); diff --git a/docs/cli-reference.md b/docs/cli-reference.md index fd0ee28..5c44a1c 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -187,7 +187,7 @@ xprobe measure --spec measurement.json - `evidence`: exemplars at min, p50, p90, p99, and max, the artifact path, and every pair with `--evidence full` - `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`. +Error codes include `CUPTI_AGENT_BUSY`, `NO_MATCHED_SAMPLES`, `CLOCK_ALIGNMENT_FAILED`, `EVENT_RATE_TOO_HIGH`, `EVENTS_DROPPED`, `TRIGGER_NOT_OBSERVED`, `TARGET_EXITED`, `TARGET_REUSED`, and `CLEANUP_FAILED`. ### Inventories @@ -263,6 +263,7 @@ Results follow `schemas/trigger-result.schema.json` (schema `3.0`). - Host endpoints attach every eBPF link before arming. A duration capture that reaches `--max-events` fails with `EVENT_RATE_TOO_HIGH`. - CUDA endpoints find the Agent from `--agent`, then `XPROBE_CUPTI_AGENT_PATH`, then `../lib/xprobe/cuda12|cuda13`, then the matching build path. +- One xprobe session owns the Agent at a time. While it runs, another `measure` on the same target fails with `CUPTI_AGENT_BUSY` and leaves the capture alone; combine edges into one measurement graph instead. If torch.profiler or an Nsight tool holds the target's CUPTI subscriber, `measure` fails with `CUPTI_NOT_AVAILABLE` and a hint naming them. - Live injection needs Linux x86_64, the same mount namespace as the target, and ptrace permission. It prints a warning to stderr and emits `CUPTI_AGENT_INJECTED`. On stop it disables CUPTI and removes its private socket; the `.so` stays mapped. - NVTX thread ranges are tracked by `(tid, push_level)` and process ranges by `range_id` across threads (`start_tid`). ASCII `PushA`/`StartA` and the `Ex` forms are supported; wide and registered strings and CUPTI Range Profiling are not. diff --git a/docs/cupti-agent.md b/docs/cupti-agent.md index 29d9797..2b14d9b 100644 --- a/docs/cupti-agent.md +++ b/docs/cupti-agent.md @@ -18,6 +18,16 @@ Release packages ship separate builds linked to `libcupti.so.12` and `libcupti.s **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. +### One session at a time + +The Agent serves one xprobe session at a time. The session that sends `ARM` owns the capture until it sends `STOP` or `CLOSE`; the Agent identifies it by the PID and start time of the process on the other end of the control socket. + +- While the owner is running, `xprobe_cupti_agent_start` returns `XPROBE_CUPTI_AGENT_BUSY` and changes nothing, and `ARM`, `SNAPSHOT`, `STOP`, or `CLOSE` from another process gets a header without records and stop reason `6` (`XPROBE_CUPTI_STOP_SESSION_BUSY`). The CLI reports `CUPTI_AGENT_BUSY`. To measure several edges at once, use one measurement graph. +- If the owner exited without `STOP`, the next session takes over and the Agent logs it on the target's stderr. +- If the owner's PID is not visible in the target's PID namespace, the Agent cannot track it and does not refuse other sessions. + +CUPTI allows one subscriber per process. If torch.profiler, Nsight Systems, Nsight Compute, or cuda-gdb holds it, `ARM` fails with stop reason `7` (`XPROBE_CUPTI_STOP_SUBSCRIBER_CONFLICT`), and the CLI names those tools in its hint. After a normal `STOP` the Agent unsubscribes, so those tools work again. A target started with `NVTX_INJECTION64_PATH` keeps the Agent's subscriber for its lifetime (see below). + ### 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. @@ -59,6 +69,7 @@ Defined in `cupti/include/xprobe/cupti_agent.h`: - 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`. +- Stop reasons `6` (another session owns the capture) and `7` (another CUPTI client holds the subscriber) are described in [One session at a time](#one-session-at-a-time). ### 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. @@ -75,6 +86,6 @@ Defined in `cupti/include/xprobe/cupti_agent.h`: ## Verification - `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-injection-live` / `just test-injection-live-cuda12`: first-load injection, reactivation, and a second session refused while the first captures. - `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/schemas/cpu-sampling-validate.schema.json b/schemas/cpu-sampling-validate.schema.json index 3d09884..6bfa9be 100644 --- a/schemas/cpu-sampling-validate.schema.json +++ b/schemas/cpu-sampling-validate.schema.json @@ -113,6 +113,7 @@ "INVALID_CORRELATION_POLICY", "CUPTI_NOT_AVAILABLE", "CUPTI_AGENT_NOT_LOADED", + "CUPTI_AGENT_BUSY", "CUDA_CONTEXT_NOT_FOUND", "UNSUPPORTED_CUDA_VERSION", "UNSUPPORTED_PYTHON_VERSION", diff --git a/schemas/error.schema.json b/schemas/error.schema.json index be3d2e2..561ad6b 100644 --- a/schemas/error.schema.json +++ b/schemas/error.schema.json @@ -34,6 +34,7 @@ "INVALID_CORRELATION_POLICY", "CUPTI_NOT_AVAILABLE", "CUPTI_AGENT_NOT_LOADED", + "CUPTI_AGENT_BUSY", "CUDA_CONTEXT_NOT_FOUND", "UNSUPPORTED_CUDA_VERSION", "UNSUPPORTED_PYTHON_VERSION", diff --git a/schemas/measurement-graph-validate.schema.json b/schemas/measurement-graph-validate.schema.json index ea20f6f..2489f79 100644 --- a/schemas/measurement-graph-validate.schema.json +++ b/schemas/measurement-graph-validate.schema.json @@ -97,6 +97,7 @@ "INVALID_CORRELATION_POLICY", "CUPTI_NOT_AVAILABLE", "CUPTI_AGENT_NOT_LOADED", + "CUPTI_AGENT_BUSY", "CUDA_CONTEXT_NOT_FOUND", "UNSUPPORTED_CUDA_VERSION", "UNSUPPORTED_PYTHON_VERSION", diff --git a/schemas/syscall-aggregate-validate.schema.json b/schemas/syscall-aggregate-validate.schema.json index 6eefaf6..bbd8db3 100644 --- a/schemas/syscall-aggregate-validate.schema.json +++ b/schemas/syscall-aggregate-validate.schema.json @@ -87,6 +87,7 @@ "INVALID_CORRELATION_POLICY", "CUPTI_NOT_AVAILABLE", "CUPTI_AGENT_NOT_LOADED", + "CUPTI_AGENT_BUSY", "CUDA_CONTEXT_NOT_FOUND", "UNSUPPORTED_CUDA_VERSION", "UNSUPPORTED_PYTHON_VERSION", diff --git a/schemas/validate.schema.json b/schemas/validate.schema.json index 2137123..880a2b4 100644 --- a/schemas/validate.schema.json +++ b/schemas/validate.schema.json @@ -96,6 +96,7 @@ "INVALID_CORRELATION_POLICY", "CUPTI_NOT_AVAILABLE", "CUPTI_AGENT_NOT_LOADED", + "CUPTI_AGENT_BUSY", "CUDA_CONTEXT_NOT_FOUND", "UNSUPPORTED_CUDA_VERSION", "UNSUPPORTED_PYTHON_VERSION", diff --git a/tests/integration/run-inject-live.sh b/tests/integration/run-inject-live.sh index 3eb451e..8c04936 100755 --- a/tests/integration/run-inject-live.sh +++ b/tests/integration/run-inject-live.sh @@ -129,11 +129,39 @@ run_aggregate_limit() { fi } +# While one session captures, a second one cannot take over the Agent. +run_busy_pair() { + agent_args=() + if [[ ${auto_agent} != 1 ]]; then + agent_args=(--agent "${agent}") + fi + "${xprobe_bin}" measure \ + --pid "${target_pid}" \ + "${agent_args[@]}" \ + --from 'cuda:runtime_api:cudaLaunchKernel:entry' \ + --to 'cuda:runtime_api:cudaLaunchKernel:exit' \ + --match exact \ + --duration-ms 3000 \ + --max-events 10000 \ + --timeout-ms 10000 \ + --json --non-interactive --no-color \ + >"$1/owner.json" 2>"$1/owner.stderr" & + owner_pid=$! + sleep 1 + if run_api_measure "$1/busy"; then + echo "a second session took over a running capture" >&2 + return 1 + fi + wait "${owner_pid}" +} + run_measure "$1/first" run_measure "$1/second" run_api_measure "$1/api" run_aggregate_measure "$1/aggregate" run_aggregate_limit "$1/aggregate-limit" +run_busy_pair "$1" +run_api_measure "$1/after-busy" if [[ ${auto_agent} == 1 ]]; then mapped_agents=$(awk '$0 ~ /lib\/xprobe\/cuda(12|13)\/libxprobe-cupti.so/ {print $NF}' "/proc/${target_pid}/maps" | sort -u | wc -l) diff --git a/tests/integration/test_inject.py b/tests/integration/test_inject.py index c6a2536..3bf4586 100755 --- a/tests/integration/test_inject.py +++ b/tests/integration/test_inject.py @@ -103,6 +103,15 @@ def main() -> None: assert aggregate_limit["error"]["code"] == "EVENT_RATE_TOO_HIGH" assert aggregate_limit["error"]["details"]["group_capacity"] == 1 assert aggregate_limit["error"]["details"]["observed_activities"] >= 2 + owner = json.loads((output / "owner.json").read_text()) + assert owner["ok"] is True + assert owner["measurement"]["samples"]["matched"] > 0 + busy = json.loads((output / "busy.json").read_text()) + assert busy["ok"] is False + assert busy["error"]["code"] == "CUPTI_AGENT_BUSY" + after_busy = json.loads((output / "after-busy.json").read_text()) + assert after_busy["ok"] is True + assert after_busy["measurement"]["samples"]["matched"] == 3 assert int((output / "mapped-agents.txt").read_text()) == 1 if package is not None: expected_major = 12 if ":12." in sys.argv[1] else 13 diff --git a/xprobe/cli/src/live.rs b/xprobe/cli/src/live.rs index dfdf47a..09ab928 100644 --- a/xprobe/cli/src/live.rs +++ b/xprobe/cli/src/live.rs @@ -656,12 +656,27 @@ pub(crate) fn arm_cupti_capture( }; let capture = match cupti::arm(path, request.timeout, &request.options.session_id, config) { Ok(capture) => capture, + Err(cupti::CuptiSnapshotError::SessionBusy) => { + // The Agent belongs to the other session; leave it alone. + return Err(agent_busy_failure()); + } Err(error) => { let failure = CommandFailure::new(ErrorCode::CuptiNotAvailable, error.to_string(), true); return cleanup_failed_arm(activation, request, failure); } }; + if capture.stop_reason == cupti::CuptiStopReason::SubscriberConflict { + let failure = CommandFailure::new( + ErrorCode::CuptiNotAvailable, + "another CUPTI client holds the target's CUPTI subscriber", + true, + ) + .with_hint( + "stop torch.profiler, Nsight Systems, Nsight Compute, or cuda-gdb in the target, then retry", + ); + return cleanup_failed_arm(activation, request, failure); + } if needs_nvtx && !capture.nvtx_callbacks_active { let failure = CommandFailure::new( ErrorCode::CuptiNotAvailable, @@ -685,6 +700,17 @@ pub(crate) fn arm_cupti_capture( Ok(Some(capture)) } +pub(crate) fn agent_busy_failure() -> CommandFailure { + CommandFailure::new( + ErrorCode::CuptiAgentBusy, + "the CUPTI Agent in the target is serving another xprobe session", + true, + ) + .with_hint( + "wait for the other measure to finish, or combine the edges into one measurement graph", + ) +} + pub(crate) fn cleanup_failed_arm( activation: &CuptiActivation, request: &LiveMeasureRequest, diff --git a/xprobe/collector/src/cupti.rs b/xprobe/collector/src/cupti.rs index 275adbc..a5399c8 100644 --- a/xprobe/collector/src/cupti.rs +++ b/xprobe/collector/src/cupti.rs @@ -278,6 +278,10 @@ pub enum CuptiStopReason { OutputError, /// STOP could not disable every callback or activity kind. CleanupError, + /// Another xprobe session owns the capture; the Agent did nothing. + SessionBusy, + /// Another CUPTI client holds the process's CUPTI subscriber. + SubscriberConflict, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -425,11 +429,16 @@ impl Error for CuptiDecodeError {} #[derive(Debug)] pub enum CuptiSnapshotError { InvalidControl(String), - Connect { path: PathBuf, source: io::Error }, + Connect { + path: PathBuf, + source: io::Error, + }, Configure(io::Error), Write(io::Error), Read(io::Error), Decode(CuptiDecodeError), + /// Another xprobe session owns the Agent's capture. + SessionBusy, } impl fmt::Display for CuptiSnapshotError { @@ -452,6 +461,8 @@ impl fmt::Display for CuptiSnapshotError { Self::Write(source) => write!(formatter, "failed to request CUPTI snapshot: {source}"), Self::Read(source) => write!(formatter, "failed to read CUPTI snapshot: {source}"), Self::Decode(source) => write!(formatter, "failed to decode CUPTI snapshot: {source}"), + Self::SessionBusy => formatter + .write_str("the CUPTI Agent in the target is serving another xprobe session"), } } } @@ -459,7 +470,7 @@ impl fmt::Display for CuptiSnapshotError { impl Error for CuptiSnapshotError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { - Self::InvalidControl(_) => None, + Self::InvalidControl(_) | Self::SessionBusy => None, Self::Connect { source, .. } | Self::Configure(source) | Self::Write(source) @@ -560,7 +571,11 @@ fn request( .map_err(CuptiSnapshotError::Write)?; let mut bytes = Vec::new(); read_snapshot(&mut stream, &mut bytes)?; - decode_capture(&bytes, session_id).map_err(CuptiSnapshotError::Decode) + let capture = decode_capture(&bytes, session_id).map_err(CuptiSnapshotError::Decode)?; + if capture.stop_reason == CuptiStopReason::SessionBusy { + return Err(CuptiSnapshotError::SessionBusy); + } + Ok(capture) } fn encode_control( @@ -986,6 +1001,8 @@ fn decode_stop_reason(value: u32) -> Result { 3 => Ok(CuptiStopReason::CuptiError), 4 => Ok(CuptiStopReason::OutputError), 5 => Ok(CuptiStopReason::CleanupError), + 6 => Ok(CuptiStopReason::SessionBusy), + 7 => Ok(CuptiStopReason::SubscriberConflict), _ => Err(CuptiDecodeError::InvalidStopReason(value)), } } @@ -1816,6 +1833,54 @@ mod tests { assert_eq!(decoded.aggregate_groups[0].name_complete, Some(false)); } + #[test] + fn a_busy_reply_fails_the_request_and_a_conflict_decodes() { + use std::{ + io::{Read as _, Write as _}, + os::unix::net::UnixListener, + time::Duration, + }; + + use super::{CuptiSnapshotError, CuptiStopReason}; + + let directory = std::env::temp_dir().join(format!("xprobe-busy-{}", std::process::id())); + std::fs::create_dir_all(&directory).unwrap(); + let socket = directory.join("agent.sock"); + let _ = std::fs::remove_file(&socket); + let listener = UnixListener::bind(&socket).unwrap(); + // The Agent's reply to a session that does not own the capture. + let mut busy = capture(&[]); + busy[24..28].copy_from_slice(&1_u32.to_le_bytes()); + busy[28..32].copy_from_slice(&6_u32.to_le_bytes()); + busy[40..48].copy_from_slice(&0_u64.to_le_bytes()); + let agent = std::thread::spawn(move || { + let (mut client, _) = listener.accept().unwrap(); + let mut request = Vec::new(); + client.read_to_end(&mut request).unwrap(); + client.write_all(&busy).unwrap(); + }); + let config = CuptiArmConfig { + record_capacity: 16, + capture_mode: CuptiCaptureMode::Exact, + filters: vec![CuptiEventFilter { + record_kind: CuptiRecordKind::GpuKernelStart, + api_domain: CuptiApiDomain::Any, + memcpy_kind: CuptiMemcpyKind::Any, + name: CuptiNameFilter::Any, + }], + }; + let result = super::arm(&socket, Duration::from_secs(5), "xp_test", &config); + agent.join().unwrap(); + std::fs::remove_dir_all(&directory).unwrap(); + assert!(matches!(result, Err(CuptiSnapshotError::SessionBusy))); + + let mut conflict = capture(&[]); + conflict[24..28].copy_from_slice(&4_u32.to_le_bytes()); + conflict[28..32].copy_from_slice(&7_u32.to_le_bytes()); + let decoded = decode_capture(&conflict, "xp_test").unwrap(); + assert_eq!(decoded.stop_reason, CuptiStopReason::SubscriberConflict); + } + #[test] fn encodes_bounded_arm_filters() { let control = encode_control( diff --git a/xprobe/core/src/inject.rs b/xprobe/core/src/inject.rs index 46d660d..cdb4cd9 100644 --- a/xprobe/core/src/inject.rs +++ b/xprobe/core/src/inject.rs @@ -27,6 +27,8 @@ use crate::{ const RTLD_NOW: u64 = 2; const RTLD_LOCAL: u64 = 0; const AGENT_START_SYMBOL: &str = "xprobe_cupti_agent_start"; +/// `XPROBE_CUPTI_AGENT_BUSY` from `xprobe_cupti_agent_start`. +const AGENT_BUSY: u64 = 4; #[derive(Debug, Clone, PartialEq, Eq)] pub struct InjectionResult { @@ -59,6 +61,9 @@ pub enum InjectError { function: &'static str, result: u64, }, + /// The Agent is already loaded and another xprobe session owns its + /// capture. + AgentBusy, } impl InjectError { @@ -72,6 +77,7 @@ impl InjectError { | Self::UnexpectedStop(_) | Self::TimedOut => ErrorCode::PermissionDenied, Self::UnsupportedPlatform => ErrorCode::UnsupportedCudaVersion, + Self::AgentBusy => ErrorCode::CuptiAgentBusy, Self::InvalidAgent(_) | Self::MissingRuntimeSymbol(_) | Self::ShortMemoryTransfer { .. } @@ -117,6 +123,8 @@ impl fmt::Display for InjectError { ) } Self::TimedOut => formatter.write_str("remote function call timed out"), + Self::AgentBusy => formatter + .write_str("the CUPTI Agent in the target is serving another xprobe session"), Self::RemoteCallTrap { instruction_pointer, } => write!( @@ -148,7 +156,8 @@ impl Error for InjectError { | Self::TimedOut | Self::RemoteCallTrap { .. } | Self::ShortMemoryTransfer { .. } - | Self::RemoteCallFailed { .. } => None, + | Self::RemoteCallFailed { .. } + | Self::AgentBusy => None, } } } @@ -225,6 +234,9 @@ pub fn activate( } remote.detach()?; inspect::verify_target(&report.target)?; + if status == AGENT_BUSY { + return Err(InjectError::AgentBusy); + } if status != 0 { return Err(InjectError::RemoteCallFailed { function: AGENT_START_SYMBOL, diff --git a/xprobe/protocol/src/error.rs b/xprobe/protocol/src/error.rs index 71613d4..bc56dbd 100644 --- a/xprobe/protocol/src/error.rs +++ b/xprobe/protocol/src/error.rs @@ -20,6 +20,7 @@ pub enum ErrorCode { InvalidCorrelationPolicy, CuptiNotAvailable, CuptiAgentNotLoaded, + CuptiAgentBusy, CudaContextNotFound, UnsupportedCudaVersion, UnsupportedPythonVersion, @@ -50,6 +51,7 @@ impl ErrorCode { Self::InvalidCorrelationPolicy => "INVALID_CORRELATION_POLICY", Self::CuptiNotAvailable => "CUPTI_NOT_AVAILABLE", Self::CuptiAgentNotLoaded => "CUPTI_AGENT_NOT_LOADED", + Self::CuptiAgentBusy => "CUPTI_AGENT_BUSY", Self::CudaContextNotFound => "CUDA_CONTEXT_NOT_FOUND", Self::UnsupportedCudaVersion => "UNSUPPORTED_CUDA_VERSION", Self::UnsupportedPythonVersion => "UNSUPPORTED_PYTHON_VERSION", From 94ddda757df3e2b0a0e00e1f49f1fdd7ba22d815 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Tue, 1 Dec 2026 23:48:49 +0800 Subject: [PATCH 02/22] =?UTF-8?q?=F0=9F=94=A7=20chore:=20install=20CPU=20b?= =?UTF-8?q?enchmark=20packages=20from=20the=20Azure=20mirror?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- benchmarks/cpu-inventory/run-container.sh | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/benchmarks/cpu-inventory/run-container.sh b/benchmarks/cpu-inventory/run-container.sh index 7e4cbc3..dcec8d0 100755 --- a/benchmarks/cpu-inventory/run-container.sh +++ b/benchmarks/cpu-inventory/run-container.sh @@ -2,6 +2,12 @@ set -euo pipefail export DEBIAN_FRONTEND=noninteractive +# Canonical's archive has had outages; install from the Azure mirror. +for sources in /etc/apt/sources.list /etc/apt/sources.list.d/ubuntu.sources; do + if [[ -f ${sources} ]]; then + sed -i -E 's#http://(archive|security)\.ubuntu\.com#http://azure.archive.ubuntu.com#' "${sources}" + fi +done apt-get update apt-get install -y --no-install-recommends \ linux-tools-common linux-tools-generic python3 python3-pip From d603f427633dcfb3363d69a9ac13318e1f69de3f Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 03:33:19 +0800 Subject: [PATCH 03/22] =?UTF-8?q?=F0=9F=93=9D=20docs:=20clarify=20Skill=20?= =?UTF-8?q?usage,=20tuning=20limits,=20and=20CLI=20behavior?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Separate kernel and memcpy --aggregate commands, fix exact policy scope, and show how to join CUDA API and memcpy events by correlation_id offline. - Document --python-sample thread capacity sizing, --cpu-sample tuning, completeness checks beyond status == completed, container discover fallback, triage window duration, and keeping libxprobe-cupti.so on disk while injected targets remain running. - Relax Skill word budgets in test_contract.py (1200 / 8000), sync new schema/attribute checks, and tighten prose across docs and Skill files. --- docs/architecture.md | 2 +- docs/cli-reference.md | 22 +++-- docs/cupti-agent.md | 5 +- docs/installation.md | 2 +- docs/releasing.md | 2 +- skills/xprobe-perf-profiling/SKILL.md | 70 ++++++++-------- .../references/data-format.md | 84 ++++++++++++++----- .../references/selectors.md | 16 ++-- tests/agent-contract/test_contract.py | 18 ++-- 9 files changed, 143 insertions(+), 78 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 774020f..697fb19 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -91,7 +91,7 @@ Single-edge and measurement-graph live runs share one capture loop (attach, poll | Policy | Pairing | Confidence | | --- | --- | --- | -| `exact` | CUPTI correlation ID, NVTX range ID, or same-thread syscall/CPython GC lifecycle | exact | +| `exact` | Launch API ↔ kernel (CUPTI correlation ID), same CUDA API entry ↔ exit, kernel/memcpy/memset start ↔ end, NVTX range ID, or same-thread syscall/CPython GC | exact | | `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 | diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 5c44a1c..02e3901 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -54,7 +54,7 @@ Asks NVML for active CUDA compute processes under the process tree rooted at `-- NVML lists processes from every container that shares a GPU: - PIDs this PID namespace cannot see, or that exited during inspection, are reported in `nvml_pids` with `NVML_PROCESS_UNAVAILABLE` instead of failing the command. -- When none are visible, `NVML_PID_NAMESPACE_MISMATCH` notes that NVML returned host PIDs. Inside a container, pass the namespace-local PID to `validate` and `measure` directly. +- When none are visible, `NVML_PID_NAMESPACE_MISMATCH` notes that NVML returned host PIDs. Inside a container, locate CUDA processes via `ps` or `/proc/*/maps` (`libcuda`) / `/proc/*/fd` (`/dev/nvidia*`), then pass the namespace-local PID to `validate` and `measure` directly. - A failed NVML query or a missing root PID is an error. ## Selectors @@ -115,7 +115,7 @@ A read-only check of target identity, probe resolution, CUDA filters, correlatio | Policy | Pairs | | --- | --- | -| `exact` | By CUPTI correlation ID, NVTX range kind and ID, same-thread syscall entry and exit, or same-thread CPython GC start and end | +| `exact` | Launch API ↔ kernel (by CUPTI correlation ID), same CUDA API entry ↔ exit, kernel/memcpy/memset start ↔ end, NVTX range kind and ID, same-thread syscall entry and exit, or same-thread CPython GC start and end | | `stack-nested` | Same-thread host function entry and return, innermost first | | `stream-order` | A GPU activity end with the next kernel, copy, or memset start on the same device, context, and stream | | `first-after`, `nearest` | By time across unrelated sources; always warned as heuristic | @@ -149,8 +149,8 @@ xprobe measure --pid 4242 \ --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 +xprobe measure --pid 4242 --cpu-sample --duration-ms 2000 \ + --frequency-hz 999 --max-samples 20000 --max-groups 2048 --stack-depth 64 --max-threads 1024 # External CPython stacks & GIL holder xprobe measure --pid 4242 --python-sample --duration-ms 2000 @@ -159,9 +159,11 @@ xprobe measure --pid 4242 --python-sample --duration-ms 2000 xprobe measure --pid 4242 --syscall-aggregate --duration-ms 1000 \ --max-groups 256 --max-inflight 1024 -# GPU kernel/memcpy/memset totals inventory +# GPU kernel or memcpy totals inventory (one activity kind per run) 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 --from 'cuda:memcpy_start' --to 'cuda:memcpy_end' \ + --match exact --aggregate --duration-ms 1000 --max-groups 4096 # Same-window multi-source snapshot xprobe measure --pid 4242 --triage --duration-ms 2000 @@ -202,16 +204,18 @@ Each inventory is a live mode that runs for `--duration-ms` and reports totals i `--cpu-sample`, `--syscall-aggregate`, and `--aggregate` write no Event JSONL, so their output cannot be passed to `--input` or `--events-out`. -**`--cpu-sample`** defaults to 99 Hz, 10,000 samples, 256 groups, depth 64, and 1,024 threads. It resolves ELF symbols and `/tmp/perf-.map` Python frames separately and reports `python_status`, uprobe selector hints, lost samples, and truncation. +**`--cpu-sample`** defaults to 99 Hz, 10,000 samples, 256 groups, depth 64, and 1,024 threads. For short 1–2 s captures on busy native processes, raise `--frequency-hz` (e.g. `499`–`999`) and `--max-groups` (e.g. `2048`) to avoid sparse counts or `CPU_GROUP_CAPACITY_REACHED`. It resolves ELF symbols and `/tmp/perf-.map` Python frames separately; when `python_status` is `unsupported` (CPython <3.12) or `inactive` (no `-X perf`), use `--python-sample` instead. **`--python-sample`** reads CPython 3.9–3.14 memory with `process_vm_readv`. It needs ptrace access but no perf events, eBPF, `-X perf`, or injection. - It samples the GIL holder at `--python-hz` (default 2000) and all threads at `--python-threads-hz` (default 100). +- Sample capacity is sized assuming 64 threads (`(python_hz + python_threads_hz * 64) * duration_s`). On processes with many more threads, lower `--python-threads-hz` (or set it to `0` for GIL-only) and check `collection.over_capacity == 0` and `warnings` (`PYTHON_SAMPLES_OVER_CAPACITY`): capacity overflow keeps only the earliest prefix of the window while still reporting `status: "completed"`. - On 3.13 and later it checks its offsets against `_Py_DebugOffsets`. Unsupported and free-threaded builds return `UNSUPPORTED_PYTHON_VERSION`. - Reads that race with the interpreter are discarded and counted in `inconsistent_reads`. - For blocked threads it reports native waits from `/proc//task//syscall`. - Every sample is written with its `CLOCK_MONOTONIC` time to a JSONL artifact (`schemas/python-sample-record.schema.json`). - Frames report `first_line`, the line where the function starts, not the current line. +- `inventory` reports counts and proportions; estimate wall time from `proportion * collection.elapsed_ns` (or `samples / collection.gil_hz_achieved` / `threads_hz_achieved`). **`--syscall-aggregate`** filters by PID in BPF maps sized by `--max-inflight` and `--max-groups`. It reports each syscall's count, errors, min, mean, max, and total duration, with selector hints. It records no per-call events and no pointer values. @@ -231,7 +235,7 @@ Each inventory is a live mode that runs for `--duration-ms` and reports totals i - NVML device health - the CUDA kernel aggregate, which may inject CUPTI -Full inventories go to one artifact per source, and the top 5 entries of each are kept inline. Optional rule-based `findings` and `not_covered` notes are attached. A source that is unavailable or saturated is marked `unavailable` with `TRIAGE_SOURCE_UNAVAILABLE` instead of failing the run. Schema `3.0`. +Full inventories go to one artifact per source, and the top 5 entries of each are kept inline. Optional rule-based `findings` and `not_covered` notes are attached. Because triage includes attach and multi-collector setup around `--duration-ms`, read the actual `window_ms` (and `threads.window_ns`) rather than assuming the requested duration. A source that is unavailable or saturated is marked `unavailable` with `TRIAGE_SOURCE_UNAVAILABLE` instead of failing the run. Schema `3.0`. ### Triggered capture @@ -264,7 +268,7 @@ Results follow `schemas/trigger-result.schema.json` (schema `3.0`). - Host endpoints attach every eBPF link before arming. A duration capture that reaches `--max-events` fails with `EVENT_RATE_TOO_HIGH`. - CUDA endpoints find the Agent from `--agent`, then `XPROBE_CUPTI_AGENT_PATH`, then `../lib/xprobe/cuda12|cuda13`, then the matching build path. - One xprobe session owns the Agent at a time. While it runs, another `measure` on the same target fails with `CUPTI_AGENT_BUSY` and leaves the capture alone; combine edges into one measurement graph instead. If torch.profiler or an Nsight tool holds the target's CUPTI subscriber, `measure` fails with `CUPTI_NOT_AVAILABLE` and a hint naming them. -- Live injection needs Linux x86_64, the same mount namespace as the target, and ptrace permission. It prints a warning to stderr and emits `CUPTI_AGENT_INJECTED`. On stop it disables CUPTI and removes its private socket; the `.so` stays mapped. +- Live injection needs Linux x86_64, the same mount namespace as the target, and ptrace permission. It prints a warning to stderr and emits `CUPTI_AGENT_INJECTED`. On stop it disables CUPTI and removes its private socket while leaving the `.so` mapped. Keep the installed `libxprobe-cupti.so` path on disk while injected targets remain running (deleting a temporary venv or install directory breaks re-attaches until those processes restart). Check mapped state with `xprobe validate` or `grep libxprobe-cupti /proc/$PID/maps`; see [CUPTI Agent](cupti-agent.md) for lifecycle details. - NVTX thread ranges are tracked by `(tid, push_level)` and process ranges by `range_id` across threads (`start_tid`). ASCII `PushA`/`StartA` and the `Ex` forms are supported; wide and registered strings and CUPTI Range Profiling are not. ### Artifacts and offline input @@ -307,4 +311,4 @@ A graph measures 1–8 edges over 1–8 named endpoints from one capture (`schem - `target.process_start_time` is optional; `measure` reads it and checks 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 have no limit; CUDA endpoints share the 8 Agent filters; syscall, tracepoint, and USDT endpoints share 2 Linux slots. -- Each edge correlates on its own (`schemas/measurement-graph-result.schema.json`, schema `3.0`). If any edge fails, the command fails with `details.edge`, and the shared Event JSONL is still written for offline `measure --input`. +- Each edge correlates on its own (`schemas/measurement-graph-result.schema.json`, schema `3.0`). Validation errors on any edge fail before collection with no artifact written; if an edge fails after collection has run, the command fails with `details.edge` while still writing the shared Event JSONL for offline `measure --input`. diff --git a/docs/cupti-agent.md b/docs/cupti-agent.md index 2b14d9b..679f0c4 100644 --- a/docs/cupti-agent.md +++ b/docs/cupti-agent.md @@ -15,6 +15,7 @@ Release packages ship separate builds linked to `libcupti.so.12` and `libcupti.s - `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. + - Keep the installed `libxprobe-cupti.so` path on disk while injected targets remain running; deleting the install directory or venv breaks later attaches until those processes restart. Check mapped state with `xprobe validate` (`requirements.agent_activation`) or `grep libxprobe-cupti /proc/$PID/maps`. **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. @@ -47,7 +48,7 @@ An aggregate `ARM` allocates a fixed `--max-groups` hash table instead of per-ev ### 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. +- Activity still running at `STOP` keeps a start record so the stream stays busy through capture end rather than looking idle. When CUPTI reports no start time (or an unconverted one), the Agent flags it (`XPROBE_CUPTI_RECORD_START_UNKNOWN`) and skips the clock check. The CLI assigns the stream's last activity end (or capture start if empty) and marks `attributes.start_unknown`; these records never become duration, gap, or latency endpoints. - Records with unavailable timestamps after the first timed activity count as dropped. ## Control and capture ABI @@ -64,7 +65,7 @@ Defined in `cupti/include/xprobe/cupti_agent.h`: - 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 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 or MIG UUID. The Agent reads UUIDs from the driver outside CUDA init and Agent locks without recording its 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. diff --git a/docs/installation.md b/docs/installation.md index 1c8bdd1..335408f 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -76,7 +76,7 @@ Re-run the new release's installer with the same `--prefix` to upgrade, or unins sh install.sh --prefix "$HOME/.local" --uninstall ``` -Uninstall removes only xprobe-owned files under `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`. If a running CUDA process currently has `libxprobe-cupti.so` injected from that prefix, wait until it restarts before deleting the directory so later attaches keep working. ## AI Agent Skill diff --git a/docs/releasing.md b/docs/releasing.md index 7294c00..2550a02 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -7,7 +7,7 @@ Work on a feature or fix branch, rebase-merge into `master`, then tag the merged 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` +- Versioned links in `README.md` and `docs/installation.md` `just test-agent-contract` verifies these agree. diff --git a/skills/xprobe-perf-profiling/SKILL.md b/skills/xprobe-perf-profiling/SKILL.md index 9a759f1..77ab68c 100644 --- a/skills/xprobe-perf-profiling/SKILL.md +++ b/skills/xprobe-perf-profiling/SKILL.md @@ -5,39 +5,43 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA # 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. +`xprobe` profiles live Linux CPU, Python, syscall, and CUDA processes (or re-analyzes saved traces). When stdout is piped, every command writes one JSON document to stdout alongside raw JSONL artifacts. Run `xprobe --help` for full flags. + +## Pick a mode + +| Need | Command | Notes | +| --- | --- | --- | +| Check host/container permissions | `xprobe doctor` | Read-only; run first when eBPF, perf, ptrace, or CUPTI access is unknown | +| List CUDA PIDs under a root | `xprobe discover --pid "$ROOT"` | Uses NVML; inside containers (`NVML_PID_NAMESPACE_MISMATCH`), scan `ps` or `/proc/*/maps` (`libcuda`) | +| Check selectors or injection state | `xprobe validate --pid "$PID" --from A --to B --match exact` | Read-only; reports `requirements.agent_activation` (`already_loaded` vs `injection_required`) | +| Python stacks, GIL & native waits | `xprobe measure --pid "$PID" --python-sample --duration-ms 2000` | CPython 3.9–3.14; ptrace only (no eBPF/perf/injection); lower `--python-threads-hz` if target has >64 threads | +| Native CPU callchain hotspots | `xprobe measure --pid "$PID" --cpu-sample --duration-ms 2000 --frequency-hz 999 --max-groups 2048` | Needs perf events; default 99 Hz / 256 groups is too sparse for short windows | +| Syscall count & duration totals | `xprobe measure --pid "$PID" --syscall-aggregate --duration-ms 2000` | Needs eBPF | +| GPU kernel totals | `xprobe measure --pid "$PID" --from cuda:kernel_start --to cuda:kernel_end --match exact --aggregate --duration-ms 2000` | Aggregates **one** activity kind per run | +| GPU memcpy totals (pageable vs pinned) | `xprobe measure --pid "$PID" --from cuda:memcpy_start --to cuda:memcpy_end --match exact --aggregate --duration-ms 2000` | Only `--aggregate` reports `src_memory`/`dst_memory` (`pageable` vs `pinned`); use `cuda:memset_*` for memset | +| Exact A → B latency + Event JSONL | `xprobe measure --pid "$PID" --from cuda:launch_api:exit --to cuda:kernel_start --match exact --samples 200` | `exact` supports launch API ↔ kernel, same-API entry/exit, activity start/end (not API ↔ memcpy; see [selectors.md](references/selectors.md)) | +| 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` | Captures all GPU activity (`all_gpu_activity: true`) | +| Up to 8 edges in one capture | `xprobe measure --spec graph.json` | Shares one capture and 8 CUPTI filters | +| Wait for rare GPU bubble / gap / spike | `xprobe measure --pid "$PID" --trigger-idle-ms 10 --pre-ms 50 --post-ms 50 --events-out spikes` | In-Agent ring; writes `window-N.events.jsonl` | +| Re-correlate saved Event JSONL offline | `xprobe measure --input trace.jsonl --from A --to B --match exact` | No live attach needed | +| Same-window cgroup / thread / NVML snapshot | `xprobe measure --pid "$PID" --triage --duration-ms 2000` | Actual `window_ms` exceeds `--duration-ms` (includes attach); read raw inventories instead of static `findings` | ## 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. +- **Standard GPU analysis**: run `scripts/analyze_trace.py trace.jsonl` for per-GPU busy/idle/compute/comm budgets, top idle and stream gaps, vertical slices (`--slice-gap`, `--slice-outlier`, `--around`, `--python-samples`), and multi-rank comparison (`scripts/analyze_trace.py rank0.jsonl rank1.jsonl ...`). +- **One-off scripts & RSI loops**: read [data-format.md](references/data-format.md) for stdout keys, artifact paths, JSONL shapes, `analyze_trace.py` output fields, Python time-conversion formulas, API↔memcpy correlation joins, cross-process alignment, and quality codes. +- **Selectors, policies, tuning & graphs**: read [selectors.md](references/selectors.md) and `examples/` (`request-path-graph.json`, `kernel-duration.json`). + +## Runtime limits & validity checks + +- **CUPTI injection & install path**: live CUDA capture injects `libxprobe-cupti.so` via ptrace, disables callbacks on stop, and leaves the `.so` mapped (never calls `dlclose`). Do not delete or move the xprobe install directory or venv while an injected process is running, or later attaches fail until the target restarts. Check state with `xprobe validate` or `grep libxprobe-cupti /proc/$PID/maps`. +- **One CUDA session per PID**: running two CUDA `measure` commands on the same PID fails with `CUPTI_AGENT_BUSY`; combine edges in a graph instead. `--python-sample` can run concurrently with CUDA `measure`. +- **Containers & NVTX**: run `xprobe` inside the target's PID and mount namespaces. NVTX ranges require `NVTX_INJECTION64_PATH` before the target's first NVTX call. +- **Duration & sample 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 `measure --pid` captures across processes or ranks. On one host, `host_monotonic`, `cupti_normalized_to_host_monotonic`, and `--python-sample` share `CLOCK_MONOTONIC`. Never mix PIDs in `measure --input` or subtract raw `cupti` timestamps from host timestamps. +- **Check completeness before trusting numbers**: `status == "completed"` can still hide truncation or drops. Verify: + - `warnings` is empty (or explicitly understood) + - `--python-sample`: `collection.over_capacity == 0` (no `PYTHON_SAMPLES_OVER_CAPACITY`) + - `--cpu-sample`: `collection.lost_samples == 0` (no `CPU_GROUP_CAPACITY_REACHED`) + - Exact / graph / trigger: `dropped == 0`, check `quality.verdict`, and require `all_gpu_activity == true` when reporting GPU idle time + - `--aggregate` (no `quality` object): check `collection.completeness`, `dropped_activities == 0`, and `table_utilization` diff --git a/skills/xprobe-perf-profiling/references/data-format.md b/skills/xprobe-perf-profiling/references/data-format.md index a30648e..008127e 100644 --- a/skills/xprobe-perf-profiling/references/data-format.md +++ b/skills/xprobe-perf-profiling/references/data-format.md @@ -10,10 +10,10 @@ Every `xprobe` command prints one JSON document to stdout when stdout is not a t | 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}` | +| `--aggregate` | none (inline only; no `quality` field) | `inventory.groups[]`, `collection.{completeness, 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` | +| `--triage` | per-source paths in `sources[]` (`artifact.path`) | `window_ms`, `sources[]`, `not_covered`, `threads`, `cgroup`, `cpu_hotspots`, `python_hotspots`, `gil_released_proportion`, `syscalls`, `gpu_activity`, `gpu_devices`, `cuda_devices`, `findings` | Errors exit non-zero and print JSON (`ok: false`, `error.{code, message, details, hints}`), preserving any written artifact path in `details`. @@ -30,9 +30,10 @@ One JSON object per line (`schema_version: "2.0"`). Concrete shapes for the main 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`. +- **Where names live**: `cuda.kernel_name`, `cuda.memcpy_kind` (`HtoD|DtoH|DtoD|HtoH|PtoP|unknown`), `cuda.bytes`, **`attributes.cuda_api_name`** and **`attributes.cuda_api_domain`** (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`. +- **Memcpy memory type**: Event JSONL `cuda` records carry `memcpy_kind` and `bytes` only — pageable vs pinned source/destination memory types are reported only by `--aggregate` over `cuda:memcpy_start` → `cuda:memcpy_end`. +- **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: they mark the stream busy through capture end and 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. Because CUPTI reports no numeric interpolation error bound, cross-process GPU-to-host comparisons can still have small millisecond-scale offsets. Raw `cupti` timestamps only compare within the same capture. Within identical timestamps, order by `sequence`. ## Capture manifest (`.manifest.json`) @@ -74,15 +75,24 @@ One line per sample at `result["artifact"]["path"]`: - `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`. +- **Converting proportions/counts to estimated time**: `inventory` reports `samples` and `proportion` only. Estimate GIL-held wall time as `proportion * collection.elapsed_ns` (or `samples / collection.gil_hz_achieved` seconds); estimate per-thread sweep time as `samples / collection.threads_hz_achieved` seconds. +- **Completeness**: check `collection.over_capacity == 0` and `warnings` for `PYTHON_SAMPLES_OVER_CAPACITY`. When `over_capacity > 0`, `status` is still `completed` and only the earliest prefix of the window was kept; lower `--python-threads-hz` and re-capture. +- `collection` also reports `gil_hz_achieved`, `threads_hz_achieved`, `elapsed_ns`, `threads`, `sample_capacity`, `inconsistent_reads`, `tid_source`, and `wall_clock`. -## Inventory, measurement, and trigger stdout fields +## Inventory, measurement, triage, and quality 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}`. +- **GPU `--aggregate`**: no `quality` object; check `collection.{completeness, dropped_activities, table_utilization, cuda_devices}`. `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, file_offset, build_id}`, `exclusive_proportion`, `inclusive_proportion`, `entry_selector_hint`, `return_selector_hint`), `inventory.stack_groups[]`, `symbolization.python_status` (`inactive`/`unsupported` means native frames only — use `--python-sample` for CPython 3.9–3.14), `collection.{completeness, lost_samples, truncated_stacks, threads_attached, threads_observed, table_utilization}`. Check `warnings` for `CPU_GROUP_CAPACITY_REACHED`. - **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`. +- **Triage `--triage`**: `window_ms` is the actual wall span (often longer than `--duration-ms` because of attach/setup), `threads` (`window_ns`, `top_threads[]`), `cgroup`, `cpu_hotspots[]`, `python_hotspots[]`, `gil_released_proportion`, `syscalls[]`, `gpu_activity[]`, `gpu_devices[]`, `cuda_devices[]`, `sources[]` (with per-source `status` and `artifact.path`), `not_covered[]`, and `findings[]` (static heuristic hints — verify against raw inventories). + +### Reading quality and collection diagnostics + +- **`inconsistent_reads`** (`--python-sample`): stack reads discarded because the GIL holder or innermost frame changed mid-read. A few percent of ticks is normal; only investigate if it rivals kept `gil_samples`. +- **`AMBIGUOUS_PAIRS` / `UNMATCHED_EVENTS`**: under `stream-order`, overlapping activities on a stream or capture-edge boundaries commonly trigger these (`UNMATCHED_EVENTS` is `info` when unmatched `<= matched`, `caution` when `> matched`). Check `measurement.samples` counts to see if they are tiny edge artifacts or a real selector mismatch. +- **`CLOCK_ERROR_UNAVAILABLE`**: informational (`info`, does not make `quality.verdict` `caution`). CUPTI reports no numeric interpolation error bound for `cupti_normalized_to_host_monotonic`. ## Bundled analyzer (`scripts/analyze_trace.py`) @@ -92,7 +102,7 @@ Use it instead of rewriting interval-union math by hand: # 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 +# Vertical slice across the largest GPU idle gap (±2 ms) + 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 @@ -103,11 +113,29 @@ scripts/analyze_trace.py trace.jsonl --around 1000000:2000000 --python-samples p 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). +Concrete single-trace output shape: + +```json +{ + "analysis_version": "1.5", + "capture": {"manifest": true, "all_gpu_activity": true, "window": {"start_ns": 1000, "end_ns": 3000}, "wall_clock_drift_ns": 0}, + "devices": [{"pid": 4242, "device_id": 0, "uuid": "GPU-...", "span": {"start_ns": 1000, "end_ns": 3000, "ns": 2000}, "busy_ns": 1500, "idle_ns": 500, "compute_ns": 1200, "communication_ns": 300, "communication_only_ns": 200, "transfer_ns": 100, "top_idle_gaps": [{"start_ns": 1400, "end_ns": 1900, "gap_ns": 500}], "top_compute_gaps": []}], + "gpu": {"summed_activity_ns": 1600, "top_idle_gaps": [{"pid": 4242, "device_id": 0, "clock_domain": "cupti_normalized_to_host_monotonic", "start_ns": 1400, "end_ns": 1900, "gap_ns": 500, "after": "gemm", "before": "attn"}]}, + "kernels": {"duration": {"count": 10, "total_ns": 1200, "min_ns": 80, "p50_ns": 120, "p95_ns": 180, "max_ns": 200}, "busy_union_ns": 1200, "overlap_factor": 1.0, "by_name": [{"name": "gemm", "selector_hint": {}, "launch_variants": []}]}, + "memcpy": {"duration": {}, "total_bytes": 0, "bandwidth_gbps": null, "by_kind": []}, + "streams": [{"stream_id": 7, "gaps": {}, "top_gaps": []}], + "slice": {"start_ns": 1400, "end_ns": 1900, "events": [], "total_events": 12, "truncated": false, "python": {"samples": 40, "gil_samples": 30, "gil_stacks": [], "threads": {}, "native_waits": []}}, + "warnings": [] +} +``` + +- `--slice-gap N` covers the **entire** N-th idle gap `[gap.start_ns - window_ms, gap.end_ns + window_ms]`; Event JSONL is capped by `--max-slice-events` (default 200), while `--python-samples` summarizes every sample inside that full range. To inspect one specific thread (`tid`) over a long gap, filter `py.jsonl` directly in Python. +- Multi-trace mode adds `devices[].shares` (`busy`, `idle`, `compute`, `communication_only`) and `spread` (`compute_share`, `most_compute`, `most_communication_only`, `most_idle`). +- `--comm-kernel` defaults to `nccl` (unanchored, matching 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) +### 1. Pair GPU intervals & compute true device busy/idle ```python import collections, json @@ -140,21 +168,39 @@ def merge_union(spans): # [(start_ns, end_ns), ...] -> non-overlapping merged s return merged ``` -### 2. Cross-process / cross-source timeline join (same host) +### 2. Join CUDA API ↔ memcpy (and Python caller) by `correlation_id` + +Capture API (`entry`→`exit`) and `memcpy` (`start`→`end`) as two `exact` edges in one graph, then join offline on `cuda.correlation_id` (and link `api["tid"]` + `timestamp_ns` to `py.jsonl`): + +```python +api_by_corr, copy_starts = {}, {} +for e in map(json.loads, open("copy_graph.jsonl")): + cid = (e.get("cuda") or {}).get("correlation_id") + if e["event_type"] == "cuda_api_entry": + api_by_corr[cid] = e + elif e["event_type"] == "gpu_memcpy_start": + copy_starts[cid] = e + elif e["event_type"] == "gpu_memcpy_end" and cid in copy_starts and cid in api_by_corr: + a, s = api_by_corr[cid], copy_starts[cid] + # a["tid"], a["attributes"]["cuda_api_name"], s["cuda"]["bytes"], e["timestamp_ns"] - s["timestamp_ns"] +``` + +### 3. 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`: +Run concurrent `xprobe measure --pid ...` captures (e.g., API/scheduler `--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] +t0, t1 = gap_start_ns, gap_end_ns +py_in_gap = [r for r in map(json.loads, open("api_py.jsonl")) if t0 <= r["timestamp_ns"] <= t1] +main_tid_in_gap = [r for r in py_in_gap if r["tid"] == main_tid] 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) +### 4. Convert `CLOCK_MONOTONIC` to UTC wall time (join with app logs) ```python wc = json.load(open("trace.jsonl.manifest.json"))["wall_clock"] @@ -165,10 +211,10 @@ def mono_to_utc_ns(t_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 +### 5. 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`). +- Guard every comparison: require `ok == True`, zero drops, `collection.over_capacity == 0` (Python), `collection.lost_samples == 0` (CPU), no truncation `warnings`, 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 diff --git a/skills/xprobe-perf-profiling/references/selectors.md b/skills/xprobe-perf-profiling/references/selectors.md index b1ee632..8772a50 100644 --- a/skills/xprobe-perf-profiling/references/selectors.md +++ b/skills/xprobe-perf-profiling/references/selectors.md @@ -1,4 +1,4 @@ -# Selectors, policies, specs, and overhead limits +# Selectors, policies, specs, and tuning 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. @@ -32,13 +32,15 @@ Use file offsets (not runtime virtual addresses) for `+0x`. Re-validate | 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 | +| `exact` | Same CUPTI `correlation_id` (launch API ↔ kernel only), same CUDA API entry ↔ exit, kernel/memcpy/memset 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 | +| `first-after`, `nearest` | Unrelated sources (e.g. host uprobe ↔ GPU kernel, or `cudaMemcpyAsync` ↔ `memcpy_start` if paired directly) | heuristic | `validate` returns `policy_recommendation` with compatible alternatives; `measure` never overrides `--match` silently. +**API ↔ memcpy exact correlation**: `validate` does not currently allow `--match exact` directly between `cuda:runtime_api:cudaMemcpy*` (or Driver copy APIs) and `cuda:memcpy_start`, even though both emit the same `cuda.correlation_id`. To get exact API ↔ copy pairing, capture both in one measurement graph using two `exact` edges (API `entry` → `exit` and `memcpy_start` → `memcpy_end`) and join the Event JSONL on `cuda.correlation_id` (see [data-format.md](data-format.md)). + ## JSON specs & measurement graphs For single-edge or repeatable RSI specs (`schema_version: "2.0"`), see [examples/kernel-duration.json](../examples/kernel-duration.json). @@ -71,10 +73,12 @@ 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`. +- **Failure behavior**: validation errors (invalid selector or incompatible `match_policy` on any edge) fail *before* collection with no artifact written. Once collection has run, any post-collection edge failure still writes the shared Event JSONL artifact so remaining edges can be re-correlated offline with `measure --input`. -## Filter pushdown & overhead limits +## Parameter tuning & overhead limits +- **`--python-sample` on high-thread processes**: sample capacity is sized as `(python_hz + python_threads_hz * 64) * duration_s`. If the target has many more than 64 threads (`ls /proc/$PID/task | wc -l`), default `--python-threads-hz 100` fills capacity early, keeps only the start of the window, and emits `PYTHON_SAMPLES_OVER_CAPACITY` with `collection.over_capacity > 0` while still reporting `status: "completed"`. Lower `--python-threads-hz` (e.g. `10` or `5`, or `0` for GIL-holder only) so `threads * threads_hz * duration_s` fits cleanly. +- **`--cpu-sample` frequency & groups**: defaults (`--frequency-hz 99`, `--max-groups 256`) produce very few samples on 1–2 s captures and saturate groups quickly on deep stacks (`CPU_GROUP_CAPACITY_REACHED`). Use `--frequency-hz 999 --max-groups 2048` (and raise `--max-samples` if needed) on busy native processes. If `symbolization.python_status` is `unsupported` (CPython <3.12) or `inactive` (3.12+ without `-X perf`), use `--python-sample` instead. - **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`. +- **High-rate GPU workloads**: `stream-order` and `--trigger-*` record all GPU activity. Size `--max-events` from an `--aggregate` count (`~2 * activities * duration_s` plus headroom), keep `--duration-ms` short, or bound hot paths with `--samples`. On `EVENT_RATE_TOO_HIGH`, narrow the selector or shorten the window before raising `--max-events`. diff --git a/tests/agent-contract/test_contract.py b/tests/agent-contract/test_contract.py index df4bd02..946242f 100755 --- a/tests/agent-contract/test_contract.py +++ b/tests/agent-contract/test_contract.py @@ -17,8 +17,8 @@ } SKILL_NAME = "xprobe-perf-profiling" SKILL_PATH = f"skills/{SKILL_NAME}/SKILL.md" -SKILL_WORD_BUDGET = 800 -SKILL_TOTAL_WORD_BUDGET = 4000 +SKILL_WORD_BUDGET = 1200 +SKILL_TOTAL_WORD_BUDGET = 8000 def run_json( @@ -107,7 +107,12 @@ def check_documented_flags( "measure", "good", "caution", + "info", + "completed", "timed_out", + "exact", + "entry", + "exit", "host_monotonic", "cupti_normalized_to_host_monotonic", "cupti", @@ -147,7 +152,7 @@ def check_documented_flags( "p95", } -EVENT_ATTRIBUTES = {"start_unknown", "cuda_api_name"} +EVENT_ATTRIBUTES = {"start_unknown", "cuda_api_name", "cuda_api_domain"} ALL_RESULT_SCHEMAS = [ "measurement-result", @@ -169,9 +174,10 @@ def check_documented_flags( "python-sample-record", "python-sample-result", ], - "Inventory, measurement, and trigger stdout fields": ALL_RESULT_SCHEMAS, + "Inventory, measurement, triage, and quality fields": ALL_RESULT_SCHEMAS, "Bundled analyzer (`scripts/analyze_trace.py`)": [], - "One-off script recipes & RSI loops": ALL_RESULT_SCHEMAS + ["capture-manifest"], + "One-off script recipes & RSI loops": ALL_RESULT_SCHEMAS + + ["capture-manifest", "event"], } @@ -263,7 +269,7 @@ def check_artifact_fields( else set() ) for cited in re.findall(r"`([a-z_][a-z0-9_.\[\]]*)`", prose): - if cited.endswith(".py"): + if cited.endswith((".py", ".jsonl")): continue parts = [ part From 9e40607cf2fd1810cc199fdebbe97c6787c8b9e8 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 03:40:56 +0800 Subject: [PATCH 04/22] =?UTF-8?q?=E2=9C=A8=20feat:=20pair=20any=20CUDA=20A?= =?UTF-8?q?PI=20exactly=20with=20the=20GPU=20work=20it=20issued?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A kernel, copy, or memset carries the CUPTI correlation ID of the API call that issued it, but validate allowed exact pairing only between launch APIs and kernels. Any Runtime or Driver API endpoint now pairs exactly with kernel, memcpy, or memset endpoints. A Driver API endpoint warns DRIVER_API_CORRELATION: activity carries the outermost call's ID, so it matches only work issued through the Driver API directly. The Skill drops the two-graph join workaround and shows how to attribute copies to the API call and the Python stack sampled before it. --- docs/architecture.md | 2 +- docs/cli-reference.md | 2 +- skills/xprobe-perf-profiling/SKILL.md | 4 +- .../references/data-format.md | 36 +++++--- .../references/selectors.md | 6 +- tests/integration/test_cupti.py | 23 +++++ xprobe/core/src/validate.rs | 84 +++++++++++++++++-- 7 files changed, 133 insertions(+), 24 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 697fb19..2f57161 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -91,7 +91,7 @@ Single-edge and measurement-graph live runs share one capture loop (attach, poll | Policy | Pairing | Confidence | | --- | --- | --- | -| `exact` | Launch API ↔ kernel (CUPTI correlation ID), same CUDA API entry ↔ exit, kernel/memcpy/memset start ↔ end, NVTX range ID, or same-thread syscall/CPython GC | exact | +| `exact` | CUDA API ↔ the kernel, copy, or memset it issued (CUPTI correlation ID), same CUDA API entry ↔ exit, kernel/memcpy/memset start ↔ end, NVTX range ID, or same-thread syscall/CPython GC | exact | | `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 | diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 02e3901..df27b3f 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -115,7 +115,7 @@ A read-only check of target identity, probe resolution, CUDA filters, correlatio | Policy | Pairs | | --- | --- | -| `exact` | Launch API ↔ kernel (by CUPTI correlation ID), same CUDA API entry ↔ exit, kernel/memcpy/memset start ↔ end, NVTX range kind and ID, same-thread syscall entry and exit, or same-thread CPython GC start and end | +| `exact` | A CUDA API call ↔ the kernel, copy, or memset it issued (by CUPTI correlation ID), same CUDA API entry ↔ exit, kernel/memcpy/memset start ↔ end, NVTX range kind and ID, same-thread syscall entry and exit, or same-thread CPython GC start and end | | `stack-nested` | Same-thread host function entry and return, innermost first | | `stream-order` | A GPU activity end with the next kernel, copy, or memset start on the same device, context, and stream | | `first-after`, `nearest` | By time across unrelated sources; always warned as heuristic | diff --git a/skills/xprobe-perf-profiling/SKILL.md b/skills/xprobe-perf-profiling/SKILL.md index 77ab68c..9a2b9b1 100644 --- a/skills/xprobe-perf-profiling/SKILL.md +++ b/skills/xprobe-perf-profiling/SKILL.md @@ -19,7 +19,7 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA | Syscall count & duration totals | `xprobe measure --pid "$PID" --syscall-aggregate --duration-ms 2000` | Needs eBPF | | GPU kernel totals | `xprobe measure --pid "$PID" --from cuda:kernel_start --to cuda:kernel_end --match exact --aggregate --duration-ms 2000` | Aggregates **one** activity kind per run | | GPU memcpy totals (pageable vs pinned) | `xprobe measure --pid "$PID" --from cuda:memcpy_start --to cuda:memcpy_end --match exact --aggregate --duration-ms 2000` | Only `--aggregate` reports `src_memory`/`dst_memory` (`pageable` vs `pinned`); use `cuda:memset_*` for memset | -| Exact A → B latency + Event JSONL | `xprobe measure --pid "$PID" --from cuda:launch_api:exit --to cuda:kernel_start --match exact --samples 200` | `exact` supports launch API ↔ kernel, same-API entry/exit, activity start/end (not API ↔ memcpy; see [selectors.md](references/selectors.md)) | +| Exact A → B latency + Event JSONL | `xprobe measure --pid "$PID" --from cuda:launch_api:exit --to cuda:kernel_start --match exact --samples 200` | `exact` pairs any CUDA API with the kernel, copy, or memset it issued, an API's entry/exit, or an activity's start/end (see [selectors.md](references/selectors.md)) | | 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` | Captures all GPU activity (`all_gpu_activity: true`) | | Up to 8 edges in one capture | `xprobe measure --spec graph.json` | Shares one capture and 8 CUPTI filters | | Wait for rare GPU bubble / gap / spike | `xprobe measure --pid "$PID" --trigger-idle-ms 10 --pre-ms 50 --post-ms 50 --events-out spikes` | In-Agent ring; writes `window-N.events.jsonl` | @@ -29,7 +29,7 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA ## 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, vertical slices (`--slice-gap`, `--slice-outlier`, `--around`, `--python-samples`), and multi-rank comparison (`scripts/analyze_trace.py rank0.jsonl rank1.jsonl ...`). -- **One-off scripts & RSI loops**: read [data-format.md](references/data-format.md) for stdout keys, artifact paths, JSONL shapes, `analyze_trace.py` output fields, Python time-conversion formulas, API↔memcpy correlation joins, cross-process alignment, and quality codes. +- **One-off scripts & RSI loops**: read [data-format.md](references/data-format.md) for stdout keys, artifact paths, JSONL shapes, `analyze_trace.py` output fields, Python time-conversion formulas, API-to-Python-caller joins, cross-process alignment, and quality codes. - **Selectors, policies, tuning & graphs**: read [selectors.md](references/selectors.md) and `examples/` (`request-path-graph.json`, `kernel-duration.json`). ## Runtime limits & validity checks diff --git a/skills/xprobe-perf-profiling/references/data-format.md b/skills/xprobe-perf-profiling/references/data-format.md index 008127e..d24ae32 100644 --- a/skills/xprobe-perf-profiling/references/data-format.md +++ b/skills/xprobe-perf-profiling/references/data-format.md @@ -168,21 +168,33 @@ def merge_union(spans): # [(start_ns, end_ns), ...] -> non-overlapping merged s return merged ``` -### 2. Join CUDA API ↔ memcpy (and Python caller) by `correlation_id` +### 2. Attribute copies to the API call and Python caller -Capture API (`entry`→`exit`) and `memcpy` (`start`→`end`) as two `exact` edges in one graph, then join offline on `cuda.correlation_id` (and link `api["tid"]` + `timestamp_ns` to `py.jsonl`): +`exact` pairs a CUDA API call with the copy it issued; the API record's `tid` and `timestamp_ns` then link it to the Python stack sampled on that thread just before the call: + +```bash +xprobe measure --pid "$PID" --from cuda:runtime_api:cudaMemcpyAsync:entry --to cuda:memcpy_start \ + --match exact --duration-ms 2000 --events-out copy.jsonl +xprobe measure --pid "$PID" --python-sample --duration-ms 2000 --events-out py.jsonl # concurrently +``` ```python -api_by_corr, copy_starts = {}, {} -for e in map(json.loads, open("copy_graph.jsonl")): - cid = (e.get("cuda") or {}).get("correlation_id") - if e["event_type"] == "cuda_api_entry": - api_by_corr[cid] = e - elif e["event_type"] == "gpu_memcpy_start": - copy_starts[cid] = e - elif e["event_type"] == "gpu_memcpy_end" and cid in copy_starts and cid in api_by_corr: - a, s = api_by_corr[cid], copy_starts[cid] - # a["tid"], a["attributes"]["cuda_api_name"], s["cuda"]["bytes"], e["timestamp_ns"] - s["timestamp_ns"] +import bisect, json +events = [json.loads(line) for line in open("copy.jsonl")] +calls = {e["cuda"]["correlation_id"]: e for e in events if e["event_type"] == "cuda_api_entry"} +samples = {} +for r in map(json.loads, open("py.jsonl")): + samples.setdefault(r["tid"], []).append((r["timestamp_ns"], r)) +for times in samples.values(): + times.sort(key=lambda item: item[0]) +for copy in (e for e in events if e["event_type"] == "gpu_memcpy_start"): + call = calls.get(copy["cuda"]["correlation_id"]) + if call is None: + continue + thread = samples.get(call["tid"], []) + at = bisect.bisect_right([t for t, _ in thread], call["timestamp_ns"]) - 1 + python = thread[at][1] if at >= 0 else None # nearest earlier sample: temporal, not causal + # copy["cuda"]["bytes"], copy["cuda"]["memcpy_kind"], copy["timestamp_ns"] - call["timestamp_ns"] ``` ### 3. Cross-process / cross-source timeline join (same host) diff --git a/skills/xprobe-perf-profiling/references/selectors.md b/skills/xprobe-perf-profiling/references/selectors.md index 8772a50..4fc526b 100644 --- a/skills/xprobe-perf-profiling/references/selectors.md +++ b/skills/xprobe-perf-profiling/references/selectors.md @@ -32,14 +32,14 @@ Use file offsets (not runtime virtual addresses) for `+0x`. Re-validate | Policy | Pairs | Confidence | | --- | --- | --- | -| `exact` | Same CUPTI `correlation_id` (launch API ↔ kernel only), same CUDA API entry ↔ exit, kernel/memcpy/memset start ↔ end, NVTX range ID, syscall entry ↔ exit per thread, CPython GC start ↔ end | exact | +| `exact` | Same CUPTI `correlation_id` (any CUDA API ↔ the kernel, copy, or memset it issued), same CUDA API entry ↔ exit, kernel/memcpy/memset 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, or `cudaMemcpyAsync` ↔ `memcpy_start` if paired directly) | heuristic | +| `first-after`, `nearest` | Unrelated sources (e.g. host uprobe ↔ GPU kernel) | heuristic | `validate` returns `policy_recommendation` with compatible alternatives; `measure` never overrides `--match` silently. -**API ↔ memcpy exact correlation**: `validate` does not currently allow `--match exact` directly between `cuda:runtime_api:cudaMemcpy*` (or Driver copy APIs) and `cuda:memcpy_start`, even though both emit the same `cuda.correlation_id`. To get exact API ↔ copy pairing, capture both in one measurement graph using two `exact` edges (API `entry` → `exit` and `memcpy_start` → `memcpy_end`) and join the Event JSONL on `cuda.correlation_id` (see [data-format.md](data-format.md)). +**API ↔ GPU activity**: a kernel, copy, or memset carries the `correlation_id` of the outermost API call that issued it, so `cuda:runtime_api:cudaMemcpyAsync:entry` → `cuda:memcpy_start` pairs exactly. A Driver API endpoint matches only work issued through the Driver API directly (`validate` warns `DRIVER_API_CORRELATION`). One call that issues several activities, such as `cudaGraphLaunch`, counts as ambiguous instead of a pair. ## JSON specs & measurement graphs diff --git a/tests/integration/test_cupti.py b/tests/integration/test_cupti.py index cb12454..c791279 100755 --- a/tests/integration/test_cupti.py +++ b/tests/integration/test_cupti.py @@ -269,10 +269,27 @@ def main() -> None: "cuda:kernel_start:name~xprobe_test_kernel.*", "3", ) + # A copy or memset carries the correlation ID of the API call + # that issued it. + api_to_copy = measure( + xprobe, + capture, + "cuda:runtime_api:cudaMemcpy:entry", + "cuda:memcpy_start:kind=HtoD", + "2", + ) + api_to_memset = measure( + xprobe, + capture, + "cuda:runtime_api:cudaMemset:entry", + "cuda:memset_end", + "1", + ) else: assert cross_domain.returncode != 0 assert cross_measurement["error"]["code"] == "CLOCK_ALIGNMENT_FAILED" driver_measurement = None + api_to_copy = api_to_memset = None memcpy_measurement = measure( xprobe, capture, @@ -482,6 +499,12 @@ def main() -> None: assert memset_measurement["measurement"]["samples"]["matched"] == 1 assert memset_measurement["measurement"]["latency_ns"]["min"] > 0 assert memset_measurement["correlation"]["confidence"] == "exact" + for api_to_activity, expected in ((api_to_copy, 2), (api_to_memset, 1)): + if api_to_activity is None: + continue + assert api_to_activity["measurement"]["samples"]["matched"] == expected, api_to_activity + assert api_to_activity["correlation"]["confidence"] == "exact" + assert api_to_activity["measurement"]["latency_ns"]["min"] > 0 print( json.dumps( diff --git a/xprobe/core/src/validate.rs b/xprobe/core/src/validate.rs index d78a98a..cf39894 100644 --- a/xprobe/core/src/validate.rs +++ b/xprobe/core/src/validate.rs @@ -982,6 +982,12 @@ fn check_policy( "exact matching requires endpoints that share a deterministic correlation key" .to_owned(), )), + MatchPolicy::Exact if driver_api_with_activity(&start.kind, &end.kind) => { + warnings.push(warning( + "DRIVER_API_CORRELATION", + "GPU activity carries the correlation ID of the outermost API call; a Driver API endpoint matches only work the target issued through the Driver API directly, not through the Runtime API", + )); + } MatchPolicy::FirstAfter => warnings.push(warning( "HEURISTIC_CORRELATION", "first-after matching does not prove request-level causality", @@ -1021,10 +1027,20 @@ fn supports_exact(start: &EndpointKind, end: &EndpointKind) -> bool { name: end_name, }, ) => start_domain == end_domain && start_name == end_name, + // A kernel, copy, or memset carries the correlation ID of the API + // call that issued it. (EndpointKind::Kernel, EndpointKind::Kernel) | (EndpointKind::Memcpy, EndpointKind::Memcpy) | (EndpointKind::Memset, EndpointKind::Memset) - | (EndpointKind::PythonGcStart, EndpointKind::PythonGcEnd) => true, + | (EndpointKind::PythonGcStart, EndpointKind::PythonGcEnd) + | ( + EndpointKind::CudaApi { .. }, + EndpointKind::Kernel | EndpointKind::Memcpy | EndpointKind::Memset, + ) + | ( + EndpointKind::Kernel | EndpointKind::Memcpy | EndpointKind::Memset, + EndpointKind::CudaApi { .. }, + ) => true, ( EndpointKind::NvtxRange { name_regex: start_name, @@ -1037,14 +1053,24 @@ fn supports_exact(start: &EndpointKind, end: &EndpointKind) -> bool { EndpointKind::SyscallEntry { name: start_name }, EndpointKind::SyscallExit { name: end_name }, ) => start_name == end_name, - (EndpointKind::CudaApi { domain, name }, EndpointKind::Kernel) - | (EndpointKind::Kernel, EndpointKind::CudaApi { domain, name }) => { - domain == "launch_api" || xprobe_protocol::is_cuda_launch_api(domain, name) - } _ => false, } } +/// A Driver API endpoint paired with GPU activity: the activity carries the +/// ID of the outermost API call, the Runtime one when the Runtime API made +/// the Driver call. +fn driver_api_with_activity(start: &EndpointKind, end: &EndpointKind) -> bool { + let activity = |kind: &EndpointKind| { + matches!( + kind, + EndpointKind::Kernel | EndpointKind::Memcpy | EndpointKind::Memset + ) + }; + let driver = |kind: &EndpointKind| matches!(kind, EndpointKind::CudaApi { domain, .. } if domain == "driver_api"); + (driver(start) && activity(end)) || (activity(start) && driver(end)) +} + fn supports_stack_nested(start: &Endpoint, end: &Endpoint) -> bool { if !matches!(start.kind, EndpointKind::HostEntry) || !matches!(end.kind, EndpointKind::HostReturn) @@ -1308,6 +1334,54 @@ mod tests { ); } + #[test] + fn any_cuda_api_pairs_exactly_with_the_activity_it_issued() { + let report = inspect::run(std::process::id()).unwrap(); + for (from, to) in [ + ( + "cuda:runtime_api:cudaMemcpyAsync:entry", + "cuda:memcpy_start:kind=HtoD", + ), + ("cuda:memset_end", "cuda:runtime_api:cudaMemsetAsync:exit"), + ( + "cuda:runtime_api:cudaGraphLaunch:entry", + "cuda:kernel_start", + ), + ] { + let result = run(&report, from, to, "exact").unwrap(); + assert!(result.valid, "{from} -> {to}: {:?}", result.issues); + assert_eq!( + result.policy_recommendation.reason, + PolicyRecommendationReason::DeterministicCorrelationKey, + "{from} -> {to}" + ); + assert!( + result + .warnings + .iter() + .all(|warning| warning.code != "DRIVER_API_CORRELATION") + ); + } + let driver = run( + &report, + "cuda:driver_api:cuMemcpyHtoDAsync_v2:exit", + "cuda:memcpy_start", + "exact", + ) + .unwrap(); + assert!(driver.valid, "{:?}", driver.issues); + assert!( + driver + .warnings + .iter() + .any(|warning| warning.code == "DRIVER_API_CORRELATION") + ); + // Two different activities never share an ID. + let copy_after_kernel = + run(&report, "cuda:kernel_end", "cuda:memcpy_start", "exact").unwrap(); + assert!(!copy_after_kernel.valid); + } + #[test] fn accepts_exact_kernel_duration_when_agent_is_available() { let mut report = inspect::run(std::process::id()).unwrap(); From b6680452d9cbb5e4c947d424452fcb84bc4dfda9 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 03:44:54 +0800 Subject: [PATCH 05/22] =?UTF-8?q?=E2=9C=A8=20feat:=20record=20each=20copy'?= =?UTF-8?q?s=20source=20and=20destination=20memory=20kind?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pageable or pinned host memory was reported only by --aggregate. The Agent now stores a copy's CUPTI memory kinds in its exact record and sets XPROBE_CUPTI_FEATURE_MEMORY_KINDS for every capture; the CLI writes them as attributes.src_memory and attributes.dst_memory on memcpy events. The output ABI version does not change: older readers ignore the fields. --- cupti/include/xprobe/cupti_agent.h | 3 ++ cupti/src/cupti_agent.c | 6 ++- docs/cupti-agent.md | 2 +- skills/xprobe-perf-profiling/SKILL.md | 2 +- .../references/data-format.md | 2 +- tests/agent-contract/test_contract.py | 11 +++- tests/integration/test_cupti.py | 16 +++++- xprobe/collector/src/cupti.rs | 53 ++++++++++++++++++- xprobe/protocol/src/event.rs | 5 ++ xprobe/protocol/src/lib.rs | 6 +-- 10 files changed, 95 insertions(+), 11 deletions(-) diff --git a/cupti/include/xprobe/cupti_agent.h b/cupti/include/xprobe/cupti_agent.h index 6fef988..8122bab 100644 --- a/cupti/include/xprobe/cupti_agent.h +++ b/cupti/include/xprobe/cupti_agent.h @@ -20,6 +20,9 @@ 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, + /* Copies report their source and destination CUpti_ActivityMemoryKind: + * in an exact record's block_x and block_y, in an aggregate record's + * src_memory_kind and dst_memory_kind. */ 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, diff --git a/cupti/src/cupti_agent.c b/cupti/src/cupti_agent.c index 0dc1ba3..b0ad6d9 100644 --- a/cupti/src/cupti_agent.c +++ b/cupti/src/cupti_agent.c @@ -1505,6 +1505,8 @@ static void enqueue_memcpy_record(const struct xprobe_memcpy_activity *memcpy_re record.runtime_correlation_id = memcpy_record->runtime_correlation_id; set_transfer_bytes(&record, memcpy_record->bytes); record.grid_z = memcpy_record->copy_kind; + record.block_x = memcpy_record->src_kind; + record.block_y = memcpy_record->dst_kind; enqueue_record(&record); } @@ -1942,9 +1944,9 @@ static void initialize_output_header(struct xprobe_cupti_output_header *header, if (device_count != 0U) { header->feature_flags |= XPROBE_CUPTI_FEATURE_DEVICE_TABLE; } + header->feature_flags |= XPROBE_CUPTI_FEATURE_MEMORY_KINDS; if (capture_mode == XPROBE_CUPTI_CAPTURE_AGGREGATE) { - header->feature_flags |= XPROBE_CUPTI_FEATURE_AGGREGATE_RECORDS | - XPROBE_CUPTI_FEATURE_MEMORY_KINDS; + header->feature_flags |= XPROBE_CUPTI_FEATURE_AGGREGATE_RECORDS; } else if (activity_timestamps_are_host_monotonic(checked, checked_count) != 0) { header->feature_flags |= XPROBE_CUPTI_FEATURE_HOST_MONOTONIC_TIMESTAMPS; } diff --git a/docs/cupti-agent.md b/docs/cupti-agent.md index 679f0c4..90e17be 100644 --- a/docs/cupti-agent.md +++ b/docs/cupti-agent.md @@ -41,7 +41,7 @@ Online attach cannot retrofit an already initialized NVTX dispatch table. Set `N ### 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`. +- Kernels group by `(name, device_id)`; memcpy by `(direction, src_memory, dst_memory, device_id)`; memset by `device_id`. Exact copy records carry the same source and destination memory kinds (`XPROBE_CUPTI_FEATURE_MEMORY_KINDS`), which the CLI writes as `attributes.src_memory` and `attributes.dst_memory`. - 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. diff --git a/skills/xprobe-perf-profiling/SKILL.md b/skills/xprobe-perf-profiling/SKILL.md index 9a2b9b1..171fe05 100644 --- a/skills/xprobe-perf-profiling/SKILL.md +++ b/skills/xprobe-perf-profiling/SKILL.md @@ -18,7 +18,7 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA | Native CPU callchain hotspots | `xprobe measure --pid "$PID" --cpu-sample --duration-ms 2000 --frequency-hz 999 --max-groups 2048` | Needs perf events; default 99 Hz / 256 groups is too sparse for short windows | | Syscall count & duration totals | `xprobe measure --pid "$PID" --syscall-aggregate --duration-ms 2000` | Needs eBPF | | GPU kernel totals | `xprobe measure --pid "$PID" --from cuda:kernel_start --to cuda:kernel_end --match exact --aggregate --duration-ms 2000` | Aggregates **one** activity kind per run | -| GPU memcpy totals (pageable vs pinned) | `xprobe measure --pid "$PID" --from cuda:memcpy_start --to cuda:memcpy_end --match exact --aggregate --duration-ms 2000` | Only `--aggregate` reports `src_memory`/`dst_memory` (`pageable` vs `pinned`); use `cuda:memset_*` for memset | +| GPU memcpy totals (pageable vs pinned) | `xprobe measure --pid "$PID" --from cuda:memcpy_start --to cuda:memcpy_end --match exact --aggregate --duration-ms 2000` | Groups by `src_memory`/`dst_memory` (`pageable` vs `pinned`), which every copy event also carries; use `cuda:memset_*` for memset | | Exact A → B latency + Event JSONL | `xprobe measure --pid "$PID" --from cuda:launch_api:exit --to cuda:kernel_start --match exact --samples 200` | `exact` pairs any CUDA API with the kernel, copy, or memset it issued, an API's entry/exit, or an activity's start/end (see [selectors.md](references/selectors.md)) | | 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` | Captures all GPU activity (`all_gpu_activity: true`) | | Up to 8 edges in one capture | `xprobe measure --spec graph.json` | Shares one capture and 8 CUPTI filters | diff --git a/skills/xprobe-perf-profiling/references/data-format.md b/skills/xprobe-perf-profiling/references/data-format.md index d24ae32..e684c11 100644 --- a/skills/xprobe-perf-profiling/references/data-format.md +++ b/skills/xprobe-perf-profiling/references/data-format.md @@ -31,7 +31,7 @@ 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`** and **`attributes.cuda_api_domain`** (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`. -- **Memcpy memory type**: Event JSONL `cuda` records carry `memcpy_kind` and `bytes` only — pageable vs pinned source/destination memory types are reported only by `--aggregate` over `cuda:memcpy_start` → `cuda:memcpy_end`. +- **Memcpy memory type**: each copy event has `attributes.src_memory` and `attributes.dst_memory` (`pageable`, `pinned`, `device`, `managed`, ...) next to `cuda.memcpy_kind` and `cuda.bytes`. `--aggregate` groups copies by the same fields. - **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: they mark the stream busy through capture end and 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. Because CUPTI reports no numeric interpolation error bound, cross-process GPU-to-host comparisons can still have small millisecond-scale offsets. Raw `cupti` timestamps only compare within the same capture. Within identical timestamps, order by `sequence`. diff --git a/tests/agent-contract/test_contract.py b/tests/agent-contract/test_contract.py index 946242f..1aa39e6 100755 --- a/tests/agent-contract/test_contract.py +++ b/tests/agent-contract/test_contract.py @@ -114,6 +114,9 @@ def check_documented_flags( "entry", "exit", "host_monotonic", + "pinned", + "device", + "managed", "cupti_normalized_to_host_monotonic", "cupti", "pageable", @@ -152,7 +155,13 @@ def check_documented_flags( "p95", } -EVENT_ATTRIBUTES = {"start_unknown", "cuda_api_name", "cuda_api_domain"} +EVENT_ATTRIBUTES = { + "start_unknown", + "cuda_api_name", + "cuda_api_domain", + "src_memory", + "dst_memory", +} ALL_RESULT_SCHEMAS = [ "measurement-result", diff --git a/tests/integration/test_cupti.py b/tests/integration/test_cupti.py index c791279..2f0ebbe 100755 --- a/tests/integration/test_cupti.py +++ b/tests/integration/test_cupti.py @@ -39,6 +39,8 @@ def decode_record(raw: bytes) -> dict[str, int | str]: "bytes": fields[10] | (fields[11] << 32), "copy_kind": fields[12], "memset_value": fields[13], + "src_memory_kind": fields[13], + "dst_memory_kind": fields[14], "runtime_correlation_id": fields[16], "name": fields[17].split(b"\0", 1)[0].decode("utf-8"), } @@ -72,7 +74,7 @@ def read_capture(path: pathlib.Path) -> tuple[dict[str, int], list[dict[str, int assert header["record_size"] == 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 + assert header["feature_flags"] & ~(1 | 32) == 2 | 16 | 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"] = [ @@ -382,8 +384,20 @@ def main() -> None: for record in records if record["kind"] in {7, 8} ) + # The fixture copies between pageable std::vector buffers and the device. + assert collections.Counter( + (record["copy_kind"], record["src_memory_kind"], record["dst_memory_kind"]) + for record in records + if record["kind"] in {5, 6} + ) == {(1, 1, 3): 4, (2, 3, 1): 2} assert len(events) == len(records) + copies = [event for event in events if event["event_type"].startswith("gpu_memcpy")] + assert copies and all( + {event["attributes"]["src_memory"], event["attributes"]["dst_memory"]} + == {"pageable", "device"} + for event in copies + ) assert {event["event_type"] for event in events} == EXPECTED_EVENT_TYPES assert all(event["session_id"] == "xp_cupti_live" for event in events) assert [event["sequence"] for event in events] == list(range(len(events))) diff --git a/xprobe/collector/src/cupti.rs b/xprobe/collector/src/cupti.rs index a5399c8..210a54f 100644 --- a/xprobe/collector/src/cupti.rs +++ b/xprobe/collector/src/cupti.rs @@ -50,7 +50,9 @@ 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}; +use xprobe_protocol::{ + DST_MEMORY_ATTRIBUTE, SRC_MEMORY_ATTRIBUTE, 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 @@ -323,6 +325,10 @@ pub enum CuptiDecodeError { index: usize, message: &'static str, }, + InvalidMemcpyRecord { + index: usize, + message: &'static str, + }, InvalidCaptureState(u32), InvalidStopReason(u32), InvalidCounters { @@ -395,6 +401,12 @@ impl fmt::Display for CuptiDecodeError { Self::InvalidNvtxRecord { index, message } => { write!(formatter, "CUPTI NVTX record {index} is invalid: {message}") } + Self::InvalidMemcpyRecord { index, message } => { + write!( + formatter, + "CUPTI memcpy record {index} is invalid: {message}" + ) + } Self::InvalidAggregateRecord { index, message } => { write!( formatter, @@ -1062,6 +1074,9 @@ fn decode_record( if matches!(kind, 7 | 8) { attributes.insert("memset_value".to_owned(), Value::from(read_u32(record, 56))); } + if matches!(kind, 5 | 6) && feature_flags & FEATURE_MEMORY_KINDS != 0 { + insert_memory_kinds(&mut attributes, record, index)?; + } // 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; @@ -1110,6 +1125,25 @@ fn decode_record( }) } +/// A copy's source and destination memory, from its record's block fields. +fn insert_memory_kinds( + attributes: &mut BTreeMap, + record: &[u8], + index: usize, +) -> Result<(), CuptiDecodeError> { + for (attribute, offset) in [(SRC_MEMORY_ATTRIBUTE, 56), (DST_MEMORY_ATTRIBUTE, 60)] { + let memory = decode_memory_kind(read_u32(record, offset)).map_err(|()| { + CuptiDecodeError::InvalidMemcpyRecord { + index, + message: "memory kind is unsupported", + } + })?; + let value = serde_json::to_value(memory).expect("a memory kind serializes"); + attributes.insert(attribute.to_owned(), value); + } + Ok(()) +} + fn decode_record_kind( kind: u32, index: usize, @@ -1543,6 +1577,23 @@ mod tests { assert_eq!(memcpy_payload.memcpy_kind, Some(MemcpyKind::HostToDevice)); assert_eq!(memcpy_payload.start_ns, Some(10_500)); assert_eq!(memcpy_payload.grid, None); + assert!(!memcpy_event.attributes.contains_key("src_memory")); + + // With memory kinds, a pageable-to-device copy names both sides. + let mut kinds = transfer_capture(&[transfer_record(5, 10_500, 43, bytes, 1)]); + let flags = + u32::from_le_bytes(kinds[20..24].try_into().unwrap()) | super::FEATURE_MEMORY_KINDS; + kinds[20..24].copy_from_slice(&flags.to_le_bytes()); + kinds[HEADER_SIZE + 56..HEADER_SIZE + 60].copy_from_slice(&1_u32.to_le_bytes()); + kinds[HEADER_SIZE + 60..HEADER_SIZE + 64].copy_from_slice(&3_u32.to_le_bytes()); + let attributes = &decode_capture(&kinds, "xp_test").unwrap().events[0].attributes; + assert_eq!(attributes["src_memory"], "pageable"); + assert_eq!(attributes["dst_memory"], "device"); + kinds[HEADER_SIZE + 56..HEADER_SIZE + 60].copy_from_slice(&99_u32.to_le_bytes()); + assert!(matches!( + decode_capture(&kinds, "xp_test"), + Err(CuptiDecodeError::InvalidMemcpyRecord { .. }) + )); let memset_event = &decoded.events[1]; assert_eq!(memset_event.event_type, EventType::GpuMemsetEnd); diff --git a/xprobe/protocol/src/event.rs b/xprobe/protocol/src/event.rs index dc6fd97..b8974f9 100644 --- a/xprobe/protocol/src/event.rs +++ b/xprobe/protocol/src/event.rs @@ -244,6 +244,11 @@ pub const CUDA_RECORD_NAME_MAX_BYTES: usize = 127; /// lower bound: the end of the previous activity on its stream. pub const START_UNKNOWN_ATTRIBUTE: &str = "start_unknown"; +/// Attributes of a copy's source and destination memory: a [`MemoryKind`] +/// such as `pageable` or `pinned`. +pub const SRC_MEMORY_ATTRIBUTE: &str = "src_memory"; +pub const DST_MEMORY_ATTRIBUTE: &str = "dst_memory"; + /// Whether an activity start's time is only a lower bound; see /// [`START_UNKNOWN_ATTRIBUTE`]. #[must_use] diff --git a/xprobe/protocol/src/lib.rs b/xprobe/protocol/src/lib.rs index bea89ae..fa6fd65 100644 --- a/xprobe/protocol/src/lib.rs +++ b/xprobe/protocol/src/lib.rs @@ -34,9 +34,9 @@ pub use discover::{CudaProcessCandidate, DiscoveryResult}; pub use error::{ErrorCode, ErrorResponse, XprobeError}; pub use event::{ 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, + CudaEvent, DST_MEMORY_ATTRIBUTE, Dim3, Event, EventSource, EventType, HostEvent, HostProbeKind, + MemcpyKind, MemoryKind, NvtxEvent, NvtxRangeKind, SRC_MEMORY_ATTRIBUTE, + START_UNKNOWN_ATTRIBUTE, activity_boundary, is_cuda_launch_api, start_unknown, }; pub use export::{ExportFormat, TraceExportResult}; pub use graph::{ From 04368c0aead4121b3ceb4bfcfa76683e56ddf24c Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 03:47:02 +0800 Subject: [PATCH 06/22] =?UTF-8?q?=E2=9C=A8=20feat:=20report=20quality=20on?= =?UTF-8?q?=20GPU=20aggregates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Aggregate results had no quality object, so a script had to check them differently from every other mode. An aggregate that returns counted every activity, so its verdict is good; NAME_TRUNCATED notes groups whose kernel names were cut at 127 bytes and may hold several kernels. --- .../aggregate-inventory-result.schema.json | 68 ++++++++++++++++++- skills/xprobe-perf-profiling/SKILL.md | 2 +- .../references/data-format.md | 4 +- xprobe/core/src/gpu_aggregate.rs | 43 +++++++++++- xprobe/protocol/src/measurement.rs | 3 + xprobe/protocol/tests/contracts.rs | 1 + 6 files changed, 115 insertions(+), 6 deletions(-) diff --git a/schemas/aggregate-inventory-result.schema.json b/schemas/aggregate-inventory-result.schema.json index dd17a7f..4db1cc8 100644 --- a/schemas/aggregate-inventory-result.schema.json +++ b/schemas/aggregate-inventory-result.schema.json @@ -12,6 +12,10 @@ "ok": { "type": "boolean" }, + "quality": { + "description": "An aggregate that returns has every activity counted; issues are\nlimits on reading the groups.", + "$ref": "#/$defs/ResultQuality" + }, "schema_version": { "$ref": "#/$defs/SchemaVersion3" }, @@ -36,7 +40,8 @@ "session_id", "status", "inventory", - "collection" + "collection", + "quality" ], "$defs": { "AggregateActivity": { @@ -314,6 +319,67 @@ "managed_static" ] }, + "QualityIssue": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "severity": { + "$ref": "#/$defs/QualitySeverity" + } + }, + "additionalProperties": false, + "required": [ + "code", + "severity", + "message" + ] + }, + "QualitySeverity": { + "type": "string", + "enum": [ + "info", + "caution" + ] + }, + "QualityVerdict": { + "oneOf": [ + { + "description": "No caution-level issue; info issues may still be listed.", + "type": "string", + "const": "good" + }, + { + "description": "At least one issue limits how the latency may be interpreted.", + "type": "string", + "const": "caution" + } + ] + }, + "ResultQuality": { + "description": "Deterministic interpretation of the result's quality fields.", + "type": "object", + "properties": { + "issues": { + "type": "array", + "items": { + "$ref": "#/$defs/QualityIssue" + } + }, + "verdict": { + "$ref": "#/$defs/QualityVerdict" + } + }, + "additionalProperties": false, + "required": [ + "verdict", + "issues" + ] + }, "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", diff --git a/skills/xprobe-perf-profiling/SKILL.md b/skills/xprobe-perf-profiling/SKILL.md index 171fe05..9392ac8 100644 --- a/skills/xprobe-perf-profiling/SKILL.md +++ b/skills/xprobe-perf-profiling/SKILL.md @@ -44,4 +44,4 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA - `--python-sample`: `collection.over_capacity == 0` (no `PYTHON_SAMPLES_OVER_CAPACITY`) - `--cpu-sample`: `collection.lost_samples == 0` (no `CPU_GROUP_CAPACITY_REACHED`) - Exact / graph / trigger: `dropped == 0`, check `quality.verdict`, and require `all_gpu_activity == true` when reporting GPU idle time - - `--aggregate` (no `quality` object): check `collection.completeness`, `dropped_activities == 0`, and `table_utilization` + - `--aggregate`: `quality.verdict` and `quality.issues` (`NAME_TRUNCATED` merges kernels that share a cut name) diff --git a/skills/xprobe-perf-profiling/references/data-format.md b/skills/xprobe-perf-profiling/references/data-format.md index e684c11..a2117e0 100644 --- a/skills/xprobe-perf-profiling/references/data-format.md +++ b/skills/xprobe-perf-profiling/references/data-format.md @@ -10,7 +10,7 @@ Every `xprobe` command prints one JSON document to stdout when stdout is not a t | 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; no `quality` field) | `inventory.groups[]`, `collection.{completeness, cuda_devices, dropped_activities, table_utilization}` | +| `--aggregate` | none (inline only) | `inventory.groups[]`, `quality`, `collection.{completeness, 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[]` (`artifact.path`) | `window_ms`, `sources[]`, `not_covered`, `threads`, `cgroup`, `cpu_hotspots`, `python_hotspots`, `gil_released_proportion`, `syscalls`, `gpu_activity`, `gpu_devices`, `cuda_devices`, `findings` | @@ -82,7 +82,7 @@ One line per sample at `result["artifact"]["path"]`: ## Inventory, measurement, triage, and quality 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`**: no `quality` object; check `collection.{completeness, dropped_activities, table_utilization, cuda_devices}`. `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`. +- **GPU `--aggregate`**: an aggregate that returns counted every activity, so `quality.verdict` is `good`; `NAME_TRUNCATED` (info) means kernels sharing a name cut at 127 bytes share a group. `collection.{completeness, dropped_activities, table_utilization, cuda_devices}` give the counts. `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, file_offset, build_id}`, `exclusive_proportion`, `inclusive_proportion`, `entry_selector_hint`, `return_selector_hint`), `inventory.stack_groups[]`, `symbolization.python_status` (`inactive`/`unsupported` means native frames only — use `--python-sample` for CPython 3.9–3.14), `collection.{completeness, lost_samples, truncated_stacks, threads_attached, threads_observed, table_utilization}`. Check `warnings` for `CPU_GROUP_CAPACITY_REACHED`. - **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`. diff --git a/xprobe/core/src/gpu_aggregate.rs b/xprobe/core/src/gpu_aggregate.rs index 5e7115d..f63edad 100644 --- a/xprobe/core/src/gpu_aggregate.rs +++ b/xprobe/core/src/gpu_aggregate.rs @@ -5,7 +5,8 @@ use std::{error::Error, fmt}; use xprobe_protocol::{ AggregateActivity, AggregateCollectionSummary, AggregateDuration, AggregateGroup, AggregateInventory, AggregateInventoryResult, CaptureCompleteness, ErrorCode, MemcpyKind, - MemoryKind, SchemaVersion3, SessionStatus, + MemoryKind, QualityIssue, QualitySeverity, QualityVerdict, ResultQuality, SchemaVersion3, + SessionStatus, }; /// One Agent aggregate table slot. Several slots may describe the same group. @@ -86,6 +87,30 @@ impl fmt::Display for GpuAggregateError { impl Error for GpuAggregateError {} +/// Every activity was counted when an aggregate returns, so the verdict is +/// good. A kernel name cut at the record's name capacity is noted: kernels +/// sharing that prefix share a group. +fn quality(groups: &[AggregateGroup]) -> ResultQuality { + let truncated = groups + .iter() + .filter(|group| group.name_complete == Some(false)) + .count(); + let issues = (truncated != 0) + .then(|| QualityIssue { + code: "NAME_TRUNCATED".to_owned(), + severity: QualitySeverity::Info, + message: format!( + "{truncated} group name(s) were cut at 127 bytes; kernels sharing a cut name share its group" + ), + }) + .into_iter() + .collect(); + ResultQuality { + verdict: QualityVerdict::Good, + issues, + } +} + /// Merge Agent aggregate slots into deterministic groups with selector hints. /// /// # Errors @@ -116,6 +141,7 @@ pub fn analyze( .into_iter() .map(protocol_group) .collect::, _>>()?; + let quality = quality(&groups); Ok(AggregateInventoryResult { schema_version: SchemaVersion3::current(), ok: true, @@ -138,6 +164,7 @@ pub fn analyze( occupied_slots, table_utilization: utilization(occupied_slots, capture.group_capacity), }, + quality, warnings: Vec::new(), }) } @@ -305,7 +332,7 @@ fn utilization(occupied: u64, capacity: u64) -> f64 { #[cfg(test)] mod tests { - use xprobe_protocol::{AggregateActivity, MemcpyKind, MemoryKind}; + use xprobe_protocol::{AggregateActivity, MemcpyKind, MemoryKind, QualityVerdict}; use super::{ GpuAggregateCapture, GpuAggregateError, GpuAggregateRequest, RawGpuAggregateGroup, analyze, @@ -381,6 +408,18 @@ mod tests { assert_eq!(result.collection.groups, 3); assert_eq!(result.collection.occupied_slots, 4); assert!((result.collection.table_utilization - 0.5).abs() < f64::EPSILON); + assert_eq!(result.quality.verdict, QualityVerdict::Good); + assert_eq!(result.quality.issues, []); + + // A cut kernel name stays good but is noted. + let cut = GpuAggregateCapture { + groups: vec![kernel("flash_attention_prefix", false, 1, 10)], + observed_activities: 1, + group_capacity: 8, + }; + let quality = analyze(request(), cut).unwrap().quality; + assert_eq!(quality.verdict, QualityVerdict::Good); + assert_eq!(quality.issues[0].code, "NAME_TRUNCATED"); } #[test] diff --git a/xprobe/protocol/src/measurement.rs b/xprobe/protocol/src/measurement.rs index ab3089a..fce3d88 100644 --- a/xprobe/protocol/src/measurement.rs +++ b/xprobe/protocol/src/measurement.rs @@ -325,6 +325,9 @@ pub struct AggregateInventoryResult { pub status: SessionStatus, pub inventory: AggregateInventory, pub collection: AggregateCollectionSummary, + /// An aggregate that returns has every activity counted; issues are + /// limits on reading the groups. + pub quality: ResultQuality, #[serde(default)] pub warnings: Vec, } diff --git a/xprobe/protocol/tests/contracts.rs b/xprobe/protocol/tests/contracts.rs index 452aca2..4cf6177 100644 --- a/xprobe/protocol/tests/contracts.rs +++ b/xprobe/protocol/tests/contracts.rs @@ -226,6 +226,7 @@ fn aggregate_inventory_contract_round_trips() { "occupied_slots": 1, "table_utilization": 0.000_244_140_625 }, + "quality": {"verdict": "good", "issues": []}, "warnings": [] })); } From b7b065c7981a2d66c8e3054a6ea9efb8739acac3 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 03:56:09 +0800 Subject: [PATCH 07/22] =?UTF-8?q?=E2=9C=A8=20feat:=20keep=20every=20Python?= =?UTF-8?q?=20sample=20and=20report=20time=20per=20stack?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --python-sample stopped keeping samples at a capacity sized for 64 threads, so a process with many threads kept only the start of the window while reporting completed. Samples now hold an index into the distinct stacks, every one is kept, and the JSONL is written as it is produced rather than built in memory. Read times go into fixed buckets. The GIL holder is sampled at 999 Hz by default. Sweeps of every thread run up to 100 times a second and slow down to stay within 6,400 stack reads a second; --python-threads-hz fixes the rate and 0 turns sweeps off. Stack groups, hotspots, native waits, and GIL release time carry estimated_ns, and collection reports sweep_reads_per_second. Triage uses the same defaults. --- docs/architecture.md | 2 +- docs/cli-reference.md | 6 +- schemas/python-sample-result.schema.json | 60 +++- schemas/triage-result.schema.json | 15 +- skills/xprobe-perf-profiling/SKILL.md | 3 +- .../references/data-format.md | 9 +- .../references/selectors.md | 2 +- tests/integration/test_python_sample.py | 9 +- xprobe/cli/src/args.rs | 10 +- xprobe/cli/src/dev.rs | 26 +- xprobe/cli/src/python.rs | 82 ++--- xprobe/cli/src/triage.rs | 4 +- xprobe/collector/src/python_sampling.rs | 124 ++++++-- xprobe/core/src/python_sampling.rs | 298 +++++++++++++----- xprobe/core/src/triage.rs | 2 + xprobe/protocol/src/python_sampling.rs | 20 +- 16 files changed, 466 insertions(+), 206 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 2f57161..4e50f55 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -70,7 +70,7 @@ CPU sampling, syscall aggregation, and measurement graphs each have their own va ### 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. +- **`--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 999) and sweeps all threads up to 100 times a second within 6,400 stack reads a second (`--python-threads-hz` fixes the rate), keeps every sample, discards 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. diff --git a/docs/cli-reference.md b/docs/cli-reference.md index df27b3f..b2dbe66 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -208,14 +208,14 @@ Each inventory is a live mode that runs for `--duration-ms` and reports totals i **`--python-sample`** reads CPython 3.9–3.14 memory with `process_vm_readv`. It needs ptrace access but no perf events, eBPF, `-X perf`, or injection. -- It samples the GIL holder at `--python-hz` (default 2000) and all threads at `--python-threads-hz` (default 100). -- Sample capacity is sized assuming 64 threads (`(python_hz + python_threads_hz * 64) * duration_s`). On processes with many more threads, lower `--python-threads-hz` (or set it to `0` for GIL-only) and check `collection.over_capacity == 0` and `warnings` (`PYTHON_SAMPLES_OVER_CAPACITY`): capacity overflow keeps only the earliest prefix of the window while still reporting `status: "completed"`. +- It samples the GIL holder at `--python-hz` (default 999). By default it sweeps every thread up to 100 times a second, slower when the threads would take more than 6,400 stack reads a second (`collection.sweep_reads_per_second`); `--python-threads-hz N` fixes the sweep rate and `0` turns sweeps off. `collection` reports the requested and achieved rate of each. +- Every sample is kept: memory grows by a few dozen bytes per sample plus each distinct stack, and the JSONL is written as it is produced. - On 3.13 and later it checks its offsets against `_Py_DebugOffsets`. Unsupported and free-threaded builds return `UNSUPPORTED_PYTHON_VERSION`. - Reads that race with the interpreter are discarded and counted in `inconsistent_reads`. - For blocked threads it reports native waits from `/proc//task//syscall`. - Every sample is written with its `CLOCK_MONOTONIC` time to a JSONL artifact (`schemas/python-sample-record.schema.json`). - Frames report `first_line`, the line where the function starts, not the current line. -- `inventory` reports counts and proportions; estimate wall time from `proportion * collection.elapsed_ns` (or `samples / collection.gil_hz_achieved` / `threads_hz_achieved`). +- Every stack group, hotspot, and native wait has `estimated_ns`: samples times the average GIL tick (wall time of the GIL holder) or sweep interval (thread time summed over threads). **`--syscall-aggregate`** filters by PID in BPF maps sized by `--max-inflight` and `--max-groups`. It reports each syscall's count, errors, min, mean, max, and total duration, with selector hints. It records no per-call events and no pointer values. diff --git a/schemas/python-sample-result.schema.json b/schemas/python-sample-result.schema.json index 92967a9..13c6d78 100644 --- a/schemas/python-sample-result.schema.json +++ b/schemas/python-sample-result.schema.json @@ -140,6 +140,11 @@ "PythonHotspot": { "type": "object", "properties": { + "exclusive_estimated_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "exclusive_proportion": { "type": "number", "format": "double" @@ -152,6 +157,12 @@ "frame": { "$ref": "#/$defs/PythonFrame" }, + "inclusive_estimated_ns": { + "description": "Samples times the average GIL tick.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "inclusive_proportion": { "type": "number", "format": "double" @@ -168,7 +179,9 @@ "inclusive_samples", "exclusive_samples", "inclusive_proportion", - "exclusive_proportion" + "exclusive_proportion", + "inclusive_estimated_ns", + "exclusive_estimated_ns" ] }, "PythonNativeLeaf": { @@ -202,6 +215,12 @@ "description": "Thread samples blocked at one native leaf.", "type": "object", "properties": { + "estimated_ns": { + "description": "Thread time spent here, summed over threads: samples times the\naverage sweep interval.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "leaf": { "$ref": "#/$defs/PythonNativeLeaf" }, @@ -220,7 +239,8 @@ "required": [ "leaf", "samples", - "proportion" + "proportion", + "estimated_ns" ] }, "PythonSampleCollection": { @@ -274,12 +294,6 @@ "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" }, @@ -298,13 +312,17 @@ } ] }, - "sample_capacity": { + "stack_depth": { "type": "integer", - "format": "uint64", + "format": "uint32", "minimum": 0 }, - "stack_depth": { - "type": "integer", + "sweep_reads_per_second": { + "description": "Stack reads per second the sweeps may spend; the sweep rate drops as\nthe thread count grows. Absent for a fixed rate.", + "type": [ + "integer", + "null" + ], "format": "uint32", "minimum": 0 }, @@ -328,6 +346,7 @@ "format": "double" }, "threads_hz_requested": { + "description": "The sweep rate asked for, or its cap when `sweep_reads_per_second`\nis set; 0 sweeps no threads.", "type": "integer", "format": "uint32", "minimum": 0 @@ -371,8 +390,6 @@ "inconsistent_reads", "native_unreadable", "late_ticks", - "sample_capacity", - "over_capacity", "stack_depth", "truncated_stacks" ] @@ -391,6 +408,11 @@ "$ref": "#/$defs/PythonHotspot" } }, + "gil_released_estimated_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "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", @@ -430,6 +452,7 @@ "gil_stack_groups", "gil_hotspots", "gil_released_proportion", + "gil_released_estimated_ns", "thread_stack_groups", "native_waits" ] @@ -438,6 +461,12 @@ "description": "Identical stacks, innermost frame first.", "type": "object", "properties": { + "estimated_ns": { + "description": "Time in this stack: samples times the average GIL tick (GIL groups,\nwall time) or sweep interval (thread groups, thread time summed over\nthreads).", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "frames": { "type": "array", "items": { @@ -459,7 +488,8 @@ "required": [ "frames", "samples", - "proportion" + "proportion", + "estimated_ns" ] }, "PythonTidSource": { diff --git a/schemas/triage-result.schema.json b/schemas/triage-result.schema.json index 714deb0..127c003 100644 --- a/schemas/triage-result.schema.json +++ b/schemas/triage-result.schema.json @@ -717,6 +717,11 @@ "PythonHotspot": { "type": "object", "properties": { + "exclusive_estimated_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "exclusive_proportion": { "type": "number", "format": "double" @@ -729,6 +734,12 @@ "frame": { "$ref": "#/$defs/PythonFrame" }, + "inclusive_estimated_ns": { + "description": "Samples times the average GIL tick.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "inclusive_proportion": { "type": "number", "format": "double" @@ -745,7 +756,9 @@ "inclusive_samples", "exclusive_samples", "inclusive_proportion", - "exclusive_proportion" + "exclusive_proportion", + "inclusive_estimated_ns", + "exclusive_estimated_ns" ] }, "SchemaVersion": { diff --git a/skills/xprobe-perf-profiling/SKILL.md b/skills/xprobe-perf-profiling/SKILL.md index 9392ac8..2f1dbc9 100644 --- a/skills/xprobe-perf-profiling/SKILL.md +++ b/skills/xprobe-perf-profiling/SKILL.md @@ -14,7 +14,7 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA | Check host/container permissions | `xprobe doctor` | Read-only; run first when eBPF, perf, ptrace, or CUPTI access is unknown | | List CUDA PIDs under a root | `xprobe discover --pid "$ROOT"` | Uses NVML; inside containers (`NVML_PID_NAMESPACE_MISMATCH`), scan `ps` or `/proc/*/maps` (`libcuda`) | | Check selectors or injection state | `xprobe validate --pid "$PID" --from A --to B --match exact` | Read-only; reports `requirements.agent_activation` (`already_loaded` vs `injection_required`) | -| Python stacks, GIL & native waits | `xprobe measure --pid "$PID" --python-sample --duration-ms 2000` | CPython 3.9–3.14; ptrace only (no eBPF/perf/injection); lower `--python-threads-hz` if target has >64 threads | +| Python stacks, GIL & native waits | `xprobe measure --pid "$PID" --python-sample --duration-ms 2000` | CPython 3.9–3.14; ptrace only (no eBPF/perf/injection); sweeps of every thread slow down on processes with many threads | | Native CPU callchain hotspots | `xprobe measure --pid "$PID" --cpu-sample --duration-ms 2000 --frequency-hz 999 --max-groups 2048` | Needs perf events; default 99 Hz / 256 groups is too sparse for short windows | | Syscall count & duration totals | `xprobe measure --pid "$PID" --syscall-aggregate --duration-ms 2000` | Needs eBPF | | GPU kernel totals | `xprobe measure --pid "$PID" --from cuda:kernel_start --to cuda:kernel_end --match exact --aggregate --duration-ms 2000` | Aggregates **one** activity kind per run | @@ -41,7 +41,6 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA - **Cross-process & clocks**: run concurrent `measure --pid` captures across processes or ranks. On one host, `host_monotonic`, `cupti_normalized_to_host_monotonic`, and `--python-sample` share `CLOCK_MONOTONIC`. Never mix PIDs in `measure --input` or subtract raw `cupti` timestamps from host timestamps. - **Check completeness before trusting numbers**: `status == "completed"` can still hide truncation or drops. Verify: - `warnings` is empty (or explicitly understood) - - `--python-sample`: `collection.over_capacity == 0` (no `PYTHON_SAMPLES_OVER_CAPACITY`) - `--cpu-sample`: `collection.lost_samples == 0` (no `CPU_GROUP_CAPACITY_REACHED`) - Exact / graph / trigger: `dropped == 0`, check `quality.verdict`, and require `all_gpu_activity == true` when reporting GPU idle time - `--aggregate`: `quality.verdict` and `quality.issues` (`NAME_TRUNCATED` merges kernels that share a cut name) diff --git a/skills/xprobe-perf-profiling/references/data-format.md b/skills/xprobe-perf-profiling/references/data-format.md index a2117e0..0cbbb8a 100644 --- a/skills/xprobe-perf-profiling/references/data-format.md +++ b/skills/xprobe-perf-profiling/references/data-format.md @@ -74,10 +74,9 @@ One line per sample at `result["artifact"]["path"]`: - `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. -- **Converting proportions/counts to estimated time**: `inventory` reports `samples` and `proportion` only. Estimate GIL-held wall time as `proportion * collection.elapsed_ns` (or `samples / collection.gil_hz_achieved` seconds); estimate per-thread sweep time as `samples / collection.threads_hz_achieved` seconds. -- **Completeness**: check `collection.over_capacity == 0` and `warnings` for `PYTHON_SAMPLES_OVER_CAPACITY`. When `over_capacity > 0`, `status` is still `completed` and only the earliest prefix of the window was kept; lower `--python-threads-hz` and re-capture. -- `collection` also reports `gil_hz_achieved`, `threads_hz_achieved`, `elapsed_ns`, `threads`, `sample_capacity`, `inconsistent_reads`, `tid_source`, and `wall_clock`. +- `gil: true` = GIL-holder ticks (default 999 Hz); `gil: false` = all-thread sweep samples (up to 100 Hz, slower for many threads), with `native` populated when a swept thread was blocked in a syscall/native call. +- **Time**: `gil_stack_groups[]` and `gil_hotspots[]` give `estimated_ns` (and `inclusive_estimated_ns` / `exclusive_estimated_ns`) as GIL-holder wall time, `inventory.gil_released_estimated_ns` the time no thread held the GIL; `thread_stack_groups[]` and `native_waits[]` give thread time summed over threads. Every sample is kept, so the whole window is covered. +- `collection` reports `gil_hz_requested`, `gil_hz_achieved`, `threads_hz_requested`, `threads_hz_achieved`, `sweep_reads_per_second` (set when sweeps adapt to the thread count), `elapsed_ns`, `threads`, `inconsistent_reads`, `tid_source`, and `wall_clock`. ## Inventory, measurement, triage, and quality fields @@ -226,7 +225,7 @@ Check `abs((wc["end"]["realtime_ns"] - wc["end"]["monotonic_ns"]) - (wc["start"] ### 5. 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`, zero drops, `collection.over_capacity == 0` (Python), `collection.lost_samples == 0` (CPU), no truncation `warnings`, and check `quality.verdict` (plus `all_gpu_activity == True` when comparing `idle_ns`). +- Guard every comparison: require `ok == True`, zero drops, `collection.lost_samples == 0` (CPU), no truncation `warnings`, 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 diff --git a/skills/xprobe-perf-profiling/references/selectors.md b/skills/xprobe-perf-profiling/references/selectors.md index 4fc526b..587a0e9 100644 --- a/skills/xprobe-perf-profiling/references/selectors.md +++ b/skills/xprobe-perf-profiling/references/selectors.md @@ -77,7 +77,7 @@ Graph rules: ## Parameter tuning & overhead limits -- **`--python-sample` on high-thread processes**: sample capacity is sized as `(python_hz + python_threads_hz * 64) * duration_s`. If the target has many more than 64 threads (`ls /proc/$PID/task | wc -l`), default `--python-threads-hz 100` fills capacity early, keeps only the start of the window, and emits `PYTHON_SAMPLES_OVER_CAPACITY` with `collection.over_capacity > 0` while still reporting `status: "completed"`. Lower `--python-threads-hz` (e.g. `10` or `5`, or `0` for GIL-holder only) so `threads * threads_hz * duration_s` fits cleanly. +- **`--python-sample` rates**: the GIL holder is sampled at 999 Hz. All-thread sweeps run up to 100 times a second and slow down to stay within 6,400 stack reads a second, so 640 threads sweep about 10 times a second; `collection.threads_hz_achieved` shows the rate reached. Set `--python-threads-hz` for a fixed rate, or `0` to sample only the GIL holder. Every sample is kept. - **`--cpu-sample` frequency & groups**: defaults (`--frequency-hz 99`, `--max-groups 256`) produce very few samples on 1–2 s captures and saturate groups quickly on deep stacks (`CPU_GROUP_CAPACITY_REACHED`). Use `--frequency-hz 999 --max-groups 2048` (and raise `--max-samples` if needed) on busy native processes. If `symbolization.python_status` is `unsupported` (CPython <3.12) or `inactive` (3.12+ without `-X perf`), use `--python-sample` instead. - **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`. diff --git a/tests/integration/test_python_sample.py b/tests/integration/test_python_sample.py index 517889b..b2e4b15 100644 --- a/tests/integration/test_python_sample.py +++ b/tests/integration/test_python_sample.py @@ -27,7 +27,11 @@ def check(minor: int, output: pathlib.Path, expected: dict) -> dict: 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["gil_hz_requested"] == 999, collection + assert collection["gil_hz_achieved"] >= 0.9 * collection["gil_hz_requested"], collection + # Two threads fit the default sweep budget at its full rate. + assert collection["sweep_reads_per_second"] == 6400, collection + assert collection["threads_hz_achieved"] >= 90, collection assert collection["threads"] == 2, collection clock = collection["wall_clock"] assert clock["start"]["monotonic_ns"] < clock["end"]["monotonic_ns"], clock @@ -36,6 +40,9 @@ def check(minor: int, output: pathlib.Path, expected: dict) -> dict: hottest = result["inventory"]["gil_hotspots"][0] assert hottest["frame"]["function"] == "hot_inner", hottest assert hottest["exclusive_proportion"] >= 0.8, hottest + # GIL time is wall time: the hot loop's share of the run. + estimated = hottest["exclusive_estimated_ns"] / collection["elapsed_ns"] + assert abs(estimated - hottest["exclusive_proportion"]) < 0.01, hottest sleeper = [ group for group in result["inventory"]["thread_stack_groups"] diff --git a/xprobe/cli/src/args.rs b/xprobe/cli/src/args.rs index eaeac25..d76f62c 100644 --- a/xprobe/cli/src/args.rs +++ b/xprobe/cli/src/args.rs @@ -422,12 +422,14 @@ pub(crate) struct MeasureArgs { /// 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)] + #[arg(long, requires = "python_sample", default_value_t = 999)] 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, + /// Sweeps per second over every Python thread; 0 turns them off. By + /// default sweeps run up to 100 times a second and slow down when the + /// threads would take more than 6,400 stack reads a second. + #[arg(long, requires = "python_sample")] + pub(crate) python_threads_hz: Option, /// 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"])] diff --git a/xprobe/cli/src/dev.rs b/xprobe/cli/src/dev.rs index 1e3464f..734a56a 100644 --- a/xprobe/cli/src/dev.rs +++ b/xprobe/cli/src/dev.rs @@ -250,6 +250,15 @@ pub(crate) fn load_completed_inputs( } pub(crate) fn write_export_file(path: &Path, bytes: &[u8]) -> Result<(), String> { + write_export_with(path, |writer| writer.write_all(bytes)) +} + +/// Write an artifact through `write`, streaming into a private temporary +/// file that replaces `path` only once it is complete. +pub(crate) fn write_export_with( + path: &Path, + write: impl FnOnce(&mut std::io::BufWriter<&mut fs::File>) -> std::io::Result, +) -> Result { let parent = path .parent() .filter(|parent| !parent.as_os_str().is_empty()) @@ -269,10 +278,18 @@ pub(crate) fn write_export_file(path: &Path, bytes: &[u8]) -> Result<(), String> .mode(0o600) .open(&temporary) .map_err(|error| format!("failed to create {}: {error}", temporary.display()))?; - if let Err(error) = file.write_all(bytes).and_then(|()| file.sync_all()) { - let original = format!("failed to write {}: {error}", temporary.display()); - return Err(remove_temporary_artifact(&temporary, original)); + let written = { + let mut writer = std::io::BufWriter::new(&mut file); + write(&mut writer).and_then(|value| writer.flush().map(|()| value)) } + .and_then(|value| file.sync_all().map(|()| value)); + let value = match written { + Ok(value) => value, + Err(error) => { + let original = format!("failed to write {}: {error}", temporary.display()); + return Err(remove_temporary_artifact(&temporary, original)); + } + }; drop(file); if let Err(error) = fs::rename(&temporary, path) { let original = format!( @@ -289,7 +306,8 @@ pub(crate) fn write_export_file(path: &Path, bytes: &[u8]) -> Result<(), String> "failed to sync artifact directory {}: {error}", parent.display() ) - }) + })?; + Ok(value) } pub(crate) fn remove_temporary_artifact(path: &Path, original: String) -> String { diff --git a/xprobe/cli/src/python.rs b/xprobe/cli/src/python.rs index 3166b22..e09c221 100644 --- a/xprobe/cli/src/python.rs +++ b/xprobe/cli/src/python.rs @@ -10,17 +10,18 @@ use xprobe_collector::python_sampling::{ 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_core::python_sampling::{SamplingRequest, analyze, native_addresses, write_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; +/// Default cap on sweeps of every thread per second. +const SWEEP_HZ: u32 = 100; +/// Stack reads per second default sweeps may spend: 100 sweeps of 64 +/// threads. More threads slow the sweeps instead of the target's reads. +const SWEEP_READS_PER_SECOND: u32 = 6_400; pub(crate) struct PythonSampleRequest<'a> { pub(crate) pid: u32, @@ -29,7 +30,9 @@ pub(crate) struct PythonSampleRequest<'a> { pub(crate) name: Option, pub(crate) duration_ms: u64, pub(crate) gil_hz: u32, - pub(crate) threads_hz: u32, + /// Sweeps per second; `None` adapts them to the thread count, 0 turns + /// them off. + pub(crate) threads_hz: Option, pub(crate) events_out: Option<&'a Path>, } @@ -113,23 +116,23 @@ fn sampler_failure(error: &SamplerError) -> CommandFailure { } } -/// 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) } +/// The sweep rate (or its cap) and the read budget that adapts it. +fn sweep_rate(threads_hz: Option) -> (u32, Option) { + threads_hz.map_or((SWEEP_HZ, Some(SWEEP_READS_PER_SECOND)), |hz| (hz, None)) +} + pub(crate) fn python_sample( request: &PythonSampleRequest<'_>, ) -> Result { - if request.duration_ms == 0 || request.threads_hz == 0 { + let (threads_hz, sweep_reads_per_second) = sweep_rate(request.threads_hz); + if request.duration_ms == 0 || (request.gil_hz == 0 && threads_hz == 0) { return Err(CommandFailure::new( ErrorCode::SessionLimitExceeded, - "--python-sample needs a positive --duration-ms and --python-threads-hz", + "--python-sample needs a positive --duration-ms and a positive --python-hz or --python-threads-hz", true, )); } @@ -142,7 +145,6 @@ pub(crate) fn python_sample( }; 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( @@ -151,8 +153,8 @@ pub(crate) fn python_sample( 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), + threads_period: period(threads_hz), + sweep_reads_per_second, max_depth: STACK_DEPTH, }, ) @@ -177,8 +179,8 @@ pub(crate) fn python_sample( python_binary: runtime.binary.display().to_string(), duration, gil_hz: request.gil_hz, - threads_hz: request.threads_hz, - sample_capacity, + threads_hz, + sweep_reads_per_second, stack_depth: u32::try_from(STACK_DEPTH).unwrap_or(u32::MAX), }, &capture, @@ -189,47 +191,27 @@ pub(crate) fn python_sample( 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, - ) - })?; + // Records are written as they are made; none are held as text. + let events = crate::dev::write_export_with(&path, |writer| { + write_records(&capture, request.pid, &native, writer) + }) + .map_err(|error| CommandFailure::new(ErrorCode::TraceExportFailed, error, false))?; result.artifact = Some(EvidenceArtifact { path: path.display().to_string(), format: ExportFormat::Jsonl, - events: lines.len() as u64, + events, }); Ok(result) } #[cfg(test)] mod tests { - use super::{PythonSampleRequest, capacity}; + use super::{SWEEP_HZ, SWEEP_READS_PER_SECOND, sweep_rate}; #[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); + fn sweeps_adapt_by_default_and_follow_a_given_rate() { + assert_eq!(sweep_rate(None), (SWEEP_HZ, Some(SWEEP_READS_PER_SECOND))); + assert_eq!(sweep_rate(Some(50)), (50, None)); + assert_eq!(sweep_rate(Some(0)), (0, None)); } } diff --git a/xprobe/cli/src/triage.rs b/xprobe/cli/src/triage.rs index e12771e..ad0fe86 100644 --- a/xprobe/cli/src/triage.rs +++ b/xprobe/cli/src/triage.rs @@ -147,8 +147,8 @@ fn triage(request: &TriageRequest) -> Result { runtime: python_runtime.as_ref().ok().cloned(), name: None, duration_ms: request.duration_ms, - gil_hz: 2000, - threads_hz: 100, + gil_hz: 999, + threads_hz: None, events_out: Some(&python_artifact), }; let (cpu, syscalls, gpu_activity, gpu_rounds, python) = thread::scope(|scope| { diff --git a/xprobe/collector/src/python_sampling.rs b/xprobe/collector/src/python_sampling.rs index 39faf20..2411d2f 100644 --- a/xprobe/collector/src/python_sampling.rs +++ b/xprobe/collector/src/python_sampling.rs @@ -21,7 +21,7 @@ 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, + Code, NativeLeaf, PythonCapture, PythonSample, ReadTimes, SamplerCounters, Stack, TidSource, parse_task_syscall, }; @@ -756,18 +756,36 @@ fn search_pthread_tid_offset( Ok(chosen.map(|(offset, _)| offset)) } -/// When and how much to sample. +/// When and how much to sample. Every sample is kept: memory grows by a +/// few dozen bytes per sample plus each distinct stack. #[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, + /// Shortest period of sweeps of every thread, or `None` for none. + pub threads_period: Option, + /// Stack reads per second the sweeps may spend: with many threads the + /// sweep period grows to fit. `None` keeps `threads_period`. + pub sweep_reads_per_second: Option, pub max_depth: usize, } +impl SamplerConfig { + /// The period until the next sweep after one over `threads` threads. + fn sweep_period(&self, threads: usize) -> Option { + let period = self.threads_period?; + let threads = u32::try_from(threads).unwrap_or(u32::MAX); + let budget = self + .sweep_reads_per_second + .filter(|reads| *reads != 0) + .map_or(Duration::ZERO, |reads| { + Duration::from_secs(1) * threads / reads + }); + Some(period.max(budget)) + } +} + fn monotonic_ns() -> Result { let now = clock_gettime(ClockId::CLOCK_MONOTONIC) .map_err(|error| SamplerError::Clock(error.to_string()))?; @@ -807,22 +825,29 @@ struct Run<'w, 'm, M: RemoteMemory> { walker: &'w mut Walker<'m, M>, pid: u32, interpreter: u64, - config: SamplerConfig, capture: PythonCapture, + /// Index of each distinct stack in `capture.stacks`. + stack_ids: HashMap, /// Where `struct pthread` stores the TID, once found (before 3.11). pthread_offset: Option, } impl Run<'_, '_, M> { + fn intern(&mut self, stack: Stack) -> u32 { + if let Some(id) = self.stack_ids.get(&stack) { + return *id; + } + let id = u32::try_from(self.capture.stacks.len()).expect("distinct stacks fit u32"); + self.capture.stacks.push(stack.clone()); + self.stack_ids.insert(stack, id); + id + } + /// 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); @@ -840,14 +865,15 @@ impl Run<'_, '_, M> { } }; self.capture - .read_ns - .push(u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX)); + .read_times + .record(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, }; + let stack = self.intern(stack); self.capture.samples.push(PythonSample { timestamp_ns, tid, @@ -913,7 +939,8 @@ impl Run<'_, '_, M> { } /// Refresh the thread list and its TIDs, then sample every thread. - fn sweep(&mut self) -> Result<(), SamplerError> { + /// Returns how many threads there were. + fn sweep(&mut self) -> Result { let threads = self.walker .threads(self.interpreter) @@ -933,10 +960,11 @@ impl Run<'_, '_, M> { .map_or(TidSource::Unmapped, TidSource::Pthread); } self.capture.counters.thread_sweeps += 1; + let count = threads.len(); for thread in threads { self.read(thread, None)?; } - Ok(()) + Ok(count) } } @@ -946,6 +974,10 @@ impl Run<'_, '_, M> { /// /// Returns [`SamplerError`] when the runtime cannot be read or verified, the /// target denies access, or it exits. +/// +/// # Panics +/// +/// Panics if one run sees more than `u32::MAX` distinct stacks. pub fn sample( walker: &mut Walker<'_, M>, pid: u32, @@ -958,12 +990,12 @@ pub fn sample( walker, pid, interpreter, - config, capture: PythonCapture { samples: Vec::new(), + stacks: Vec::new(), codes: Vec::new(), counters: SamplerCounters::default(), - read_ns: Vec::new(), + read_times: ReadTimes::default(), elapsed: Duration::ZERO, tid_source: if native_tids { TidSource::Native @@ -972,11 +1004,13 @@ pub fn sample( }, threads: BTreeSet::new(), }, + stack_ids: HashMap::new(), pthread_offset: None, }; let start = Instant::now(); let end = start + config.duration; - let mut next_sweep = start; + // Without sweeps the next one never comes. + let mut next_sweep = config.threads_period.map_or(end, |_| start); let mut next_gil = start; loop { let now = Instant::now(); @@ -984,13 +1018,10 @@ pub fn sample( break; } if now >= next_sweep { - run.sweep()?; - next_sweep = advance( - next_sweep, - config.threads_period, - now, - &mut run.capture.counters, - ); + let threads = run.sweep()?; + next_sweep = config.sweep_period(threads).map_or(end, |period| { + advance(next_sweep, period, now, &mut run.capture.counters) + }); } if let Some(period) = config.gil_period && now >= next_gil @@ -1250,26 +1281,55 @@ mod tests { 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(), + stacks: Vec::new(), codes: Vec::new(), counters: xprobe_core::python_sampling::SamplerCounters::default(), - read_ns: Vec::new(), + read_times: super::ReadTimes::default(), elapsed: std::time::Duration::ZERO, tid_source: xprobe_core::python_sampling::TidSource::Native, threads: std::collections::BTreeSet::new(), }, + stack_ids: std::collections::HashMap::new(), pthread_offset: None, } } + #[test] + fn identical_stacks_share_one_entry_and_sweeps_slow_with_many_threads() { + let memory = python_312(); + let mut walker = Walker::new(&memory, runtime(12), 64); + let mut run = run(&mut walker); + run.read(0x3000, None).unwrap(); + run.read(0x3000, None).unwrap(); + assert_eq!(run.capture.samples.len(), 2); + assert_eq!(run.capture.stacks.len(), 1); + assert_eq!(run.capture.samples[1].stack, run.capture.samples[0].stack); + + let config = super::SamplerConfig { + duration: std::time::Duration::from_secs(1), + gil_period: None, + threads_period: Some(std::time::Duration::from_millis(10)), + sweep_reads_per_second: Some(6_400), + max_depth: 64, + }; + // 64 threads fit 100 sweeps a second; 640 take ten times as long. + assert_eq!( + config.sweep_period(64), + Some(std::time::Duration::from_millis(10)) + ); + assert_eq!( + config.sweep_period(640), + Some(std::time::Duration::from_millis(100)) + ); + let off = super::SamplerConfig { + threads_period: None, + ..config + }; + assert_eq!(off.sweep_period(64), None); + } + #[test] fn a_gil_sample_needs_the_same_holder_throughout() { let memory = python_312(); diff --git a/xprobe/core/src/python_sampling.rs b/xprobe/core/src/python_sampling.rs index 03004bd..11ad5ca 100644 --- a/xprobe/core/src/python_sampling.rs +++ b/xprobe/core/src/python_sampling.rs @@ -4,6 +4,7 @@ //! their data and turns a finished capture into a `PythonSampleResult`. use std::collections::{BTreeMap, BTreeSet}; +use std::io::{self, Write}; use std::time::Duration; use xprobe_protocol::{ @@ -24,21 +25,22 @@ pub struct Code { } /// One stack, innermost frame first. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Stack { pub frames: Vec, pub truncated: bool, } /// One stack read. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, 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, + /// Index into [`PythonCapture::stacks`]. + pub stack: u32, /// Where a blocked thread waits in native code (sweep samples only). pub native: Option, } @@ -77,8 +79,6 @@ pub struct SamplerCounters { 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. @@ -95,14 +95,63 @@ pub enum TidSource { Unmapped, } +/// Stack read times in log-linear buckets, 16 per power of two, so memory +/// stays fixed and a percentile is within about 6% of the exact value. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ReadTimes { + counts: BTreeMap, + total: u64, + max: u64, +} + +impl ReadTimes { + pub fn record(&mut self, ns: u64) { + *self.counts.entry(Self::bucket(ns)).or_default() += 1; + self.total += 1; + self.max = self.max.max(ns); + } + + fn bucket(ns: u64) -> u32 { + if ns < 16 { + return u32::try_from(ns).expect("below 16"); + } + let exponent = ns.ilog2(); + let step = u32::try_from((ns >> (exponent - 4)) & 15).expect("four bits"); + exponent * 16 + step + } + + /// The largest value in `bucket`. + fn upper(bucket: u32) -> u64 { + if bucket < 16 { + return u64::from(bucket); + } + let (exponent, step) = (bucket / 16, u64::from(bucket % 16)); + ((17 + step) << (exponent - 4)) - 1 + } + + fn percentile(&self, percentile: u64) -> u64 { + let rank = (percentile * self.total).div_ceil(100).max(1); + let mut seen = 0; + for (bucket, count) in &self.counts { + seen += count; + if seen >= rank { + return Self::upper(*bucket).min(self.max); + } + } + self.max + } +} + /// A finished sampling run. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PythonCapture { pub samples: Vec, + /// Distinct stacks, which samples index. + pub stacks: Vec, pub codes: Vec, pub counters: SamplerCounters, - /// Wall time of each kept stack read, in nanoseconds. - pub read_ns: Vec, + /// Wall time of the kept stack reads. + pub read_times: ReadTimes, pub elapsed: Duration, pub tid_source: TidSource, /// Every TID seen in the interpreter's thread list. @@ -126,8 +175,11 @@ pub struct SamplingRequest { pub python_binary: String, pub duration: Duration, pub gil_hz: u32, + /// The sweep rate, or its cap when `sweep_reads_per_second` adapts it. pub threads_hz: u32, - pub sample_capacity: u64, + /// Stack reads per second that sweeps of every thread may spend; the + /// sweep rate drops as the thread count grows. + pub sweep_reads_per_second: Option, pub stack_depth: u32, } @@ -158,21 +210,57 @@ fn ratio(numerator: u64, denominator: u64) -> f64 { } } +/// Time one sample stands for: a GIL tick's or a sweep's share of the run. +#[allow( + clippy::cast_precision_loss, + reason = "nanosecond and tick counts stay far below 2^52" +)] +fn sample_ns(elapsed: Duration, ticks: u64) -> f64 { + if ticks == 0 { + 0.0 + } else { + elapsed.as_nanos() as f64 / ticks as f64 + } +} + +#[allow( + clippy::cast_precision_loss, + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "estimates are rounded nonnegative nanoseconds" +)] +fn estimate(samples: u64, sample_ns: f64) -> u64 { + (samples as f64 * sample_ns).round() as u64 +} + +/// How a list's proportions and time estimates are computed. +#[derive(Clone, Copy)] +struct Scale { + total: u64, + sample_ns: f64, +} + fn groups<'a>( samples: impl Iterator, - codes: &[Code], - total: u64, + capture: &PythonCapture, + scale: Scale, ) -> Vec { let mut counts = BTreeMap::<&[u32], u64>::new(); for sample in samples { - *counts.entry(sample.stack.frames.as_slice()).or_default() += 1; + *counts + .entry(capture.stacks[sample.stack as usize].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(), + frames: frames + .iter() + .map(|index| frame(&capture.codes, *index)) + .collect(), samples, - proportion: ratio(samples, total), + proportion: ratio(samples, scale.total), + estimated_ns: estimate(samples, scale.sample_ns), }) .collect::>(); groups.sort_by(|left, right| { @@ -187,17 +275,18 @@ fn groups<'a>( fn hotspots<'a>( samples: impl Iterator, - codes: &[Code], - total: u64, + capture: &PythonCapture, + scale: Scale, ) -> Vec { let mut inclusive = BTreeMap::::new(); let mut exclusive = BTreeMap::::new(); for sample in samples { + let frames = &capture.stacks[sample.stack as usize].frames; // A recursive function counts once per sample. - for index in sample.stack.frames.iter().collect::>() { + for index in frames.iter().collect::>() { *inclusive.entry(*index).or_default() += 1; } - if let Some(leaf) = sample.stack.frames.first() { + if let Some(leaf) = frames.first() { *exclusive.entry(*leaf).or_default() += 1; } } @@ -206,11 +295,13 @@ fn hotspots<'a>( .map(|(index, inclusive_samples)| { let exclusive_samples = exclusive.get(&index).copied().unwrap_or(0); PythonHotspot { - frame: frame(codes, index), + frame: frame(&capture.codes, index), inclusive_samples, exclusive_samples, - inclusive_proportion: ratio(inclusive_samples, total), - exclusive_proportion: ratio(exclusive_samples, total), + inclusive_proportion: ratio(inclusive_samples, scale.total), + exclusive_proportion: ratio(exclusive_samples, scale.total), + inclusive_estimated_ns: estimate(inclusive_samples, scale.sample_ns), + exclusive_estimated_ns: estimate(exclusive_samples, scale.sample_ns), } }) .collect::>(); @@ -225,15 +316,11 @@ fn hotspots<'a>( 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 latency(times: &ReadTimes) -> Option { + (times.total != 0).then(|| ReadLatency { + p50_ns: times.percentile(50), + p99_ns: times.percentile(99), + max_ns: times.max, }) } @@ -245,8 +332,7 @@ fn warning(code: &str, message: String) -> Warning { } } -/// Warnings for discarded reads, missed rates, unmapped TIDs, and samples -/// over capacity. +/// Warnings for discarded reads, missed rates, and unmapped TIDs. fn quality_warnings( request: &SamplingRequest, capture: &PythonCapture, @@ -265,9 +351,15 @@ fn quality_warnings( ), )); } + // An adaptive sweep rate drops below its cap by design. + let fixed_threads_hz = if request.sweep_reads_per_second.is_some() { + 0 + } else { + request.threads_hz + }; for (what, requested, achieved) in [ ("GIL", request.gil_hz, gil_hz_achieved), - ("thread", request.threads_hz, threads_hz_achieved), + ("thread", fixed_threads_hz, threads_hz_achieved), ] { if requested != 0 && achieved < f64::from(requested) * RATE_WARNING_SHARE { warnings.push(warning( @@ -282,15 +374,6 @@ fn quality_warnings( "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 } @@ -325,8 +408,16 @@ pub fn analyze( let truncated_stacks = capture .samples .iter() - .filter(|sample| sample.stack.truncated) + .filter(|sample| capture.stacks[sample.stack as usize].truncated) .count() as u64; + let gil_scale = Scale { + total: counters.gil_ticks, + sample_ns: sample_ns(capture.elapsed, counters.gil_ticks), + }; + let thread_scale = Scale { + total: thread_samples, + sample_ns: sample_ns(capture.elapsed, counters.thread_sweeps), + }; PythonSampleResult { schema_version: SchemaVersion3::current(), ok: true, @@ -336,11 +427,12 @@ pub fn analyze( 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_stack_groups: groups(gil(), capture, gil_scale), + gil_hotspots: hotspots(gil(), capture, gil_scale), 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), + gil_released_estimated_ns: estimate(counters.gil_idle, gil_scale.sample_ns), + thread_stack_groups: groups(threads(), capture, thread_scale), + native_waits: native_waits(threads(), native, thread_scale), }, collection: PythonSampleCollection { wall_clock: None, @@ -356,6 +448,7 @@ pub fn analyze( gil_hz_achieved, threads_hz_requested: request.threads_hz, threads_hz_achieved, + sweep_reads_per_second: request.sweep_reads_per_second, gil_ticks: counters.gil_ticks, gil_samples, gil_released_ticks: counters.gil_idle, @@ -365,11 +458,9 @@ pub fn analyze( 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), + read_latency: latency(&capture.read_times), }, artifact: None, warnings, @@ -402,7 +493,7 @@ fn native_leaf(leaf: NativeLeaf, native: &BTreeMap) -> Pytho fn native_waits<'a>( samples: impl Iterator, native: &BTreeMap, - total: u64, + scale: Scale, ) -> Vec { let mut counts = BTreeMap::::new(); for leaf in samples.filter_map(|sample| sample.native) { @@ -413,7 +504,8 @@ fn native_waits<'a>( .map(|(leaf, samples)| PythonNativeWait { leaf, samples, - proportion: ratio(samples, total), + proportion: ratio(samples, scale.total), + estimated_ns: estimate(samples, scale.sample_ns), }) .collect::>(); waits.sort_by(|left, right| { @@ -426,31 +518,36 @@ fn native_waits<'a>( waits } -/// Every sample as an artifact record. -#[must_use] -pub fn records( +/// Write every sample as one JSON line to `writer`, returning how many. +/// +/// # Errors +/// +/// Returns the writer's I/O error. +pub fn write_records( capture: &PythonCapture, pid: u32, native: &BTreeMap, -) -> Vec { - capture - .samples - .iter() - .map(|sample| PythonSampleRecord { + writer: &mut impl Write, +) -> io::Result { + for sample in &capture.samples { + let stack = &capture.stacks[sample.stack as usize]; + let record = PythonSampleRecord { timestamp_ns: sample.timestamp_ns, pid, tid: sample.tid, gil: sample.gil, - truncated: sample.stack.truncated, - frames: sample - .stack + truncated: stack.truncated, + frames: stack .frames .iter() .map(|index| frame(&capture.codes, *index)) .collect(), native: sample.native.map(|leaf| native_leaf(leaf, native)), - }) - .collect() + }; + serde_json::to_writer(&mut *writer, &record).map_err(io::Error::other)?; + writer.write_all(b"\n")?; + } + Ok(capture.samples.len() as u64) } #[cfg(test)] @@ -461,23 +558,41 @@ mod tests { use xprobe_protocol::TargetIdentity; use super::{ - Code, NativeLeaf, PythonCapture, PythonSample, SamplerCounters, SamplingRequest, Stack, - TidSource, analyze, parse_task_syscall, records, + Code, NativeLeaf, PythonCapture, PythonSample, ReadTimes, SamplerCounters, SamplingRequest, + Stack, TidSource, analyze, parse_task_syscall, write_records, }; - fn sample(gil: bool, frames: &[u32]) -> PythonSample { + fn sample(gil: bool, stack: u32) -> PythonSample { PythonSample { timestamp_ns: 1, tid: Some(7), gil, - stack: Stack { - frames: frames.to_vec(), - truncated: false, - }, + stack, native: None, } } + fn stack(frames: &[u32]) -> Stack { + Stack { + frames: frames.to_vec(), + truncated: false, + } + } + + #[test] + fn read_time_percentiles_stay_within_a_bucket() { + let mut times = ReadTimes::default(); + for ns in 1..=10_000 { + times.record(ns); + } + // Exact p50 is 5000 and p99 9900; buckets are within 1/16. + let p50 = times.percentile(50); + let p99 = times.percentile(99); + assert!((5000..=5000 + 5000 / 16).contains(&p50), "{p50}"); + assert!((9900..=10_000).contains(&p99), "{p99}"); + assert_eq!(times.max, 10_000); + } + #[test] fn parses_task_syscall_states() { assert_eq!(parse_task_syscall("running\n"), None); @@ -508,12 +623,13 @@ mod tests { // 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]), + sample(true, 0), + sample(true, 0), + sample(true, 0), + sample(true, 1), + sample(false, 1), ], + stacks: vec![stack(&[0, 2]), stack(&[1, 2])], codes: vec![code("step"), code("load"), code("main")], counters: SamplerCounters { gil_ticks: 5, @@ -521,7 +637,13 @@ mod tests { thread_sweeps: 1, ..SamplerCounters::default() }, - read_ns: vec![10, 20, 30, 40, 1000], + read_times: [10, 20, 30, 40, 1000].into_iter().fold( + ReadTimes::default(), + |mut times, ns| { + times.record(ns); + times + }, + ), elapsed: Duration::from_millis(2), tid_source: TidSource::Native, threads: BTreeSet::from([7]), @@ -538,7 +660,7 @@ mod tests { duration: Duration::from_millis(2), gil_hz: 2500, threads_hz: 500, - sample_capacity: 100, + sweep_reads_per_second: None, stack_depth: 128, }; let result = analyze(&request, &capture, &std::collections::BTreeMap::new()); @@ -546,6 +668,11 @@ mod tests { 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); + // Five GIL ticks over 2 ms: 0.4 ms each. + assert_eq!(inventory.gil_stack_groups[0].estimated_ns, 1_200_000); + assert_eq!(inventory.gil_released_estimated_ns, 400_000); + // One sweep over 2 ms: each thread sample stands for 2 ms. + assert_eq!(inventory.thread_stack_groups[0].estimated_ns, 2_000_000); let step = &inventory.gil_hotspots[0]; assert_eq!(step.frame.function, "step"); assert_eq!((step.exclusive_samples, step.inclusive_samples), (3, 3)); @@ -555,6 +682,7 @@ mod tests { .find(|hotspot| hotspot.frame.function == "main") .unwrap(); assert_eq!((main.exclusive_samples, main.inclusive_samples), (0, 4)); + assert_eq!(main.inclusive_estimated_ns, 1_600_000); 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)); @@ -566,9 +694,15 @@ mod tests { ); 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"); + let mut text = Vec::new(); + let written = + write_records(&capture, 1, &std::collections::BTreeMap::new(), &mut text).unwrap(); + assert_eq!(written, 5); + let lines = String::from_utf8(text).unwrap(); + let first: xprobe_protocol::PythonSampleRecord = + serde_json::from_str(lines.lines().next().unwrap()).unwrap(); + assert_eq!(lines.lines().count(), 5); + assert_eq!(first.frames[0].function, "step"); + assert_eq!(first.frames[1].function, "main"); } } diff --git a/xprobe/core/src/triage.rs b/xprobe/core/src/triage.rs index 0b05ad2..3f7b90f 100644 --- a/xprobe/core/src/triage.rs +++ b/xprobe/core/src/triage.rs @@ -890,6 +890,8 @@ mod tests { exclusive_samples: 0, inclusive_proportion: inclusive, exclusive_proportion: exclusive, + inclusive_estimated_ns: 0, + exclusive_estimated_ns: 0, }; let hotspots = [ python("collate", 0.62, 0.62), diff --git a/xprobe/protocol/src/python_sampling.rs b/xprobe/protocol/src/python_sampling.rs index ceb33cc..c6f4b35 100644 --- a/xprobe/protocol/src/python_sampling.rs +++ b/xprobe/protocol/src/python_sampling.rs @@ -36,6 +36,9 @@ pub struct PythonNativeWait { pub samples: u64, /// Share of thread samples. pub proportion: f64, + /// Thread time spent here, summed over threads: samples times the + /// average sweep interval. + pub estimated_ns: u64, } /// Identical stacks, innermost frame first. @@ -46,6 +49,10 @@ pub struct PythonStackGroup { pub samples: u64, /// Share of the samples this group was drawn from. pub proportion: f64, + /// Time in this stack: samples times the average GIL tick (GIL groups, + /// wall time) or sweep interval (thread groups, thread time summed over + /// threads). + pub estimated_ns: u64, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] @@ -56,6 +63,9 @@ pub struct PythonHotspot { pub exclusive_samples: u64, pub inclusive_proportion: f64, pub exclusive_proportion: f64, + /// Samples times the average GIL tick. + pub inclusive_estimated_ns: u64, + pub exclusive_estimated_ns: u64, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] @@ -70,6 +80,7 @@ pub struct PythonSampleInventory { /// 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, + pub gil_released_estimated_ns: u64, /// Stacks of every thread from the slower sweeps; proportions are of /// thread samples. pub thread_stack_groups: Vec, @@ -112,8 +123,14 @@ pub struct PythonSampleCollection { pub gil_hz_requested: u32, /// GIL ticks per second actually reached. pub gil_hz_achieved: f64, + /// The sweep rate asked for, or its cap when `sweep_reads_per_second` + /// is set; 0 sweeps no threads. pub threads_hz_requested: u32, pub threads_hz_achieved: f64, + /// Stack reads per second the sweeps may spend; the sweep rate drops as + /// the thread count grows. Absent for a fixed rate. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sweep_reads_per_second: Option, pub gil_ticks: u64, pub gil_samples: u64, pub gil_released_ticks: u64, @@ -128,9 +145,6 @@ pub struct PythonSampleCollection { 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. From 9fe65d7ecc5a6f719bb7f3bdba70f9dd9cfd3041 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:07:29 +0800 Subject: [PATCH 08/22] =?UTF-8?q?=E2=9C=A8=20feat:=20keep=20every=20CPU=20?= =?UTF-8?q?sample=20with=20its=20time=20and=20on-CPU=20duration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --cpu-sample stopped at --max-samples and listed hotspots computed only from the groups that fit --max-groups, so short captures looked sparse and long ones lost samples. Every sample is now kept, stamped on CLOCK_MONOTONIC with its perf period, and written to --events-out as JSONL: each stack once, then the samples that use it. --max-samples is gone; --max-groups only sets how many groups and hotspots are listed. Groups and hotspots give estimated_ns from perf periods, and collection reports cpu_time_ns and elapsed_ns. The default rate is 999 Hz, in triage too. analyze_trace.py --cpu-samples adds the on-CPU stacks sampled inside a gap, outlier, or time slice, ranked by CPU time. --- benchmarks/cpu-inventory/run.py | 5 +- docs/architecture.md | 2 +- docs/cli-reference.md | 6 +- .../cpu-sample-inventory-result.schema.json | 88 +++- schemas/cpu-sample-record.schema.json | 152 +++++++ schemas/cpu-sampling-spec.schema.json | 7 +- schemas/triage-result.schema.json | 15 +- skills/xprobe-perf-profiling/SKILL.md | 6 +- .../references/data-format.md | 26 +- .../references/selectors.md | 2 +- .../scripts/analyze_trace.py | 124 ++++-- tests/agent-contract/test_contract.py | 15 +- tests/agent-contract/test_trace_analysis.py | 35 +- xprobe/cli/src/args.rs | 17 +- xprobe/cli/src/inventory.rs | 70 +++- xprobe/cli/src/main.rs | 3 +- xprobe/cli/src/triage.rs | 14 +- xprobe/collector/src/cpu_sampling.rs | 86 ++-- xprobe/core/src/cpu_sampling_analysis.rs | 389 ++++++++++++------ xprobe/core/src/triage.rs | 2 + xprobe/protocol/src/cpu_sampling.rs | 52 ++- xprobe/protocol/src/lib.rs | 6 +- xprobe/protocol/src/schema.rs | 10 +- xprobe/protocol/tests/contracts.rs | 11 +- 24 files changed, 863 insertions(+), 280 deletions(-) create mode 100644 schemas/cpu-sample-record.schema.json diff --git a/benchmarks/cpu-inventory/run.py b/benchmarks/cpu-inventory/run.py index 2ba00be..8368967 100644 --- a/benchmarks/cpu-inventory/run.py +++ b/benchmarks/cpu-inventory/run.py @@ -315,8 +315,6 @@ def cpu_sample_command(xprobe: pathlib.Path, seconds: int) -> list[str]: str(seconds * 1000), "--frequency-hz", str(FREQUENCY_HZ), - "--max-samples", - str(seconds * FREQUENCY_HZ * 4), "--max-groups", "512", "--json", @@ -440,9 +438,8 @@ def cpu_quality(result: dict) -> dict: "observed_samples": observed, "grouped_samples": collection["grouped_samples"], "lost_samples": collection["lost_samples"], - "sample_capacity": collection["sample_capacity"], - "group_capacity": collection["group_capacity"], "groups": collection["groups"], + "cpu_time_ns": collection["cpu_time_ns"], "stack_coverage": collection["grouped_samples"] / observed if observed else 0.0, "symbol_coverage": resolved / total_frames if total_frames else 0.0, "python_status": symbols["python_status"], diff --git a/docs/architecture.md b/docs/architecture.md index 4e50f55..081d740 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -69,7 +69,7 @@ CPU sampling, syscall aggregation, and measurement graphs each have their own va - 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. +- **`--cpu-sample`**: opens software CPU-clock perf events per target thread with `CLOCK_MONOTONIC` timestamps and periods, keeps every sample with an index into the distinct callchains, writes them as JSONL, 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 999) and sweeps all threads up to 100 times a second within 6,400 stack reads a second (`--python-threads-hz` fixes the rate), keeps every sample, discards 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`) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index b2dbe66..2ffe3bb 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -150,7 +150,7 @@ xprobe measure --pid 4242 \ # CPU callchain hotspot inventory xprobe measure --pid 4242 --cpu-sample --duration-ms 2000 \ - --frequency-hz 999 --max-samples 20000 --max-groups 2048 --stack-depth 64 --max-threads 1024 + --max-groups 256 --stack-depth 64 --max-threads 1024 --events-out cpu-samples.jsonl # External CPython stacks & GIL holder xprobe measure --pid 4242 --python-sample --duration-ms 2000 @@ -202,9 +202,9 @@ Each inventory is a live mode that runs for `--duration-ms` and reports totals i | `--syscall-aggregate` | Per-syscall counts and durations in BPF maps | `2.0` | | `--aggregate` | Agent-side totals for one kernel, memcpy, or memset start/end pair | `3.0` | -`--cpu-sample`, `--syscall-aggregate`, and `--aggregate` write no Event JSONL, so their output cannot be passed to `--input` or `--events-out`. +`--syscall-aggregate` and `--aggregate` write no Event JSONL, so their output cannot be passed to `--input` or `--events-out`. -**`--cpu-sample`** defaults to 99 Hz, 10,000 samples, 256 groups, depth 64, and 1,024 threads. For short 1–2 s captures on busy native processes, raise `--frequency-hz` (e.g. `499`–`999`) and `--max-groups` (e.g. `2048`) to avoid sparse counts or `CPU_GROUP_CAPACITY_REACHED`. It resolves ELF symbols and `/tmp/perf-.map` Python frames separately; when `python_status` is `unsupported` (CPython <3.12) or `inactive` (no `-X perf`), use `--python-sample` instead. +**`--cpu-sample`** defaults to 999 Hz, depth 64, and 1,024 threads. Every sample is kept and written with its `CLOCK_MONOTONIC` time to `--events-out` (or a private file) as JSONL (`schemas/cpu-sample-record.schema.json`): each stack once, before the first sample that uses it, then samples that name it. `--max-groups` (default 256) sets how many stack groups and hotspots are listed; every sample is counted. Each group and hotspot gives `estimated_ns`, the on-CPU time summed from perf periods, and `collection.cpu_time_ns` the total. It resolves ELF symbols and `/tmp/perf-.map` Python frames separately; when `python_status` is `unsupported` (CPython <3.12) or `inactive` (no `-X perf`), use `--python-sample` instead. **`--python-sample`** reads CPython 3.9–3.14 memory with `process_vm_readv`. It needs ptrace access but no perf events, eBPF, `-X perf`, or injection. diff --git a/schemas/cpu-sample-inventory-result.schema.json b/schemas/cpu-sample-inventory-result.schema.json index 730388f..8b02d74 100644 --- a/schemas/cpu-sample-inventory-result.schema.json +++ b/schemas/cpu-sample-inventory-result.schema.json @@ -3,6 +3,17 @@ "title": "CpuSampleInventoryResult", "type": "object", "properties": { + "artifact": { + "description": "Every sample with its time, as `CpuSampleRecord` lines.", + "anyOf": [ + { + "$ref": "#/$defs/EvidenceArtifact" + }, + { + "type": "null" + } + ] + }, "collection": { "$ref": "#/$defs/CpuSampleCollectionSummary" }, @@ -71,6 +82,11 @@ "null" ] }, + "exclusive_estimated_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "exclusive_proportion": { "type": "number", "format": "double" @@ -83,6 +99,12 @@ "frame": { "$ref": "#/$defs/CpuStackFrame" }, + "inclusive_estimated_ns": { + "description": "On-CPU time with this frame on the stack, and as the leaf.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "inclusive_proportion": { "type": "number", "format": "double" @@ -105,7 +127,9 @@ "inclusive_samples", "exclusive_samples", "inclusive_proportion", - "exclusive_proportion" + "exclusive_proportion", + "inclusive_estimated_ns", + "exclusive_estimated_ns" ] }, "CpuSampleCollectionSummary": { @@ -114,32 +138,34 @@ "completeness": { "$ref": "#/$defs/CpuCaptureCompleteness" }, - "group_capacity": { + "cpu_time_ns": { + "description": "On-CPU time of every sample: the sum of their perf periods.", "type": "integer", "format": "uint64", "minimum": 0 }, - "grouped_samples": { + "elapsed_ns": { "type": "integer", "format": "uint64", "minimum": 0 }, - "groups": { + "grouped_samples": { "type": "integer", "format": "uint64", "minimum": 0 }, - "lost_samples": { + "groups": { + "description": "Distinct stacks; `max_groups` of them are listed.", "type": "integer", "format": "uint64", "minimum": 0 }, - "observed_samples": { + "lost_samples": { "type": "integer", "format": "uint64", "minimum": 0 }, - "sample_capacity": { + "observed_samples": { "type": "integer", "format": "uint64", "minimum": 0 @@ -149,10 +175,6 @@ "format": "uint32", "minimum": 0 }, - "table_utilization": { - "type": "number", - "format": "double" - }, "thread_capacity": { "type": "integer", "format": "uint32", @@ -180,10 +202,9 @@ "observed_samples", "grouped_samples", "lost_samples", - "sample_capacity", - "group_capacity", "groups", - "table_utilization", + "elapsed_ns", + "cpu_time_ns", "stack_depth", "truncated_stacks", "threads_observed", @@ -310,6 +331,12 @@ "CpuStackGroup": { "type": "object", "properties": { + "estimated_ns": { + "description": "On-CPU time: the sum of the samples' perf periods.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "frames": { "type": "array", "items": { @@ -330,7 +357,8 @@ "required": [ "frames", "samples", - "proportion" + "proportion", + "estimated_ns" ] }, "CpuSymbolizationSummary": { @@ -369,6 +397,36 @@ "python_status" ] }, + "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" + ] + }, "PythonSymbolizationStatus": { "type": "string", "enum": [ diff --git a/schemas/cpu-sample-record.schema.json b/schemas/cpu-sample-record.schema.json new file mode 100644 index 0000000..ab003f8 --- /dev/null +++ b/schemas/cpu-sample-record.schema.json @@ -0,0 +1,152 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "CpuSampleRecord", + "description": "One line of a CPU sample artifact: a stack, written before the first\nsample that uses it, or a sample.", + "anyOf": [ + { + "$ref": "#/$defs/CpuStackRecord" + }, + { + "$ref": "#/$defs/CpuSampleLine" + } + ], + "$defs": { + "CpuFrameLanguage": { + "type": "string", + "enum": [ + "native", + "python", + "unknown" + ] + }, + "CpuSampleLine": { + "type": "object", + "properties": { + "cpu_ns": { + "description": "On-CPU time the sample stands for: its perf period.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "pid": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "stack": { + "description": "A stack written on an earlier line.", + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "tid": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "timestamp_ns": { + "description": "`CLOCK_MONOTONIC` time of the sample.", + "type": "integer", + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "timestamp_ns", + "pid", + "tid", + "cpu_ns", + "stack" + ] + }, + "CpuStackFrame": { + "type": "object", + "properties": { + "address": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, + "build_id": { + "type": [ + "string", + "null" + ] + }, + "file_offset": { + "type": [ + "integer", + "null" + ], + "format": "uint64", + "minimum": 0 + }, + "language": { + "$ref": "#/$defs/CpuFrameLanguage" + }, + "line": { + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0 + }, + "module_path": { + "type": [ + "string", + "null" + ] + }, + "source_path": { + "type": [ + "string", + "null" + ] + }, + "symbol": { + "type": [ + "string", + "null" + ] + }, + "symbol_offset": { + "type": [ + "integer", + "null" + ], + "format": "uint64", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "address", + "language" + ] + }, + "CpuStackRecord": { + "type": "object", + "properties": { + "frames": { + "description": "Innermost frame first.", + "type": "array", + "items": { + "$ref": "#/$defs/CpuStackFrame" + } + }, + "stack": { + "type": "integer", + "format": "uint32", + "minimum": 0 + } + }, + "additionalProperties": false, + "required": [ + "stack", + "frames" + ] + } + } +} diff --git a/schemas/cpu-sampling-spec.schema.json b/schemas/cpu-sampling-spec.schema.json index fdeea0c..242c972 100644 --- a/schemas/cpu-sampling-spec.schema.json +++ b/schemas/cpu-sampling-spec.schema.json @@ -14,11 +14,7 @@ "minimum": 0 }, "max_groups": { - "type": "integer", - "format": "uint64", - "minimum": 0 - }, - "max_samples": { + "description": "Stack groups and hotspots listed; every sample is counted.", "type": "integer", "format": "uint64", "minimum": 0 @@ -62,7 +58,6 @@ "frequency_hz", "duration_ms", "timeout_ms", - "max_samples", "max_groups", "stack_depth", "max_threads" diff --git a/schemas/triage-result.schema.json b/schemas/triage-result.schema.json index 127c003..b7f1b20 100644 --- a/schemas/triage-result.schema.json +++ b/schemas/triage-result.schema.json @@ -326,6 +326,11 @@ "null" ] }, + "exclusive_estimated_ns": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "exclusive_proportion": { "type": "number", "format": "double" @@ -338,6 +343,12 @@ "frame": { "$ref": "#/$defs/CpuStackFrame" }, + "inclusive_estimated_ns": { + "description": "On-CPU time with this frame on the stack, and as the leaf.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "inclusive_proportion": { "type": "number", "format": "double" @@ -360,7 +371,9 @@ "inclusive_samples", "exclusive_samples", "inclusive_proportion", - "exclusive_proportion" + "exclusive_proportion", + "inclusive_estimated_ns", + "exclusive_estimated_ns" ] }, "CpuStackFrame": { diff --git a/skills/xprobe-perf-profiling/SKILL.md b/skills/xprobe-perf-profiling/SKILL.md index 2f1dbc9..8f9c6f6 100644 --- a/skills/xprobe-perf-profiling/SKILL.md +++ b/skills/xprobe-perf-profiling/SKILL.md @@ -15,7 +15,7 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA | List CUDA PIDs under a root | `xprobe discover --pid "$ROOT"` | Uses NVML; inside containers (`NVML_PID_NAMESPACE_MISMATCH`), scan `ps` or `/proc/*/maps` (`libcuda`) | | Check selectors or injection state | `xprobe validate --pid "$PID" --from A --to B --match exact` | Read-only; reports `requirements.agent_activation` (`already_loaded` vs `injection_required`) | | Python stacks, GIL & native waits | `xprobe measure --pid "$PID" --python-sample --duration-ms 2000` | CPython 3.9–3.14; ptrace only (no eBPF/perf/injection); sweeps of every thread slow down on processes with many threads | -| Native CPU callchain hotspots | `xprobe measure --pid "$PID" --cpu-sample --duration-ms 2000 --frequency-hz 999 --max-groups 2048` | Needs perf events; default 99 Hz / 256 groups is too sparse for short windows | +| Native CPU callchain hotspots | `xprobe measure --pid "$PID" --cpu-sample --duration-ms 2000 --events-out cpu.jsonl` | Needs perf events; 999 Hz; every sample timestamped in the JSONL | | Syscall count & duration totals | `xprobe measure --pid "$PID" --syscall-aggregate --duration-ms 2000` | Needs eBPF | | GPU kernel totals | `xprobe measure --pid "$PID" --from cuda:kernel_start --to cuda:kernel_end --match exact --aggregate --duration-ms 2000` | Aggregates **one** activity kind per run | | GPU memcpy totals (pageable vs pinned) | `xprobe measure --pid "$PID" --from cuda:memcpy_start --to cuda:memcpy_end --match exact --aggregate --duration-ms 2000` | Groups by `src_memory`/`dst_memory` (`pageable` vs `pinned`), which every copy event also carries; use `cuda:memset_*` for memset | @@ -28,7 +28,7 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA ## 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, vertical slices (`--slice-gap`, `--slice-outlier`, `--around`, `--python-samples`), and multi-rank comparison (`scripts/analyze_trace.py rank0.jsonl rank1.jsonl ...`). +- **Standard GPU analysis**: run `scripts/analyze_trace.py trace.jsonl` for per-GPU busy/idle/compute/comm budgets, top idle and stream gaps, vertical slices (`--slice-gap`, `--slice-outlier`, `--around`, `--python-samples`, `--cpu-samples`), and multi-rank comparison (`scripts/analyze_trace.py rank0.jsonl rank1.jsonl ...`). - **One-off scripts & RSI loops**: read [data-format.md](references/data-format.md) for stdout keys, artifact paths, JSONL shapes, `analyze_trace.py` output fields, Python time-conversion formulas, API-to-Python-caller joins, cross-process alignment, and quality codes. - **Selectors, policies, tuning & graphs**: read [selectors.md](references/selectors.md) and `examples/` (`request-path-graph.json`, `kernel-duration.json`). @@ -41,6 +41,6 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA - **Cross-process & clocks**: run concurrent `measure --pid` captures across processes or ranks. On one host, `host_monotonic`, `cupti_normalized_to_host_monotonic`, and `--python-sample` share `CLOCK_MONOTONIC`. Never mix PIDs in `measure --input` or subtract raw `cupti` timestamps from host timestamps. - **Check completeness before trusting numbers**: `status == "completed"` can still hide truncation or drops. Verify: - `warnings` is empty (or explicitly understood) - - `--cpu-sample`: `collection.lost_samples == 0` (no `CPU_GROUP_CAPACITY_REACHED`) + - `--cpu-sample`: `collection.lost_samples == 0` and `collection.completeness == "complete"` - Exact / graph / trigger: `dropped == 0`, check `quality.verdict`, and require `all_gpu_activity == true` when reporting GPU idle time - `--aggregate`: `quality.verdict` and `quality.issues` (`NAME_TRUNCATED` merges kernels that share a cut name) diff --git a/skills/xprobe-perf-profiling/references/data-format.md b/skills/xprobe-perf-profiling/references/data-format.md index 0cbbb8a..abf2935 100644 --- a/skills/xprobe-perf-profiling/references/data-format.md +++ b/skills/xprobe-perf-profiling/references/data-format.md @@ -11,7 +11,7 @@ Every `xprobe` command prints one JSON document to stdout when stdout is not a t | `--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[]`, `quality`, `collection.{completeness, cuda_devices, dropped_activities, table_utilization}` | -| `--cpu-sample` | none (inline only) | `inventory.{hotspots, stack_groups}`, `symbolization.python_status`, `collection` | +| `--cpu-sample` | `artifact.path` (CPU sample JSONL) | `inventory.{hotspots, stack_groups}`, `symbolization.python_status`, `collection` | | `--syscall-aggregate` | none (inline only) | `inventory.groups[]`, `collection` | | `--triage` | per-source paths in `sources[]` (`artifact.path`) | `window_ms`, `sources[]`, `not_covered`, `threads`, `cgroup`, `cpu_hotspots`, `python_hotspots`, `gil_released_proportion`, `syscalls`, `gpu_activity`, `gpu_devices`, `cuda_devices`, `findings` | @@ -63,6 +63,18 @@ Written beside every Event JSONL (`schema_version: "1.0"`). Keep it beside the t - `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. +## CPU sample JSONL (`--cpu-sample`) + +At `result["artifact"]["path"]`. A stack line comes before the first sample that uses it; samples are in time order: + +```json +{"stack":0,"frames":[{"address":4198400,"module_path":"/srv/app","build_id":"ab12","file_offset":4096,"symbol":"hot_loop","symbol_offset":16,"language":"native","source_path":null,"line":null}]} +{"timestamp_ns":1001234,"pid":4242,"tid":4250,"cpu_ns":1001001,"stack":0} +``` + +- `timestamp_ns` is `CLOCK_MONOTONIC`; `cpu_ns` is the on-CPU time the sample stands for (its perf period). +- `frames[0]` is the innermost frame. Build `stacks = {r["stack"]: r["frames"] for r in lines if "frames" in r}` first. + ## Python sample JSONL (`--python-sample`) One line per sample at `result["artifact"]["path"]`: @@ -82,7 +94,7 @@ One line per sample at `result["artifact"]["path"]`: - **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`**: an aggregate that returns counted every activity, so `quality.verdict` is `good`; `NAME_TRUNCATED` (info) means kernels sharing a name cut at 127 bytes share a group. `collection.{completeness, dropped_activities, table_utilization, cuda_devices}` give the counts. `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, file_offset, build_id}`, `exclusive_proportion`, `inclusive_proportion`, `entry_selector_hint`, `return_selector_hint`), `inventory.stack_groups[]`, `symbolization.python_status` (`inactive`/`unsupported` means native frames only — use `--python-sample` for CPython 3.9–3.14), `collection.{completeness, lost_samples, truncated_stacks, threads_attached, threads_observed, table_utilization}`. Check `warnings` for `CPU_GROUP_CAPACITY_REACHED`. +- **CPU `--cpu-sample`**: `inventory.hotspots[]` (`frame.{symbol, module_path, language, file_offset, build_id}`, `exclusive_proportion`, `inclusive_proportion`, `entry_selector_hint`, `return_selector_hint`), `inventory.stack_groups[]`, `symbolization.python_status` (`inactive`/`unsupported` means native frames only — use `--python-sample` for CPython 3.9–3.14), `collection.{completeness, lost_samples, truncated_stacks, threads_attached, threads_observed, groups, cpu_time_ns, elapsed_ns}`. Groups and hotspots give `estimated_ns` / `inclusive_estimated_ns` / `exclusive_estimated_ns` as on-CPU time. - **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`. - **Triage `--triage`**: `window_ms` is the actual wall span (often longer than `--duration-ms` because of attach/setup), `threads` (`window_ns`, `top_threads[]`), `cgroup`, `cpu_hotspots[]`, `python_hotspots[]`, `gil_released_proportion`, `syscalls[]`, `gpu_activity[]`, `gpu_devices[]`, `cuda_devices[]`, `sources[]` (with per-source `status` and `artifact.path`), `not_covered[]`, and `findings[]` (static heuristic hints — verify against raw inventories). @@ -101,8 +113,8 @@ Use it instead of rewriting interval-union math by hand: # 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 across the largest GPU idle gap (±2 ms) + concurrent Python stacks -scripts/analyze_trace.py trace.jsonl --slice-gap 1 --window-ms 2 --python-samples py.jsonl +# Vertical slice across the largest GPU idle gap (±2 ms) + concurrent Python and on-CPU stacks +scripts/analyze_trace.py trace.jsonl --slice-gap 1 --window-ms 2 --python-samples py.jsonl --cpu-samples cpu.jsonl # Slice around slowest measured pair or explicit CLOCK_MONOTONIC timestamps scripts/analyze_trace.py trace.jsonl --measurement res.json --slice-outlier 1 @@ -116,19 +128,19 @@ Concrete single-trace output shape: ```json { - "analysis_version": "1.5", + "analysis_version": "1.6", "capture": {"manifest": true, "all_gpu_activity": true, "window": {"start_ns": 1000, "end_ns": 3000}, "wall_clock_drift_ns": 0}, "devices": [{"pid": 4242, "device_id": 0, "uuid": "GPU-...", "span": {"start_ns": 1000, "end_ns": 3000, "ns": 2000}, "busy_ns": 1500, "idle_ns": 500, "compute_ns": 1200, "communication_ns": 300, "communication_only_ns": 200, "transfer_ns": 100, "top_idle_gaps": [{"start_ns": 1400, "end_ns": 1900, "gap_ns": 500}], "top_compute_gaps": []}], "gpu": {"summed_activity_ns": 1600, "top_idle_gaps": [{"pid": 4242, "device_id": 0, "clock_domain": "cupti_normalized_to_host_monotonic", "start_ns": 1400, "end_ns": 1900, "gap_ns": 500, "after": "gemm", "before": "attn"}]}, "kernels": {"duration": {"count": 10, "total_ns": 1200, "min_ns": 80, "p50_ns": 120, "p95_ns": 180, "max_ns": 200}, "busy_union_ns": 1200, "overlap_factor": 1.0, "by_name": [{"name": "gemm", "selector_hint": {}, "launch_variants": []}]}, "memcpy": {"duration": {}, "total_bytes": 0, "bandwidth_gbps": null, "by_kind": []}, "streams": [{"stream_id": 7, "gaps": {}, "top_gaps": []}], - "slice": {"start_ns": 1400, "end_ns": 1900, "events": [], "total_events": 12, "truncated": false, "python": {"samples": 40, "gil_samples": 30, "gil_stacks": [], "threads": {}, "native_waits": []}}, + "slice": {"start_ns": 1400, "end_ns": 1900, "events": [], "total_events": 12, "truncated": false, "python": {"samples": 40, "gil_samples": 30, "gil_stacks": [], "threads": {}, "native_waits": []}, "cpu": {"samples": 12, "cpu_ns": 12012012, "stacks": [{"frames": ["spin (app)"], "samples": 12, "cpu_ns": 12012012, "proportion": 1.0}], "threads": {"4250": 12012012}}}, "warnings": [] } ``` -- `--slice-gap N` covers the **entire** N-th idle gap `[gap.start_ns - window_ms, gap.end_ns + window_ms]`; Event JSONL is capped by `--max-slice-events` (default 200), while `--python-samples` summarizes every sample inside that full range. To inspect one specific thread (`tid`) over a long gap, filter `py.jsonl` directly in Python. +- `--slice-gap N` covers the **entire** N-th idle gap `[gap.start_ns - window_ms, gap.end_ns + window_ms]`; Event JSONL is capped by `--max-slice-events` (default 200), while `--python-samples` and `--cpu-samples` summarize every sample inside that full range (CPU stacks ranked by `cpu_ns`). To inspect one specific thread (`tid`) over a long gap, filter `py.jsonl` directly in Python. - Multi-trace mode adds `devices[].shares` (`busy`, `idle`, `compute`, `communication_only`) and `spread` (`compute_share`, `most_compute`, `most_communication_only`, `most_idle`). - `--comm-kernel` defaults to `nccl` (unanchored, matching mangled names such as `_Z40ncclDevKernel_AllReduce...`); extend it for custom collectives (vLLM, TRT-LLM, FlashInfer, NVSHMEM/DeepEP). diff --git a/skills/xprobe-perf-profiling/references/selectors.md b/skills/xprobe-perf-profiling/references/selectors.md index 587a0e9..1d2bc67 100644 --- a/skills/xprobe-perf-profiling/references/selectors.md +++ b/skills/xprobe-perf-profiling/references/selectors.md @@ -78,7 +78,7 @@ Graph rules: ## Parameter tuning & overhead limits - **`--python-sample` rates**: the GIL holder is sampled at 999 Hz. All-thread sweeps run up to 100 times a second and slow down to stay within 6,400 stack reads a second, so 640 threads sweep about 10 times a second; `collection.threads_hz_achieved` shows the rate reached. Set `--python-threads-hz` for a fixed rate, or `0` to sample only the GIL holder. Every sample is kept. -- **`--cpu-sample` frequency & groups**: defaults (`--frequency-hz 99`, `--max-groups 256`) produce very few samples on 1–2 s captures and saturate groups quickly on deep stacks (`CPU_GROUP_CAPACITY_REACHED`). Use `--frequency-hz 999 --max-groups 2048` (and raise `--max-samples` if needed) on busy native processes. If `symbolization.python_status` is `unsupported` (CPython <3.12) or `inactive` (3.12+ without `-X perf`), use `--python-sample` instead. +- **`--cpu-sample` rate & lists**: samples each thread's on-CPU time at 999 Hz and keeps every sample; `--max-groups` only sets how many groups and hotspots are listed. If `symbolization.python_status` is `unsupported` (CPython <3.12) or `inactive` (3.12+ without `-X perf`), use `--python-sample` instead. - **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. Size `--max-events` from an `--aggregate` count (`~2 * activities * duration_s` plus headroom), keep `--duration-ms` short, or bound hot paths with `--samples`. 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 index be2896e..e5ca7d7 100755 --- a/skills/xprobe-perf-profiling/scripts/analyze_trace.py +++ b/skills/xprobe-perf-profiling/scripts/analyze_trace.py @@ -646,6 +646,64 @@ def load_python_samples(path: pathlib.Path) -> list[dict]: return samples +def load_cpu_samples(path: pathlib.Path) -> tuple[dict, list[dict]]: + """Stacks and samples written by `measure --cpu-sample`.""" + stacks, samples = {}, [] + for number, line in enumerate(path.read_text().splitlines(), 1): + if not line.strip(): + continue + record = json.loads(line) + if isinstance(record, dict) and "frames" in record and "stack" in record: + stacks[record["stack"]] = record["frames"] + elif isinstance(record, dict) and "timestamp_ns" in record and "cpu_ns" in record: + samples.append(record) + else: + raise ValueError(f"{path}:{number}: not a CPU sample record") + missing = {sample["stack"] for sample in samples} - stacks.keys() + if missing: + raise ValueError(f"{path}: samples name stacks never written: {sorted(missing)[:5]}") + return stacks, samples + + +def native_label(frame: dict) -> str: + module = (frame.get("module_path") or "").rsplit("/", 1)[-1] + if frame.get("symbol"): + return f"{frame['symbol']} ({module})" if module else frame["symbol"] + if module and frame.get("file_offset") is not None: + return f"{module}+0x{frame['file_offset']:x}" + return f"0x{frame['address']:x}" + + +def cpu_slice( + stacks: dict, samples: list[dict], start_ns: int, end_ns: int, limit: int = 10 +) -> dict: + """On-CPU stacks sampled inside [start_ns, end_ns], by CPU time.""" + inside = [sample for sample in samples if start_ns <= sample["timestamp_ns"] <= end_ns] + total = sum(sample["cpu_ns"] for sample in inside) + by_stack = collections.Counter() + counts = collections.Counter() + threads = collections.Counter() + for sample in inside: + by_stack[sample["stack"]] += sample["cpu_ns"] + counts[sample["stack"]] += 1 + threads[str(sample["tid"])] += sample["cpu_ns"] + ranked = sorted(by_stack.items(), key=lambda item: (-item[1], item[0]))[:limit] + return { + "samples": len(inside), + "cpu_ns": total, + "stacks": [ + { + "frames": [native_label(frame) for frame in stacks[stack]], + "samples": counts[stack], + "cpu_ns": cpu_ns, + "proportion": round(cpu_ns / total, 6) if total else 0.0, + } + for stack, cpu_ns in ranked + ], + "threads": dict(sorted(threads.items())), + } + + def frame_label(frame: dict) -> str: return f"{frame['function']} ({frame['file']}:{frame['first_line']})" @@ -850,6 +908,7 @@ def analyze( window_ns: int = 0, max_slice_events: int = 200, python_samples: pathlib.Path | None = None, + cpu_samples: pathlib.Path | None = None, ) -> dict: events = load_events(path) manifest = load_manifest(path) @@ -898,9 +957,8 @@ def analyze( "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 + if python_samples is not None or cpu_samples is not None: + # Sampled stacks 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. @@ -916,24 +974,39 @@ def analyze( 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) + aligned = bool(domains) and domains <= HOST_CLOCKS + for name, label, path_arg in ( + ("python", "Python", python_samples), + ("cpu", "CPU", cpu_samples), + ): + if path_arg is None: + continue + window_report[name] = None + if not aligned: + warnings.append( + { + "code": f"{name.upper()}_CLOCK_UNALIGNED", + "message": f"the slice's timestamps are not all CLOCK_MONOTONIC; {label} samples were not placed in it", + } + ) + continue + if name == "python": + samples = load_python_samples(path_arg) + else: + stacks, samples = load_cpu_samples(path_arg) 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", + "code": f"{name.upper()}_SAMPLES_OTHER_PROCESS", + "message": f"{len(samples) - len(matching)} {label} samples come from processes other than the slice's and were left out", } ) - window_report["python"] = python_slice(matching, start_ns, end_ns) + window_report[name] = ( + python_slice(matching, start_ns, end_ns) + if name == "python" + else cpu_slice(stacks, matching, start_ns, end_ns) + ) if outlier_report and outlier_report["source"] == ["rank_exemplars"]: warnings.append( { @@ -950,7 +1023,7 @@ def analyze( } ) report = { - "analysis_version": "1.5", + "analysis_version": "1.6", "input": str(path), "events": { "total": len(events), @@ -1077,7 +1150,7 @@ def extreme(key, pick): "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", + "analysis_version": "1.6", "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, @@ -1137,22 +1210,26 @@ def main() -> None: 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") + parser.add_argument("--cpu-samples", type=pathlib.Path, + help="measure --cpu-sample artifact whose on-CPU 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") + if ( + args.measurement or args.slice_gap or args.slice_outlier or args.around + or args.python_samples or args.cpu_samples + ): + parser.error("--measurement, slices, --python-samples, and --cpu-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") + for flag, value in (("--python-samples", args.python_samples), ("--cpu-samples", args.cpu_samples)): + if value is not None and not (args.slice_gap or args.slice_outlier or args.around): + parser.error(f"{flag} requires --slice-gap, --slice-outlier, or --around") if args.window_ms < 0: parser.error("--window-ms must not be negative") window = None @@ -1172,6 +1249,7 @@ def main() -> None: window_ns=round(args.window_ms * 1_000_000), max_slice_events=args.max_slice_events, python_samples=args.python_samples, + cpu_samples=args.cpu_samples, ) json.dump(report, sys.stdout, indent=2, sort_keys=True) sys.stdout.write("\n") diff --git a/tests/agent-contract/test_contract.py b/tests/agent-contract/test_contract.py index 1aa39e6..8b71932 100755 --- a/tests/agent-contract/test_contract.py +++ b/tests/agent-contract/test_contract.py @@ -179,6 +179,10 @@ def check_documented_flags( "Stdout & artifact paths by mode": ALL_RESULT_SCHEMAS, "Event JSONL (`*.jsonl`)": ["event"], "Capture manifest (`.manifest.json`)": ["capture-manifest"], + "CPU sample JSONL (`--cpu-sample`)": [ + "cpu-sample-record", + "cpu-sample-inventory-result", + ], "Python sample JSONL (`--python-sample`)": [ "python-sample-record", "python-sample-result", @@ -414,8 +418,15 @@ def check_schemas(workspace: pathlib.Path) -> None: for path in schema_paths: schema = json.loads(path.read_text()) assert schema["$schema"] == "https://json-schema.org/draft/2020-12/schema" - assert schema["type"] == "object" - assert schema["additionalProperties"] is False + # A JSONL record with several line shapes lists them in anyOf; each + # shape is a closed object like any other document. + shapes = [ + schema["$defs"][variant["$ref"].removeprefix("#/$defs/")] + for variant in schema.get("anyOf", []) + ] or [schema] + for shape in shapes: + assert shape["type"] == "object", path + assert shape["additionalProperties"] is False, path def check_installation_docs(workspace: pathlib.Path) -> None: diff --git a/tests/agent-contract/test_trace_analysis.py b/tests/agent-contract/test_trace_analysis.py index b376b3b..8b5e567 100755 --- a/tests/agent-contract/test_trace_analysis.py +++ b/tests/agent-contract/test_trace_analysis.py @@ -391,6 +391,26 @@ def check_gaps_outliers_and_slices(script: pathlib.Path) -> None: ) ) + cpu = pathlib.Path(directory) / "cpu-samples.jsonl" + native = lambda symbol: { + "address": 4096, "module_path": "/srv/app", "build_id": None, "file_offset": 16, + "symbol": symbol, "symbol_offset": 0, "language": "native", "source_path": None, "line": None, + } + cpu.write_text( + "".join( + json.dumps(record) + "\n" + for record in [ + {"stack": 0, "frames": [native("spin"), native("main")]}, + {"timestamp_ns": 260, "pid": 1234, "tid": 1, "cpu_ns": 1000, "stack": 0}, + {"stack": 1, "frames": [native("copy")]}, + {"timestamp_ns": 400, "pid": 1234, "tid": 2, "cpu_ns": 3000, "stack": 1}, + {"timestamp_ns": 410, "pid": 1234, "tid": 1, "cpu_ns": 1000, "stack": 0}, + {"timestamp_ns": 600, "pid": 1234, "tid": 1, "cpu_ns": 1000, "stack": 0}, + {"timestamp_ns": 300, "pid": 999, "tid": 9, "cpu_ns": 1000, "stack": 0}, + ] + ) + ) + def run(*arguments: str) -> dict: return json.loads( subprocess.run( @@ -410,7 +430,10 @@ def run(*arguments: str) -> dict: for item in events ) ) - aligned = run("--slice-gap", "1", "--window-ms", "0.00005", "--python-samples", str(python)) + aligned = run( + "--slice-gap", "1", "--window-ms", "0.00005", + "--python-samples", str(python), "--cpu-samples", str(cpu), + ) unsliced_python = subprocess.run( [script, trace, "--python-samples", str(python)], check=False, capture_output=True, text=True ) @@ -460,9 +483,17 @@ def run(*arguments: str) -> dict: assert stacks["native_waits"] == [ {"syscall": "futex", "module": "libc.so.6", "symbol": None, "samples": 1} ] + # On-CPU stacks in the same window, heaviest CPU time first. + on_cpu = aligned["slice"]["cpu"] + assert (on_cpu["samples"], on_cpu["cpu_ns"]) == (3, 5000), on_cpu + assert [(stack["frames"][0], stack["cpu_ns"]) for stack in on_cpu["stacks"]] == [ + ("copy (app)", 3000), + ("spin (app)", 2000), + ], on_cpu + assert on_cpu["threads"] == {"1": 2000, "2": 3000} codes = {item["code"] for item in aligned["warnings"]} assert "PYTHON_CLOCK_UNALIGNED" not in codes - assert "PYTHON_SAMPLES_OTHER_PROCESS" in codes + assert {"PYTHON_SAMPLES_OTHER_PROCESS", "CPU_SAMPLES_OTHER_PROCESS"} <= codes assert unsliced_python.returncode != 0 and "requires --slice-gap" in unsliced_python.stderr diff --git a/xprobe/cli/src/args.rs b/xprobe/cli/src/args.rs index d76f62c..694cf36 100644 --- a/xprobe/cli/src/args.rs +++ b/xprobe/cli/src/args.rs @@ -302,7 +302,7 @@ pub(crate) struct ValidateArgs { )] pub(crate) struct MeasureArgs { /// Versioned measurement JSON for a live target. - #[arg(long, conflicts_with_all = ["input", "pid", "from", "to", "match_policy", "cpu_sample", "syscall_aggregate", "samples", "duration_ms", "timeout_ms", "max_events", "max_samples", "frequency_hz", "stack_depth", "max_threads", "max_inflight", "aggregate", "max_groups", "name"])] + #[arg(long, conflicts_with_all = ["input", "pid", "from", "to", "match_policy", "cpu_sample", "syscall_aggregate", "samples", "duration_ms", "timeout_ms", "max_events", "frequency_hz", "stack_depth", "max_threads", "max_inflight", "aggregate", "max_groups", "name"])] pub(crate) spec: Option, /// Completed CUPTI binary, host capture JSON, or Event JSONL; repeat to merge. @@ -370,26 +370,19 @@ pub(crate) struct MeasureArgs { #[arg(long = "match")] pub(crate) match_policy: Option, - /// Collect a bounded PID-scoped CPU hotspot inventory. - #[arg(long, conflicts_with_all = ["input", "from", "to", "match_policy", "samples", "aggregate", "events_out", "format", "cupti_socket", "agent"])] + /// Sample PID-scoped CPU callchains; writes every timestamped sample to + /// --events-out (JSONL) and lists the heaviest stacks and hotspots. + #[arg(long, conflicts_with_all = ["input", "from", "to", "match_policy", "samples", "aggregate", "format", "cupti_socket", "agent"])] pub(crate) cpu_sample: bool, /// Target CPU sampling frequency in hertz. #[arg( long, requires = "cpu_sample", - default_value_if("cpu_sample", "true", "99") + default_value_if("cpu_sample", "true", "999") )] pub(crate) frequency_hz: Option, - /// Bound all observed CPU sample records. - #[arg( - long, - requires = "cpu_sample", - default_value_if("cpu_sample", "true", "10000") - )] - pub(crate) max_samples: Option, - /// Bound user-space callchain depth. #[arg( long, diff --git a/xprobe/cli/src/inventory.rs b/xprobe/cli/src/inventory.rs index 7fec2e6..0a20502 100644 --- a/xprobe/cli/src/inventory.rs +++ b/xprobe/cli/src/inventory.rs @@ -30,10 +30,10 @@ pub(crate) fn run_direct_cpu_sampling( frequency_hz: u64, duration_ms: u64, timeout_ms: u64, - max_samples: u64, max_groups: u64, stack_depth: u32, max_threads: u32, + events_out: Option<&Path>, json: bool, ) -> ExitCode { let report = match inspect::run(pid) { @@ -50,28 +50,31 @@ pub(crate) fn run_direct_cpu_sampling( frequency_hz, duration_ms, timeout_ms, - max_samples, max_groups, stack_depth, max_threads, }; - run_cpu_sampling_spec(&spec, Some(report), json) + run_cpu_sampling_spec(&spec, Some(report), events_out, json) } pub(crate) fn run_cpu_sampling_spec( spec: &CpuSamplingSpec, inspected: Option, + events_out: Option<&Path>, json: bool, ) -> ExitCode { - match cpu_inventory(spec, inspected) { + match cpu_inventory(spec, inspected, events_out) { Ok(result) => emit_cpu_inventory(&result, json), Err(error) => emit_command_failure(error, json), } } +/// Sample, analyze, and write every sample to `events_out` (or a private +/// file) as JSON lines. pub(crate) fn cpu_inventory( spec: &CpuSamplingSpec, inspected: Option, + events_out: Option<&Path>, ) -> Result { let report = match inspected.map_or_else(|| inspect::run(spec.target.pid), Ok) { Ok(report) => report, @@ -125,13 +128,17 @@ pub(crate) fn cpu_inventory( } let capture = CpuCaptureData { samples: capture - .stacks + .samples .into_iter() - .map(|stack| RawCpuSample { - thread_id: stack.thread_id, - addresses: stack.addresses, + .map(|sample| RawCpuSample { + thread_id: sample.thread_id, + timestamp_ns: sample.timestamp_ns, + period_ns: sample.period_ns, + stack: sample.stack, }) .collect(), + stacks: capture.stacks, + elapsed: capture.elapsed, observed_samples: capture.observed_samples, lost_samples: capture.lost_samples, truncated_stacks: capture.truncated_stacks, @@ -139,16 +146,15 @@ pub(crate) fn cpu_inventory( threads_observed: capture.threads_observed, threads_attached: capture.threads_attached, skipped_threads: capture.skipped_threads, - capacity_reached: capture.capacity_reached, python_status: validation.python_status, }; - let result = match cpu_sampling_analysis::analyze( + let analysis = match cpu_sampling_analysis::analyze( &report, spec, format!("xp_cpu_{}", std::process::id()), &capture, ) { - Ok(result) => result, + Ok(analysis) => analysis, Err(error) => { return Err(CommandFailure::new( error.code(), @@ -157,32 +163,53 @@ pub(crate) fn cpu_inventory( )); } }; + let mut result = analysis.result; + result.artifact = Some(write_cpu_samples( + &capture, + &analysis.frames, + spec.target.pid, + events_out, + )?); Ok(result) } +/// Write every CPU sample to `events_out`, or a private file, as JSON lines. +fn write_cpu_samples( + capture: &CpuCaptureData, + frames: &[Vec], + pid: u32, + events_out: Option<&Path>, +) -> Result { + let path = match events_out { + Some(path) => path.to_path_buf(), + None => crate::private_artifact_dir()?.join("cpu-samples.jsonl"), + }; + let lines = crate::dev::write_export_with(&path, |writer| { + cpu_sampling_analysis::write_records(capture, frames, pid, writer) + }) + .map_err(|error| CommandFailure::new(ErrorCode::TraceExportFailed, error, false))?; + Ok(xprobe_protocol::EvidenceArtifact { + path: path.display().to_string(), + format: xprobe_protocol::ExportFormat::Jsonl, + events: lines, + }) +} + pub(crate) fn cpu_collector_request( spec: &CpuSamplingSpec, ) -> Result { if spec.frequency_hz == 0 || spec.duration_ms == 0 - || spec.max_samples == 0 || spec.max_groups == 0 || spec.stack_depth == 0 || spec.max_threads == 0 { return Err(CommandFailure::new( ErrorCode::SessionLimitExceeded, - "CPU sampling frequency, duration, samples, groups, stack depth, and threads must be positive", + "CPU sampling frequency, duration, groups, stack depth, and threads must be positive", true, )); } - let max_samples = usize::try_from(spec.max_samples).map_err(|error| { - CommandFailure::new( - ErrorCode::SessionLimitExceeded, - format!("CPU max_samples exceed this platform: {error}"), - true, - ) - })?; let max_threads = usize::try_from(spec.max_threads).map_err(|error| { CommandFailure::new( ErrorCode::SessionLimitExceeded, @@ -205,7 +232,6 @@ pub(crate) fn cpu_collector_request( frequency_hz: spec.frequency_hz, duration: Duration::from_millis(spec.duration_ms), timeout: Duration::from_millis(spec.timeout_ms), - max_samples, max_threads, stack_depth, }) @@ -484,7 +510,7 @@ pub(crate) fn run_cpu_sampling_file_spec( ); } }; - run_cpu_sampling_spec(&spec, None, json) + run_cpu_sampling_spec(&spec, None, None, json) } pub(crate) fn run_syscall_aggregate_file_spec( diff --git a/xprobe/cli/src/main.rs b/xprobe/cli/src/main.rs index e42fc8c..80e4011 100644 --- a/xprobe/cli/src/main.rs +++ b/xprobe/cli/src/main.rs @@ -96,7 +96,6 @@ fn run_measure(args: MeasureArgs) -> ExitCode { python_hz, python_threads_hz, frequency_hz, - max_samples, stack_depth, max_threads, max_inflight, @@ -161,11 +160,11 @@ fn run_measure(args: MeasureArgs) -> ExitCode { frequency_hz.expect("clap supplies CPU sampling frequency"), duration_ms, timeout_ms, - max_samples.expect("clap supplies CPU sample capacity"), u64::try_from(max_groups.expect("clap supplies CPU group capacity")) .unwrap_or(u64::MAX), stack_depth.expect("clap supplies CPU stack depth"), max_threads.expect("clap supplies CPU thread capacity"), + events_out.as_deref(), json, ); } diff --git a/xprobe/cli/src/triage.rs b/xprobe/cli/src/triage.rs index ad0fe86..2a5e445 100644 --- a/xprobe/cli/src/triage.rs +++ b/xprobe/cli/src/triage.rs @@ -34,12 +34,10 @@ use crate::{ /// Entries kept inline per summary list; full results go to artifacts. const TOP: usize = 5; -const CPU_FREQUENCY_HZ: u64 = 99; +const CPU_FREQUENCY_HZ: u64 = 999; const CPU_MAX_GROUPS: u64 = 256; const CPU_STACK_DEPTH: u32 = 64; const CPU_MAX_THREADS: u32 = 1024; -/// Concurrently running threads the CPU sample capacity is sized for. -const CPU_SAMPLED_THREAD_BUDGET: u64 = 64; const SYSCALL_MAX_GROUPS: u64 = 256; const SYSCALL_MAX_INFLIGHT: u64 = 1024; const GPU_MAX_GROUPS: usize = 4096; @@ -152,7 +150,13 @@ fn triage(request: &TriageRequest) -> Result { 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 cpu = scope.spawn(|| { + cpu_inventory( + &cpu_spec(&report, request), + Some(report.clone()), + Some(&artifacts.join("cpu-samples.jsonl")), + ) + }); let syscalls = scope .spawn(|| syscall_inventory(&syscall_spec(&report, request), Some(report.clone()))); let gpu_activity = report @@ -457,8 +461,6 @@ fn cpu_spec(report: &ProcessReport, request: &TriageRequest) -> CpuSamplingSpec frequency_hz: CPU_FREQUENCY_HZ, duration_ms: request.duration_ms, timeout_ms: request.timeout_ms, - max_samples: (CPU_FREQUENCY_HZ * request.duration_ms / 1000 + 1) - * CPU_SAMPLED_THREAD_BUDGET, max_groups: CPU_MAX_GROUPS, stack_depth: CPU_STACK_DEPTH, max_threads: CPU_MAX_THREADS, diff --git a/xprobe/collector/src/cpu_sampling.rs b/xprobe/collector/src/cpu_sampling.rs index d3fa6c0..e84dea0 100644 --- a/xprobe/collector/src/cpu_sampling.rs +++ b/xprobe/collector/src/cpu_sampling.rs @@ -1,11 +1,14 @@ use std::{ + collections::HashMap, error::Error, fmt, io, thread, time::{Duration, Instant}, }; use perf_event_open::{ - config::{CallChain as CallChainConfig, Cpu, Opts, Priv as ExcludedPriv, Proc, SampleOn}, + config::{ + CallChain as CallChainConfig, Clock, Cpu, Opts, Priv as ExcludedPriv, Proc, SampleOn, + }, count::Counter, event::sw::Software, sample::{ @@ -23,20 +26,27 @@ pub struct CpuSamplingRequest { pub frequency_hz: u64, pub duration: Duration, pub timeout: Duration, - pub max_samples: usize, pub max_threads: usize, pub stack_depth: u16, } -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct RawCpuStack { +/// One sample: its thread, `CLOCK_MONOTONIC` time, perf period (on-CPU +/// nanoseconds it stands for), and index into the distinct stacks. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RawCpuSample { pub thread_id: u32, - pub addresses: Vec, + pub timestamp_ns: u64, + pub period_ns: u64, + pub stack: u32, } +/// Every sample is kept: memory grows by a sample's few dozen bytes plus +/// each distinct stack. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CpuSampleCapture { - pub stacks: Vec, + pub samples: Vec, + /// Distinct user-space callchains, innermost address first. + pub stacks: Vec>, pub observed_samples: u64, pub lost_samples: u64, pub truncated_stacks: u64, @@ -44,10 +54,21 @@ pub struct CpuSampleCapture { pub threads_observed: usize, pub threads_attached: usize, pub skipped_threads: Vec, - pub capacity_reached: bool, pub elapsed: Duration, } +impl CpuSampleCapture { + fn intern(&mut self, ids: &mut HashMap, u32>, addresses: Vec) -> u32 { + if let Some(id) = ids.get(&addresses) { + return *id; + } + let id = u32::try_from(self.stacks.len()).unwrap_or(u32::MAX); + self.stacks.push(addresses.clone()); + ids.insert(addresses, id); + id + } +} + #[derive(Debug)] pub enum CpuSamplingError { InvalidRequest(&'static str), @@ -178,7 +199,8 @@ pub fn collect(request: &CpuSamplingRequest) -> Result Result= deadline { disable_all(&samplers)?; return Err(CpuSamplingError::Timeout); } - drain(&samplers, request, &mut capture); + drain(&samplers, request, &mut capture, &mut stack_ids); let now = Instant::now(); - if now < capture_deadline && capture.observed_samples < request.max_samples as u64 { + if now < capture_deadline { thread::sleep(DRAIN_INTERVAL.min(capture_deadline.duration_since(now))); } } disable_all(&samplers)?; - drain(&samplers, request, &mut capture); - capture.capacity_reached = capture.observed_samples >= request.max_samples as u64; + drain(&samplers, request, &mut capture, &mut stack_ids); capture.elapsed = capture_started.elapsed(); Ok(capture) } @@ -231,11 +251,6 @@ fn validate_request(request: &CpuSamplingRequest) -> Result<(), CpuSamplingError "timeout must be at least the capture duration", )); } - if request.max_samples == 0 { - return Err(CpuSamplingError::InvalidRequest( - "max_samples must be positive", - )); - } if request.max_threads == 0 { return Err(CpuSamplingError::InvalidRequest( "max_threads must be positive", @@ -260,8 +275,12 @@ fn sampling_options(request: &CpuSamplingRequest) -> Opts { idle: true, user: false, }, + // Sample times on CLOCK_MONOTONIC line up with GPU and Python records. + timer: Some(Clock::Monotonic), ..Opts::default() }; + opts.record_id_format.time = true; + opts.sample_format.period = true; opts.sample_format.code_addr = true; opts.sample_format.call_chain = Some(CallChainConfig { exclude_user: false, @@ -314,26 +333,30 @@ fn disable_subset(samplers: &[ThreadSampler]) -> Vec { .collect() } -fn drain(samplers: &[ThreadSampler], request: &CpuSamplingRequest, capture: &mut CpuSampleCapture) { +fn drain( + samplers: &[ThreadSampler], + request: &CpuSamplingRequest, + capture: &mut CpuSampleCapture, + stack_ids: &mut HashMap, u32>, +) { for sampler in samplers { for (_, record) in sampler.sampler.iter() { match record { - Record::Sample(sample) if capture.observed_samples < request.max_samples as u64 => { + Record::Sample(sample) => { capture.observed_samples += 1; if let Some((addresses, truncated)) = user_addresses(&sample, request.stack_depth) { capture.truncated_stacks += u64::from(truncated); - capture.stacks.push(RawCpuStack { + let stack = capture.intern(stack_ids, addresses); + capture.samples.push(RawCpuSample { thread_id: sampler.thread_id, - addresses, + timestamp_ns: sample.record_id.time.unwrap_or(0), + period_ns: sample.period.unwrap_or(0), + stack, }); } } - Record::Sample(_) => { - capture.capacity_reached = true; - return; - } Record::LostRecords(lost) => { capture.lost_samples = capture.lost_samples.saturating_add(lost.lost_records); } @@ -345,10 +368,6 @@ fn drain(samplers: &[ThreadSampler], request: &CpuSamplingRequest, capture: &mut } _ => {} } - if capture.observed_samples >= request.max_samples as u64 { - capture.capacity_reached = true; - return; - } } } } @@ -386,7 +405,6 @@ mod tests { frequency_hz: 99, duration: Duration::from_millis(10), timeout: Duration::from_millis(20), - max_samples: 100, max_threads: 8, stack_depth: 64, } @@ -395,7 +413,7 @@ mod tests { #[test] fn rejects_zero_resource_bounds() { let mut value = request(); - value.max_samples = 0; + value.max_threads = 0; assert!(matches!( validate_request(&value), Err(CpuSamplingError::InvalidRequest(_)) diff --git a/xprobe/core/src/cpu_sampling_analysis.rs b/xprobe/core/src/cpu_sampling_analysis.rs index 32354c2..33ae6f5 100644 --- a/xprobe/core/src/cpu_sampling_analysis.rs +++ b/xprobe/core/src/cpu_sampling_analysis.rs @@ -1,32 +1,41 @@ use std::{ collections::{BTreeMap, BTreeSet}, error::Error, - fmt, fs, io, + fmt, fs, + io::{self, Write}, path::{Path, PathBuf}, + time::Duration, }; use cpp_demangle::{DemangleOptions, Symbol as CppSymbol}; use object::{Object, ObjectSegment, ObjectSymbol, SymbolKind}; use xprobe_protocol::{ CpuCaptureCompleteness, CpuFrameLanguage, CpuHotspot, CpuSampleCollectionSummary, - CpuSampleEvent, CpuSampleInventory, CpuSampleInventoryResult, CpuSamplingSpec, CpuStackFrame, - CpuStackGroup, CpuSymbolizationSummary, ErrorCode, ProcessReport, PythonSymbolizationStatus, - SchemaVersion, SessionStatus, Warning, + CpuSampleEvent, CpuSampleInventory, CpuSampleInventoryResult, CpuSampleLine, CpuSampleRecord, + CpuSamplingSpec, CpuStackFrame, CpuStackGroup, CpuStackRecord, CpuSymbolizationSummary, + ErrorCode, ProcessReport, PythonSymbolizationStatus, SchemaVersion, SessionStatus, Warning, }; use crate::inspect::{self, InspectError}; const MAX_PERF_MAP_BYTES: u64 = 16 * 1024 * 1024; -#[derive(Debug, Clone, PartialEq, Eq)] +/// One sample: its thread, `CLOCK_MONOTONIC` time, perf period (on-CPU +/// nanoseconds it stands for), and index into [`CpuCaptureData::stacks`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct RawCpuSample { pub thread_id: u32, - pub addresses: Vec, + pub timestamp_ns: u64, + pub period_ns: u64, + pub stack: u32, } #[derive(Debug, Clone)] pub struct CpuCaptureData { pub samples: Vec, + /// Distinct user-space callchains, innermost address first. + pub stacks: Vec>, + pub elapsed: Duration, pub observed_samples: u64, pub lost_samples: u64, pub truncated_stacks: u64, @@ -34,10 +43,23 @@ pub struct CpuCaptureData { pub threads_observed: usize, pub threads_attached: usize, pub skipped_threads: Vec, - pub capacity_reached: bool, pub python_status: PythonSymbolizationStatus, } +/// An analyzed capture and the symbolized frames of each distinct stack, +/// for [`write_records`]. +pub struct CpuAnalysis { + pub result: CpuSampleInventoryResult, + pub frames: Vec>, +} + +/// One distinct stack: its samples and their summed perf periods. +struct StackTotal { + stack: u32, + samples: u64, + period_ns: u64, +} + #[derive(Debug)] pub enum CpuAnalysisError { Inspect(InspectError), @@ -201,43 +223,48 @@ pub fn analyze( spec: &CpuSamplingSpec, session_id: String, capture: &CpuCaptureData, -) -> Result { +) -> Result { inspect::verify_target(&report.target)?; - let (raw_groups, group_capacity_reached) = - aggregate_raw_stacks(&capture.samples, spec.max_groups); - let sampled = raw_groups + let totals = stack_totals(capture); + let sampled = capture + .stacks .iter() - .flat_map(|(addresses, _)| addresses.iter().copied()) + .flat_map(|addresses| addresses.iter().copied()) .collect::>(); let mut symbolizer = Symbolizer::load(report, capture.python_status, &sampled)?; - let grouped_samples = raw_groups.iter().map(|(_, count)| count).sum::(); - let sample_denominator = capture.observed_samples.max(1); - let stack_groups = raw_groups + let frames = capture + .stacks .iter() - .map(|(addresses, samples)| CpuStackGroup { - frames: addresses + .map(|addresses| { + addresses .iter() .map(|address| symbolizer.symbolize(*address)) - .collect(), - samples: *samples, - proportion: ratio(*samples, sample_denominator), + .collect::>() + }) + .collect::>(); + let sample_denominator = capture.observed_samples.max(1); + let listed = usize::try_from(spec.max_groups).unwrap_or(usize::MAX); + let all_groups = totals + .iter() + .map(|total| CpuStackGroup { + frames: frames[total.stack as usize].clone(), + samples: total.samples, + proportion: ratio(total.samples, sample_denominator), + estimated_ns: total.period_ns, }) .collect::>(); + let symbolization = summarize_symbolization(&all_groups, symbolizer.python_status); + let mut stack_groups = all_groups; + stack_groups.truncate(listed); let hotspots = aggregate_hotspots( - &raw_groups, + &totals, + capture, &symbolizer, sample_denominator, spec.max_groups, ); - let symbolization = summarize_symbolization(&stack_groups, symbolizer.python_status); let mut warnings = std::mem::take(&mut symbolizer.warnings); append_capture_warnings(capture, &mut warnings); - if group_capacity_reached { - warnings.push(warning( - "CPU_GROUP_CAPACITY_REACHED", - "distinct stack groups exceeded max_groups; only the heaviest groups and hotspots were retained", - )); - } if symbolization.python_status == PythonSymbolizationStatus::Active && symbolization.resolved_python_frames == 0 { @@ -248,7 +275,7 @@ pub fn analyze( } inspect::verify_target(&report.target)?; - Ok(CpuSampleInventoryResult { + let result = CpuSampleInventoryResult { schema_version: SchemaVersion::current(), ok: true, session_id, @@ -262,46 +289,125 @@ pub fn analyze( stack_groups, hotspots, }, - collection: CpuSampleCollectionSummary { - completeness: if capture_is_complete(capture, grouped_samples, group_capacity_reached) { - CpuCaptureCompleteness::Complete - } else { - CpuCaptureCompleteness::Incomplete - }, - observed_samples: capture.observed_samples, - grouped_samples, - lost_samples: capture.lost_samples, - sample_capacity: spec.max_samples, - group_capacity: spec.max_groups, - groups: u64::try_from(raw_groups.len()).map_err(|_| CpuAnalysisError::Limit { - name: "group count", - value: u64::MAX, - })?, - table_utilization: ratio( - u64::try_from(raw_groups.len()).unwrap_or(u64::MAX), - spec.max_groups.max(1), - ), - stack_depth: spec.stack_depth, - truncated_stacks: capture.truncated_stacks, - threads_observed: u32::try_from(capture.threads_observed).map_err(|_| { - CpuAnalysisError::Limit { - name: "observed thread count", - value: u64::MAX, - } - })?, - threads_attached: u32::try_from(capture.threads_attached).map_err(|_| { - CpuAnalysisError::Limit { - name: "attached thread count", - value: u64::MAX, - } - })?, - thread_capacity: spec.max_threads, - }, + collection: collection_summary(spec, capture, &totals)?, symbolization, + artifact: None, warnings, + }; + Ok(CpuAnalysis { result, frames }) +} + +fn collection_summary( + spec: &CpuSamplingSpec, + capture: &CpuCaptureData, + totals: &[StackTotal], +) -> Result { + let grouped_samples = totals.iter().map(|total| total.samples).sum::(); + let cpu_time_ns = totals.iter().map(|total| total.period_ns).sum::(); + Ok(CpuSampleCollectionSummary { + completeness: if capture_is_complete(capture, grouped_samples) { + CpuCaptureCompleteness::Complete + } else { + CpuCaptureCompleteness::Incomplete + }, + observed_samples: capture.observed_samples, + grouped_samples, + lost_samples: capture.lost_samples, + groups: u64::try_from(totals.len()).map_err(|_| CpuAnalysisError::Limit { + name: "group count", + value: u64::MAX, + })?, + elapsed_ns: u64::try_from(capture.elapsed.as_nanos()).unwrap_or(u64::MAX), + cpu_time_ns, + stack_depth: spec.stack_depth, + truncated_stacks: capture.truncated_stacks, + threads_observed: u32::try_from(capture.threads_observed).map_err(|_| { + CpuAnalysisError::Limit { + name: "observed thread count", + value: u64::MAX, + } + })?, + threads_attached: u32::try_from(capture.threads_attached).map_err(|_| { + CpuAnalysisError::Limit { + name: "attached thread count", + value: u64::MAX, + } + })?, + thread_capacity: spec.max_threads, }) } +/// Every distinct stack's samples and periods, most samples first. +fn stack_totals(capture: &CpuCaptureData) -> Vec { + let mut totals = BTreeMap::::new(); + for sample in &capture.samples { + let entry = totals.entry(sample.stack).or_default(); + entry.0 = entry.0.saturating_add(1); + entry.1 = entry.1.saturating_add(sample.period_ns); + } + let mut totals = totals + .into_iter() + .map(|(stack, (samples, period_ns))| StackTotal { + stack, + samples, + period_ns, + }) + .collect::>(); + totals.sort_by(|left, right| { + right.samples.cmp(&left.samples).then_with(|| { + capture.stacks[left.stack as usize].cmp(&capture.stacks[right.stack as usize]) + }) + }); + totals +} + +/// Write every sample in time order as JSON lines, each stack on its own +/// line before the first sample that uses it. Returns the lines written. +/// +/// # Errors +/// +/// Returns the writer's I/O error. +pub fn write_records( + capture: &CpuCaptureData, + frames: &[Vec], + pid: u32, + writer: &mut impl Write, +) -> io::Result { + let mut order = (0..capture.samples.len()).collect::>(); + order.sort_by_key(|index| capture.samples[*index].timestamp_ns); + let mut written = BTreeSet::new(); + let mut lines = 0_u64; + let mut line = |record: &CpuSampleRecord, writer: &mut dyn Write| -> io::Result<()> { + serde_json::to_writer(&mut *writer, record).map_err(io::Error::other)?; + writer.write_all(b"\n")?; + lines += 1; + Ok(()) + }; + for index in order { + let sample = capture.samples[index]; + if written.insert(sample.stack) { + line( + &CpuSampleRecord::Stack(CpuStackRecord { + stack: sample.stack, + frames: frames[sample.stack as usize].clone(), + }), + writer, + )?; + } + line( + &CpuSampleRecord::Sample(CpuSampleLine { + timestamp_ns: sample.timestamp_ns, + pid, + tid: sample.thread_id, + cpu_ns: sample.period_ns, + stack: sample.stack, + }), + writer, + )?; + } + Ok(lines) +} + impl Symbolizer { /// Load symbols only for modules and offsets that appear in `sampled`. /// Large runtimes map gigabytes of libraries; reading and demangling every @@ -390,49 +496,45 @@ impl Symbolizer { } } -fn aggregate_raw_stacks(samples: &[RawCpuSample], max_groups: u64) -> (Vec<(Vec, u64)>, bool) { - let mut groups = BTreeMap::, u64>::new(); - for sample in samples { - groups - .entry(sample.addresses.clone()) - .and_modify(|count| *count = count.saturating_add(1)) - .or_insert(1); - } - let mut groups = groups.into_iter().collect::>(); - groups.sort_by(|(left_stack, left_count), (right_stack, right_count)| { - right_count - .cmp(left_count) - .then_with(|| left_stack.cmp(right_stack)) - }); - let capacity = usize::try_from(max_groups).unwrap_or(usize::MAX); - let capacity_reached = groups.len() > capacity; - groups.truncate(capacity); - (groups, capacity_reached) +/// Samples and on-CPU time with an address on the stack (inclusive) and as +/// the leaf (exclusive). +#[derive(Default)] +struct AddressTotal { + inclusive: u64, + exclusive: u64, + inclusive_ns: u64, + exclusive_ns: u64, } +/// Hotspots over every stack; `max_hotspots` of them are listed. fn aggregate_hotspots( - groups: &[(Vec, u64)], + totals: &[StackTotal], + capture: &CpuCaptureData, symbolizer: &Symbolizer, denominator: u64, max_hotspots: u64, ) -> Vec { - let mut counts = BTreeMap::::new(); - for (stack, samples) in groups { + let mut counts = BTreeMap::::new(); + for total in totals { + let stack = &capture.stacks[total.stack as usize]; if let Some(address) = stack.first() { let entry = counts.entry(*address).or_default(); - entry.1 = entry.1.saturating_add(*samples); + entry.exclusive = entry.exclusive.saturating_add(total.samples); + entry.exclusive_ns = entry.exclusive_ns.saturating_add(total.period_ns); } let mut seen = BTreeSet::new(); for address in stack { if seen.insert(*address) { let entry = counts.entry(*address).or_default(); - entry.0 = entry.0.saturating_add(*samples); + entry.inclusive = entry.inclusive.saturating_add(total.samples); + entry.inclusive_ns = entry.inclusive_ns.saturating_add(total.period_ns); } } } let mut hotspots = counts .into_iter() - .map(|(address, (inclusive, exclusive))| { + .map(|(address, total)| { + let (inclusive, exclusive) = (total.inclusive, total.exclusive); let frame = symbolizer.symbolize(address); let (entry_selector_hint, return_selector_hint) = selector_hints(&frame); CpuHotspot { @@ -441,6 +543,8 @@ fn aggregate_hotspots( exclusive_samples: exclusive, inclusive_proportion: ratio(inclusive, denominator), exclusive_proportion: ratio(exclusive, denominator), + inclusive_estimated_ns: total.inclusive_ns, + exclusive_estimated_ns: total.exclusive_ns, entry_selector_hint, return_selector_hint, } @@ -500,12 +604,6 @@ fn summarize_symbolization( } fn append_capture_warnings(capture: &CpuCaptureData, warnings: &mut Vec) { - if capture.capacity_reached { - warnings.push(warning( - "CPU_SAMPLE_CAPACITY_REACHED", - "the configured sample capacity was reached; shorten or lower the sampling frequency before interpreting proportions", - )); - } if capture.lost_samples != 0 { warnings.push(warning( "CPU_SAMPLES_LOST", @@ -532,14 +630,8 @@ fn append_capture_warnings(capture: &CpuCaptureData, warnings: &mut Vec } } -fn capture_is_complete( - capture: &CpuCaptureData, - grouped_samples: u64, - group_capacity_reached: bool, -) -> bool { - !capture.capacity_reached - && !group_capacity_reached - && capture.lost_samples == 0 +fn capture_is_complete(capture: &CpuCaptureData, grouped_samples: u64) -> bool { + capture.lost_samples == 0 && capture.throttled_records == 0 && capture.skipped_threads.is_empty() && grouped_samples == capture.observed_samples @@ -849,19 +941,83 @@ mod tests { assert_eq!(module.symbols[&(offset + 1)].file_offset, offset); } + /// Stacks 0 = [1, 2], 1 = [3, 4], 2 = [5, 6]; each sample one 1 ms + /// period, at the time given. + fn capture(samples: &[(u32, u64)]) -> CpuCaptureData { + CpuCaptureData { + samples: samples + .iter() + .map(|(stack, timestamp_ns)| RawCpuSample { + thread_id: 1, + timestamp_ns: *timestamp_ns, + period_ns: 1_000_000, + stack: *stack, + }) + .collect(), + stacks: vec![vec![1, 2], vec![3, 4], vec![5, 6]], + elapsed: Duration::from_secs(1), + observed_samples: samples.len() as u64, + lost_samples: 0, + truncated_stacks: 0, + throttled_records: 0, + threads_observed: 1, + threads_attached: 1, + skipped_threads: Vec::new(), + python_status: PythonSymbolizationStatus::NotDetected, + } + } + #[test] - fn keeps_the_heaviest_stack_groups_deterministically() { - let samples = vec![ - raw(&[1, 2]), - raw(&[3, 4]), - raw(&[1, 2]), - raw(&[5, 6]), - raw(&[3, 4]), - raw(&[1, 2]), - ]; + fn counts_every_stack_heaviest_first_with_its_cpu_time() { + let capture = capture(&[(0, 1), (1, 2), (0, 3), (2, 4), (1, 5), (0, 6)]); + let totals = stack_totals(&capture) + .into_iter() + .map(|total| (total.stack, total.samples, total.period_ns)) + .collect::>(); assert_eq!( - aggregate_raw_stacks(&samples, 2), - (vec![(vec![1, 2], 3), (vec![3, 4], 2)], true) + totals, + [(0, 3, 3_000_000), (1, 2, 2_000_000), (2, 1, 1_000_000)] + ); + } + + #[test] + fn writes_samples_in_time_order_with_each_stack_first() { + let capture = capture(&[(1, 20), (0, 10), (1, 30)]); + let frames = capture + .stacks + .iter() + .map(|stack| { + stack + .iter() + .map(|address| unresolved_frame(*address)) + .collect() + }) + .collect::>(); + let mut text = Vec::new(); + assert_eq!(write_records(&capture, &frames, 7, &mut text).unwrap(), 5); + let lines = String::from_utf8(text) + .unwrap() + .lines() + .map(|line| serde_json::from_str::(line).unwrap()) + .collect::>(); + let shape = lines + .iter() + .map(|record| match record { + CpuSampleRecord::Stack(stack) => format!("stack {}", stack.stack), + CpuSampleRecord::Sample(sample) => { + format!("sample {} at {}", sample.stack, sample.timestamp_ns) + } + }) + .collect::>(); + assert_eq!( + shape, + [ + "stack 0", + "sample 0 at 10", + "stack 1", + "sample 1 at 20", + "sample 1 at 30" + ] ); } @@ -929,11 +1085,4 @@ mod tests { }; assert_eq!(selector_hints(&frame), (None, None)); } - - fn raw(addresses: &[u64]) -> RawCpuSample { - RawCpuSample { - thread_id: 1, - addresses: addresses.to_vec(), - } - } } diff --git a/xprobe/core/src/triage.rs b/xprobe/core/src/triage.rs index 3f7b90f..8a11b73 100644 --- a/xprobe/core/src/triage.rs +++ b/xprobe/core/src/triage.rs @@ -654,6 +654,8 @@ mod tests { exclusive_samples: 10, inclusive_proportion: exclusive, exclusive_proportion: exclusive, + inclusive_estimated_ns: 0, + exclusive_estimated_ns: 0, entry_selector_hint: Some(format!("uprobe:/srv/app:{symbol}:entry")), return_selector_hint: Some(format!("uprobe:/srv/app:{symbol}:return")), } diff --git a/xprobe/protocol/src/cpu_sampling.rs b/xprobe/protocol/src/cpu_sampling.rs index aae2e2d..ccf4a21 100644 --- a/xprobe/protocol/src/cpu_sampling.rs +++ b/xprobe/protocol/src/cpu_sampling.rs @@ -1,7 +1,10 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use crate::{CheckResult, SchemaVersion, SessionStatus, TargetIdentity, ValidationIssue, Warning}; +use crate::{ + CheckResult, EvidenceArtifact, SchemaVersion, SessionStatus, TargetIdentity, ValidationIssue, + Warning, +}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "snake_case")] @@ -19,7 +22,7 @@ pub struct CpuSamplingSpec { pub frequency_hz: u64, pub duration_ms: u64, pub timeout_ms: u64, - pub max_samples: u64, + /// Stack groups and hotspots listed; every sample is counted. pub max_groups: u64, pub stack_depth: u32, pub max_threads: u32, @@ -53,6 +56,8 @@ pub struct CpuStackGroup { pub frames: Vec, pub samples: u64, pub proportion: f64, + /// On-CPU time: the sum of the samples' perf periods. + pub estimated_ns: u64, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)] @@ -63,6 +68,9 @@ pub struct CpuHotspot { pub exclusive_samples: u64, pub inclusive_proportion: f64, pub exclusive_proportion: f64, + /// On-CPU time with this frame on the stack, and as the leaf. + pub inclusive_estimated_ns: u64, + pub exclusive_estimated_ns: u64, pub entry_selector_hint: Option, pub return_selector_hint: Option, } @@ -94,10 +102,11 @@ pub struct CpuSampleCollectionSummary { pub observed_samples: u64, pub grouped_samples: u64, pub lost_samples: u64, - pub sample_capacity: u64, - pub group_capacity: u64, + /// Distinct stacks; `max_groups` of them are listed. pub groups: u64, - pub table_utilization: f64, + pub elapsed_ns: u64, + /// On-CPU time of every sample: the sum of their perf periods. + pub cpu_time_ns: u64, pub stack_depth: u32, pub truncated_stacks: u64, pub threads_observed: u32, @@ -133,10 +142,43 @@ pub struct CpuSampleInventoryResult { pub inventory: CpuSampleInventory, pub collection: CpuSampleCollectionSummary, pub symbolization: CpuSymbolizationSummary, + /// Every sample with its time, as `CpuSampleRecord` lines. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub artifact: Option, #[serde(default)] pub warnings: Vec, } +/// One line of a CPU sample artifact: a stack, written before the first +/// sample that uses it, or a sample. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(untagged)] +pub enum CpuSampleRecord { + Stack(CpuStackRecord), + Sample(CpuSampleLine), +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CpuStackRecord { + pub stack: u32, + /// Innermost frame first. + pub frames: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct CpuSampleLine { + /// `CLOCK_MONOTONIC` time of the sample. + pub timestamp_ns: u64, + pub pid: u32, + pub tid: u32, + /// On-CPU time the sample stands for: its perf period. + pub cpu_ns: u64, + /// A stack written on an earlier line. + pub stack: u32, +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct CpuSamplingRequirements { diff --git a/xprobe/protocol/src/lib.rs b/xprobe/protocol/src/lib.rs index fa6fd65..048e83a 100644 --- a/xprobe/protocol/src/lib.rs +++ b/xprobe/protocol/src/lib.rs @@ -26,9 +26,9 @@ pub use capability::{ pub use capture::HostCaptureResult; pub use cpu_sampling::{ CpuCaptureCompleteness, CpuFrameLanguage, CpuHotspot, CpuSampleCollectionSummary, - CpuSampleEvent, CpuSampleInventory, CpuSampleInventoryResult, CpuSamplingRequirements, - CpuSamplingSpec, CpuSamplingValidationResult, CpuStackFrame, CpuStackGroup, - CpuSymbolizationSummary, PythonSymbolizationStatus, + CpuSampleEvent, CpuSampleInventory, CpuSampleInventoryResult, CpuSampleLine, CpuSampleRecord, + CpuSamplingRequirements, CpuSamplingSpec, CpuSamplingValidationResult, CpuStackFrame, + CpuStackGroup, CpuStackRecord, CpuSymbolizationSummary, PythonSymbolizationStatus, }; pub use discover::{CudaProcessCandidate, DiscoveryResult}; pub use error::{ErrorCode, ErrorResponse, XprobeError}; diff --git a/xprobe/protocol/src/schema.rs b/xprobe/protocol/src/schema.rs index b736f6c..9df7807 100644 --- a/xprobe/protocol/src/schema.rs +++ b/xprobe/protocol/src/schema.rs @@ -2,8 +2,8 @@ use schemars::{Schema, schema_for}; use crate::{ AggregateInventoryResult, CapabilityReport, CaptureManifest, CpuSampleInventoryResult, - CpuSamplingSpec, CpuSamplingValidationResult, DiscoveryResult, ErrorResponse, Event, - HostCaptureResult, MeasurementGraphResult, MeasurementGraphSpec, + CpuSampleRecord, CpuSamplingSpec, CpuSamplingValidationResult, DiscoveryResult, ErrorResponse, + Event, HostCaptureResult, MeasurementGraphResult, MeasurementGraphSpec, MeasurementGraphValidationResult, MeasurementResult, MeasurementSpec, ProcessReport, PythonSampleRecord, PythonSampleResult, ResolvedProbe, SyscallAggregateResult, SyscallAggregateSpec, SyscallAggregateValidationResult, TraceExportResult, TriageResult, @@ -11,7 +11,7 @@ use crate::{ }; #[must_use] -pub fn generated_schemas() -> [(&'static str, Schema); 26] { +pub fn generated_schemas() -> [(&'static str, Schema); 27] { [ ("event.schema.json", schema_for!(Event)), ("capture-manifest.schema.json", schema_for!(CaptureManifest)), @@ -64,6 +64,10 @@ pub fn generated_schemas() -> [(&'static str, Schema); 26] { "python-sample-record.schema.json", schema_for!(PythonSampleRecord), ), + ( + "cpu-sample-record.schema.json", + schema_for!(CpuSampleRecord), + ), ("triage-result.schema.json", schema_for!(TriageResult)), ("trigger-result.schema.json", schema_for!(TriggerResult)), ( diff --git a/xprobe/protocol/tests/contracts.rs b/xprobe/protocol/tests/contracts.rs index 4cf6177..c378266 100644 --- a/xprobe/protocol/tests/contracts.rs +++ b/xprobe/protocol/tests/contracts.rs @@ -241,7 +241,6 @@ fn cpu_sampling_spec_contract_round_trips() { "frequency_hz": 99, "duration_ms": 1000, "timeout_ms": 30000, - "max_samples": 10000, "max_groups": 4096, "stack_depth": 64, "max_threads": 1024 @@ -275,7 +274,8 @@ fn cpu_sample_inventory_contract_round_trips() { "stack_groups": [{ "frames": [frame.clone()], "samples": 80, - "proportion": 0.8 + "proportion": 0.8, + "estimated_ns": 80_000_000 }], "hotspots": [{ "frame": frame, @@ -283,6 +283,8 @@ fn cpu_sample_inventory_contract_round_trips() { "exclusive_samples": 60, "inclusive_proportion": 0.8, "exclusive_proportion": 0.6, + "inclusive_estimated_ns": 80_000_000, + "exclusive_estimated_ns": 60_000_000, "entry_selector_hint": "uprobe:/srv/app:handle_request:entry", "return_selector_hint": "uprobe:/srv/app:handle_request:return" }] @@ -292,10 +294,9 @@ fn cpu_sample_inventory_contract_round_trips() { "observed_samples": 100, "grouped_samples": 100, "lost_samples": 0, - "sample_capacity": 10000, - "group_capacity": 4096, "groups": 4, - "table_utilization": 0.000_976_562_5, + "elapsed_ns": 1_000_000_000, + "cpu_time_ns": 100_000_000, "stack_depth": 64, "truncated_stacks": 0, "threads_observed": 8, From ff0c08d5896a10c61eeb492adb54c3b0cd2c28a5 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:11:34 +0800 Subject: [PATCH 09/22] =?UTF-8?q?=F0=9F=90=9B=20fix:=20reuse=20a=20loaded?= =?UTF-8?q?=20Agent=20after=20its=20file=20is=20deleted?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit measure read the loaded Agent's ELF file to find its start function, so deleting the install directory, as when a temporary venv is removed, made every later CUDA capture of that process fail until it restarted. measure now asks the target's loader for the Agent by the name it was loaded under (dlopen with RTLD_NOLOAD) and takes the start function from dlsym, without reading the file. validate warns CUPTI_AGENT_ALREADY_LOADED with agent_path and file_deleted when a target holds an Agent, and the docs state what a loaded Agent keeps between captures: its mapping and the last capture's record buffers. --- docs/cli-reference.md | 2 +- docs/cupti-agent.md | 3 +- docs/installation.md | 2 +- skills/xprobe-perf-profiling/SKILL.md | 2 +- tests/integration/run-inject-live.sh | 38 +++++++++++++ tests/integration/test_inject.py | 4 ++ xprobe/core/src/inject.rs | 77 ++++++++++++++++----------- xprobe/core/src/validate.rs | 41 +++++++++++++- 8 files changed, 134 insertions(+), 35 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 2ffe3bb..6b2b5f0 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -268,7 +268,7 @@ Results follow `schemas/trigger-result.schema.json` (schema `3.0`). - Host endpoints attach every eBPF link before arming. A duration capture that reaches `--max-events` fails with `EVENT_RATE_TOO_HIGH`. - CUDA endpoints find the Agent from `--agent`, then `XPROBE_CUPTI_AGENT_PATH`, then `../lib/xprobe/cuda12|cuda13`, then the matching build path. - One xprobe session owns the Agent at a time. While it runs, another `measure` on the same target fails with `CUPTI_AGENT_BUSY` and leaves the capture alone; combine edges into one measurement graph instead. If torch.profiler or an Nsight tool holds the target's CUPTI subscriber, `measure` fails with `CUPTI_NOT_AVAILABLE` and a hint naming them. -- Live injection needs Linux x86_64, the same mount namespace as the target, and ptrace permission. It prints a warning to stderr and emits `CUPTI_AGENT_INJECTED`. On stop it disables CUPTI and removes its private socket while leaving the `.so` mapped. Keep the installed `libxprobe-cupti.so` path on disk while injected targets remain running (deleting a temporary venv or install directory breaks re-attaches until those processes restart). Check mapped state with `xprobe validate` or `grep libxprobe-cupti /proc/$PID/maps`; see [CUPTI Agent](cupti-agent.md) for lifecycle details. +- Live injection needs Linux x86_64, the same mount namespace as the target, and ptrace permission. It prints a warning to stderr and emits `CUPTI_AGENT_INJECTED`. On stop it disables CUPTI and removes its private socket while leaving the `.so` mapped. A later `measure` reuses the mapped Agent, even if its file was deleted. `validate` warns `CUPTI_AGENT_ALREADY_LOADED` with `agent_path` and `file_deleted` when a target holds an Agent; see [CUPTI Agent](cupti-agent.md) for what it keeps. - NVTX thread ranges are tracked by `(tid, push_level)` and process ranges by `range_id` across threads (`start_tid`). ASCII `PushA`/`StartA` and the `Ex` forms are supported; wide and registered strings and CUPTI Range Profiling are not. ### Artifacts and offline input diff --git a/docs/cupti-agent.md b/docs/cupti-agent.md index 90e17be..99e8218 100644 --- a/docs/cupti-agent.md +++ b/docs/cupti-agent.md @@ -15,7 +15,8 @@ Release packages ship separate builds linked to `libcupti.so.12` and `libcupti.s - `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. - - Keep the installed `libxprobe-cupti.so` path on disk while injected targets remain running; deleting the install directory or venv breaks later attaches until those processes restart. Check mapped state with `xprobe validate` (`requirements.agent_activation`) or `grep libxprobe-cupti /proc/$PID/maps`. + - After a capture the Agent stays mapped with CUPTI callbacks and activity off, and keeps the last capture's record buffers: 200 bytes per `--max-events` record, plus as much again for a trigger's ring snapshot, until the next capture replaces them or the target exits. + - A later `measure` finds the mapped Agent by the name it was loaded under (`dlopen` with `RTLD_NOLOAD`), so deleting its file, as when a temporary venv is removed, does not stop later captures. `validate` warns `CUPTI_AGENT_ALREADY_LOADED` with `agent_path` and `file_deleted`. **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. diff --git a/docs/installation.md b/docs/installation.md index 335408f..3a3d617 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -76,7 +76,7 @@ Re-run the new release's installer with the same `--prefix` to upgrade, or unins sh install.sh --prefix "$HOME/.local" --uninstall ``` -Uninstall removes only xprobe-owned files under `bin/xprobe`, `lib/xprobe`, `include/xprobe`, and `share/xprobe`. If a running CUDA process currently has `libxprobe-cupti.so` injected from that prefix, wait until it restarts before deleting the directory so later attaches keep working. +Uninstall removes only xprobe-owned files under `bin/xprobe`, `lib/xprobe`, `include/xprobe`, and `share/xprobe`. A running CUDA process that has `libxprobe-cupti.so` injected from that prefix keeps its mapped copy, and later measures reuse it. ## AI Agent Skill diff --git a/skills/xprobe-perf-profiling/SKILL.md b/skills/xprobe-perf-profiling/SKILL.md index 8f9c6f6..e553116 100644 --- a/skills/xprobe-perf-profiling/SKILL.md +++ b/skills/xprobe-perf-profiling/SKILL.md @@ -34,7 +34,7 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA ## Runtime limits & validity checks -- **CUPTI injection & install path**: live CUDA capture injects `libxprobe-cupti.so` via ptrace, disables callbacks on stop, and leaves the `.so` mapped (never calls `dlclose`). Do not delete or move the xprobe install directory or venv while an injected process is running, or later attaches fail until the target restarts. Check state with `xprobe validate` or `grep libxprobe-cupti /proc/$PID/maps`. +- **CUPTI injection**: live CUDA capture injects `libxprobe-cupti.so` via ptrace, disables callbacks on stop, and leaves the `.so` mapped with its last capture's buffers (200 bytes per `--max-events` record). Later captures reuse it even if its file was deleted; `validate` reports it as `CUPTI_AGENT_ALREADY_LOADED`. - **One CUDA session per PID**: running two CUDA `measure` commands on the same PID fails with `CUPTI_AGENT_BUSY`; combine edges in a graph instead. `--python-sample` can run concurrently with CUDA `measure`. - **Containers & NVTX**: run `xprobe` inside the target's PID and mount namespaces. NVTX ranges require `NVTX_INJECTION64_PATH` before the target's first NVTX call. - **Duration & sample bounds**: live `measure` requires `--samples` or `--duration-ms`. Inventory modes (`--aggregate`, `--cpu-sample`, `--python-sample`, `--syscall-aggregate`, `--triage`) accept `--duration-ms` only. diff --git a/tests/integration/run-inject-live.sh b/tests/integration/run-inject-live.sh index 8c04936..8a23e14 100755 --- a/tests/integration/run-inject-live.sh +++ b/tests/integration/run-inject-live.sh @@ -163,6 +163,44 @@ run_aggregate_limit "$1/aggregate-limit" run_busy_pair "$1" run_api_measure "$1/after-busy" +# A target keeps working after the Agent file it loaded is deleted, as when a +# temporary environment is removed. +run_deleted_agent() { + local dir="${build_dir}/deleted" + mkdir -p "${dir}" + rm -f "${dir}"/ready "${dir}"/go "${dir}"/stop + # Copy the Agent the first target loaded, built here or picked by xprobe. + local source + source=$(awk '$NF ~ /libxprobe-cupti\.so$/ {print $NF; exit}' "/proc/${target_pid}/maps") + cp "${source}" "${dir}/libxprobe-cupti.so" + "${fixture}" "${dir}/ready" "${dir}/go" "${dir}/stop" & + local pid=$! + for _ in $(seq 1 500); do + [[ -e "${dir}/ready" ]] && break + sleep 0.01 + done + touch "${dir}/go" + for name in before after; do + "${xprobe_bin}" measure \ + --pid "${pid}" \ + --agent "${dir}/libxprobe-cupti.so" \ + --from 'cuda:runtime_api:cudaLaunchKernel:entry' \ + --to 'cuda:runtime_api:cudaLaunchKernel:exit' \ + --match exact \ + --samples 3 \ + --max-events 32 \ + --timeout-ms 10000 \ + --json --non-interactive --no-color \ + >"$1/deleted-${name}.json" 2>"$1/deleted-${name}.stderr" || true + rm -f "${dir}/libxprobe-cupti.so" + done + grep -q 'libxprobe-cupti.so (deleted)' "/proc/${pid}/maps" \ + || { echo "the deleted Agent is not mapped" >&2; kill "${pid}"; return 1; } + touch "${dir}/stop" + wait "${pid}" +} +run_deleted_agent "$1" + if [[ ${auto_agent} == 1 ]]; then mapped_agents=$(awk '$0 ~ /lib\/xprobe\/cuda(12|13)\/libxprobe-cupti.so/ {print $NF}' "/proc/${target_pid}/maps" | sort -u | wc -l) else diff --git a/tests/integration/test_inject.py b/tests/integration/test_inject.py index 3bf4586..01f3d54 100755 --- a/tests/integration/test_inject.py +++ b/tests/integration/test_inject.py @@ -109,6 +109,10 @@ def main() -> None: busy = json.loads((output / "busy.json").read_text()) assert busy["ok"] is False assert busy["error"]["code"] == "CUPTI_AGENT_BUSY" + for name in ("deleted-before", "deleted-after"): + deleted = json.loads((output / f"{name}.json").read_text()) + assert deleted["ok"] is True, deleted + assert deleted["measurement"]["samples"]["matched"] == 3, deleted after_busy = json.loads((output / "after-busy.json").read_text()) assert after_busy["ok"] is True assert after_busy["measurement"]["samples"]["matched"] == 3 diff --git a/xprobe/core/src/inject.rs b/xprobe/core/src/inject.rs index cdb4cd9..9da9f04 100644 --- a/xprobe/core/src/inject.rs +++ b/xprobe/core/src/inject.rs @@ -26,6 +26,8 @@ use crate::{ const RTLD_NOW: u64 = 2; const RTLD_LOCAL: u64 = 0; +/// Return a library that is already loaded instead of loading it. +const RTLD_NOLOAD: u64 = 4; const AGENT_START_SYMBOL: &str = "xprobe_cupti_agent_start"; /// `XPROBE_CUPTI_AGENT_BUSY` from `xprobe_cupti_agent_start`. const AGENT_BUSY: u64 = 4; @@ -64,6 +66,8 @@ pub enum InjectError { /// The Agent is already loaded and another xprobe session owns its /// capture. AgentBusy, + /// The target's dynamic loader no longer finds the Agent it loaded. + LoadedAgentUnreachable(PathBuf), } impl InjectError { @@ -79,6 +83,7 @@ impl InjectError { Self::UnsupportedPlatform => ErrorCode::UnsupportedCudaVersion, Self::AgentBusy => ErrorCode::CuptiAgentBusy, Self::InvalidAgent(_) + | Self::LoadedAgentUnreachable(_) | Self::MissingRuntimeSymbol(_) | Self::ShortMemoryTransfer { .. } | Self::RemoteCallFailed { .. } @@ -125,6 +130,11 @@ impl fmt::Display for InjectError { Self::TimedOut => formatter.write_str("remote function call timed out"), Self::AgentBusy => formatter .write_str("the CUPTI Agent in the target is serving another xprobe session"), + Self::LoadedAgentUnreachable(path) => write!( + formatter, + "the target maps the CUPTI Agent from {} but its loader no longer finds it by that name; restart the target to profile it again", + path.display() + ), Self::RemoteCallTrap { instruction_pointer, } => write!( @@ -157,7 +167,8 @@ impl Error for InjectError { | Self::RemoteCallTrap { .. } | Self::ShortMemoryTransfer { .. } | Self::RemoteCallFailed { .. } - | Self::AgentBusy => None, + | Self::AgentBusy + | Self::LoadedAgentUnreachable(_) => None, } } } @@ -196,37 +207,42 @@ pub fn activate( remote.copy_c_string(malloc, socket_path.as_os_str().as_encoded_bytes())?; let mut allocations = vec![socket_address]; - let (start_address, injected) = if report.cuda.xprobe_cupti_loaded { - (resolve_agent_symbol(report, AGENT_START_SYMBOL)?, false) + // A loaded Agent is found by the name it was loaded under, so its file + // may have been deleted since; a new one is loaded from `agent_path`. + let (open_path, flags, injected) = if report.cuda.xprobe_cupti_loaded { + (loaded_agent_path(report)?, RTLD_NOW | RTLD_NOLOAD, false) } else { let agent_path = fs::canonicalize(agent_path) .map_err(|_| InjectError::InvalidAgent(agent_path.to_owned()))?; if !agent_path.is_file() { return Err(InjectError::InvalidAgent(agent_path)); } - let dlopen = resolve_runtime_symbol(report, "dlopen")?; - let dlsym = resolve_runtime_symbol(report, "dlsym")?; - let path_address = - remote.copy_c_string(malloc, agent_path.as_os_str().as_encoded_bytes())?; - allocations.push(path_address); - let handle = remote.call(dlopen, &[path_address, RTLD_NOW | RTLD_LOCAL])?; - if handle == 0 { - return Err(InjectError::RemoteCallFailed { + (agent_path, RTLD_NOW | RTLD_LOCAL, true) + }; + let dlopen = resolve_runtime_symbol(report, "dlopen")?; + let dlsym = resolve_runtime_symbol(report, "dlsym")?; + let path_address = remote.copy_c_string(malloc, open_path.as_os_str().as_encoded_bytes())?; + allocations.push(path_address); + let handle = remote.call(dlopen, &[path_address, flags])?; + if handle == 0 { + return Err(if injected { + InjectError::RemoteCallFailed { function: "dlopen", result: handle, - }); - } - let symbol_address = remote.copy_c_string(malloc, AGENT_START_SYMBOL.as_bytes())?; - allocations.push(symbol_address); - let start = remote.call(dlsym, &[handle, symbol_address])?; - if start == 0 { - return Err(InjectError::RemoteCallFailed { - function: "dlsym", - result: start, - }); - } - (start, true) - }; + } + } else { + InjectError::LoadedAgentUnreachable(open_path) + }); + } + let symbol_address = remote.copy_c_string(malloc, AGENT_START_SYMBOL.as_bytes())?; + allocations.push(symbol_address); + let start_address = remote.call(dlsym, &[handle, symbol_address])?; + if start_address == 0 { + return Err(InjectError::RemoteCallFailed { + function: "dlsym", + result: start_address, + }); + } let status = remote.call(start_address, &[socket_address, record_capacity])?; for address in allocations { @@ -279,20 +295,21 @@ fn resolve_runtime_symbol( Err(InjectError::MissingRuntimeSymbol(symbol)) } -fn resolve_agent_symbol(report: &ProcessReport, symbol: &'static str) -> Result { - let path = report +/// The path the target loaded the Agent from, as its maps name it without a +/// ` (deleted)` suffix. +fn loaded_agent_path(report: &ProcessReport) -> Result { + report .loaded_libraries .iter() + .map(|path| path.strip_suffix(" (deleted)").unwrap_or(path)) .find(|path| { Path::new(path) .file_name() .and_then(|value| value.to_str()) .is_some_and(|name| name.starts_with("libxprobe-cupti.so")) }) - .ok_or(InjectError::MissingRuntimeSymbol(symbol))?; - resolve::run(report, &format!("uprobe:{path}:{symbol}:entry")) - .map(|probe| probe.runtime_address) - .map_err(InjectError::Resolve) + .map(PathBuf::from) + .ok_or(InjectError::MissingRuntimeSymbol(AGENT_START_SYMBOL)) } struct RemoteProcess { diff --git a/xprobe/core/src/validate.rs b/xprobe/core/src/validate.rs index cf39894..e63d3d5 100644 --- a/xprobe/core/src/validate.rs +++ b/xprobe/core/src/validate.rs @@ -1,4 +1,4 @@ -use std::{collections::BTreeMap, error::Error, fmt}; +use std::{collections::BTreeMap, error::Error, fmt, path::Path}; use regex::Regex; use xprobe_protocol::{ @@ -205,6 +205,9 @@ pub fn run( &mut warnings, ); check_cupti_compatibility(report, &requirements, &mut issues); + if requirements.agent_activation == AgentActivation::AlreadyLoaded { + warnings.extend(loaded_agent(report)); + } check_policy(&start, &end, match_policy, &mut issues, &mut warnings); let policy_recommendation = recommend_policy(&start, &end); check_selector_breadth(&start, "start", &mut warnings); @@ -1125,6 +1128,29 @@ fn issue(code: ErrorCode, message: String) -> ValidationIssue { ValidationIssue { code, message } } +/// What an Agent loaded by an earlier measure leaves in the target. +fn loaded_agent(report: &ProcessReport) -> Option { + let mapped = report.loaded_libraries.iter().find(|path| { + Path::new(path.strip_suffix(" (deleted)").unwrap_or(path)) + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("libxprobe-cupti.so")) + })?; + let path = mapped.strip_suffix(" (deleted)").unwrap_or(mapped); + let mut warning = warning( + "CUPTI_AGENT_ALREADY_LOADED", + "an earlier measure loaded the CUPTI Agent; it stays mapped until the target exits, with CUPTI callbacks and activity off between captures, and keeps its last capture's record buffers (200 bytes per --max-events record, twice for triggers) until the next capture", + ); + warning + .details + .insert("agent_path".to_owned(), serde_json::Value::from(path)); + warning.details.insert( + "file_deleted".to_owned(), + serde_json::Value::from(mapped.ends_with(" (deleted)")), + ); + Some(warning) +} + fn warning(code: &str, message: &str) -> Warning { Warning { code: code.to_owned(), @@ -1388,6 +1414,9 @@ mod tests { report.cuda.xprobe_cupti_loaded = true; report.capabilities.cuda_callback = true; report.capabilities.cuda_activity = true; + report + .loaded_libraries + .push("/opt/venv/lib/xprobe/cuda12/libxprobe-cupti.so (deleted)".to_owned()); let result = run( &report, "cuda:kernel_start:name~test.*", @@ -1396,6 +1425,16 @@ mod tests { ) .unwrap(); assert!(result.valid); + let loaded = result + .warnings + .iter() + .find(|warning| warning.code == "CUPTI_AGENT_ALREADY_LOADED") + .unwrap(); + assert_eq!( + loaded.details["agent_path"], + "/opt/venv/lib/xprobe/cuda12/libxprobe-cupti.so" + ); + assert_eq!(loaded.details["file_deleted"], true); assert_eq!( result.requirements.agent_activation, AgentActivation::AlreadyLoaded From 542825919445ada319660f7a3428559684c7f11b Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:15:20 +0800 Subject: [PATCH 10/22] =?UTF-8?q?=E2=9C=A8=20feat:=20list=20procfs=20CUDA?= =?UTF-8?q?=20hints=20when=20NVML's=20PIDs=20are=20not=20visible?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Inside a container NVML names CUDA processes by host PID, so discover found nothing. When none of NVML's processes are visible, discover now lists procfs_hints: processes at or below the root that map libcuda or hold /dev/nvidia* files open, with that evidence. They are kept apart from candidates, which stay NVML-confirmed context holders: loading CUDA or opening a device does not show a context. --- docs/cli-reference.md | 2 +- schemas/discover.schema.json | 50 +++++++++ skills/xprobe-perf-profiling/SKILL.md | 2 +- xprobe/core/src/discover.rs | 151 ++++++++++++++++++++++++-- xprobe/protocol/src/discover.rs | 19 ++++ xprobe/protocol/src/lib.rs | 2 +- 6 files changed, 214 insertions(+), 12 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 6b2b5f0..029d006 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -54,7 +54,7 @@ Asks NVML for active CUDA compute processes under the process tree rooted at `-- NVML lists processes from every container that shares a GPU: - PIDs this PID namespace cannot see, or that exited during inspection, are reported in `nvml_pids` with `NVML_PROCESS_UNAVAILABLE` instead of failing the command. -- When none are visible, `NVML_PID_NAMESPACE_MISMATCH` notes that NVML returned host PIDs. Inside a container, locate CUDA processes via `ps` or `/proc/*/maps` (`libcuda`) / `/proc/*/fd` (`/dev/nvidia*`), then pass the namespace-local PID to `validate` and `measure` directly. +- When none are visible, `NVML_PID_NAMESPACE_MISMATCH` notes that NVML returned host PIDs, and `procfs_hints` lists the processes at or below the root that map `libcuda` (`libcuda_mapped`) or hold `/dev/nvidia*` files open (`nvidia_device_fds`). Each loaded CUDA or opened a device, which does not show a CUDA context; pass the namespace-local PID to `validate` and `measure`. - A failed NVML query or a missing root PID is an error. ## Selectors diff --git a/schemas/discover.schema.json b/schemas/discover.schema.json index 8e2b8ae..dc70b6c 100644 --- a/schemas/discover.schema.json +++ b/schemas/discover.schema.json @@ -17,6 +17,13 @@ "ok": { "type": "boolean" }, + "procfs_hints": { + "description": "When NVML's processes are not visible in this PID namespace: processes\nat or below the root that mapped `libcuda` or hold an NVIDIA device\nfile. Each loaded CUDA or opened a device; neither shows a context.", + "type": "array", + "items": { + "$ref": "#/$defs/ProcfsCudaHint" + } + }, "root": { "$ref": "#/$defs/TargetIdentity" }, @@ -86,6 +93,49 @@ "gpu_uuids" ] }, + "ProcfsCudaHint": { + "type": "object", + "properties": { + "command_line": { + "type": "array", + "items": { + "type": "string" + } + }, + "executable": { + "type": "string" + }, + "libcuda_mapped": { + "description": "`/proc//maps` maps a `libcuda.so`.", + "type": "boolean" + }, + "nvidia_device_fds": { + "description": "Open `/dev/nvidia*` files, or `None` when `/proc//fd` is not\nreadable.", + "type": [ + "integer", + "null" + ], + "format": "uint32", + "minimum": 0 + }, + "parent_pid": { + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "target": { + "$ref": "#/$defs/TargetIdentity" + } + }, + "additionalProperties": false, + "required": [ + "target", + "parent_pid", + "executable", + "command_line", + "libcuda_mapped" + ] + }, "SchemaVersion": { "type": "string", "enum": [ diff --git a/skills/xprobe-perf-profiling/SKILL.md b/skills/xprobe-perf-profiling/SKILL.md index e553116..9a3eb49 100644 --- a/skills/xprobe-perf-profiling/SKILL.md +++ b/skills/xprobe-perf-profiling/SKILL.md @@ -12,7 +12,7 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA | Need | Command | Notes | | --- | --- | --- | | Check host/container permissions | `xprobe doctor` | Read-only; run first when eBPF, perf, ptrace, or CUPTI access is unknown | -| List CUDA PIDs under a root | `xprobe discover --pid "$ROOT"` | Uses NVML; inside containers (`NVML_PID_NAMESPACE_MISMATCH`), scan `ps` or `/proc/*/maps` (`libcuda`) | +| List CUDA PIDs under a root | `xprobe discover --pid "$ROOT"` | Uses NVML; inside containers (`NVML_PID_NAMESPACE_MISMATCH`) see `procfs_hints`: processes that loaded `libcuda` or opened `/dev/nvidia*` | | Check selectors or injection state | `xprobe validate --pid "$PID" --from A --to B --match exact` | Read-only; reports `requirements.agent_activation` (`already_loaded` vs `injection_required`) | | Python stacks, GIL & native waits | `xprobe measure --pid "$PID" --python-sample --duration-ms 2000` | CPython 3.9–3.14; ptrace only (no eBPF/perf/injection); sweeps of every thread slow down on processes with many threads | | Native CPU callchain hotspots | `xprobe measure --pid "$PID" --cpu-sample --duration-ms 2000 --events-out cpu.jsonl` | Needs perf events; 999 Hz; every sample timestamped in the JSONL | diff --git a/xprobe/core/src/discover.rs b/xprobe/core/src/discover.rs index b93865b..787ff7b 100644 --- a/xprobe/core/src/discover.rs +++ b/xprobe/core/src/discover.rs @@ -1,12 +1,14 @@ use std::{ collections::{BTreeMap, BTreeSet}, error::Error, - fmt, io, + fmt, fs, io, + path::Path, process::Command, }; use xprobe_protocol::{ - CudaProcessCandidate, DiscoveryResult, ErrorCode, ProcessReport, SchemaVersion, Warning, + CudaProcessCandidate, DiscoveryResult, ErrorCode, ProcessReport, ProcfsCudaHint, SchemaVersion, + Warning, }; use crate::inspect::{self, InspectError}; @@ -18,6 +20,7 @@ pub enum DiscoverError { NvmlCommand(io::Error), NvmlFailed { status: Option, stderr: String }, InvalidNvmlOutput(String), + Procfs(String), } impl DiscoverError { @@ -27,7 +30,7 @@ impl DiscoverError { Self::Inspect(error) => error.code(), Self::InvalidLimit => ErrorCode::SessionLimitExceeded, Self::NvmlCommand(_) | Self::NvmlFailed { .. } => ErrorCode::CuptiNotAvailable, - Self::InvalidNvmlOutput(_) => ErrorCode::Internal, + Self::InvalidNvmlOutput(_) | Self::Procfs(_) => ErrorCode::Internal, } } @@ -36,7 +39,7 @@ impl DiscoverError { match self { Self::Inspect(error) => error.recoverable(), Self::InvalidLimit | Self::NvmlCommand(_) | Self::NvmlFailed { .. } => true, - Self::InvalidNvmlOutput(_) => false, + Self::InvalidNvmlOutput(_) | Self::Procfs(_) => false, } } } @@ -51,6 +54,7 @@ impl fmt::Display for DiscoverError { formatter, "nvidia-smi compute-process query failed with status {status:?}: {stderr}" ), + Self::Procfs(error) => write!(formatter, "failed to list /proc: {error}"), Self::InvalidNvmlOutput(line) => { write!( formatter, @@ -66,7 +70,10 @@ impl Error for DiscoverError { match self { Self::Inspect(error) => Some(error), Self::NvmlCommand(error) => Some(error), - Self::InvalidLimit | Self::NvmlFailed { .. } | Self::InvalidNvmlOutput(_) => None, + Self::InvalidLimit + | Self::NvmlFailed { .. } + | Self::InvalidNvmlOutput(_) + | Self::Procfs(_) => None, } } } @@ -136,6 +143,14 @@ pub fn run(report: &ProcessReport, limit: usize) -> Result Result candidates.len(), candidates, + procfs_hints, warnings: discovery_warnings(&unavailable, total_candidates), }) } +/// Processes at or below `root` that map `libcuda` or hold an NVIDIA device +/// file, by PID. A process that exits during the scan is skipped. +fn procfs_hints(root: u32) -> Result, DiscoverError> { + let mut pids = fs::read_dir("/proc") + .map_err(|source| DiscoverError::Procfs(source.to_string()))? + .filter_map(|entry| entry.ok()?.file_name().to_str()?.parse::().ok()) + .collect::>(); + pids.sort_unstable(); + let mut hints = Vec::new(); + for pid in pids { + if ancestry(pid, root, inspect::read_parent_pid)? != Ancestry::Descendant { + continue; + } + let Some((libcuda_mapped, nvidia_device_fds)) = cuda_evidence(pid) else { + continue; + }; + if !libcuda_mapped && nvidia_device_fds.unwrap_or(0) == 0 { + continue; + } + let hint = inspect::run(pid).and_then(|process| { + Ok(ProcfsCudaHint { + parent_pid: inspect::read_parent_pid(pid)?, + target: process.target, + executable: process.executable, + command_line: process.command_line, + libcuda_mapped, + nvidia_device_fds, + }) + }); + match hint { + Ok(hint) => hints.push(hint), + Err(InspectError::TargetExited { .. } | InspectError::TargetNotFound { .. }) => {} + Err(error) => return Err(error.into()), + } + } + Ok(hints) +} + +/// Whether a `/proc//maps` text maps a `libcuda.so`. +fn maps_libcuda(maps: &str) -> bool { + maps.lines().any(|line| { + line.split_whitespace() + .last() + .and_then(|path| Path::new(path).file_name()?.to_str()) + .is_some_and(|name| name.starts_with("libcuda.so")) + }) +} + +/// Whether `pid` maps `libcuda.so`, and how many `/dev/nvidia*` files it +/// holds open (`None` when its fd directory is not readable). `None` +/// overall when its maps cannot be read, as when it exited. +fn cuda_evidence(pid: u32) -> Option<(bool, Option)> { + let maps = fs::read_to_string(format!("/proc/{pid}/maps")).ok()?; + let libcuda_mapped = maps_libcuda(&maps); + let fds = fs::read_dir(format!("/proc/{pid}/fd")).ok().map(|entries| { + let count = entries + .filter_map(|entry| fs::read_link(entry.ok()?.path()).ok()) + .filter(|target| target.starts_with("/dev/nvidia")) + .count(); + u32::try_from(count).unwrap_or(u32::MAX) + }); + Some((libcuda_mapped, fds)) +} + /// Relationship between an NVML compute PID and the requested root. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Ancestry { @@ -207,9 +287,9 @@ fn discovery_warnings(unavailable: &[u32], candidates: usize) -> Vec { warnings.push(Warning { code: "NVML_PID_NAMESPACE_MISMATCH".to_owned(), message: "NVML reports CUDA processes by host PID, and none are visible here; \ - inside a container, find the worker with ps or the application's own \ - records and pass its namespace-local PID to validate and measure, or \ - run discover in the host PID namespace" + procfs_hints lists processes under the root that loaded libcuda or hold \ + an NVIDIA device file; pass a namespace-local PID to validate and \ + measure, or run discover in the host PID namespace" .to_owned(), details: [("nvml_pids".to_owned(), serde_json::json!(unavailable))] .into_iter() @@ -260,7 +340,60 @@ mod tests { use crate::inspect::InspectError; - use super::{Ancestry, DiscoverError, ancestry, parse_compute_processes, unavailable_warning}; + use super::{ + Ancestry, DiscoverError, ancestry, maps_libcuda, parse_compute_processes, + unavailable_warning, + }; + + #[test] + fn procfs_hints_find_a_descendant_that_maps_libcuda() { + let directory = + std::env::temp_dir().join(format!("xprobe-discover-{}", std::process::id())); + std::fs::create_dir_all(&directory).unwrap(); + let library = directory.join("libcuda.so.1"); + std::fs::write(&library, [0_u8; 4096]).unwrap(); + // A child that maps a file named like the CUDA driver library. + let mut child = std::process::Command::new("python3") + .args([ + "-c", + "import mmap,sys,time\n\ + f=open(sys.argv[1],'rb'); m=mmap.mmap(f.fileno(),0,prot=mmap.PROT_READ)\n\ + print('ready',flush=True); time.sleep(30)", + ]) + .arg(&library) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let mut ready = String::new(); + std::io::BufRead::read_line( + &mut std::io::BufReader::new(child.stdout.as_mut().unwrap()), + &mut ready, + ) + .unwrap(); + let hints = super::procfs_hints(std::process::id()); + child.kill().unwrap(); + child.wait().unwrap(); + std::fs::remove_dir_all(&directory).unwrap(); + let hint = hints + .unwrap() + .into_iter() + .find(|hint| hint.target.pid == child.id()) + .expect("the child maps libcuda"); + assert!(hint.libcuda_mapped); + assert_eq!(hint.parent_pid, std::process::id()); + assert_eq!(hint.nvidia_device_fds, Some(0)); + } + + #[test] + fn finds_libcuda_by_file_name_only() { + assert!(maps_libcuda( + "7f00-7f10 r-xp 00000000 08:01 42 /usr/lib/x86_64-linux-gnu/libcuda.so.580.95.05\n" + )); + assert!(!maps_libcuda( + "7f00-7f10 r-xp 00000000 08:01 42 /opt/libcudart.so.12\n\ + 7f10-7f20 r-xp 00000000 08:01 43 /srv/libcuda.so-notes/app\n" + )); + } fn tree(edges: &[(u32, u32)]) -> impl Fn(u32) -> Result { let parents = edges.iter().copied().collect::>(); diff --git a/xprobe/protocol/src/discover.rs b/xprobe/protocol/src/discover.rs index f06b4f6..85bd18e 100644 --- a/xprobe/protocol/src/discover.rs +++ b/xprobe/protocol/src/discover.rs @@ -23,6 +23,25 @@ pub struct DiscoveryResult { pub total_candidates: u64, pub truncated: bool, pub candidates: Vec, + /// When NVML's processes are not visible in this PID namespace: processes + /// at or below the root that mapped `libcuda` or hold an NVIDIA device + /// file. Each loaded CUDA or opened a device; neither shows a context. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub procfs_hints: Vec, #[serde(default)] pub warnings: Vec, } + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ProcfsCudaHint { + pub target: TargetIdentity, + pub parent_pid: u32, + pub executable: String, + pub command_line: Vec, + /// `/proc//maps` maps a `libcuda.so`. + pub libcuda_mapped: bool, + /// Open `/dev/nvidia*` files, or `None` when `/proc//fd` is not + /// readable. + pub nvidia_device_fds: Option, +} diff --git a/xprobe/protocol/src/lib.rs b/xprobe/protocol/src/lib.rs index 048e83a..281d543 100644 --- a/xprobe/protocol/src/lib.rs +++ b/xprobe/protocol/src/lib.rs @@ -30,7 +30,7 @@ pub use cpu_sampling::{ CpuSamplingRequirements, CpuSamplingSpec, CpuSamplingValidationResult, CpuStackFrame, CpuStackGroup, CpuStackRecord, CpuSymbolizationSummary, PythonSymbolizationStatus, }; -pub use discover::{CudaProcessCandidate, DiscoveryResult}; +pub use discover::{CudaProcessCandidate, DiscoveryResult, ProcfsCudaHint}; pub use error::{ErrorCode, ErrorResponse, XprobeError}; pub use event::{ ActivityBoundary, ArgumentValue, CUDA_LAUNCH_APIS, CUDA_RECORD_NAME_MAX_BYTES, ClockDomain, From 087ffec49175278d1c2607db7abde972cf98c66c Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:29:13 +0800 Subject: [PATCH 11/22] =?UTF-8?q?=F0=9F=90=9B=20fix:=20measure=20triage=20?= =?UTF-8?q?thread=20and=20cgroup=20time=20over=20the=20requested=20window?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Triage read thread and cgroup counters before every source started and after the slowest finished, including attach and symbol analysis, so a 2 s triage reported a 10 s window and diluted thread shares. The counters now span exactly --duration-ms in their own thread; window_ms is that window and the new elapsed_ms is the whole command. The readable output presents findings as rule-based leads to check against the data. --- docs/cli-reference.md | 2 +- schemas/triage-result.schema.json | 10 +++- skills/xprobe-perf-profiling/SKILL.md | 2 +- .../references/data-format.md | 4 +- xprobe/cli/src/render.rs | 10 ++-- xprobe/cli/src/triage.rs | 49 +++++++++++++------ xprobe/protocol/src/triage.rs | 8 ++- xprobe/protocol/tests/contracts.rs | 1 + 8 files changed, 61 insertions(+), 25 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 029d006..e5cf918 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -235,7 +235,7 @@ Each inventory is a live mode that runs for `--duration-ms` and reports totals i - NVML device health - the CUDA kernel aggregate, which may inject CUPTI -Full inventories go to one artifact per source, and the top 5 entries of each are kept inline. Optional rule-based `findings` and `not_covered` notes are attached. Because triage includes attach and multi-collector setup around `--duration-ms`, read the actual `window_ms` (and `threads.window_ns`) rather than assuming the requested duration. A source that is unavailable or saturated is marked `unavailable` with `TRIAGE_SOURCE_UNAVAILABLE` instead of failing the run. Schema `3.0`. +Full inventories go to one artifact per source, and the top 5 entries of each are kept inline. Thread and cgroup counters span exactly `--duration-ms` (`window_ms`); every other source runs a window of the same length after its own setup, alongside, and `elapsed_ms` is the whole command. Rule-based `findings` are leads to check against the inventories, and `not_covered` lists what the triage cannot answer. A source that is unavailable or saturated is marked `unavailable` with `TRIAGE_SOURCE_UNAVAILABLE` instead of failing the run. Schema `3.0`. ### Triggered capture diff --git a/schemas/triage-result.schema.json b/schemas/triage-result.schema.json index b7f1b20..38ac4b9 100644 --- a/schemas/triage-result.schema.json +++ b/schemas/triage-result.schema.json @@ -27,8 +27,14 @@ "$ref": "#/$defs/CudaDevice" } }, + "elapsed_ms": { + "description": "The whole command, including attach, setup, and analysis.", + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "findings": { - "description": "Ranked by estimated window share; findings without an estimate last.", + "description": "Rule-based leads ranked by estimated window share, findings without an\nestimate last. Check each against the inventories before acting on it.", "type": "array", "items": { "$ref": "#/$defs/TriageFinding" @@ -107,6 +113,7 @@ } }, "window_ms": { + "description": "The window thread and cgroup counters span: `--duration-ms`. Each\nsource in `sources` runs a window of the same length after its own\nsetup, alongside.", "type": "integer", "format": "uint64", "minimum": 0 @@ -120,6 +127,7 @@ "status", "target", "window_ms", + "elapsed_ms", "findings", "threads", "cpu_hotspots", diff --git a/skills/xprobe-perf-profiling/SKILL.md b/skills/xprobe-perf-profiling/SKILL.md index 9a3eb49..e745b6d 100644 --- a/skills/xprobe-perf-profiling/SKILL.md +++ b/skills/xprobe-perf-profiling/SKILL.md @@ -24,7 +24,7 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA | Up to 8 edges in one capture | `xprobe measure --spec graph.json` | Shares one capture and 8 CUPTI filters | | Wait for rare GPU bubble / gap / spike | `xprobe measure --pid "$PID" --trigger-idle-ms 10 --pre-ms 50 --post-ms 50 --events-out spikes` | In-Agent ring; writes `window-N.events.jsonl` | | Re-correlate saved Event JSONL offline | `xprobe measure --input trace.jsonl --from A --to B --match exact` | No live attach needed | -| Same-window cgroup / thread / NVML snapshot | `xprobe measure --pid "$PID" --triage --duration-ms 2000` | Actual `window_ms` exceeds `--duration-ms` (includes attach); read raw inventories instead of static `findings` | +| Same-window cgroup / thread / NVML snapshot | `xprobe measure --pid "$PID" --triage --duration-ms 2000` | Read the raw inventories; `findings` are rule-based leads to check | ## Analyze outputs & build scripts diff --git a/skills/xprobe-perf-profiling/references/data-format.md b/skills/xprobe-perf-profiling/references/data-format.md index abf2935..b820cf6 100644 --- a/skills/xprobe-perf-profiling/references/data-format.md +++ b/skills/xprobe-perf-profiling/references/data-format.md @@ -13,7 +13,7 @@ Every `xprobe` command prints one JSON document to stdout when stdout is not a t | `--aggregate` | none (inline only) | `inventory.groups[]`, `quality`, `collection.{completeness, cuda_devices, dropped_activities, table_utilization}` | | `--cpu-sample` | `artifact.path` (CPU sample JSONL) | `inventory.{hotspots, stack_groups}`, `symbolization.python_status`, `collection` | | `--syscall-aggregate` | none (inline only) | `inventory.groups[]`, `collection` | -| `--triage` | per-source paths in `sources[]` (`artifact.path`) | `window_ms`, `sources[]`, `not_covered`, `threads`, `cgroup`, `cpu_hotspots`, `python_hotspots`, `gil_released_proportion`, `syscalls`, `gpu_activity`, `gpu_devices`, `cuda_devices`, `findings` | +| `--triage` | per-source paths in `sources[]` (`artifact.path`) | `window_ms`, `elapsed_ms`, `sources[]`, `not_covered`, `threads`, `cgroup`, `cpu_hotspots`, `python_hotspots`, `gil_released_proportion`, `syscalls`, `gpu_activity`, `gpu_devices`, `cuda_devices`, `findings` | Errors exit non-zero and print JSON (`ok: false`, `error.{code, message, details, hints}`), preserving any written artifact path in `details`. @@ -97,7 +97,7 @@ One line per sample at `result["artifact"]["path"]`: - **CPU `--cpu-sample`**: `inventory.hotspots[]` (`frame.{symbol, module_path, language, file_offset, build_id}`, `exclusive_proportion`, `inclusive_proportion`, `entry_selector_hint`, `return_selector_hint`), `inventory.stack_groups[]`, `symbolization.python_status` (`inactive`/`unsupported` means native frames only — use `--python-sample` for CPython 3.9–3.14), `collection.{completeness, lost_samples, truncated_stacks, threads_attached, threads_observed, groups, cpu_time_ns, elapsed_ns}`. Groups and hotspots give `estimated_ns` / `inclusive_estimated_ns` / `exclusive_estimated_ns` as on-CPU time. - **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`. -- **Triage `--triage`**: `window_ms` is the actual wall span (often longer than `--duration-ms` because of attach/setup), `threads` (`window_ns`, `top_threads[]`), `cgroup`, `cpu_hotspots[]`, `python_hotspots[]`, `gil_released_proportion`, `syscalls[]`, `gpu_activity[]`, `gpu_devices[]`, `cuda_devices[]`, `sources[]` (with per-source `status` and `artifact.path`), `not_covered[]`, and `findings[]` (static heuristic hints — verify against raw inventories). +- **Triage `--triage`**: `window_ms` is the `--duration-ms` window thread and cgroup counters span (each other source runs one of the same length after its own setup), `elapsed_ms` the whole command, `threads` (`window_ns`, `top_threads[]`), `cgroup`, `cpu_hotspots[]`, `python_hotspots[]`, `gil_released_proportion`, `syscalls[]`, `gpu_activity[]`, `gpu_devices[]`, `cuda_devices[]`, `sources[]` (with per-source `status` and `artifact.path`), `not_covered[]`, and `findings[]` (static heuristic hints — verify against raw inventories). ### Reading quality and collection diagnostics diff --git a/xprobe/cli/src/render.rs b/xprobe/cli/src/render.rs index 62a1deb..7382dc2 100644 --- a/xprobe/cli/src/render.rs +++ b/xprobe/cli/src/render.rs @@ -238,11 +238,15 @@ pub(crate) const fn schema_version(version: SchemaVersion) -> &'static str { pub(crate) fn print_triage_result(result: &TriageResult) { println!( - "Triage of PID {} over {} ms", - result.target.pid, result.window_ms + "Triage of PID {}: {} ms window, {} ms in total", + result.target.pid, result.window_ms, result.elapsed_ms ); if result.findings.is_empty() { - println!("No finding crossed its threshold."); + println!("No rule matched."); + } else { + println!( + "Rule-based leads; check each against the data below and the per-source artifacts before acting on it." + ); } for finding in &result.findings { let impact = finding.impact_share.map_or_else( diff --git a/xprobe/cli/src/triage.rs b/xprobe/cli/src/triage.rs index 2a5e445..55e67b2 100644 --- a/xprobe/cli/src/triage.rs +++ b/xprobe/cli/src/triage.rs @@ -129,14 +129,32 @@ fn triage(request: &TriageRequest) -> Result { .map_err(|error| inspect_failure(&error))?, None => None, }; - let cgroup_before = match &cgroup { - Some(cgroup) => Some(cgroup.counters().map_err(|error| inspect_failure(&error))?), - None => None, - }; - let threads_before = - thread_time::snapshot(request.pid).map_err(|error| inspect_failure(&error))?; let started = Instant::now(); let window = Duration::from_millis(request.duration_ms); + // Thread and cgroup counters span exactly the window; the other sources + // each run it after their own setup, alongside. + let counters = || -> Result<_, CommandFailure> { + let cgroup_before = match &cgroup { + Some(cgroup) => Some(cgroup.counters().map_err(|error| inspect_failure(&error))?), + None => None, + }; + let threads_before = + thread_time::snapshot(request.pid).map_err(|error| inspect_failure(&error))?; + let opened = Instant::now(); + thread::sleep(window); + let threads_after = + thread_time::snapshot(request.pid).map_err(|error| inspect_failure(&error))?; + let cgroup_after = match &cgroup { + Some(cgroup) => Some(cgroup.counters().map_err(|error| inspect_failure(&error))?), + None => None, + }; + Ok(( + opened.elapsed(), + threads_before, + threads_after, + cgroup_before.zip(cgroup_after), + )) + }; let python_runtime = python_layout::locate(&report); let python_artifact = artifacts.join("python-samples.jsonl"); @@ -149,7 +167,8 @@ fn triage(request: &TriageRequest) -> Result { threads_hz: None, events_out: Some(&python_artifact), }; - let (cpu, syscalls, gpu_activity, gpu_rounds, python) = thread::scope(|scope| { + let (counted, cpu, syscalls, gpu_activity, gpu_rounds, python) = thread::scope(|scope| { + let counted = scope.spawn(counters); let cpu = scope.spawn(|| { cpu_inventory( &cpu_spec(&report, request), @@ -168,6 +187,7 @@ fn triage(request: &TriageRequest) -> Result { .is_ok() .then(|| scope.spawn(|| python_sample(&python_request))); ( + counted.join(), cpu.join(), syscalls.join(), gpu_activity.map(thread::ScopedJoinHandle::join), @@ -176,12 +196,6 @@ fn triage(request: &TriageRequest) -> Result { ) }); let elapsed = started.elapsed(); - let threads_after = - thread_time::snapshot(request.pid).map_err(|error| inspect_failure(&error))?; - let cgroup_after = match &cgroup { - Some(cgroup) => Some(cgroup.counters().map_err(|error| inspect_failure(&error))?), - None => None, - }; inspect::verify_target(&target).map_err(|error| inspect_failure(&error))?; let panicked = |source: &str| { @@ -191,6 +205,8 @@ fn triage(request: &TriageRequest) -> Result { false, ) }; + let (counted_window, threads_before, threads_after, cgroup_counters) = + counted.map_err(|_| panicked("thread time"))??; let cpu = classify(cpu.map_err(|_| panicked("CPU sampling"))?)?; let syscalls = classify(syscalls.map_err(|_| panicked("syscall aggregate"))?)?; let gpu_activity = match gpu_activity { @@ -207,11 +223,11 @@ fn triage(request: &TriageRequest) -> Result { (None, Ok(_)) => unreachable!("a located CPython runtime is sampled"), }; - let window_ns = u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX); + let window_ns = u64::try_from(counted_window.as_nanos()).unwrap_or(u64::MAX); let threads = thread_time::breakdown(&threads_before, &threads_after, window_ns, TOP); let cgroup_throttling = cgroup .as_ref() - .zip(cgroup_before.zip(cgroup_after)) + .zip(cgroup_counters) .map(|(cgroup, (before, after))| cgroup_cpu::throttling(cgroup, quota, before, after)); let mut sources = vec![ @@ -383,7 +399,8 @@ fn triage(request: &TriageRequest) -> Result { session_id: format!("xp_triage_{}", std::process::id()), status: SessionStatus::Completed, target, - window_ms: u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX), + window_ms: u64::try_from(counted_window.as_millis()).unwrap_or(u64::MAX), + elapsed_ms: u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX), findings: found, threads, cgroup: cgroup_throttling, diff --git a/xprobe/protocol/src/triage.rs b/xprobe/protocol/src/triage.rs index 81ac44f..1b588e8 100644 --- a/xprobe/protocol/src/triage.rs +++ b/xprobe/protocol/src/triage.rs @@ -94,8 +94,14 @@ pub struct TriageResult { pub session_id: String, pub status: crate::SessionStatus, pub target: crate::TargetIdentity, + /// The window thread and cgroup counters span: `--duration-ms`. Each + /// source in `sources` runs a window of the same length after its own + /// setup, alongside. pub window_ms: u64, - /// Ranked by estimated window share; findings without an estimate last. + /// The whole command, including attach, setup, and analysis. + pub elapsed_ms: u64, + /// Rule-based leads ranked by estimated window share, findings without an + /// estimate last. Check each against the inventories before acting on it. pub findings: Vec, pub threads: ThreadTimeBreakdown, pub cgroup: Option, diff --git a/xprobe/protocol/tests/contracts.rs b/xprobe/protocol/tests/contracts.rs index c378266..4d4f9ce 100644 --- a/xprobe/protocol/tests/contracts.rs +++ b/xprobe/protocol/tests/contracts.rs @@ -737,6 +737,7 @@ fn triage_result_contract_round_trips() { "status": "completed", "target": {"pid": 42, "process_start_time": 9}, "window_ms": 2100, + "elapsed_ms": 2600, "findings": [ { "rank": 1, From 8ac61b8c736e16abad63b7fdcef2c8324475bab8 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:36:46 +0800 Subject: [PATCH 12/22] =?UTF-8?q?=E2=9C=A8=20feat:=20show=20what=20the=20C?= =?UTF-8?q?LI=20can=20do=20in=20its=20help=20and=20on=20stderr?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit xprobe --help named only the four commands, so a caller could not tell that measure samples Python and CPU stacks, counts syscalls and GPU work, waits on triggers, or triages. The top-level help now ends with one line per common measurement. measure --help groups its options by mode and ends with the selector syntax, the policies, and examples. A live measure prints the defaults it fell back on as `xprobe: defaults: ...` on stderr, so a sparse or truncated result points at the flag to change. Hints name the flags to adjust, and a policy error names the policy to use. --- docs/cli-reference.md | 2 + tests/agent-contract/test_contract.py | 10 +- xprobe/cli/src/args.rs | 184 ++++++++++++++++++-------- xprobe/cli/src/defaults.rs | 142 ++++++++++++++++++++ xprobe/cli/src/failure.rs | 13 +- xprobe/cli/src/live.rs | 9 +- xprobe/cli/src/main.rs | 16 ++- 7 files changed, 305 insertions(+), 71 deletions(-) create mode 100644 xprobe/cli/src/defaults.rs diff --git a/docs/cli-reference.md b/docs/cli-reference.md index e5cf918..8110d8f 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -15,6 +15,8 @@ When stdout is not a terminal, every command writes one versioned JSON document xprobe never prompts and never colors output; `--non-interactive` and `--no-color` are accepted for scripts that pass them. Diagnostics and injection warnings go to stderr. +A live `measure` first prints the defaults it used for options you did not set, as one stderr line such as `xprobe: defaults: --max-groups 256 --max-inflight 1024 --timeout-ms 30000`. `xprobe --help` lists every mode with an example; `xprobe measure --help` groups the options by mode. + | Schema version | Documents | | --- | --- | | **`3.0`** | Measurement and measurement-graph (spec, validate, result), GPU `--aggregate`, `--python-sample`, `--triage`, and `--trigger-*` results | diff --git a/tests/agent-contract/test_contract.py b/tests/agent-contract/test_contract.py index 8b71932..7809e84 100755 --- a/tests/agent-contract/test_contract.py +++ b/tests/agent-contract/test_contract.py @@ -458,11 +458,11 @@ def main() -> None: help_result = subprocess.run( [binary, "--help"], check=True, capture_output=True, text=True ) - commands = { - line.split()[0] - for line in help_result.stdout.splitlines() - if line.startswith(" ") and line.strip() and not line.lstrip().startswith("-") - } + # Subcommands are the "Commands:" section, up to the next blank line. + lines = help_result.stdout.splitlines() + start = lines.index("Commands:") + 1 + end = next((index for index in range(start, len(lines)) if not lines[index].strip()), len(lines)) + commands = {line.split()[0] for line in lines[start:end]} commands.discard("help") assert STABLE_COMMANDS == commands, {"commands": sorted(commands)} diff --git a/xprobe/cli/src/args.rs b/xprobe/cli/src/args.rs index 694cf36..ec51bba 100644 --- a/xprobe/cli/src/args.rs +++ b/xprobe/cli/src/args.rs @@ -4,8 +4,63 @@ use clap::Subcommand; use clap::ValueEnum; use std::path::PathBuf; +const TOP_HELP: &str = "Common measurements: + xprobe doctor what this host and container allow + xprobe discover --pid ROOT CUDA processes under a process tree + xprobe measure --pid PID --python-sample --duration-ms 2000 + CPython stacks and the GIL holder + xprobe measure --pid PID --cpu-sample --duration-ms 2000 + on-CPU native callchains + xprobe measure --pid PID --syscall-aggregate --duration-ms 2000 + syscall counts and durations + xprobe measure --pid PID --from cuda:kernel_start --to cuda:kernel_end \\ + --match exact --aggregate --duration-ms 2000 GPU kernel totals + xprobe measure --pid PID --from cuda:kernel_end --to cuda:kernel_start \\ + --match stream-order --duration-ms 2000 every GPU activity, gaps, idle + xprobe measure --pid PID --trigger-idle-ms 10 --events-out DIR + wait for a rare GPU idle span + xprobe measure --pid PID --triage --duration-ms 2000 + one window of every source + +`xprobe measure --help` lists selectors, policies, and every option."; + +const MEASURE_HELP: &str = "Selectors (--from / --to): + uprobe:::entry|return native function (symbol=, +0x) + syscall::entry|exit system call + tracepoint:: kernel tracepoint + python:gc_start | python:gc_end CPython garbage collection + cuda:launch_api:entry|exit any kernel launch API + cuda:runtime_api::entry|exit CUDA Runtime API (also driver_api) + cuda:kernel_start|kernel_end[:name~REGEX] kernel activity + 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 + +Policies (--match): + exact same CUPTI correlation ID, API entry/exit, activity start/end, + NVTX range, or syscall/GC lifecycle on one thread + stack-nested entry and return of one host function per thread + stream-order an activity end and the next activity on its stream + first-after the first end after each start (heuristic) + nearest the closest end to each start (heuristic) + +Examples: + xprobe measure --pid 4242 --from cuda:launch_api:exit --to cuda:kernel_start \\ + --match exact --samples 200 + xprobe measure --pid 4242 --from cuda:runtime_api:cudaMemcpyAsync:entry \\ + --to cuda:memcpy_start --match exact --duration-ms 2000 --events-out copy.jsonl + xprobe measure --input trace.jsonl --from A --to B --match exact + xprobe measure --spec graph.json + +Live captures print the defaults they used on stderr."; + #[derive(Debug, Parser)] -#[command(name = "xprobe", version, about = "Runtime host-to-GPU latency probe")] +#[command( + name = "xprobe", + version, + about = "Live Linux CPU, Python, syscall, and CUDA profiler", + after_help = TOP_HELP +)] pub(crate) struct Cli { /// Print human-readable output even when stdout is not a terminal. #[arg(long, global = true)] @@ -69,9 +124,11 @@ pub(crate) enum Command { /// Resolve a userspace event selector against a target process. #[command(hide = true)] Resolve(ResolveArgs), - /// Validate two event selectors and their correlation policy. + /// Check selectors and a policy, or a sampling mode, without attaching. Validate(ValidateArgs), - /// Measure latency between two events in files or a running process. + /// Profile a running process or saved captures: event latency, GPU + /// activity, CPU and Python samples, syscalls, triggers, and triage. + #[command(after_help = MEASURE_HELP)] Measure(Box), /// Run a live measurement from a versioned specification. #[command(hide = true)] @@ -271,23 +328,25 @@ pub(crate) struct ValidateArgs { )] pub(crate) spec: Option, - /// Start event selector. + /// Start event selector, e.g. `cuda:launch_api:exit`; `xprobe measure + /// --help` lists them. #[arg(long)] pub(crate) from: Option, - /// End event selector. + /// End event selector, e.g. `cuda:kernel_start:name~gemm`. #[arg(long)] pub(crate) to: Option, - /// Correlation policy. + /// Correlation policy: exact, stack-nested, stream-order, first-after, + /// or nearest. #[arg(long = "match")] pub(crate) match_policy: Option, - /// Validate bounded PID-scoped CPU sampling instead of an event pair. + /// Check CPU sampling of the target instead of an event pair. #[arg(long, conflicts_with_all = ["from", "to", "match_policy", "syscall_aggregate"])] pub(crate) cpu_sample: bool, - /// Validate bounded PID-scoped syscall aggregation instead of an event pair. + /// Check syscall totals of the target instead of an event pair. #[arg(long, conflicts_with_all = ["from", "to", "match_policy", "cpu_sample"])] pub(crate) syscall_aggregate: bool, @@ -301,36 +360,37 @@ pub(crate) struct ValidateArgs { reason = "mutually exclusive clap mode flags with declared conflicts" )] pub(crate) struct MeasureArgs { - /// Versioned measurement JSON for a live target. - #[arg(long, conflicts_with_all = ["input", "pid", "from", "to", "match_policy", "cpu_sample", "syscall_aggregate", "samples", "duration_ms", "timeout_ms", "max_events", "frequency_hz", "stack_depth", "max_threads", "max_inflight", "aggregate", "max_groups", "name"])] + /// Versioned measurement or graph JSON for a live target. + #[arg(help_heading = "Target and input", long, conflicts_with_all = ["input", "pid", "from", "to", "match_policy", "cpu_sample", "syscall_aggregate", "samples", "duration_ms", "timeout_ms", "max_events", "frequency_hz", "stack_depth", "max_threads", "max_inflight", "aggregate", "max_groups", "name"])] pub(crate) spec: Option, /// Completed CUPTI binary, host capture JSON, or Event JSONL; repeat to merge. - #[arg(long)] + #[arg(help_heading = "Target and input", long)] pub(crate) input: Vec, /// Collect from a running target process instead of completed capture files. - #[arg(long)] + #[arg(help_heading = "Target and input", long)] pub(crate) pid: Option, /// Unix socket exposed by the target's xprobe CUPTI agent. #[arg(long, hide = true)] pub(crate) cupti_socket: Option, - /// CUPTI agent shared object used for automatic online injection. - #[arg(long)] + /// CUPTI Agent to inject; by default the one installed with xprobe. + #[arg(help_heading = "Target and input", long)] pub(crate) agent: Option, - /// Write the complete bounded event capture to this file. Live captures - /// default to a private file under the temporary directory. - #[arg(long)] + /// Where to write the capture: Event JSONL, the samples of --cpu-sample + /// and --python-sample, or a directory of trigger windows. Defaults to a + /// private temporary file. + #[arg(help_heading = "Output", long)] pub(crate) events_out: Option, - /// 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. + /// One window of thread time, cgroup throttling, CPU and Python + /// samples, syscall totals, GPU health, and kernel totals, with + /// rule-based leads to check. Requires --pid and --duration-ms. #[arg( + help_heading = "Triage", long, requires_all = ["pid", "duration_ms"], conflicts_with_all = [ @@ -343,6 +403,7 @@ pub(crate) struct MeasureArgs { /// Inline matched pairs: `summary` keeps rank exemplars and the artifact /// path; `full` also inlines every pair. #[arg( + help_heading = "Output", long, value_enum, default_value_t = EvidenceArg::Summary, @@ -351,48 +412,51 @@ pub(crate) struct MeasureArgs { pub(crate) evidence: EvidenceArg, /// Evidence event format; defaults to jsonl when --events-out is set. - #[arg(long, value_enum)] + #[arg(help_heading = "Output", long, value_enum)] pub(crate) format: Option, - /// Bound foreground collection and cleanup to this many milliseconds. - #[arg(long, default_value_t = 30_000)] + /// Give up and clean up after this many milliseconds. + #[arg(help_heading = "Limits", long, default_value_t = 30_000)] pub(crate) timeout_ms: u64, - /// Start event selector. - #[arg(long)] + /// Start event selector; see Selectors below. + #[arg(help_heading = "Event pairs", long)] pub(crate) from: Option, - /// End event selector. - #[arg(long)] + /// End event selector; see Selectors below. + #[arg(help_heading = "Event pairs", long)] pub(crate) to: Option, - /// Correlation policy. - #[arg(long = "match")] + /// Correlation policy; see Policies below. + #[arg(help_heading = "Event pairs", long = "match")] pub(crate) match_policy: Option, - /// Sample PID-scoped CPU callchains; writes every timestamped sample to - /// --events-out (JSONL) and lists the heaviest stacks and hotspots. - #[arg(long, conflicts_with_all = ["input", "from", "to", "match_policy", "samples", "aggregate", "format", "cupti_socket", "agent"])] + /// Sample the target's on-CPU callchains with perf; writes every sample + /// with its time to --events-out and lists the heaviest stacks. + #[arg(help_heading = "CPU sampling", long, conflicts_with_all = ["input", "from", "to", "match_policy", "samples", "aggregate", "format", "cupti_socket", "agent"])] pub(crate) cpu_sample: bool, - /// Target CPU sampling frequency in hertz. + /// Samples per second of each thread's on-CPU time [default: 999]. #[arg( + help_heading = "CPU sampling", long, requires = "cpu_sample", default_value_if("cpu_sample", "true", "999") )] pub(crate) frequency_hz: Option, - /// Bound user-space callchain depth. + /// Deepest callchain kept [default: 64]. #[arg( + help_heading = "CPU sampling", long, requires = "cpu_sample", default_value_if("cpu_sample", "true", "64") )] pub(crate) stack_depth: Option, - /// Bound target threads attached by CPU sampling. + /// Most target threads sampled [default: 1024]. #[arg( + help_heading = "CPU sampling", long, requires = "cpu_sample", default_value_if("cpu_sample", "true", "1024") @@ -404,6 +468,7 @@ pub(crate) struct MeasureArgs { /// --python-threads-hz. Needs ptrace access to the target; requires /// --pid and --duration-ms. #[arg( + help_heading = "Python sampling", long, requires_all = ["pid", "duration_ms"], conflicts_with_all = [ @@ -415,45 +480,56 @@ pub(crate) struct MeasureArgs { /// Samples per second of the thread holding the GIL; 0 samples only the /// all-thread sweeps. - #[arg(long, requires = "python_sample", default_value_t = 999)] + #[arg( + help_heading = "Python sampling", + long, + requires = "python_sample", + default_value_t = 999 + )] pub(crate) python_hz: u32, /// Sweeps per second over every Python thread; 0 turns them off. By /// default sweeps run up to 100 times a second and slow down when the /// threads would take more than 6,400 stack reads a second. - #[arg(long, requires = "python_sample")] + #[arg(help_heading = "Python sampling", long, requires = "python_sample")] pub(crate) python_threads_hz: Option, - /// 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"])] + /// Count each system call and its duration in BPF maps; needs eBPF. + #[arg(help_heading = "Syscall totals", long, conflicts_with_all = ["input", "from", "to", "match_policy", "samples", "cpu_sample", "aggregate", "events_out", "format", "cupti_socket", "agent"])] pub(crate) syscall_aggregate: bool, - /// Bound concurrent syscall lifecycle starts retained in BPF. + /// System calls in progress at once that BPF tracks [default: 1024]. #[arg( + help_heading = "Syscall totals", long, requires = "syscall_aggregate", default_value_if("syscall_aggregate", "true", "1024") )] pub(crate) max_inflight: Option, - /// Stop after this many matched samples. - #[arg(long)] + /// Stop after this many matched pairs. + #[arg(help_heading = "Limits", long)] pub(crate) samples: Option, - /// Restrict events to this many milliseconds from the first selected event. - #[arg(long)] + /// Collect for this many milliseconds; offline, keep this long after the + /// first selected event. + #[arg(help_heading = "Limits", long)] pub(crate) duration_ms: Option, - /// Reject captures containing more events than this limit. - #[arg(long, default_value_t = 100_000)] + /// Records a live capture holds; a duration capture that fills it fails + /// with `EVENT_RATE_TOO_HIGH`, and a trigger keeps the newest this many. + #[arg(help_heading = "Limits", long, default_value_t = 100_000)] pub(crate) max_events: usize, - /// Return bounded activity aggregates instead of exact event evidence. - #[arg(long, conflicts_with_all = ["input", "samples", "events_out", "format"])] + /// Count matching kernels, copies, or memsets in the Agent instead of + /// recording each one. + #[arg(help_heading = "Event pairs", long, conflicts_with_all = ["input", "samples", "events_out", "format"])] pub(crate) aggregate: bool, - /// Bound distinct groups retained by aggregate or CPU inventory mode. + /// Groups kept by --aggregate (4096) and --syscall-aggregate (256), or + /// listed by --cpu-sample (256). #[arg( + help_heading = "Limits", long, default_value_if("aggregate", "true", "4096"), default_value_if("cpu_sample", "true", "256"), @@ -462,16 +538,16 @@ pub(crate) struct MeasureArgs { pub(crate) max_groups: Option, /// Optional measurement name. - #[arg(long)] + #[arg(help_heading = "Output", long)] pub(crate) name: Option, - #[command(flatten)] + #[command(flatten, next_help_heading = "Triggers")] pub(crate) trigger: TriggerArgs, - #[command(flatten)] + #[command(flatten, next_help_heading = "Triggers")] pub(crate) trigger_window: TriggerWindowArgs, - #[command(flatten)] + #[command(flatten, next_help_heading = "Output")] pub(crate) output: CommonOutputArgs, } diff --git a/xprobe/cli/src/defaults.rs b/xprobe/cli/src/defaults.rs new file mode 100644 index 0000000..b3ce8fc --- /dev/null +++ b/xprobe/cli/src/defaults.rs @@ -0,0 +1,142 @@ +//! The defaults a live `measure` falls back on, printed to stderr so a +//! caller sees which limits and rates shaped the result. + +use clap::ArgMatches; +use clap::parser::ValueSource; + +/// Options each live mode uses, in the order they are printed. +fn mode_options(matches: &ArgMatches) -> &'static [&'static str] { + let set = |id: &str| matches.get_flag(id); + let trigger = [ + "trigger_gap_ms", + "trigger_idle_ms", + "trigger_duration_ms", + "trigger_latency_ms", + ] + .iter() + .any(|id| matches.value_source(id).is_some()); + if set("triage") { + &["timeout_ms"] + } else if set("python_sample") { + &["python_hz"] + } else if set("cpu_sample") { + &[ + "frequency_hz", + "max_groups", + "stack_depth", + "max_threads", + "timeout_ms", + ] + } else if set("syscall_aggregate") { + &["max_groups", "max_inflight", "timeout_ms"] + } else if set("aggregate") { + &["max_groups", "timeout_ms"] + } else if trigger { + &["pre_ms", "post_ms", "windows", "max_events", "timeout_ms"] + } else { + &["evidence", "max_events", "timeout_ms"] + } +} + +/// `xprobe: defaults: ...` for the options of a live `measure` that the +/// caller left unset, or `None` when it set them all or reads saved files. +pub(crate) fn line(matches: &ArgMatches) -> Option { + let live = matches.value_source("pid").is_some() && matches.value_source("spec").is_none(); + if !live { + return None; + } + let mut parts = mode_options(matches) + .iter() + .filter(|id| matches.value_source(id) == Some(ValueSource::DefaultValue)) + .filter_map(|id| { + let value = matches.get_raw(id)?.next()?.to_string_lossy().into_owned(); + Some(format!("--{} {value}", id.replace('_', "-"))) + }) + .collect::>(); + if matches.get_flag("python_sample") && matches.value_source("python_threads_hz").is_none() { + parts.push( + "--python-threads-hz auto (up to 100 sweeps/s within 6,400 stack reads/s)".to_owned(), + ); + } + (!parts.is_empty()).then(|| format!("xprobe: defaults: {}", parts.join(" "))) +} + +#[cfg(test)] +mod tests { + use clap::CommandFactory; + + use crate::args::Cli; + + fn line(arguments: &[&str]) -> Option { + let matches = Cli::command().try_get_matches_from(arguments).unwrap(); + super::line(matches.subcommand_matches("measure").unwrap()) + } + + #[test] + fn lists_only_the_defaults_a_live_mode_uses() { + assert_eq!( + line(&["xprobe", "measure", "--pid", "1", "--cpu-sample", "--duration-ms", "500", "--max-groups", "64"]), + Some( + "xprobe: defaults: --frequency-hz 999 --stack-depth 64 --max-threads 1024 --timeout-ms 30000" + .to_owned() + ) + ); + assert_eq!( + line(&["xprobe", "measure", "--pid", "1", "--python-sample", "--duration-ms", "500"]), + Some( + "xprobe: defaults: --python-hz 999 --python-threads-hz auto (up to 100 sweeps/s within 6,400 stack reads/s)" + .to_owned() + ) + ); + assert_eq!( + line(&[ + "xprobe", + "measure", + "--pid", + "1", + "--trigger-idle-ms", + "5", + "--windows", + "2" + ]), + Some( + "xprobe: defaults: --pre-ms 50 --post-ms 50 --max-events 100000 --timeout-ms 30000" + .to_owned() + ) + ); + } + + #[test] + fn stays_quiet_offline_and_when_every_option_is_set() { + assert_eq!( + line(&[ + "xprobe", "measure", "--input", "a.jsonl", "--from", "a", "--to", "b", "--match", + "exact" + ]), + None + ); + assert_eq!( + line(&[ + "xprobe", + "measure", + "--pid", + "1", + "--from", + "a", + "--to", + "b", + "--match", + "exact", + "--samples", + "5", + "--evidence", + "full", + "--max-events", + "10", + "--timeout-ms", + "100", + ]), + None + ); + } +} diff --git a/xprobe/cli/src/failure.rs b/xprobe/cli/src/failure.rs index 9bf81cc..a84a991 100644 --- a/xprobe/cli/src/failure.rs +++ b/xprobe/cli/src/failure.rs @@ -79,23 +79,24 @@ pub(crate) fn measurement_failure( failure = failure.with_hint("run xprobe validate with the exact selector text"); } MeasureError::InvalidPolicy(_) => { - failure = failure - .with_hint("use policy_recommendation.compatible_policies from xprobe validate"); + failure = + failure.with_hint("pick --match from policy_recommendation in xprobe validate"); } MeasureError::InvalidLimit(_) => { - failure = failure - .with_hint("set positive samples or duration, timeout, and max-events bounds"); + failure = failure.with_hint( + "set a positive --samples or --duration-ms, --timeout-ms, and --max-events", + ); } MeasureError::EventLimitExceeded { actual, maximum } => { failure = failure .with_detail("observed_events", *actual as u64) .with_detail("max_events", *maximum as u64) - .with_hint("narrow the selectors or explicitly increase max-events"); + .with_hint("narrow --from/--to, shorten --duration-ms, or raise --max-events"); } MeasureError::EventsDropped { count } => { failure = failure .with_detail("dropped_events", *count) - .with_hint("reduce the event rate or explicitly increase the capture capacity"); + .with_hint("shorten --duration-ms or raise --max-events"); } MeasureError::ClockDomainsDiffer { start, end } => { failure = failure diff --git a/xprobe/cli/src/live.rs b/xprobe/cli/src/live.rs index 09ab928..0a330e9 100644 --- a/xprobe/cli/src/live.rs +++ b/xprobe/cli/src/live.rs @@ -461,7 +461,10 @@ pub(crate) fn single_edge_plan(request: &LiveMeasureRequest) -> Result ExitCode { - let mut cli = Cli::parse(); + let matches = Cli::command().get_matches(); + let mut cli = Cli::from_arg_matches(&matches).unwrap_or_else(|error| error.exit()); if let Err(message) = cli.resolve_output(io::stdout().is_terminal()) { Cli::command() .error(clap::error::ErrorKind::ArgumentConflict, message) @@ -67,7 +69,15 @@ fn main() -> ExitCode { Command::Inspect(args) => run_inspect(args), Command::Resolve(args) => run_resolve(args), Command::Validate(args) => run_validate(args), - Command::Measure(args) => run_measure(*args), + Command::Measure(args) => { + if let Some(line) = matches + .subcommand_matches("measure") + .and_then(defaults::line) + { + eprintln!("{line}"); + } + run_measure(*args) + } Command::Trace(args) => run_trace(args), Command::Export(args) => run_export(args), Command::Capture(args) | Command::Dev(args) => run_capture(args), From d8ad82bfe333b19a6b25a19ab3db175baf621527 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:37:01 +0800 Subject: [PATCH 13/22] =?UTF-8?q?=F0=9F=90=9B=20fix:=20count=20/dev/nvidia?= =?UTF-8?q?0=20and=20other=20NVIDIA=20devices=20in=20discover=20hints?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- xprobe/core/src/discover.rs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/xprobe/core/src/discover.rs b/xprobe/core/src/discover.rs index 787ff7b..d8adf4c 100644 --- a/xprobe/core/src/discover.rs +++ b/xprobe/core/src/discover.rs @@ -203,6 +203,15 @@ fn procfs_hints(root: u32) -> Result, DiscoverError> { Ok(hints) } +/// Whether an open file is an NVIDIA device: `/dev/nvidia0`, +/// `/dev/nvidiactl`, `/dev/nvidia-uvm`, and the like. The prefix is a name +/// prefix, not a path component. +fn nvidia_device(target: &Path) -> bool { + target + .to_str() + .is_some_and(|path| path.starts_with("/dev/nvidia")) +} + /// Whether a `/proc//maps` text maps a `libcuda.so`. fn maps_libcuda(maps: &str) -> bool { maps.lines().any(|line| { @@ -222,7 +231,7 @@ fn cuda_evidence(pid: u32) -> Option<(bool, Option)> { let fds = fs::read_dir(format!("/proc/{pid}/fd")).ok().map(|entries| { let count = entries .filter_map(|entry| fs::read_link(entry.ok()?.path()).ok()) - .filter(|target| target.starts_with("/dev/nvidia")) + .filter(|target| nvidia_device(target)) .count(); u32::try_from(count).unwrap_or(u32::MAX) }); @@ -341,10 +350,24 @@ mod tests { use crate::inspect::InspectError; use super::{ - Ancestry, DiscoverError, ancestry, maps_libcuda, parse_compute_processes, + Ancestry, DiscoverError, ancestry, maps_libcuda, nvidia_device, parse_compute_processes, unavailable_warning, }; + #[test] + fn nvidia_devices_match_by_name_prefix() { + for device in [ + "/dev/nvidia0", + "/dev/nvidiactl", + "/dev/nvidia-uvm", + "/dev/nvidia-caps/nvidia-cap1", + ] { + assert!(nvidia_device(std::path::Path::new(device)), "{device}"); + } + assert!(!nvidia_device(std::path::Path::new("/dev/null"))); + assert!(!nvidia_device(std::path::Path::new("/tmp/dev/nvidia0"))); + } + #[test] fn procfs_hints_find_a_descendant_that_maps_libcuda() { let directory = From 298f4cff558134de474a76fa2eee4e4581483fe7 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:37:51 +0800 Subject: [PATCH 14/22] =?UTF-8?q?=F0=9F=90=9B=20fix:=20claim=20the=20Agent?= =?UTF-8?q?=20before=20restarting=20it=20and=20subscribe=20for=20activity?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A start checked for a live session and then restarted the Agent, so a second measure could pass the check before the first sent ARM and then close its socket. The check now also claims the Agent; while it restarts, every command, including another start, is busy. Captures of GPU activity alone registered CUPTI activity callbacks without subscribing, so on a process torch.profiler or Nsight was profiling they replaced that tool's buffer callbacks instead of reporting the conflict. Every capture now subscribes first and fails with the conflict. --- cupti/src/cupti_agent.c | 42 +++++++++++++++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/cupti/src/cupti_agent.c b/cupti/src/cupti_agent.c index b0ad6d9..daae20a 100644 --- a/cupti/src/cupti_agent.c +++ b/cupti/src/cupti_agent.c @@ -191,6 +191,9 @@ static char snapshot_socket_path[sizeof(((struct sockaddr_un *)0)->sun_path)]; * owner's PID is not visible from the target. Guarded by flush_mutex. */ static pid_t owner_pid; static unsigned long long owner_start_time; +/* A start is closing and reopening the control socket. Guarded by + * flush_mutex. */ +static int restarting; static pthread_mutex_t flush_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t subscriber_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_t snapshot_thread; @@ -2411,6 +2414,9 @@ static int owned_by_another_session(pid_t pid, unsigned long long start_time) { unsigned long long current; + if (restarting != 0) { + return 1; + } if (owner_pid == 0 || (owner_pid == pid && owner_start_time == start_time)) { return 0; } @@ -3020,10 +3026,11 @@ static int activate_capture(void) XPROBE_CUPTI_AGENT_READY) { return XPROBE_CUPTI_AGENT_OUTPUT_ERROR; } - if (needs_runtime != 0 || needs_driver != 0 || needs_nvtx != 0) { - if (ensure_subscriber() != XPROBE_CUPTI_AGENT_READY) { - return XPROBE_CUPTI_AGENT_CUPTI_ERROR; - } + /* Subscribe even for activity alone: CUPTI allows one subscriber, so + * this fails on a process another tool (torch.profiler, Nsight) is + * profiling, before its activity buffer callbacks would be replaced. */ + if (ensure_subscriber() != XPROBE_CUPTI_AGENT_READY) { + return XPROBE_CUPTI_AGENT_CUPTI_ERROR; } if (needs_activities != 0) { #if CUPTI_API_VERSION < 130000 @@ -3133,19 +3140,25 @@ static void finalize_agent(void) } } +static int restart_agent(const char *configured_socket, uint64_t capacity); + int xprobe_cupti_agent_start(const char *configured_socket, uint64_t capacity) { - size_t length; int busy; + int status; /* Restarting would close the socket and drop the capture of a session * that is still running. The caller is not a socket peer, so any live - * owner makes the Agent busy. */ + * owner makes the Agent busy. The check and the claim are one step: + * while restarting, every command, including another start, is busy. */ if (pthread_mutex_lock(&flush_mutex) != 0) { remember_output_error(); return XPROBE_CUPTI_AGENT_OUTPUT_ERROR; } busy = owned_by_another_session(0, 0U); + if (busy == 0) { + restarting = 1; + } if (pthread_mutex_unlock(&flush_mutex) != 0) { remember_output_error(); return XPROBE_CUPTI_AGENT_OUTPUT_ERROR; @@ -3153,6 +3166,23 @@ int xprobe_cupti_agent_start(const char *configured_socket, uint64_t capacity) if (busy != 0) { return XPROBE_CUPTI_AGENT_BUSY; } + status = restart_agent(configured_socket, capacity); + if (pthread_mutex_lock(&flush_mutex) != 0) { + remember_output_error(); + return XPROBE_CUPTI_AGENT_OUTPUT_ERROR; + } + restarting = 0; + if (pthread_mutex_unlock(&flush_mutex) != 0) { + remember_output_error(); + return XPROBE_CUPTI_AGENT_OUTPUT_ERROR; + } + return status; +} + +static int restart_agent(const char *configured_socket, uint64_t capacity) +{ + size_t length; + stop_snapshot_server(); if (shutdown_agent() != XPROBE_CUPTI_AGENT_READY) { return xprobe_cupti_agent_status(); From fa1bae9e8b69e87db47e84243475ab62ec4458d1 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:38:20 +0800 Subject: [PATCH 15/22] =?UTF-8?q?=F0=9F=90=9B=20fix:=20pair=20CUDA=20API?= =?UTF-8?q?=20and=20GPU=20activity=20without=20requiring=20the=20same=20co?= =?UTF-8?q?ntext?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- xprobe/correlator/src/lib.rs | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/xprobe/correlator/src/lib.rs b/xprobe/correlator/src/lib.rs index a9d1ce0..2df69b7 100644 --- a/xprobe/correlator/src/lib.rs +++ b/xprobe/correlator/src/lib.rs @@ -1653,11 +1653,9 @@ fn stream_key(event: &Event) -> Option { #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] enum CorrelationKey { - Cuda { - pid: u32, - context_id: u32, - correlation_id: u32, - }, + /// CUPTI correlation IDs are unique within a process. The context is + /// left out: an API call that creates its thread's context reports none. + Cuda { pid: u32, correlation_id: u32 }, Nvtx { pid: u32, range_kind: NvtxRangeKind, @@ -1676,7 +1674,6 @@ fn correlation_key(event: &Event) -> Option { let cuda = event.cuda.as_ref()?; Some(CorrelationKey::Cuda { pid: event.pid, - context_id: cuda.context_id?, correlation_id: cuda.correlation_id?, }) } @@ -1904,6 +1901,17 @@ mod tests { assert_eq!(result.correlation.method, "exact_cupti_correlation_id"); } + #[test] + fn exact_matching_ignores_a_context_the_api_call_did_not_report() { + // The first API call on a thread creates its context, so CUPTI + // reports none for it; the kernel it launched has one. + let mut start = event(EventType::GpuKernelStart, 100, 3); + start.cuda.as_mut().unwrap().context_id = None; + let end = event(EventType::GpuKernelEnd, 150, 3); + let result = measure(&[start, end], &options(MatchPolicy::Exact)).unwrap(); + assert_eq!(result.measurement.samples.matched, 1); + } + #[test] fn exact_matching_pairs_reused_ids_in_timestamp_order() { let events = vec![ From 29dd34121690eee1b27fe51c3ff4097de66259de Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:40:23 +0800 Subject: [PATCH 16/22] =?UTF-8?q?=F0=9F=90=9B=20fix:=20weight=20each=20Pyt?= =?UTF-8?q?hon=20sweep=20sample=20by=20its=20own=20sweep's=20interval?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sweeps slow down as threads are added, but estimated_ns gave every sweep sample the run's average interval, so time before a thread pool grew was overstated and time after it understated. The sampler records when each sweep starts, and a sweep sample now counts the interval until the next sweep, or the end of the run. --- docs/cli-reference.md | 2 +- schemas/python-sample-result.schema.json | 4 +- xprobe/collector/src/python_sampling.rs | 28 +++- xprobe/core/src/python_sampling.rs | 168 +++++++++++++++++++---- xprobe/protocol/src/python_sampling.rs | 10 +- 5 files changed, 167 insertions(+), 45 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 8110d8f..9929339 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -217,7 +217,7 @@ Each inventory is a live mode that runs for `--duration-ms` and reports totals i - For blocked threads it reports native waits from `/proc//task//syscall`. - Every sample is written with its `CLOCK_MONOTONIC` time to a JSONL artifact (`schemas/python-sample-record.schema.json`). - Frames report `first_line`, the line where the function starts, not the current line. -- Every stack group, hotspot, and native wait has `estimated_ns`: samples times the average GIL tick (wall time of the GIL holder) or sweep interval (thread time summed over threads). +- Every stack group, hotspot, and native wait has `estimated_ns`. A GIL sample counts one average GIL tick (wall time of the GIL holder); a sweep sample counts the interval of its own sweep (thread time summed over threads). **`--syscall-aggregate`** filters by PID in BPF maps sized by `--max-inflight` and `--max-groups`. It reports each syscall's count, errors, min, mean, max, and total duration, with selector hints. It records no per-call events and no pointer values. diff --git a/schemas/python-sample-result.schema.json b/schemas/python-sample-result.schema.json index 13c6d78..1f82a97 100644 --- a/schemas/python-sample-result.schema.json +++ b/schemas/python-sample-result.schema.json @@ -216,7 +216,7 @@ "type": "object", "properties": { "estimated_ns": { - "description": "Thread time spent here, summed over threads: samples times the\naverage sweep interval.", + "description": "Thread time spent here, summed over threads: each sample counts its\nown sweep's interval.", "type": "integer", "format": "uint64", "minimum": 0 @@ -462,7 +462,7 @@ "type": "object", "properties": { "estimated_ns": { - "description": "Time in this stack: samples times the average GIL tick (GIL groups,\nwall time) or sweep interval (thread groups, thread time summed over\nthreads).", + "description": "Time in this stack: each GIL sample counts one average GIL tick (wall\ntime); each sweep sample counts its own sweep's interval (thread time\nsummed over threads).", "type": "integer", "format": "uint64", "minimum": 0 diff --git a/xprobe/collector/src/python_sampling.rs b/xprobe/collector/src/python_sampling.rs index 2411d2f..1bac22d 100644 --- a/xprobe/collector/src/python_sampling.rs +++ b/xprobe/collector/src/python_sampling.rs @@ -847,7 +847,12 @@ impl Run<'_, '_, M> { /// 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> { + fn read( + &mut self, + thread: u64, + gil: Option, + sweep: Option, + ) -> Result<(), SamplerError> { let timestamp_ns = monotonic_ns()?; let started = Instant::now(); let outcome = self.consistent_stack(thread, gil); @@ -879,6 +884,7 @@ impl Run<'_, '_, M> { tid, gil: gil.is_some(), stack, + sweep, native, }); Ok(()) @@ -960,9 +966,11 @@ impl Run<'_, '_, M> { .map_or(TidSource::Unmapped, TidSource::Pthread); } self.capture.counters.thread_sweeps += 1; + let sweep = u32::try_from(self.capture.sweeps.len()).unwrap_or(u32::MAX); + self.capture.sweeps.push(monotonic_ns()?); let count = threads.len(); for thread in threads { - self.read(thread, None)?; + self.read(thread, None, Some(sweep))?; } Ok(count) } @@ -993,6 +1001,8 @@ pub fn sample( capture: PythonCapture { samples: Vec::new(), stacks: Vec::new(), + sweeps: Vec::new(), + end_ns: 0, codes: Vec::new(), counters: SamplerCounters::default(), read_times: ReadTimes::default(), @@ -1033,7 +1043,7 @@ pub fn sample( holder: Some(holder), .. }, - ) => run.read(holder, Some(state))?, + ) => run.read(holder, Some(state), None)?, Ok(GilState { holder: None, .. }) => run.capture.counters.gil_idle += 1, Err(ReadError::Fault) => run.capture.counters.inconsistent += 1, Err(error) => { @@ -1056,6 +1066,7 @@ pub fn sample( } let mut capture = run.capture; capture.elapsed = start.elapsed(); + capture.end_ns = monotonic_ns()?; capture.codes = std::mem::take(&mut run.walker.codes); Ok(capture) } @@ -1284,6 +1295,8 @@ mod tests { capture: xprobe_core::python_sampling::PythonCapture { samples: Vec::new(), stacks: Vec::new(), + sweeps: Vec::new(), + end_ns: 0, codes: Vec::new(), counters: xprobe_core::python_sampling::SamplerCounters::default(), read_times: super::ReadTimes::default(), @@ -1301,8 +1314,8 @@ mod tests { let memory = python_312(); let mut walker = Walker::new(&memory, runtime(12), 64); let mut run = run(&mut walker); - run.read(0x3000, None).unwrap(); - run.read(0x3000, None).unwrap(); + run.read(0x3000, None, None).unwrap(); + run.read(0x3000, None, None).unwrap(); assert_eq!(run.capture.samples.len(), 2); assert_eq!(run.capture.stacks.len(), 1); assert_eq!(run.capture.samples[1].stack, run.capture.samples[0].stack); @@ -1337,13 +1350,13 @@ mod tests { 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(); + run.read(0x3000, Some(before), None).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(); + run.read(0x3000, Some(before), None).unwrap(); assert_eq!(run.capture.samples.len(), 2); // The GIL went to another thread and came back during the read. @@ -1353,6 +1366,7 @@ mod tests { switches: 3, ..before }), + None, ) .unwrap(); assert_eq!(run.capture.samples.len(), 2); diff --git a/xprobe/core/src/python_sampling.rs b/xprobe/core/src/python_sampling.rs index 11ad5ca..812f340 100644 --- a/xprobe/core/src/python_sampling.rs +++ b/xprobe/core/src/python_sampling.rs @@ -41,6 +41,9 @@ pub struct PythonSample { pub gil: bool, /// Index into [`PythonCapture::stacks`]. pub stack: u32, + /// The sweep it was taken in, an index into [`PythonCapture::sweeps`]; + /// `None` for a GIL sample. + pub sweep: Option, /// Where a blocked thread waits in native code (sweep samples only). pub native: Option, } @@ -148,6 +151,10 @@ pub struct PythonCapture { pub samples: Vec, /// Distinct stacks, which samples index. pub stacks: Vec, + /// `CLOCK_MONOTONIC` start of each sweep of every thread. + pub sweeps: Vec, + /// `CLOCK_MONOTONIC` end of the run. + pub end_ns: u64, pub codes: Vec, pub counters: SamplerCounters, /// Wall time of the kept stack reads. @@ -233,11 +240,53 @@ fn estimate(samples: u64, sample_ns: f64) -> u64 { (samples as f64 * sample_ns).round() as u64 } -/// How a list's proportions and time estimates are computed. +/// How a list's proportions and time estimates are computed. A GIL sample +/// stands for one average tick; a sweep sample for its own sweep's interval, +/// since sweeps slow down as threads are added. #[derive(Clone, Copy)] -struct Scale { +struct Scale<'s> { total: u64, - sample_ns: f64, + gil_ns: f64, + sweep_ns: &'s [f64], +} + +impl Scale<'_> { + fn weight(&self, sample: &PythonSample) -> f64 { + sample + .sweep + .and_then(|sweep| self.sweep_ns.get(sweep as usize).copied()) + .unwrap_or(self.gil_ns) + } +} + +/// Each sweep's interval: until the next sweep starts, or the run ends. +#[allow( + clippy::cast_precision_loss, + reason = "nanosecond intervals stay far below 2^52" +)] +fn sweep_intervals(capture: &PythonCapture) -> Vec { + capture + .sweeps + .iter() + .enumerate() + .map(|(index, start)| { + let next = capture + .sweeps + .get(index + 1) + .copied() + .unwrap_or(capture.end_ns); + next.saturating_sub(*start) as f64 + }) + .collect() +} + +#[allow( + clippy::cast_possible_truncation, + clippy::cast_sign_loss, + reason = "estimates are rounded nonnegative nanoseconds" +)] +fn rounded(ns: f64) -> u64 { + ns.round() as u64 } fn groups<'a>( @@ -245,22 +294,24 @@ fn groups<'a>( capture: &PythonCapture, scale: Scale, ) -> Vec { - let mut counts = BTreeMap::<&[u32], u64>::new(); + let mut counts = BTreeMap::<&[u32], (u64, f64)>::new(); for sample in samples { - *counts + let entry = counts .entry(capture.stacks[sample.stack as usize].frames.as_slice()) - .or_default() += 1; + .or_default(); + entry.0 += 1; + entry.1 += scale.weight(sample); } let mut groups = counts .into_iter() - .map(|(frames, samples)| PythonStackGroup { + .map(|(frames, (samples, ns))| PythonStackGroup { frames: frames .iter() .map(|index| frame(&capture.codes, *index)) .collect(), samples, proportion: ratio(samples, scale.total), - estimated_ns: estimate(samples, scale.sample_ns), + estimated_ns: rounded(ns), }) .collect::>(); groups.sort_by(|left, right| { @@ -278,30 +329,36 @@ fn hotspots<'a>( capture: &PythonCapture, scale: Scale, ) -> Vec { - let mut inclusive = BTreeMap::::new(); - let mut exclusive = BTreeMap::::new(); + let mut inclusive = BTreeMap::::new(); + let mut exclusive = BTreeMap::::new(); for sample in samples { let frames = &capture.stacks[sample.stack as usize].frames; + let weight = scale.weight(sample); // A recursive function counts once per sample. for index in frames.iter().collect::>() { - *inclusive.entry(*index).or_default() += 1; + let entry = inclusive.entry(*index).or_default(); + entry.0 += 1; + entry.1 += weight; } if let Some(leaf) = frames.first() { - *exclusive.entry(*leaf).or_default() += 1; + let entry = exclusive.entry(*leaf).or_default(); + entry.0 += 1; + entry.1 += weight; } } let mut hotspots = inclusive .into_iter() - .map(|(index, inclusive_samples)| { - let exclusive_samples = exclusive.get(&index).copied().unwrap_or(0); + .map(|(index, (inclusive_samples, inclusive_ns))| { + let (exclusive_samples, exclusive_ns) = + exclusive.get(&index).copied().unwrap_or_default(); PythonHotspot { frame: frame(&capture.codes, index), inclusive_samples, exclusive_samples, inclusive_proportion: ratio(inclusive_samples, scale.total), exclusive_proportion: ratio(exclusive_samples, scale.total), - inclusive_estimated_ns: estimate(inclusive_samples, scale.sample_ns), - exclusive_estimated_ns: estimate(exclusive_samples, scale.sample_ns), + inclusive_estimated_ns: rounded(inclusive_ns), + exclusive_estimated_ns: rounded(exclusive_ns), } }) .collect::>(); @@ -410,13 +467,15 @@ pub fn analyze( .iter() .filter(|sample| capture.stacks[sample.stack as usize].truncated) .count() as u64; + let sweep_ns = sweep_intervals(capture); let gil_scale = Scale { total: counters.gil_ticks, - sample_ns: sample_ns(capture.elapsed, counters.gil_ticks), + gil_ns: sample_ns(capture.elapsed, counters.gil_ticks), + sweep_ns: &sweep_ns, }; let thread_scale = Scale { total: thread_samples, - sample_ns: sample_ns(capture.elapsed, counters.thread_sweeps), + ..gil_scale }; PythonSampleResult { schema_version: SchemaVersion3::current(), @@ -430,7 +489,7 @@ pub fn analyze( gil_stack_groups: groups(gil(), capture, gil_scale), gil_hotspots: hotspots(gil(), capture, gil_scale), gil_released_proportion: ratio(counters.gil_idle, counters.gil_ticks), - gil_released_estimated_ns: estimate(counters.gil_idle, gil_scale.sample_ns), + gil_released_estimated_ns: estimate(counters.gil_idle, gil_scale.gil_ns), thread_stack_groups: groups(threads(), capture, thread_scale), native_waits: native_waits(threads(), native, thread_scale), }, @@ -495,17 +554,21 @@ fn native_waits<'a>( native: &BTreeMap, scale: Scale, ) -> 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 counts = BTreeMap::::new(); + for sample in samples { + if let Some(leaf) = sample.native { + let entry = counts.entry(native_leaf(leaf, native)).or_default(); + entry.0 += 1; + entry.1 += scale.weight(sample); + } } let mut waits = counts .into_iter() - .map(|(leaf, samples)| PythonNativeWait { + .map(|(leaf, (samples, ns))| PythonNativeWait { leaf, samples, proportion: ratio(samples, scale.total), - estimated_ns: estimate(samples, scale.sample_ns), + estimated_ns: rounded(ns), }) .collect::>(); waits.sort_by(|left, right| { @@ -562,12 +625,14 @@ mod tests { Stack, TidSource, analyze, parse_task_syscall, write_records, }; + /// A GIL sample, or a sample of the first sweep. fn sample(gil: bool, stack: u32) -> PythonSample { PythonSample { timestamp_ns: 1, tid: Some(7), gil, stack, + sweep: (!gil).then_some(0), native: None, } } @@ -612,14 +677,14 @@ mod tests { ); } - #[test] - fn aggregates_gil_and_thread_samples_separately() { + /// Four GIL samples and one sweep sample over a 2 ms run. + fn two_ms_capture() -> PythonCapture { let code = |function: &str| Code { function: function.to_owned(), file: "app.py".to_owned(), first_line: 1, }; - let capture = PythonCapture { + PythonCapture { // Three GIL samples in `step` under `main`, one in `load`; the // fifth GIL tick found the GIL released. samples: vec![ @@ -630,6 +695,9 @@ mod tests { sample(false, 1), ], stacks: vec![stack(&[0, 2]), stack(&[1, 2])], + // One sweep over the whole 2 ms run. + sweeps: vec![0], + end_ns: 2_000_000, codes: vec![code("step"), code("load"), code("main")], counters: SamplerCounters { gil_ticks: 5, @@ -647,8 +715,11 @@ mod tests { elapsed: Duration::from_millis(2), tid_source: TidSource::Native, threads: BTreeSet::from([7]), - }; - let request = SamplingRequest { + } + } + + fn two_ms_request() -> SamplingRequest { + SamplingRequest { session_id: "xp".to_owned(), name: None, target: TargetIdentity { @@ -662,7 +733,13 @@ mod tests { threads_hz: 500, sweep_reads_per_second: None, stack_depth: 128, - }; + } + } + + #[test] + fn aggregates_gil_and_thread_samples_separately() { + let capture = two_ms_capture(); + let request = two_ms_request(); let result = analyze(&request, &capture, &std::collections::BTreeMap::new()); let inventory = &result.inventory; assert_eq!(inventory.gil_stack_groups[0].samples, 3); @@ -705,4 +782,35 @@ mod tests { assert_eq!(first.frames[0].function, "step"); assert_eq!(first.frames[1].function, "main"); } + + #[test] + fn weights_each_sweep_sample_by_its_own_sweep() { + // Sweeps that slow down as threads are added: a sample of the second, + // 9 ms sweep stands for 9 ms, not the 5 ms average. + let mut slowing = two_ms_capture(); + slowing.samples = vec![ + sample(false, 0), + PythonSample { + sweep: Some(1), + ..sample(false, 1) + }, + ]; + slowing.sweeps = vec![0, 1_000_000]; + slowing.end_ns = 10_000_000; + slowing.elapsed = Duration::from_millis(10); + slowing.counters.thread_sweeps = 2; + let groups = analyze( + &two_ms_request(), + &slowing, + &std::collections::BTreeMap::new(), + ) + .inventory + .thread_stack_groups; + let by_leaf = groups + .iter() + .map(|group| (group.frames[0].function.as_str(), group.estimated_ns)) + .collect::>(); + assert_eq!(by_leaf["step"], 1_000_000); + assert_eq!(by_leaf["load"], 9_000_000); + } } diff --git a/xprobe/protocol/src/python_sampling.rs b/xprobe/protocol/src/python_sampling.rs index c6f4b35..7d55ab6 100644 --- a/xprobe/protocol/src/python_sampling.rs +++ b/xprobe/protocol/src/python_sampling.rs @@ -36,8 +36,8 @@ pub struct PythonNativeWait { pub samples: u64, /// Share of thread samples. pub proportion: f64, - /// Thread time spent here, summed over threads: samples times the - /// average sweep interval. + /// Thread time spent here, summed over threads: each sample counts its + /// own sweep's interval. pub estimated_ns: u64, } @@ -49,9 +49,9 @@ pub struct PythonStackGroup { pub samples: u64, /// Share of the samples this group was drawn from. pub proportion: f64, - /// Time in this stack: samples times the average GIL tick (GIL groups, - /// wall time) or sweep interval (thread groups, thread time summed over - /// threads). + /// Time in this stack: each GIL sample counts one average GIL tick (wall + /// time); each sweep sample counts its own sweep's interval (thread time + /// summed over threads). pub estimated_ns: u64, } From 5939621d04a7fd1b0614b0b7adc5d1f3b643e78a Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:44:03 +0800 Subject: [PATCH 17/22] =?UTF-8?q?=E2=9A=A1=20perf:=20write=20each=20CPU=20?= =?UTF-8?q?frame=20once=20and=20stream=20samples=20in=20the=20analyzer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CPU sample JSONL now lists each distinct frame once by address, and stack lines refer to frames by address. Only the listed stack groups are built from frames. analyze_trace.py reads sample files line by line and keeps only samples inside the slice from the slice's processes. --- schemas/cpu-sample-record.schema.json | 15 ++- .../references/data-format.md | 7 +- .../scripts/analyze_trace.py | 106 +++++++++++------- tests/agent-contract/test_trace_analysis.py | 11 +- xprobe/cli/src/inventory.rs | 2 +- xprobe/core/src/cpu_sampling_analysis.rs | 98 +++++++++------- xprobe/protocol/src/cpu_sampling.rs | 10 +- 7 files changed, 148 insertions(+), 101 deletions(-) diff --git a/schemas/cpu-sample-record.schema.json b/schemas/cpu-sample-record.schema.json index ab003f8..b22a21b 100644 --- a/schemas/cpu-sample-record.schema.json +++ b/schemas/cpu-sample-record.schema.json @@ -1,8 +1,11 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "CpuSampleRecord", - "description": "One line of a CPU sample artifact: a stack, written before the first\nsample that uses it, or a sample.", + "description": "One line of a CPU sample artifact: a frame, written before the first\nstack that holds its address; a stack, written before the first sample\nthat uses it; or a sample.", "anyOf": [ + { + "$ref": "#/$defs/CpuStackFrame" + }, { "$ref": "#/$defs/CpuStackRecord" }, @@ -129,11 +132,13 @@ "CpuStackRecord": { "type": "object", "properties": { - "frames": { - "description": "Innermost frame first.", + "addresses": { + "description": "Frame addresses, innermost first, each written on an earlier line.", "type": "array", "items": { - "$ref": "#/$defs/CpuStackFrame" + "type": "integer", + "format": "uint64", + "minimum": 0 } }, "stack": { @@ -145,7 +150,7 @@ "additionalProperties": false, "required": [ "stack", - "frames" + "addresses" ] } } diff --git a/skills/xprobe-perf-profiling/references/data-format.md b/skills/xprobe-perf-profiling/references/data-format.md index b820cf6..ffc4a07 100644 --- a/skills/xprobe-perf-profiling/references/data-format.md +++ b/skills/xprobe-perf-profiling/references/data-format.md @@ -65,15 +65,16 @@ Written beside every Event JSONL (`schema_version: "1.0"`). Keep it beside the t ## CPU sample JSONL (`--cpu-sample`) -At `result["artifact"]["path"]`. A stack line comes before the first sample that uses it; samples are in time order: +At `result["artifact"]["path"]`. Each frame line comes before the first stack that uses it, each stack line before its first sample; samples are in time order: ```json -{"stack":0,"frames":[{"address":4198400,"module_path":"/srv/app","build_id":"ab12","file_offset":4096,"symbol":"hot_loop","symbol_offset":16,"language":"native","source_path":null,"line":null}]} +{"address":4198400,"module_path":"/srv/app","build_id":"ab12","file_offset":4096,"symbol":"hot_loop","symbol_offset":16,"language":"native","source_path":null,"line":null} +{"stack":0,"addresses":[4198400]} {"timestamp_ns":1001234,"pid":4242,"tid":4250,"cpu_ns":1001001,"stack":0} ``` - `timestamp_ns` is `CLOCK_MONOTONIC`; `cpu_ns` is the on-CPU time the sample stands for (its perf period). -- `frames[0]` is the innermost frame. Build `stacks = {r["stack"]: r["frames"] for r in lines if "frames" in r}` first. +- `addresses[0]` is the innermost frame. Read frame lines into `frames = {r["address"]: r}` and stack lines into `stacks = {r["stack"]: [frames[a] for a in r["addresses"]]}`, then join samples by `stack`. ## Python sample JSONL (`--python-sample`) diff --git a/skills/xprobe-perf-profiling/scripts/analyze_trace.py b/skills/xprobe-perf-profiling/scripts/analyze_trace.py index e5ca7d7..13962af 100755 --- a/skills/xprobe-perf-profiling/scripts/analyze_trace.py +++ b/skills/xprobe-perf-profiling/scripts/analyze_trace.py @@ -633,36 +633,66 @@ def slice_events( 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) +def json_lines(path: pathlib.Path): + """(line number, record) for each non-empty line, read one line at a time.""" + with path.open() as stream: + for number, line in enumerate(stream, 1): + if line.strip(): + yield number, json.loads(line) + + +def keep_sample(sample: dict, pids: set, start_ns: int, end_ns: int, other: list) -> bool: + if not start_ns <= sample["timestamp_ns"] <= end_ns: + return False + if sample.get("pid") not in pids: + other[0] += 1 + return False + return True + + +def load_python_samples( + path: pathlib.Path, pids: set, start_ns: int, end_ns: int +) -> tuple[list[dict], int]: + """Samples from `measure --python-sample` inside the window, and how many + samples in the window came from other processes.""" + samples, other = [], [0] + for number, record in json_lines(path): 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 + if keep_sample(record, pids, start_ns, end_ns, other): + samples.append(record) + return samples, other[0] -def load_cpu_samples(path: pathlib.Path) -> tuple[dict, list[dict]]: - """Stacks and samples written by `measure --cpu-sample`.""" - stacks, samples = {}, [] - for number, line in enumerate(path.read_text().splitlines(), 1): - if not line.strip(): - continue - record = json.loads(line) - if isinstance(record, dict) and "frames" in record and "stack" in record: - stacks[record["stack"]] = record["frames"] - elif isinstance(record, dict) and "timestamp_ns" in record and "cpu_ns" in record: - samples.append(record) +def load_cpu_samples( + path: pathlib.Path, pids: set, start_ns: int, end_ns: int +) -> tuple[dict, list[dict], int]: + """Stacks (as frame lists) and samples from `measure --cpu-sample` inside + the window, and how many samples in the window came from other processes.""" + frames, stacks, samples, other = {}, {}, [], [0] + for number, record in json_lines(path): + if not isinstance(record, dict): + raise ValueError(f"{path}:{number}: not a CPU sample record") + if "timestamp_ns" in record and "cpu_ns" in record: + if record["stack"] not in stacks: + raise ValueError(f"{path}:{number}: stack {record['stack']} was not written before") + if keep_sample(record, pids, start_ns, end_ns, other): + samples.append(record) + elif "addresses" in record and "stack" in record: + missing = [address for address in record["addresses"] if address not in frames] + if missing: + raise ValueError(f"{path}:{number}: frame {missing[0]} was not written before") + stacks[record["stack"]] = record["addresses"] + elif "address" in record and "language" in record: + frames[record["address"]] = record else: raise ValueError(f"{path}:{number}: not a CPU sample record") - missing = {sample["stack"] for sample in samples} - stacks.keys() - if missing: - raise ValueError(f"{path}: samples name stacks never written: {sorted(missing)[:5]}") - return stacks, samples + used = {sample["stack"] for sample in samples} + return ( + {stack: [frames[address] for address in stacks[stack]] for stack in used}, + samples, + other[0], + ) def native_label(frame: dict) -> str: @@ -674,11 +704,8 @@ def native_label(frame: dict) -> str: return f"0x{frame['address']:x}" -def cpu_slice( - stacks: dict, samples: list[dict], start_ns: int, end_ns: int, limit: int = 10 -) -> dict: - """On-CPU stacks sampled inside [start_ns, end_ns], by CPU time.""" - inside = [sample for sample in samples if start_ns <= sample["timestamp_ns"] <= end_ns] +def cpu_slice(stacks: dict, inside: list[dict], limit: int = 10) -> dict: + """On-CPU stacks from samples already cut to the window, by CPU time.""" total = sum(sample["cpu_ns"] for sample in inside) by_stack = collections.Counter() counts = collections.Counter() @@ -708,9 +735,8 @@ 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] +def python_slice(inside: list[dict], limit: int = 10) -> dict: + """Python stacks from samples already cut to the window.""" 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 @@ -991,22 +1017,18 @@ def analyze( ) continue if name == "python": - samples = load_python_samples(path_arg) + samples, other = load_python_samples(path_arg, pids, start_ns, end_ns) + window_report[name] = python_slice(samples) else: - stacks, samples = load_cpu_samples(path_arg) - matching = [sample for sample in samples if sample.get("pid") in pids] - if len(matching) != len(samples): + stacks, samples, other = load_cpu_samples(path_arg, pids, start_ns, end_ns) + window_report[name] = cpu_slice(stacks, samples) + if other: warnings.append( { "code": f"{name.upper()}_SAMPLES_OTHER_PROCESS", - "message": f"{len(samples) - len(matching)} {label} samples come from processes other than the slice's and were left out", + "message": f"{other} {label} samples in the slice come from processes other than the slice's and were left out", } ) - window_report[name] = ( - python_slice(matching, start_ns, end_ns) - if name == "python" - else cpu_slice(stacks, matching, start_ns, end_ns) - ) if outlier_report and outlier_report["source"] == ["rank_exemplars"]: warnings.append( { diff --git a/tests/agent-contract/test_trace_analysis.py b/tests/agent-contract/test_trace_analysis.py index 8b5e567..4c475ed 100755 --- a/tests/agent-contract/test_trace_analysis.py +++ b/tests/agent-contract/test_trace_analysis.py @@ -392,17 +392,20 @@ def check_gaps_outliers_and_slices(script: pathlib.Path) -> None: ) cpu = pathlib.Path(directory) / "cpu-samples.jsonl" - native = lambda symbol: { - "address": 4096, "module_path": "/srv/app", "build_id": None, "file_offset": 16, + native = lambda address, symbol: { + "address": address, "module_path": "/srv/app", "build_id": None, "file_offset": 16, "symbol": symbol, "symbol_offset": 0, "language": "native", "source_path": None, "line": None, } cpu.write_text( "".join( json.dumps(record) + "\n" for record in [ - {"stack": 0, "frames": [native("spin"), native("main")]}, + native(4096, "spin"), + native(8192, "main"), + {"stack": 0, "addresses": [4096, 8192]}, {"timestamp_ns": 260, "pid": 1234, "tid": 1, "cpu_ns": 1000, "stack": 0}, - {"stack": 1, "frames": [native("copy")]}, + native(12288, "copy"), + {"stack": 1, "addresses": [12288]}, {"timestamp_ns": 400, "pid": 1234, "tid": 2, "cpu_ns": 3000, "stack": 1}, {"timestamp_ns": 410, "pid": 1234, "tid": 1, "cpu_ns": 1000, "stack": 0}, {"timestamp_ns": 600, "pid": 1234, "tid": 1, "cpu_ns": 1000, "stack": 0}, diff --git a/xprobe/cli/src/inventory.rs b/xprobe/cli/src/inventory.rs index 0a20502..bfe8c5c 100644 --- a/xprobe/cli/src/inventory.rs +++ b/xprobe/cli/src/inventory.rs @@ -176,7 +176,7 @@ pub(crate) fn cpu_inventory( /// Write every CPU sample to `events_out`, or a private file, as JSON lines. fn write_cpu_samples( capture: &CpuCaptureData, - frames: &[Vec], + frames: &std::collections::BTreeMap, pid: u32, events_out: Option<&Path>, ) -> Result { diff --git a/xprobe/core/src/cpu_sampling_analysis.rs b/xprobe/core/src/cpu_sampling_analysis.rs index 33ae6f5..b960bee 100644 --- a/xprobe/core/src/cpu_sampling_analysis.rs +++ b/xprobe/core/src/cpu_sampling_analysis.rs @@ -46,11 +46,11 @@ pub struct CpuCaptureData { pub python_status: PythonSymbolizationStatus, } -/// An analyzed capture and the symbolized frames of each distinct stack, +/// An analyzed capture and the symbolized frame of each distinct address, /// for [`write_records`]. pub struct CpuAnalysis { pub result: CpuSampleInventoryResult, - pub frames: Vec>, + pub frames: BTreeMap, } /// One distinct stack: its samples and their summed perf periods. @@ -232,30 +232,29 @@ pub fn analyze( .flat_map(|addresses| addresses.iter().copied()) .collect::>(); let mut symbolizer = Symbolizer::load(report, capture.python_status, &sampled)?; - let frames = capture - .stacks + // Leaf addresses differ from sample to sample, so stacks repeat far less + // than the addresses in them: symbolize each address once. + let frames = sampled .iter() - .map(|addresses| { - addresses - .iter() - .map(|address| symbolizer.symbolize(*address)) - .collect::>() - }) - .collect::>(); + .map(|address| (*address, symbolizer.symbolize(*address))) + .collect::>(); let sample_denominator = capture.observed_samples.max(1); let listed = usize::try_from(spec.max_groups).unwrap_or(usize::MAX); - let all_groups = totals + let stack_groups = totals .iter() + .take(listed) .map(|total| CpuStackGroup { - frames: frames[total.stack as usize].clone(), + frames: capture.stacks[total.stack as usize] + .iter() + .map(|address| frames[address].clone()) + .collect(), samples: total.samples, proportion: ratio(total.samples, sample_denominator), estimated_ns: total.period_ns, }) .collect::>(); - let symbolization = summarize_symbolization(&all_groups, symbolizer.python_status); - let mut stack_groups = all_groups; - stack_groups.truncate(listed); + let symbolization = + summarize_symbolization(&totals, capture, &frames, symbolizer.python_status); let hotspots = aggregate_hotspots( &totals, capture, @@ -361,21 +360,23 @@ fn stack_totals(capture: &CpuCaptureData) -> Vec { totals } -/// Write every sample in time order as JSON lines, each stack on its own -/// line before the first sample that uses it. Returns the lines written. +/// Write every sample in time order as JSON lines: each frame once, before +/// the first stack with its address, and each stack once, before the first +/// sample that uses it. Returns the lines written. /// /// # Errors /// /// Returns the writer's I/O error. pub fn write_records( capture: &CpuCaptureData, - frames: &[Vec], + frames: &BTreeMap, pid: u32, writer: &mut impl Write, ) -> io::Result { let mut order = (0..capture.samples.len()).collect::>(); order.sort_by_key(|index| capture.samples[*index].timestamp_ns); let mut written = BTreeSet::new(); + let mut frames_written = BTreeSet::new(); let mut lines = 0_u64; let mut line = |record: &CpuSampleRecord, writer: &mut dyn Write| -> io::Result<()> { serde_json::to_writer(&mut *writer, record).map_err(io::Error::other)?; @@ -386,10 +387,18 @@ pub fn write_records( for index in order { let sample = capture.samples[index]; if written.insert(sample.stack) { + let addresses = &capture.stacks[sample.stack as usize]; + for address in addresses { + if frames_written.insert(*address) + && let Some(frame) = frames.get(address) + { + line(&CpuSampleRecord::Frame(frame.clone()), writer)?; + } + } line( &CpuSampleRecord::Stack(CpuStackRecord { stack: sample.stack, - frames: frames[sample.stack as usize].clone(), + addresses: addresses.clone(), }), writer, )?; @@ -579,8 +588,11 @@ fn selector_hints(frame: &CpuStackFrame) -> (Option, Option) { ) } +/// Frames over every distinct stack, resolved or not. fn summarize_symbolization( - groups: &[CpuStackGroup], + totals: &[StackTotal], + capture: &CpuCaptureData, + frames: &BTreeMap, python_status: PythonSymbolizationStatus, ) -> CpuSymbolizationSummary { let mut summary = CpuSymbolizationSummary { @@ -590,8 +602,11 @@ fn summarize_symbolization( unresolved_frames: 0, python_status, }; - for group in groups { - for frame in &group.frames { + for total in totals { + for frame in capture.stacks[total.stack as usize] + .iter() + .filter_map(|address| frames.get(address)) + { summary.total_frames += 1; match (frame.language, frame.symbol.is_some()) { (CpuFrameLanguage::Native, true) => summary.resolved_native_frames += 1, @@ -986,34 +1001,33 @@ mod tests { let frames = capture .stacks .iter() - .map(|stack| { - stack - .iter() - .map(|address| unresolved_frame(*address)) - .collect() - }) - .collect::>(); + .flatten() + .map(|address| (*address, unresolved_frame(*address))) + .collect::>(); let mut text = Vec::new(); - assert_eq!(write_records(&capture, &frames, 7, &mut text).unwrap(), 5); - let lines = String::from_utf8(text) + assert_eq!(write_records(&capture, &frames, 7, &mut text).unwrap(), 9); + let shape = String::from_utf8(text) .unwrap() .lines() - .map(|line| serde_json::from_str::(line).unwrap()) - .collect::>(); - let shape = lines - .iter() - .map(|record| match record { - CpuSampleRecord::Stack(stack) => format!("stack {}", stack.stack), - CpuSampleRecord::Sample(sample) => { - format!("sample {} at {}", sample.stack, sample.timestamp_ns) - } - }) + .map( + |line| match serde_json::from_str::(line).unwrap() { + CpuSampleRecord::Frame(frame) => format!("frame {}", frame.address), + CpuSampleRecord::Stack(stack) => format!("stack {}", stack.stack), + CpuSampleRecord::Sample(sample) => { + format!("sample {} at {}", sample.stack, sample.timestamp_ns) + } + }, + ) .collect::>(); assert_eq!( shape, [ + "frame 1", + "frame 2", "stack 0", "sample 0 at 10", + "frame 3", + "frame 4", "stack 1", "sample 1 at 20", "sample 1 at 30" diff --git a/xprobe/protocol/src/cpu_sampling.rs b/xprobe/protocol/src/cpu_sampling.rs index ccf4a21..f831190 100644 --- a/xprobe/protocol/src/cpu_sampling.rs +++ b/xprobe/protocol/src/cpu_sampling.rs @@ -149,11 +149,13 @@ pub struct CpuSampleInventoryResult { pub warnings: Vec, } -/// One line of a CPU sample artifact: a stack, written before the first -/// sample that uses it, or a sample. +/// One line of a CPU sample artifact: a frame, written before the first +/// stack that holds its address; a stack, written before the first sample +/// that uses it; or a sample. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] #[serde(untagged)] pub enum CpuSampleRecord { + Frame(CpuStackFrame), Stack(CpuStackRecord), Sample(CpuSampleLine), } @@ -162,8 +164,8 @@ pub enum CpuSampleRecord { #[serde(deny_unknown_fields)] pub struct CpuStackRecord { pub stack: u32, - /// Innermost frame first. - pub frames: Vec, + /// Frame addresses, innermost first, each written on an earlier line. + pub addresses: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] From efa574e89e3d432c3c3daf7ba661676e4f6063b4 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:45:31 +0800 Subject: [PATCH 18/22] =?UTF-8?q?=F0=9F=90=9B=20fix:=20read=20a=20loaded?= =?UTF-8?q?=20Agent's=20start=20function=20from=20its=20file=20when=20it?= =?UTF-8?q?=20exists?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit measure called dlopen with RTLD_NOLOAD in the target for every reuse. It now reads the start function from the mapped Agent file, as before, and asks the target's loader only when the file was deleted. --- xprobe/core/src/inject.rs | 128 ++++++++++++++++++++++++++------------ 1 file changed, 89 insertions(+), 39 deletions(-) diff --git a/xprobe/core/src/inject.rs b/xprobe/core/src/inject.rs index 9da9f04..7534f8b 100644 --- a/xprobe/core/src/inject.rs +++ b/xprobe/core/src/inject.rs @@ -207,42 +207,42 @@ pub fn activate( remote.copy_c_string(malloc, socket_path.as_os_str().as_encoded_bytes())?; let mut allocations = vec![socket_address]; - // A loaded Agent is found by the name it was loaded under, so its file - // may have been deleted since; a new one is loaded from `agent_path`. - let (open_path, flags, injected) = if report.cuda.xprobe_cupti_loaded { - (loaded_agent_path(report)?, RTLD_NOW | RTLD_NOLOAD, false) - } else { - let agent_path = fs::canonicalize(agent_path) - .map_err(|_| InjectError::InvalidAgent(agent_path.to_owned()))?; - if !agent_path.is_file() { - return Err(InjectError::InvalidAgent(agent_path)); + let (start_address, injected) = match loaded_agent(report)? { + // The mapped file is still there: read the start function from it. + Some((path, false)) => ( + resolve::run( + report, + &format!("uprobe:{}:{AGENT_START_SYMBOL}:entry", path.display()), + ) + .map_err(InjectError::Resolve)? + .runtime_address, + false, + ), + // The file was deleted: ask the target's loader for the Agent by the + // name it was loaded under. + Some((path, true)) => ( + remote_start_address(report, &mut remote, malloc, &mut allocations, &path, true)?, + false, + ), + None => { + let agent_path = fs::canonicalize(agent_path) + .map_err(|_| InjectError::InvalidAgent(agent_path.to_owned()))?; + if !agent_path.is_file() { + return Err(InjectError::InvalidAgent(agent_path)); + } + ( + remote_start_address( + report, + &mut remote, + malloc, + &mut allocations, + &agent_path, + false, + )?, + true, + ) } - (agent_path, RTLD_NOW | RTLD_LOCAL, true) }; - let dlopen = resolve_runtime_symbol(report, "dlopen")?; - let dlsym = resolve_runtime_symbol(report, "dlsym")?; - let path_address = remote.copy_c_string(malloc, open_path.as_os_str().as_encoded_bytes())?; - allocations.push(path_address); - let handle = remote.call(dlopen, &[path_address, flags])?; - if handle == 0 { - return Err(if injected { - InjectError::RemoteCallFailed { - function: "dlopen", - result: handle, - } - } else { - InjectError::LoadedAgentUnreachable(open_path) - }); - } - let symbol_address = remote.copy_c_string(malloc, AGENT_START_SYMBOL.as_bytes())?; - allocations.push(symbol_address); - let start_address = remote.call(dlsym, &[handle, symbol_address])?; - if start_address == 0 { - return Err(InjectError::RemoteCallFailed { - function: "dlsym", - result: start_address, - }); - } let status = remote.call(start_address, &[socket_address, record_capacity])?; for address in allocations { @@ -265,6 +265,49 @@ pub fn activate( }) } +/// Load the Agent at `path` in the target with `dlopen` (or, when `loaded`, +/// find the already loaded one with `RTLD_NOLOAD`) and return its start +/// function from `dlsym`. +fn remote_start_address( + report: &ProcessReport, + remote: &mut RemoteProcess, + malloc: u64, + allocations: &mut Vec, + path: &Path, + loaded: bool, +) -> Result { + let dlopen = resolve_runtime_symbol(report, "dlopen")?; + let dlsym = resolve_runtime_symbol(report, "dlsym")?; + let path_address = remote.copy_c_string(malloc, path.as_os_str().as_encoded_bytes())?; + allocations.push(path_address); + let flags = if loaded { + RTLD_NOW | RTLD_NOLOAD + } else { + RTLD_NOW | RTLD_LOCAL + }; + let handle = remote.call(dlopen, &[path_address, flags])?; + if handle == 0 { + return Err(if loaded { + InjectError::LoadedAgentUnreachable(path.to_owned()) + } else { + InjectError::RemoteCallFailed { + function: "dlopen", + result: handle, + } + }); + } + let symbol_address = remote.copy_c_string(malloc, AGENT_START_SYMBOL.as_bytes())?; + allocations.push(symbol_address); + let start_address = remote.call(dlsym, &[handle, symbol_address])?; + if start_address == 0 { + return Err(InjectError::RemoteCallFailed { + function: "dlsym", + result: start_address, + }); + } + Ok(start_address) +} + fn verify_mount_namespace(report: &ProcessReport) -> Result<(), InjectError> { let local = fs::read_link("/proc/self/ns/mnt").map_err(|source| InjectError::Operation { operation: "read local mount namespace", @@ -296,19 +339,26 @@ fn resolve_runtime_symbol( } /// The path the target loaded the Agent from, as its maps name it without a -/// ` (deleted)` suffix. -fn loaded_agent_path(report: &ProcessReport) -> Result { +/// ` (deleted)` suffix, and whether the file was deleted. `None` when the +/// target has not loaded the Agent. +fn loaded_agent(report: &ProcessReport) -> Result, InjectError> { + if !report.cuda.xprobe_cupti_loaded { + return Ok(None); + } report .loaded_libraries .iter() - .map(|path| path.strip_suffix(" (deleted)").unwrap_or(path)) - .find(|path| { + .map(|path| match path.strip_suffix(" (deleted)") { + Some(path) => (path, true), + None => (path.as_str(), false), + }) + .find(|(path, _)| { Path::new(path) .file_name() .and_then(|value| value.to_str()) .is_some_and(|name| name.starts_with("libxprobe-cupti.so")) }) - .map(PathBuf::from) + .map(|(path, deleted)| Some((PathBuf::from(path), deleted))) .ok_or(InjectError::MissingRuntimeSymbol(AGENT_START_SYMBOL)) } From a254341b4777e4ab13c39173ea4b3dd09a10a37c Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:45:31 +0800 Subject: [PATCH 19/22] =?UTF-8?q?=F0=9F=90=9B=20fix:=20time=20triage=20thr?= =?UTF-8?q?ead=20counters=20from=20the=20middle=20of=20each=20snapshot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reading every thread's counters takes a while on processes with many threads. The window now runs from the middle of the first snapshot to the middle of the last, and cgroup counters are read right around the sleep. --- xprobe/cli/src/triage.rs | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/xprobe/cli/src/triage.rs b/xprobe/cli/src/triage.rs index 55e67b2..4aa881c 100644 --- a/xprobe/cli/src/triage.rs +++ b/xprobe/cli/src/triage.rs @@ -134,22 +134,28 @@ fn triage(request: &TriageRequest) -> Result { // Thread and cgroup counters span exactly the window; the other sources // each run it after their own setup, alongside. let counters = || -> Result<_, CommandFailure> { - let cgroup_before = match &cgroup { - Some(cgroup) => Some(cgroup.counters().map_err(|error| inspect_failure(&error))?), - None => None, + let cgroup_counters = || match &cgroup { + Some(cgroup) => cgroup + .counters() + .map(Some) + .map_err(|error| inspect_failure(&error)), + None => Ok(None), }; - let threads_before = - thread_time::snapshot(request.pid).map_err(|error| inspect_failure(&error))?; - let opened = Instant::now(); - thread::sleep(window); - let threads_after = - thread_time::snapshot(request.pid).map_err(|error| inspect_failure(&error))?; - let cgroup_after = match &cgroup { - Some(cgroup) => Some(cgroup.counters().map_err(|error| inspect_failure(&error))?), - None => None, + // A snapshot reads one thread at a time; time it from the middle of + // each read so a slow read over many threads does not skew rates. + let snapshot = || { + let started = Instant::now(); + let threads = + thread_time::snapshot(request.pid).map_err(|error| inspect_failure(&error))?; + Ok::<_, CommandFailure>((started + started.elapsed() / 2, threads)) }; + let (opened, threads_before) = snapshot()?; + let cgroup_before = cgroup_counters()?; + thread::sleep(window); + let cgroup_after = cgroup_counters()?; + let (closed, threads_after) = snapshot()?; Ok(( - opened.elapsed(), + closed - opened, threads_before, threads_after, cgroup_before.zip(cgroup_after), From 7dc529639092174daafa395518fb2a3d8400bdb4 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 04:45:31 +0800 Subject: [PATCH 20/22] =?UTF-8?q?=F0=9F=93=9D=20docs:=20say=20--aggregate?= =?UTF-8?q?=20leaves=20out=20activity=20still=20running=20at=20stop?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/cli-reference.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 9929339..59b7768 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -226,6 +226,7 @@ Each inventory is a live mode that runs for `--duration-ms` and reports totals i - The kernel regex must reduce to a literal the hot path can filter on. - Names cut at 127 bytes set `name_complete: false` and give a prefix hint. - Memcpy groups split by `src_memory` and `dst_memory` (`pageable`, `pinned`, `device`, `managed`, and others). +- An activity still running on the GPU when the capture stops is not counted. ### Triage From a60933f35d558037e5731afc0bb84a6990d0b58d Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 05:15:41 +0800 Subject: [PATCH 21/22] =?UTF-8?q?=F0=9F=93=9D=20docs:=20trim=20README=20de?= =?UTF-8?q?tails=20and=20refine=20Skill=20wording?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Trim over-detailed install verification phrasing and repeated JSON/JSONL suffixes in README.md, and add memcpy and --cpu-samples examples. - Update SKILL.md for CPU sample CLOCK_MONOTONIC alignment, keep the pip install hint, and state explicit read-only / user-scoped boundaries. - Note discover procfs_hints and fix a minor typo in docs/architecture.md. --- README.md | 25 ++++++++++++++----------- docs/architecture.md | 4 ++-- skills/xprobe-perf-profiling/SKILL.md | 12 ++++++------ 3 files changed, 22 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 1f40812..b21c68a 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@

xprobe

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.

+

Live Linux CPU, Python, syscall, and CUDA profiler for AI agents and engineers.

CI status Latest release @@ -49,7 +49,7 @@ 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. +Both ship the CLI plus CUDA 12 and CUDA 13 CUPTI Agents. See [Installation](docs/installation.md) for custom prefixes, upgrades, and verification. ### AI Agent Skill (Claude Code, Codex, Cursor) @@ -57,7 +57,7 @@ Both ship the CLI plus CUDA 12 and CUDA 13 CUPTI Agents. See [Installation](docs npx skills add itdevwu/xprobe ``` -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). +Installs the [`xprobe-perf-profiling`](skills/xprobe-perf-profiling/SKILL.md) skill from [skills.sh](https://skills.sh) with artifact layouts, scripting recipes, and the bundled `analyze_trace.py` analyzer. To pin a release, see [Installation](docs/installation.md#ai-agent-skill). ## 🚀 Quick examples @@ -65,31 +65,34 @@ Installs the [`xprobe-perf-profiling`](skills/xprobe-perf-profiling/SKILL.md) sk # 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) +# 2. Aggregate GPU kernels or memcpy (memcpy splits by pageable vs pinned) xprobe measure --pid 4242 --from cuda:kernel_start --to cuda:kernel_end \ --match exact --aggregate --duration-ms 2000 +xprobe measure --pid 4242 --from cuda:memcpy_start --to cuda:memcpy_end \ + --match exact --aggregate --duration-ms 2000 -# 3. Measure exact launch-to-kernel latency (or up to 8 edges via --spec graph.json) +# 3. Measure exact latency from a CUDA API call to the GPU work it issued 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 +# 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 ``` ### 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): +When stdout is piped, every command emits one JSON object alongside raw trace files and a `.manifest.json` (`CLOCK_MONOTONIC` window, UTC `wall_clock` anchors, and `cuda_devices` GPU UUIDs): ```bash -# Capture once, diff metrics across optimization iterations, or join traces in Python +# Capture once, diff metrics across iterations, or join traces in Python before=$(xprobe measure --spec kernel.json | jq '.measurement.latency_ns.p95') -# ... apply kernel / runtime change ... +# ... apply 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 +# Slice a GPU bubble alongside concurrent Python & CPU samples, or compare multi-GPU ranks +skills/xprobe-perf-profiling/scripts/analyze_trace.py trace.jsonl \ + --slice-gap 1 --python-samples py.jsonl --cpu-samples cpu.jsonl skills/xprobe-perf-profiling/scripts/analyze_trace.py rank0.jsonl rank1.jsonl rank2.jsonl rank3.jsonl ``` diff --git a/docs/architecture.md b/docs/architecture.md index 081d740..cb08da3 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -38,7 +38,7 @@ xprobe has no daemon and no persistent session API. Each foreground `measure` ow ## 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. +- `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. When a container PID namespace hides NVML host PIDs, it also reports `procfs_hints` for processes mapping `libcuda` or holding `/dev/nvidia*` open. 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 @@ -70,7 +70,7 @@ CPU sampling, syscall aggregation, and measurement graphs each have their own va ### CPU and external Python sampling - **`--cpu-sample`**: opens software CPU-clock perf events per target thread with `CLOCK_MONOTONIC` timestamps and periods, keeps every sample with an index into the distinct callchains, writes them as JSONL, 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 999) and sweeps all threads up to 100 times a second within 6,400 stack reads a second (`--python-threads-hz` fixes the rate), keeps every sample, discards inconsistent reads, and reading `/proc//task//syscall` for blocked threads' native waits. Writes every timestamped sample (`CLOCK_MONOTONIC`) to a JSONL artifact. +- **`--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 999) and sweeps all threads up to 100 times a second within 6,400 stack reads a second (`--python-threads-hz` fixes the rate), keeps every sample, discards inconsistent reads, and reads `/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. diff --git a/skills/xprobe-perf-profiling/SKILL.md b/skills/xprobe-perf-profiling/SKILL.md index e745b6d..56f9c8c 100644 --- a/skills/xprobe-perf-profiling/SKILL.md +++ b/skills/xprobe-perf-profiling/SKILL.md @@ -5,7 +5,7 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA # Profile Linux & ML workloads with xprobe -`xprobe` profiles live Linux CPU, Python, syscall, and CUDA processes (or re-analyzes saved traces). When stdout is piped, every command writes one JSON document to stdout alongside raw JSONL artifacts. Run `xprobe --help` for full flags. +`xprobe` profiles live Linux CPU, Python, syscall, and CUDA processes (or re-analyzes saved traces). If `xprobe` is not installed yet, install it with `pip install xprobe` (Linux x86_64, glibc ≥ 2.34). When stdout is piped, every command writes one JSON document to stdout alongside raw JSONL artifacts. Run `xprobe --help` for full flags. ## Pick a mode @@ -13,7 +13,7 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA | --- | --- | --- | | Check host/container permissions | `xprobe doctor` | Read-only; run first when eBPF, perf, ptrace, or CUPTI access is unknown | | List CUDA PIDs under a root | `xprobe discover --pid "$ROOT"` | Uses NVML; inside containers (`NVML_PID_NAMESPACE_MISMATCH`) see `procfs_hints`: processes that loaded `libcuda` or opened `/dev/nvidia*` | -| Check selectors or injection state | `xprobe validate --pid "$PID" --from A --to B --match exact` | Read-only; reports `requirements.agent_activation` (`already_loaded` vs `injection_required`) | +| Check selectors or CUPTI Agent status | `xprobe validate --pid "$PID" --from A --to B --match exact` | Read-only; reports `requirements.agent_activation` (`already_loaded` vs `injection_required`) | | Python stacks, GIL & native waits | `xprobe measure --pid "$PID" --python-sample --duration-ms 2000` | CPython 3.9–3.14; ptrace only (no eBPF/perf/injection); sweeps of every thread slow down on processes with many threads | | Native CPU callchain hotspots | `xprobe measure --pid "$PID" --cpu-sample --duration-ms 2000 --events-out cpu.jsonl` | Needs perf events; 999 Hz; every sample timestamped in the JSONL | | Syscall count & duration totals | `xprobe measure --pid "$PID" --syscall-aggregate --duration-ms 2000` | Needs eBPF | @@ -29,16 +29,16 @@ description: Profile live Linux CPU, CPython (stacks & GIL), syscall, and NVIDIA ## 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, vertical slices (`--slice-gap`, `--slice-outlier`, `--around`, `--python-samples`, `--cpu-samples`), and multi-rank comparison (`scripts/analyze_trace.py rank0.jsonl rank1.jsonl ...`). -- **One-off scripts & RSI loops**: read [data-format.md](references/data-format.md) for stdout keys, artifact paths, JSONL shapes, `analyze_trace.py` output fields, Python time-conversion formulas, API-to-Python-caller joins, cross-process alignment, and quality codes. +- **One-off scripts & RSI loops**: read [data-format.md](references/data-format.md) for stdout keys, artifact paths, JSONL shapes, CPU/Python sample formats, `analyze_trace.py` output fields, API-to-Python-caller joins, cross-process alignment, and quality codes. - **Selectors, policies, tuning & graphs**: read [selectors.md](references/selectors.md) and `examples/` (`request-path-graph.json`, `kernel-duration.json`). ## Runtime limits & validity checks -- **CUPTI injection**: live CUDA capture injects `libxprobe-cupti.so` via ptrace, disables callbacks on stop, and leaves the `.so` mapped with its last capture's buffers (200 bytes per `--max-events` record). Later captures reuse it even if its file was deleted; `validate` reports it as `CUPTI_AGENT_ALREADY_LOADED`. +- **Scope & CUDA collector**: profile only the user-specified target PID; never alter system services, kernel settings, or host permissions (report `xprobe doctor` output instead). Check `xprobe validate` first (`requirements.agent_activation`); live CUDA `measure` loads `libxprobe-cupti.so` into the target process, disables CUPTI callbacks on stop, and leaves the mapped library and its last capture's buffers (200 bytes per `--max-events` record) ready for reuse (`CUPTI_AGENT_ALREADY_LOADED`), even if its file on disk was removed. - **One CUDA session per PID**: running two CUDA `measure` commands on the same PID fails with `CUPTI_AGENT_BUSY`; combine edges in a graph instead. `--python-sample` can run concurrently with CUDA `measure`. -- **Containers & NVTX**: run `xprobe` inside the target's PID and mount namespaces. NVTX ranges require `NVTX_INJECTION64_PATH` before the target's first NVTX call. +- **Containers & NVTX**: run `xprobe` in the target's PID and mount namespaces. NVTX ranges are available only when the target was launched with `NVTX_INJECTION64_PATH`. - **Duration & sample 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 `measure --pid` captures across processes or ranks. On one host, `host_monotonic`, `cupti_normalized_to_host_monotonic`, and `--python-sample` share `CLOCK_MONOTONIC`. Never mix PIDs in `measure --input` or subtract raw `cupti` timestamps from host timestamps. +- **Cross-process & clocks**: run concurrent `measure --pid` captures across processes or ranks. On one host, `host_monotonic`, `cupti_normalized_to_host_monotonic`, `--python-sample`, and `--cpu-sample` share `CLOCK_MONOTONIC`. Never mix PIDs in `measure --input` or subtract raw `cupti` timestamps from host timestamps. - **Check completeness before trusting numbers**: `status == "completed"` can still hide truncation or drops. Verify: - `warnings` is empty (or explicitly understood) - `--cpu-sample`: `collection.lost_samples == 0` and `collection.completeness == "complete"` From 3c02a2d5a5fc3a43adf0aa496254e8ab2bd60213 Mon Sep 17 00:00:00 2001 From: itdevwu Date: Thu, 3 Dec 2026 05:18:01 +0800 Subject: [PATCH 22/22] =?UTF-8?q?=F0=9F=94=96=20chore:=20prepare=200.7.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CMakeLists.txt | 2 +- Cargo.lock | 12 ++++++------ Cargo.toml | 2 +- README.md | 2 +- docs/installation.md | 10 +++++----- install.sh | 4 ++-- 6 files changed, 16 insertions(+), 16 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 00110ba..30b10a8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,6 +1,6 @@ cmake_minimum_required(VERSION 3.20) -project(xprobe VERSION 0.7.0 LANGUAGES C) +project(xprobe VERSION 0.7.1 LANGUAGES C) include(CTest) diff --git a/Cargo.lock b/Cargo.lock index 783bd52..adbd3dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -803,7 +803,7 @@ dependencies = [ [[package]] name = "xprobe-cli" -version = "0.7.0" +version = "0.7.1" dependencies = [ "clap", "serde", @@ -817,7 +817,7 @@ dependencies = [ [[package]] name = "xprobe-collector" -version = "0.7.0" +version = "0.7.1" dependencies = [ "libbpf-rs", "nix", @@ -829,7 +829,7 @@ dependencies = [ [[package]] name = "xprobe-core" -version = "0.7.0" +version = "0.7.1" dependencies = [ "cpp_demangle", "nix", @@ -841,7 +841,7 @@ dependencies = [ [[package]] name = "xprobe-correlator" -version = "0.7.0" +version = "0.7.1" dependencies = [ "regex", "serde_json", @@ -850,7 +850,7 @@ dependencies = [ [[package]] name = "xprobe-exporter" -version = "0.7.0" +version = "0.7.1" dependencies = [ "serde_json", "sha2", @@ -859,7 +859,7 @@ dependencies = [ [[package]] name = "xprobe-protocol" -version = "0.7.0" +version = "0.7.1" dependencies = [ "schemars", "serde", diff --git a/Cargo.toml b/Cargo.toml index bd9faf4..c379605 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ members = [ resolver = "2" [workspace.package] -version = "0.7.0" +version = "0.7.1" edition = "2024" license = "Apache-2.0" repository = "https://github.com/itdevwu/xprobe" diff --git a/README.md b/README.md index b21c68a..ea840c7 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ 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 + https://raw.githubusercontent.com/itdevwu/xprobe/v0.7.1/install.sh | sh ``` Both ship the CLI plus CUDA 12 and CUDA 13 CUPTI Agents. See [Installation](docs/installation.md) for custom prefixes, upgrades, and verification. diff --git a/docs/installation.md b/docs/installation.md index 3a3d617..875a4ca 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -21,7 +21,7 @@ Install to `~/.local` without Python or root: ```bash curl --proto '=https' --tlsv1.2 -fsSL \ - https://raw.githubusercontent.com/itdevwu/xprobe/v0.7.0/install.sh | sh + https://raw.githubusercontent.com/itdevwu/xprobe/v0.7.1/install.sh | sh ``` The script downloads the release tarball and `.sha256`, verifies the digest, and installs: @@ -38,14 +38,14 @@ Add `~/.local/bin` to `PATH` if needed. To install elsewhere, download and pass ```bash curl --proto '=https' --tlsv1.2 -fsSLO \ - https://raw.githubusercontent.com/itdevwu/xprobe/v0.7.0/install.sh + https://raw.githubusercontent.com/itdevwu/xprobe/v0.7.1/install.sh sh install.sh --prefix /opt/xprobe ``` ### Verify checksum, SBOM, and attestation ```bash -version=0.7.0 +version=0.7.1 base=https://github.com/itdevwu/xprobe/releases/download/v$version archive=xprobe-$version-linux-x86_64.tar.gz @@ -90,7 +90,7 @@ 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.7.0/skills/xprobe-perf-profiling \ + https://github.com/itdevwu/xprobe/tree/v0.7.1/skills/xprobe-perf-profiling \ --global ``` @@ -98,7 +98,7 @@ For non-interactive installs: ```bash npx --yes skills@1 add \ - https://github.com/itdevwu/xprobe/tree/v0.7.0/skills/xprobe-perf-profiling \ + https://github.com/itdevwu/xprobe/tree/v0.7.1/skills/xprobe-perf-profiling \ --agent codex --global --copy --yes ``` diff --git a/install.sh b/install.sh index dbebcea..cd81e27 100755 --- a/install.sh +++ b/install.sh @@ -2,7 +2,7 @@ set -eu repository=${XPROBE_REPOSITORY:-itdevwu/xprobe} -version=${XPROBE_VERSION:-0.7.0} +version=${XPROBE_VERSION:-0.7.1} 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.7.0) + --version VERSION Release to install (default: 0.7.1) --prefix DIR Installation prefix (default: $HOME/.local) --uninstall Remove xprobe from the selected prefix -h, --help Show this help