Skip to content

xcl run: XCL_THREAD_SAMPLE samples every thread's CPU time and stacks - #3232

Open
CharlyRien wants to merge 3 commits into
xcl-dev:mainfrom
CharlyRien:pr/thread-sample
Open

CharlyRien wants to merge 3 commits into
xcl-dev:mainfrom
CharlyRien:pr/thread-sample

Conversation

@CharlyRien

@CharlyRien CharlyRien commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

A diagnostic, off unless set: XCL_THREAD_SAMPLE=<from s>,<period ms>,<count> samples where every thread of the process spends its CPU, without a debugger, ETW or administrator rights. We used it to find which XCL threads and functions take the time while a title runs slowly; ETW and VTune both need elevation, and XCL_THREAD_DUMP_AT gives one snapshot, not where the time goes.

From log time <from>, every <period> ms, a thread of its own reads for every other thread:

  • its cycle time since the previous sample (QueryThreadCycleTime: the CPU it used, exact);
  • when it ran: its registers and the top 16 KiB of its stack. The thread is stopped only for GetThreadContext and that copy, with no lock and no allocation while it is suspended.

The frames are unwound afterwards from the copy (RtlVirtualUnwind): RIP and up to 7 return addresses. A thread whose cycle time did not move and that waits in ntdll / win32u is not stopped again (written as "unchanged"). Everything goes to a binary file (XCL_THREAD_SAMPLE_FILE, else xcl-thread-sample.bin in the temp folder) with the modules and the thread names. xcl.log gets a start line and the totals. scripts/thread_sample.py reads the file.

What is in it

First commit, the sampler:

  • crates/xcl/src/thread_sample.rs (new): the switch, the sampling thread, the file format (documented at the top of the file), the unwinding over the copy.
    • The walk never reads outside the copy. Before each RtlVirtualUnwind step, frame_extent bounds what the step can read from the function's UNWIND_INFO: pushes, allocations, machine frame, the farthest save, chained and indirect entries, version 2 epilogue descriptors, and the return address. Unknown codes are refused. That span must lie in the copy, from RSP and, with a frame register, from FrameReg - 16 × FrameOffset. Otherwise the walk ends with a TRUNCATED (1) frame.
    • The copy starts at RSP & !15 in a 16-aligned buffer, and the CONTEXT is 16-aligned. RtlVirtualUnwind restores XMM saves with aligned moves, so a misaligned copy faults inside ntdll. A misaligned one gives RIP alone.
  • host.rs: thread_sample::start_from_env() at start; lib.rs: the module; eh.rs: thread_name is pub(crate); README.md: the switch.
  • Tests (no GPU):
    • the switch's parsing;
    • the file read back record by record;
    • the frame extent of every unwind code (synthetic UNWIND_INFOs, chained and indirect entries, refusals);
    • a real 64 KiB frame walked from a 16 KiB copy that ends at a PAGE_NOACCESS page stops with [RIP, TRUNCATED], and from the whole stack unwinds into its caller;
    • a sampling of this process that finds a spinning thread running and a waiting one unchanged.

Second and third commits, the reader (scripts/thread_sample.py, Python 3, standard library only):

  • Per thread group (the thread's name, else its start address): CPU as a share of one core, the samples split into user code, a system call at work and a wait, the share of each module, and for the busiest groups the top functions, inclusive and self, and the ntdll / win32u leaves.
  • xcl.exe is named through its PDB (dbghelp via ctypes), other DLLs through their export tables. The title's own images are printed only as title.exe / title-dll<k> plus a page offset, never by name or path.
  • Without the end record (a capture still being written, or a run that ended before it), the TSC rate comes from the first and last sample's TSC over their log uptime, said as approximate; with fewer than two timed samples the CPU shares are said to be unavailable and the cycles are shown (third commit, from andrewDoing's report below: such a capture showed every thread at 0.0 %).
  • --log <xcl.log> (a run with XCL_ACTIVITY=1) gives ms per frame from its presents. --selftest writes a synthetic file over the real ntdll and checks the shares, the names, the waits, and that no title name is printed.

+1,690 / −1 in 6 files: 1,071 lines for the sampler (its tests among them), 605 for the reader, 15 elsewhere. Over the 400-line target: the sampler and its unwinding only make sense together, and the reader is a separate commit. Nothing runs unless XCL_THREAD_SAMPLE is set.

Measured / Read / Deduced

  • Measured, an earlier version of this sampler, in our title runs:
    • one 437 s run with XCL_THREAD_SAMPLE (12,000 samples, 209 threads): 183,848 stops, 82 µs each on average, the longest 264 ms; the sampler used 2.2 ms per sample. These are that version's own totals line.
    • 4 of 85 runs with the sampler died on the sampler's thread, inside RtlVirtualUnwind. In one of them, the frame being unwound was a 146 KiB title frame, while the copy is 16 KiB. That is what frame_extent now bounds. Separately, a unit test died in ntdll on a frame that saves xmm6, from the alignment above. Both are covered by the tests in this PR; neither fix has had a title run yet.
  • Read: xcl run: thread dumps unwind a copy of each stopped thread's stack #253 (merged on main since) and xcl run: XCL_THREAD_DUMP_AT unwinds a copy of each thread's stack #2923 (open) copy each thread's stack and unwind over the copy for XCL_THREAD_DUMP_AT (one dump), xcl run: XCL_THREAD_DUMP_AT unwinds a copy of each thread's stack #2923 with a bound like frame_extent (its frame_reach). This PR samples continuously and adds the cycle times; the two could share the unwinding later.

Tested

  • Head 8eb9a99 on main 7a649b0 (rebased 29/11, no conflict; xcl run: thread dumps unwind a copy of each stopped thread's stack #253 is merged on main since the last push, its eh.rs stack copy for XCL_THREAD_DUMP_AT sits next to this PR's thread_name change without touching it). RTX 3090 24 GB (Resizable BAR off), driver 616.56, Ryzen 9 5950X, 32 GB RAM, Windows 11 22631; Rust 1.100.0, release tests; Python 3.12.10.
  • Measured on this head, CPU only (XCL_ADAPTER=warp; XCL_REQUIRE_GPU unset; nothing here uses the GPU):
    • cargo test --release -p xcl --lib -- thread_sample eh:: shaders::pipeline_library::tests shaders::warm_library::tests --test-threads=4: 21 passed, 7 failed: the 5 thread_sample tests and 12 eh:: tests passed (with xcl run: thread dumps unwind a copy of each stopped thread's stack #253's stack copy now on main). The 7 failures are 6 shaders::pipeline_library::tests and shaders::warm_library::tests::cold_publish_makes_an_unchanged_corpus_reusable: CreateComputePipelineState returns E_INVALIDARG on this machine's WARP, which has no SM 6.6 (the other 6 then fail on the poisoned lock or the same error). That is a local artefact of a WARP run here, not the CI failure (an entry count, 3 against 2).
    • The same filters on main 7a649b0: the same 7 failures with the same errors, nothing else failed (408 passed, 7 failed, 19 ignored for the union of the filters of our five PRs).
    • python -I scripts/thread_sample.py --selftest: SELFTEST PASSED, 12 checks, the no-end-record ones among them (without xcl.exe's PDB next to it, so its PDB checks were skipped).
    • The build has the same 18 compiler warnings as main 7a649b0 (no new one).
  • Measured on this head, release on the RTX 3090 machine (XCL_REQUIRE_GPU=mesh): cargo test --release -p xcl --lib -- thread_sample:: --test-threads=1: 5 passed, 0 failed, 0 ignored: the 5 thread_sample tests, the sampling of this process among them.
  • Read, CI: "Build and test (Windows, no GPU)" passed on the previous head d5b5c66. On main 7a649b0 main's own CI fails 8 tests, all in hle::d3d12x::title_textures::tests (run 46261846646): a red Build and test on this head with those 8 is main's.

Regression run
Same machine as under Tested, same title, 60 s each (the scripts/smoke.ps1 default), both through main d52ff48's scripts/smoke.ps1, XCL_PREPARE=0, the same scripted A presses (XCL_PRESS_A_AT), XCL_THREAD_SAMPLE unset. Each run started from its own copy of the same shader cache, made by another main commit, so cold for both. The head is on main 7a649b0; the main run is of main d52ff48 (the newest main today, 244 commits later), not of the head's base: the check asks for a commit of main.

main d52ff48:

xcl-smoke v1
commit: d52ff48caade1f5350d513bfffd370396dadfeb6
gpu: NVIDIA GeForce RTX 3090
title: 16b5e5d4
seconds: 60
exit: 0x0
frames shown: 517 (PresentX 517)
presents per 2 s (last 3): 61 60 61
device removals: 0
crashes: 0
peak commit: 15968 MB

this head 8eb9a99 (main 7a649b0 + this PR's three commits):

xcl-smoke v1
commit: 8eb9a992f82cbbf39a8ad92bb231ff777fecc984
gpu: NVIDIA GeForce RTX 3090
title: 16b5e5d4
seconds: 60
exit: 0x0
frames shown: 570 (PresentX 570)
presents per 2 s (last 3): 61 60 61
device removals: 0
crashes: 0
peak commit: 15629 MB
  • Measured: no device removal and no crash in either run, both ended by themselves (exit 0x0). The head shows 570 frames against main's 517 (110.3 %; the check wants at least 80 %), peak commit 15,629 MB against 15,968 MB (97.9 %; at most 125 %). Last three 2 s slices: head 61 60 61, main 61 60 61 presents. 60 s covers the start of the title, not a long stay in its world.
  • Deduced: the head's base is 244 commits behind main d52ff48, so the difference between the two runs includes those commits, not only this PR.

Not tested

  • A title run of this exact head with XCL_THREAD_SAMPLE set (the runs above were of the earlier version).
  • The cost on other CPUs; on AMD or Intel GPUs (nothing GPU-specific here).
  • Windows 10 and Wine.

AI use
AI use: the sampler, its fixes, the reader, the rebase, the test and smoke runs and this description were done with Claude Code (Claude Opus 5.5), checked and posted by me.

🤖 Generated with Claude Code

@github-actions github-actions Bot added area:docs-ci Documentation, scripts, workflows, repo governance area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH labels Nov 28, 2026
@andrewDoing

Copy link
Copy Markdown
Contributor

On a8cd5921, a capture without a complete final E record reports a busy thread as 0.0% CPU. The sample rows can still contain all their cycle deltas. That matters when inspecting a still-running capture or a run that exited before finalization.

I measured QueryThreadCycleTime, wall time (QPC), TSC and GetThreadTimes for three bounded 1.5 s spinner controls on a Windows Ryzen 7 5700X3D. TSC calibrated to 3.000 GHz; cycles/TSC gave 99.0–99.4% of a core and kernel+user thread time gave about 99.0%. Three sleeping controls gave about 0.001% by cycles.

For an exact reader comparison, I put the first measured spinner and sleeper cycle deltas into the same four synthetic S records covering 1.5 s. Those records were identical in all three files. Running this PR's unchanged scripts/thread_sample.py gave:

File ending Spinner Sleeper All threads
Complete E record 99.5% 0.0% 1.0 cores
Ends immediately after last S record 0.0% 0.0% 0.0 cores
First five bytes of E record only 0.0% 0.0% 0.0 cores

The reader labels the latter two captures truncated, but cpu(g) converts the missing final calibration into a numeric zero for every group. Reporting raw cycles and “CPU percentage unavailable” would retain the useful evidence. An explicitly approximate fallback could also use valid separated sample TSC/uptime pairs. No title process or stack unwinding was involved in this reader control.

AI assistance: OpenAI Codex ran the bounded Windows measurements, constructed the files and drafted this report.

CharlyRien added a commit to CharlyRien/xcl that referenced this pull request Nov 28, 2026
…end record

The TSC rate the cycle times are converted with came only from the end record ('E'),
so a capture still being written, or one from a run that ended before the sampler
wrote it, showed every thread at 0.0 % of a core although its samples hold all the
cycle deltas (andrewDoing on xcl-dev#3232). Without the end record the rate is now taken from
the first and last sample's TSC over their log uptime, said as approximate; with fewer
than two timed samples the shares are said to be unavailable and the cycles are shown.

--selftest: the synthetic samples carry real TSC values, and the same file without its
end record gives the same ~91 % for the busy thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added the needs-pr-check Failing the PR description check (CONTRIBUTING.md) label Nov 28, 2026
@CharlyRien

Copy link
Copy Markdown
Contributor Author

@andrewDoing thanks, you are right: the reader took the TSC rate from the end record only, so a capture without it showed 0.0 % for every thread.

Fixed in d5b5c66 (reader only, scripts/thread_sample.py):

  • Without the end record, the rate now comes from the first and last sample's TSC over their log uptime, and the output says the shares are approximate.
  • With fewer than two timed samples, it says the CPU shares are unavailable and prints the cycles instead.
  • --selftest now runs the same synthetic file without its end record and expects the same ~91 % for the busy thread. It passed here (RTX 3090 machine, Ryzen 9 5950X, Windows 11 22631; Python only, no title).

AI use: Claude Code with Claude Opus 5.5 made the fix, ran the self-test and wrote this reply.

CharlyRien and others added 3 commits November 29, 2026 14:28
XCL_THREAD_SAMPLE=<from s>,<period ms>,<count> (+ XCL_THREAD_SAMPLE_FILE):
from log time <from>, every <period> ms, a thread of its own reads for
every other thread of the process its cycle time since the previous
sample (QueryThreadCycleTime: the CPU it used, exact) and, when it ran,
its registers and the top 16 KiB of its stack. The thread is stopped
only for GetThreadContext and that copy: no lock and no allocation
while it is suspended. Frames are unwound afterwards from the copy with
RtlVirtualUnwind: RIP and up to 7 return addresses. A thread whose
cycle time did not move and that waits in ntdll / win32u is not stopped
again (its last stack is written as "unchanged"). Everything goes to a
binary file with the modules and the thread names; the log gets a start
line and the totals. Off unless set. ETW and VTune need elevation; this
needs nothing.

The walk never reads outside the copy: before each RtlVirtualUnwind,
frame_extent bounds what the step can read from the function's
UNWIND_INFO (pushes, allocations, machine frame, the farthest save,
chained and indirect entries, version 2 epilogue descriptors, plus the
return address; unknown codes are refused). That span must lie in the
copy from RSP and, with a frame register, from FrameReg - 16 x
FrameOffset; otherwise the walk ends with the frame TRUNCATED (1). The
copy starts at RSP & !15 in a 16-aligned buffer and the CONTEXT is
16-aligned: RtlVirtualUnwind restores XMM saves with aligned moves (a
misaligned copy is an access violation in ntdll); a misaligned one gives
RIP alone.

eh::thread_name is pub(crate) for the thread names.

Tests (no GPU): the switch's parsing; the file read back record by
record; the frame extent of every unwind code (synthetic UNWIND_INFOs,
chained and indirect entries, refusals); a real 64 KiB frame walked
from a 16 KiB copy that ends at a PAGE_NOACCESS page stops with
[RIP, TRUNCATED], and from the whole stack unwinds into its caller; a
sampling of this process that finds a spinning thread running and a
waiting one unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Per thread group (the thread's name, else its start address): CPU as a
share of one core from the exact cycle times, the samples split into
user code, a system call at work and a wait, the share of each module,
and for the busiest groups (and always the thread that submits command
lists) the top functions inclusive and self and the ntdll / win32u
leaves. xcl.exe is named through its PDB (dbghelp via ctypes), other
DLLs through the export table of the file at the recorded path. The
title's own images are printed only as title.exe / title-dll<k> plus a
4 KiB page offset, never by name or path. --log takes an xcl.log of a
run with XCL_ACTIVITY=1 and gives ms per frame from its presents. The
sampler's TRUNCATED frame (1) is printed as the callers past the
stack copy.

--selftest writes a synthetic file over the real ntdll (and xcl.exe
with its PDB when XCL_EXE or target/release has one) and checks the
shares, the names, the waits and that no title name is printed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…end record

The TSC rate the cycle times are converted with came only from the end record ('E'),
so a capture still being written, or one from a run that ended before the sampler
wrote it, showed every thread at 0.0 % of a core although its samples hold all the
cycle deltas (andrewDoing on xcl-dev#3232). Without the end record the rate is now taken from
the first and last sample's TSC over their log uptime, said as approximate; with fewer
than two timed samples the shares are said to be unavailable and the cycles are shown.

--selftest: the synthetic samples carry real TSC values, and the same file without its
end record gives the same ~91 % for the busy thread.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot removed the needs-pr-check Failing the PR description check (CONTRIBUTING.md) label Nov 29, 2026
@CharlyRien

Copy link
Copy Markdown
Contributor Author

Rebased on main 7a649b0; head 8eb9a99 (no conflict). Measured, CPU only (cargo test --release -p xcl --lib -- thread_sample eh:: + the library tests): 21 passed, 7 failed; the 5 thread_sample and 12 eh:: tests passed (#253 now on main), and python -I scripts/thread_sample.py --selftest passed. The 7 failures are the 6 shaders::pipeline_library::tests and warm_library::tests::cold_publish_makes_an_unchanged_corpus_reusable, the same 7 with the same errors on main 7a649b0 here: E_INVALIDARG from CreateComputePipelineState on this machine's WARP (no SM 6.6). Deduced: a local artefact of WARP here, not the CI failure mode. No title run.

Read, CI: the 4 pipeline_library / warm_library failures of our previous CI runs were main's own on 227d2cb (run 46201186646) and passed on main since fa20459; main 7a649b0 now fails 8 hle::d3d12x::title_textures::tests in CI (run 46261846646), so a red Build and test with those 8 is main's. "PR description" stays red only for the xcl-smoke pair of the new head, which needs a title run (not made: CPU only this time).

Description refreshed (Tested, Regression run, AI use).

Stack: RTX 3090 24 GB (Resizable BAR off), driver 616.56, Ryzen 9 5950X, 32 GB RAM, Windows 11 22631; Rust 1.100.0, release tests, XCL_ADAPTER=warp, XCL_REQUIRE_GPU unset.

AI use: rebase, test runs and this comment done with Claude Code (Claude Opus 5.5), checked by me.

@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Triage (#1607) – head 8eb9a99

No open or merged PR adds a CPU-time/stack sampler. The closest is #2923 (XCL_THREAD_DUMP_AT unwinds a copy of each thread's stack), which is a one-shot dump in eh.rs and shares no code with thread_sample.rs.
In thread_sample.rs:run, the target thread is suspended only for GetThreadContext and a stack copy into a preallocated buffer (no lock or heap while it is suspended), and walk checks each unwind step against the copy before calling RtlVirtualUnwind. No problems found in the diff. At +1712 lines (about 1070 in Rust), it is well over the 800-line size guideline.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

merge-check
base: 493dbd3
head: 8eb9a99
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2905 passed, 0 failed, 51 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on main); failing: none
review: read the whole diff (+1712/-1: 684 lines of sampler, 386 of tests, a 627-line Python reader). With XCL_THREAD_SAMPLE unset nothing runs: one environment read (host.rs ~263), no thread, hook, allocation or symbol loading. Findings: (1) Size and duplication. "The sampler and its unwinding only make sense together" doesn't cover the reader, which is plainly separate. The unwinder (thread_sample.rs ~201-354, walk / frame_extent) is a second, stricter copy of main's eh.rs copy_stack / unwind (~872-931) and of open #2923's frame_reach. It should replace eh::unwind as a shared helper rather than sit beside it. A split: the shared copy-and-unwind helper with its tests (agreed with #2923); the sampler, its test and README; Scripts: the reader with its self-test as scripts/test_thread_sample.py. (2) The crash fix hasn't run in a title. The description reports 4 of 85 sampler runs dying in RtlVirtualUnwind, and neither fix has had a title run with the sampler on. A fault on the sampler thread ends the title, since nothing catches it. (3) The stack is copied with a plain memory copy (~581) where eh.rs uses ReadProcessMemory, which fails cleanly. A fault would hit while the other thread is suspended. Low risk after the VirtualQuery check, but copy_stack should be reused. (4) Accuracy: a thread last seen waiting in ntdll that used under 1M cycles (~45, ~553) is marked unchanged for up to 20 samples, so short bursts are charged to the old wait stack. count has no upper bound (~70), and the thread list refreshes every 100 samples (~514), so short-lived threads are missed. (5) The live test (~989) suspends every thread of the test binary, other tests included, and asserts timing (spin_stopped >= 140), so it may flake under load. The reader's --selftest isn't run by any harness. (6) Minor: XCL_THREAD_SAMPLE is missing from legacy_warm_settings' ignore list (shaders.rs ~68). Fine: while a thread is suspended the sampler only calls GetThreadContext, VirtualQuery and the copy, with buffers allocated beforehand and everything else done after ResumeThread, the same rule as eh.rs (#106), so no heap or loader deadlock. frame_extent bounds its reads (machine frames, chained entries, v2 epilogues) and has tests. dbghelp is used only in the offline reader, and there are no new dependencies.
performance: no smoke run (the default path doesn't reach this change); not measured. The sampler is off unless XCL_THREAD_SAMPLE is set, so no smoke run; the live sampling test passed here under the full suite's load.
verdict: not yet: 1,712 lines with the reader plainly separable, and an unwinder that duplicates eh.rs / #2923 instead of replacing them; split it (shared helper, sampler, reader) and run a title with the sampler on to show the RtlVirtualUnwind crash fix holds
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:docs-ci Documentation, scripts, workflows, repo governance area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants