perf(prof): the Linux samplers name frames from the loaded objects' segments, read once, not dladdr #3155
No reviewers
Labels
No labels
area/accessibility
area/audio
area/input
area/install
area/menu
area/mods
area/renderer
area/saves
area/tooling
area/upscaling
beanstalk: approved
beanstalk: failed
beanstalk: needs approval
beanstalk: running
beanstalk: tested
ci: approved
good first issue
gpu/amd
gpu/igpu
gpu/intel
gpu/nvidia
help wanted
kind
bug
kind
chore
kind
docs
kind
feature
kind
performance
kind
question
needs measurements
platform/linux
platform/macos
platform/steam-deck
platform/windows
preview
priority
critical
priority
high
priority
low
regression
risk
high
risk
low
risk
medium
status
blocked
status
confirmed
status
duplicate
status
invalid
status
needs-info
status
wontfix
ci: approved
No milestone
No project
No assignees
3 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
MagicBeanDev/Longshot!3155
Loading…
Reference in a new issue
No description provided.
Delete branch "decohered/Longshot:perf/sampler-module-spans"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Using the slow-frame recorder (which samples every 4ms), the Linux samplers spent 13.9% of the process's CPU samples on my Steam Machine just doing dladdr to name frames.
dladdrtakes the loader's lock and walks the object's exported symbols, for every frame of every sample (14,500 of them inlongshot_vk.so)Now we have a table of all the loaded objects, sorted by their segments, and we can use binary search to find the module for any given frame. If we encounter an address that isn't in our table, we read it again, but we'll only do this once per second at most.
HOS_SLOW_FRAMES_EVERY_MSis read from the environment once, too; the sampler asked for it every sweepStart with
module_ofinhost/posix/prof.c, thentests/test_prof_modules.py.Testing
Tested: I've had this in every build I've played on my Steam Machine since. The slow-frame files name their frames the same as they used to.
Steam Machine: Navi 33 8 GB, SteamOS 3.10.1, kernel 7.3.1-valve3
tests/test_prof_modules.py,tests/test_prof_walk_fault.py,tests/test_slow_frames.pyandtests/test_profiling_mode.pypass with gcc and clangAfter review (
5a469b911),tests/test_prof_modules.pyalso unloads a library and loads another, perhaps where it was, and loads 70 objects; the code before it fails the unloadThe game builds whole at
5a469b911on Linux.mise run teston Linux at095ca3866: 863 pass, 13 skip (Windows only or a device it needs), 19 fail. The same 19 fail on main @299ed5b70with the same tools (the toolchain from nixpkgs; mise's pinned one isn't set up here), so none come from this change.The 19
byte_compile_tracked, f2i_immediate, global_load_16, native_suatom, test_check_cache, test_checks_container, test_cloth_kernels, test_dav1d_av1, test_fsr_uniform_ownership, test_game_module_imports, test_lifter, test_lifter_semantics, test_linux_pressure, test_loaded_modules_drop, test_native_zstd, test_program_cache_cleanup, test_program_cache_one_variant, test_thinlto_tls, test_ui_renderer
Still to test:
Measurements
Verdict: Naming a frame no longer calls
dladdr, which took 13.9% of the process's CPU samples on my Steam Machine with the slow-frame recorder on.299ed5b70095ca3866dladdrcalls to name a frameRisks
If a library is loaded after the table was read, it will be picked up on the next miss, so a frame in it might be unnamed for up to a second. Players will never see this though, since the samplers only run when the profiler or slow-frame recorder is active.
Checklist
Ready for review
main; the title is a Conventional Commit.mise run testpasses (any failure that also fails onmainis named).main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
tests/that reads changed source is updated, not weakened.Assisted-by:/Co-Authored-By:trailers.Ready to merge
main, measured again or a comment says why the numbers still hold.🤖 Generated with Claude Code
@review
Recommendation: Request changes. The module cache can misidentify frames after libraries are unloaded or replaced, and its fixed capacity can leave sampled modules unnamed. The new test also cannot run on Windows; the claimed performance gain remains unmeasured against the base.
The change replaces per-frame Linux dladdr calls with a cached segment lookup and caches the slow-frame sampling interval. It reduces repeated lookup work, but introduces module-lifetime and capacity problems in diagnostic output.
Blocking (3): must change before merging.
host/posix/prof.c:311: A cache hit never checks whether the object has been unloaded or replaced, and module_add also reuses an old name solely by base address. (more on the line) Do: Track loader changes and rebuild the active spans and module identities when objects are loaded or unloaded, while preserving any identities needed by accumulated samples. Add an unload and address-reuse test.host/posix/prof.c:273: The first enumeration consumes the 64 module slots for every loaded object, including objects that are never sampled, and slots are never reclaimed. (more on the line) Do: Use a dynamically sized active-object table or otherwise ensure every loaded segment can be represented; test with more than 64 loaded objects and a late-loaded object.tests/test_prof_modules.py:20: The Linux-only test is discovered on Windows without a platform skip and attempts to compile and run a program using Linux dynamic-loader headers and APIs. (more on the line) Do: Declare a Windows RUN_ALL_SKIP and guard direct invocation on unsupported platforms, as the other Linux sampler test does.Should fix (3): not blocking, but worth doing before merging.
host/posix/prof.c:264: The 64th module collides with the sampler's existing unknown-module sentinel, index 63. (more on the line) Do: Use a distinct sentinel in the sample key or reserve index 63, and test an unknown frame when the table is full.host/posix/prof.c:278: The mutex protects writes to nmods, but the periodic HOS_SAMPLE report reads nmods without that mutex while another sampler or HOS_WATCH can refresh the table. (more on the line) Do: Protect the report's module-table reads with the same mutex, or publish an immutable snapshot with proper synchronization.tests/test_prof_modules.py:96: Direct test runs ignore CC, and compiler commands containing arguments are passed as one executable name. (more on the line) Do: Default to CC when set and parse the compiler command using the repository's compiler-command helper before appending the flags.Testing before merging (1) (runs on the systems it can change; it doesn't hold the recommendation)
@fixcan do L1, L2, L3, L4, L5 and L6.Checks: Still running: 11 checks.
More: does it help, other systems, switches, what was read
Does it help: Unproven. The PR reports that dladdr accounted for 13.9% of process CPU samples on the base and that calls per frame fall from one to zero. It does not report comparable before-and-after sampler CPU, frame-rate, or frame-time measurements over multiple runs.
Other systems: The lookup serves HOS_SAMPLE, HOS_SAMPLE_ALL, slow-frame recording, profiling mode, and HOS_WATCH on Linux. The interval cache is shared host code used by the Windows sampler too. The reported game run covers one AMD SteamOS machine; it does not establish the effect on other Linux systems or frame pacing.
Switches: HOS_SLOW_FRAMES_EVERY_MS remains default 4 ms, clamped to at least 1 ms; its value is now cached on first use. No switch was added or removed.
Reviewed:
095ca38663against299ed5b704: Read AGENTS.md, CONTRIBUTING.md, docs/dev/standards.md, the PR template, the commit and complete diff, host/posix/prof.c, host/slow_frames.c, and tests/test_prof_modules.py. Traced sampler and watch callers, module loading, the test runner, and the related fault test. Skimmed references to diagnostic consumers and other library unloads. docs/review-checklist.md and ../Tooling/AGENTS.md were absent. No recorded runs, translations, or generated files were changed.; nothing run (a code review).Checked and fine:
Testing: No commands from the project were run, as requested. The author reports Linux game and test runs; CI checks were still running in the supplied results.
Overlaps and merge order: Unknown; the network was closed and no overlap information was supplied.
Automated code review by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.
@ -268,3 +276,3 @@mods[nmods].base = *base;mods[nmods].base = base;snprintf(mods[nmods].name, sizeof mods[nmods].name, "%s", b ? b + 1 : n);return nmods++;L4 (should fix): The mutex protects writes to nmods, but the periodic HOS_SAMPLE report reads nmods without that mutex while another sampler or HOS_WATCH can refresh the table.
When: With HOS_SAMPLE and HOS_WATCH enabled together, the watch thread can add a newly loaded module while the sample thread evaluates mi < nmods. The unsynchronized read and write form a C data race.
Do: Protect the report's module-table reads with the same mutex, or publish an immutable snapshot with proper synchronization.
@ -257,1 +262,3 @@static Module mods[64];typedef struct { uintptr_t lo, hi; int mod; } Span;enum { MAX_MODS = 64, MAX_SPANS = 512 };static Module mods[MAX_MODS];L3 (should fix): The 64th module collides with the sampler's existing unknown-module sentinel, index 63.
When: Once the enumeration fills all 64 entries, an unknown frame is encoded with index 63 and the periodic HOS_SAMPLE report prints the name of mods[63] instead of '?'.
Do: Use a distinct sentinel in the sample key or reserve index 63, and test an unknown frame when the table is full.
@ -265,2 +272,2 @@if (nmods >= 64) return -1;const char *n = d.dli_fname && d.dli_fname[0] ? d.dli_fname : "longshot";if (mods[i].base == base) return i;if (nmods >= MAX_MODS) return -1;L2 (blocking): The first enumeration consumes the 64 module slots for every loaded object, including objects that are never sampled, and slots are never reclaimed.
When: With more than 64 loaded objects, a frame in an object later in the loader list returns '?' on every refresh. Previously slots were consumed only by modules actually encountered in samples, so the same frame could be named.
Do: Use a dynamically sized active-object table or otherwise ensure every loaded segment can be represented; test with more than 64 loaded objects and a late-loaded object.
@ -272,0 +308,4 @@}if (lo > 0 && pc < spans[lo - 1].hi) found = spans[lo - 1].mod;else if (!pass && (!nspans || hos_now_ns() - spans_read_ns >= 1000000000LL)) {nspans = 0;L1 (blocking): A cache hit never checks whether the object has been unloaded or replaced, and module_add also reuses an old name solely by base address.
When: After a sampled library is unloaded, its spans remain in the table. If another library is mapped at that address, its frames hit the old span and are attributed to the old library indefinitely; even a later refresh retains the old name when the base is reused.
Do: Track loader changes and rebuild the active spans and module identities when objects are loaded or unloaded, while preserving any identities needed by accumulated samples. Add an unload and address-reuse test.
@ -0,0 +17,4 @@from srccut import between # noqa: E402RUN_ALL_ARGS = ["--cc", "{cc}"]L5 (blocking): The Linux-only test is discovered on Windows without a platform skip and attempts to compile and run a program using Linux dynamic-loader headers and APIs.
When: A Windows run of tests/run_all.py selects this test and invokes the Windows compiler on dlfcn.h, link.h, dl_iterate_phdr, and ELF-specific flags, so the check fails instead of being skipped.
Do: Declare a Windows RUN_ALL_SKIP and guard direct invocation on unsupported platforms, as the other Linux sampler test does.
@ -0,0 +93,4 @@parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--cc", default="cc")args = parser.parse_args()source = (ROOT / "host/posix/prof.c").read_text(encoding="utf-8")L6 (should fix): Direct test runs ignore CC, and compiler commands containing arguments are passed as one executable name.
When: With CC set to clang, running the documented command still uses cc; with the runner passing a value such as 'ccache clang', subprocess attempts to execute a file with that entire name.
Do: Default to CC when set and parse the compiler command using the repository's compiler-command helper before appending the flags.
Thanks, these were good catches -- all six are fixed in
5a469b911.The slots were the one that really mattered.
CCI added the unload to the test, too: it unloads a library, loads another one possibly in the same location, then loads 70 more. The old code fails it.
@review
Recommendation: Approve. The code is ready: only testing is left. The slot allocation, unload handling, synchronization and test portability issues are addressed. The claimed performance gain still needs a before-and-after measurement of sampler cost and frame pacing. Recommend approval; not approved on the forge.
Linux profiling and slow-frame recording name sampled frames from cached loaded-object segments instead of calling dladdr for every frame. The fix assigns slots only to sampled modules and refreshes stale mappings, at the cost of a locked lookup and periodic loader checks whose performance impact is not yet quantified.
Testing before merging (1) (runs on the systems it can change; it doesn't hold the recommendation)
Since the last review (on
095ca38663)Resolved: L1 (A cache hit never checks whether the object has been unloaded or replaced, and module_add…); L2 (The first enumeration consumes the 64 module slots for every loaded object, including obje…); L3 (The 64th module collides with the sampler's existing unknown-module sentinel, index 63.); L4 (The mutex protects writes to nmods, but the periodic HOS_SAMPLE report reads nmods without…); L5 (The Linux-only test is discovered on Windows without a platform skip and attempts to compi…); L6 (Direct test runs ignore CC, and compiler commands containing arguments are passed as one e…)
Still open: L7 (The reported reduction in calls does not quantify the performance benefit or the effect of…)
Checks: Still running: 11 checks.
More: does it help, other systems, switches, what was read
Does it help: Unproven. The author reports dladdr accounted for 13.9% of process CPU samples before the change, and calls per frame fell from one to zero; those figures do not quantify the net benefit or frame-pacing effect.
Other systems: The module lookup affects Linux profiling, slow-frame recording and HOS_WATCH; Windows uses a separate lookup. The shared slow-frame interval cache also runs on Windows. The author reports Linux game use, a Linux build, and passing focused tests with gcc and clang; the net timing effect remains unmeasured.
Switches: HOS_SLOW_FRAMES_EVERY_MS keeps its 4 ms default and minimum of 1 ms, but is now read once. It remains a diagnostic setting; no new player switch is added.
Reviewed:
5a469b9110against299ed5b704: Read AGENTS.md, CONTRIBUTING.md, the pull request template, the changed module lookup and test, host/slow_frames.c, and the compiler-command helper. Reviewed both diffs and commit summaries; the remaining profiler code and associated callers were skimmed. Tooling's separate rules were unavailable in the supplied checkout.; nothing run (a code review).Checked and fine:
Testing: No commands that build or run project code were executed. The author reports focused Linux tests with gcc and clang, a Linux game build, and in-game use; CI is still running.
Overlaps and merge order: Not checked; network access is closed.
Automated code review by BeanBot (gpt-6.1-terra), asked for by HumanBean. Nothing was run; a maintainer decides.