perf(mods): the mod runtime's per-frame cost counted (HOS_FRAME_COST) and cut #2880
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
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
MagicBeanDev/Longshot!2880
Loading…
Reference in a new issue
No description provided.
Delete branch "cleanup/area7-frame-cost"
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
On
mod-apithe game's main thread spends more CPU a frame than onmain; the gap was about 0.17 ms and no code pathread explained it. This PR first measures where the time goes, then cuts what the numbers pointed at.
HOS_FRAME_COST=1(a diagnostic switch, off by default) logs a fewframe cost:lines every 10 s:the CPU time a frame of each named step of the game side's acquire phase (the loader's, each native system mod's
frame, every services step), and every hook site's hits and time a frame, the main thread's apart from the other
threads'. The plain trampoline's sites (the engine's own Rust callbacks) count their hits too while it is on. The
frame trace (
RX_VK_FRAME_TRACE=1) has a new column,acquire_cpu_ms: the main thread's CPU time insidegame_phase_run, the whole of the mod runtime's frame, read around the call inhost/nn_vi.c(two thread-clockreads a frame, only while the frame is timed) and handed to the renderer as
MkwVkHost.main_thread_times' fourthvalue (API version 82).
next to nothing (the ones with time there are the barrier fix's sleeps, which main has too). The phase is many small
steps, none big: the settings host's step, the renderer status the HDR mod reads, the loader's manifest check, the
timers, the input step, the UI's frame end, each 2 to 8 us.
lists for every running mod each frame); the load order is shared (
Rc), so the steps that walk it take a count, nota copy; the Insert menu's fallback does nothing unless it shows or is wanted; the loader's check of the linked
manifests walks the list it set, in order, with no look-up by id; the frame event's payload is made only for a
listener; the game's moments make no listener list for an event nobody listens to; and one Rust function's handler
around an empty core (widescreen's and sprint-walk's sites) takes the plain trampoline instead of the dispatcher:
no chain loaded or walked, but still counted in the site's readers (its pointer tagged in
PLAIN), soremove_retired/remove_thenwait for a hook still in it, as they do for the dispatcher (commit 3).Read first:
game/crates/game-sites/src/cost.rs,chain.rs'spublish,api/src/services/time.rs'stimers_step.Testing
Tested: Linux (CachyOS 7.3.3), RTX 3090, NVIDIA 620.70.06. In the game, Hyrule Field (child), 1080p native, six
measured runs of 60 s through
dev.py ab(below): every system mod started, no fault, the frame trace'sacquire_cpu_msfilled on this PR's side. Before the cuts, two runs withHOS_FRAME_COST=1logged theirframe cost:lines every 10 s (the numbers in Summary). Checks:
cargo clippy -D warningsandcargo testof game-sites, api,longshot-game and the widescreen, sprint-walk and shadows system mods;
tests/run_all.py --changed(204 checks: onefailed,
test_pacing_policy.py, fixed by giving its fixture the thread clock, then passed withtest_frame_trace_waits.py); the renderer compiled for Windows with llvm-mingw. The host's Windows compile(
check_host_compile.py) compiled every unit buthost/nn_video.c, which needs FFmpeg's headers this PC's setupdoes not give it (not a file this PR changes;
host/nn_vi.ccompiled). After the review fix and the rebase ontomod-api@75bcd270(one build-mode queue job): clippy-D warningsandcargo testof game-sites (withfake),api and longshot-game,
tests/run_all.py --changed,scripts/shaders.py alland the whole Windows host compile(
check_host_compile.py, llvm-mingw, with FFmpeg's headers) all passed. game-sites' new testa_lone_function_handler_removed_while_running_waits_for_itfails without the readers' count and passes with it. game-sites'retiretests fail now and thenunder load, on
mod-apitoo (5 runs in 25 there): not this PR's.Still to test:
RX_VK_FRAME_TRACE=1), expectingacquire_cpu_msfilled and belowmain_cpu_ms;HOS_FRAME_COST=1logs itsframe cost:lines every 10 s (@Beanstalk run Hyrule Field withRX_VK_FRAME_TRACE=1 and HOS_FRAME_COST=1 and attach the log's frame cost lines)
Measurements
Verdict: the main thread is 0.09 ms a frame over
mainnow (2.018 against 1.928 ms), of which 0.066 ms is the modruntime's acquire phase. Average fps is within 1 % of
main(139.2 against 138.0). The 1% low (125.4 against 117.0,-6.7 %) and p99 (7.98 against 8.55 ms, +7.1 %) are noisy and inconclusive: their runs spread from 80 to 126 fps. The cuts' own share was not measured apart (no
mod-apiside was run): from the counters' per-step numbers they save about 10 to 15 us a frame (the timers 3 to 4 us,the manifest check about 4, the fallback about 2, the load-order copies and the moments' lists a few). The gap is not
closed: what is left is the many 1 to 8 us steps above, the settings host's step and the renderer status the HDR mod
reads being the biggest (area 2 and area 3 change those).
Setup: Linux, RTX 3090, NVIDIA 620.70.06; Hyrule Field (child), output 1920x1080, Render resolution 100 %, no upscaler,
uncapped, V-Sync and frame generation off (
dev.py ab --options native1080.ini,HOS_FPS_MAX=1000); A, B, A, B, A, B,60 s each after the warm-up, the median of three.
main_cpu_msandacquire_cpu_msare the frame trace's means overthe measured frames. A is
main's own runtime at the fork point, unconfined asmainruns (HOS_SANDBOX=0:main'sgame cannot serve the control bridge inside the builder's sandbox); B is this PR's, confined by default, as a player
runs it.
These numbers are from before the rebase. They still hold: the rebase onto
mod-api@75bcd270brought in #2855(rustfmt only), #2861 (where menu rows are placed: menu layout and settings listing) and #2881 (a mod's game language:
loader, manifest and init-time code). None of them runs per frame in Hyrule Field with the menu closed. The review fix
adds two atomics per hit on widescreen's and sprint-walk's sites. That is what the dispatcher counted before this PR,
without the chain load and walk. The user accepted the fps gap on this area, so the runs were not repeated.
46291934main_cpu_ms)acquire_cpu_ms)The third pair was noisy on both sides (p99 12 ms); the 1% low's median on B is its second run's (117.0; 124.8 and 85.5
the others). Run folder:
~/.local/share/longshot-dev/runs/ab/20261130-003115-hos_frame_cost-hos_sandbox-hyrule-field.dev.py abgave no write-up (exit 3): the sides differ in the menu's rowsmod-apiadds and in the sandbox's switches,as every
mainagainstmod-apicomparison does.The counters' run (B with
HOS_FRAME_COST=1, before the cuts, both sides confined then): acquire phase 0.133 ms withthe counters' clock reads; steps a frame: services 76 us, loader 38 (the native mods' frames 28, of which hdr 4.7),
settings host 7.9, the manifest check 5.7, input 4.0, UI frame end 3.9, timers 3.9, the game's moments 3.7, the file
watch 2.8, the menu fallback 2.3; sites on the main thread 52 us a frame, nearly all the barrier fix's sleeps
(
barrier.sleepClaim), whichmainhas too. Folder:...runs/ab/20261129-215249-hos_frame_cost-hyrule-field.Risks
once in. A publish off plain clears
PLAIN, and a hook that read the old slot goes on to the dispatcher. So a removal'sgrace still waits for it. The site's hits are not counted in the stats for it (as for an owner) unless
HOS_FRAME_COST=1.main_thread_timesnow writes four values: host and renderer change together (API version 82).Checklist
Ready for review
main; the title is a Conventional Commit. (intomod-api, onmod-api@origin75bcd270)mise run testpasses (any failure that also fails onmainis named). (the wholetests/run_all.pyon the head: 733 passed, 114 skipped, 1 failed:test_lifter.py'sbuild-coretestcontrol::tests::the_socket_is_made_private_and_a_client_handed_over, in the builder's control socket, which this PR does not touch; it fails the same way onmod-api@12f42db5, checked in #2868's run)main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
gpu/vk/switches.def.(
HOS_FRAME_COST, a diagnostic, off)tests/that reads changed source is updated, not weakened. (tests/test_frame_trace_waits.py:the new column)
MKWVK_API_VERSIONbumped (MkwVkHostorMkwVkRendereringpu/vk/vk_api.hchanged).docs/dev/reference/hooks.md,profiling.md)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
https://claude.ai/code/session_016o1k1SQVyAWsujjFVd8Wuc
@review
Recommendation: Request changes. The plain-handler optimization breaks the hook removal API’s grace-period guarantee. The claimed performance gain is also unproven because the cuts were not measured against the pull request’s base.
The change adds optional frame-cost diagnostics and reduces several mod-runtime scans and allocations. The optimization makes hook retirement less safe, and its net effect on frame time has not been isolated.
Blocking (1): must change before merging.
game/crates/game-sites/src/chain.rs:485: A lone function handler now bypasses the readers count, so remove_retired can report that its grace period passed while that handler is still running. (more on the line) Do: Keep handlers covered by the retirement readers, or provide an equivalent grace period for plain-handler calls and test removal while a function handler is in flight.Nits (1): optional.
Testing before merging (2) (runs on the systems it can change; it doesn't hold the recommendation)
cb37f5abagainst this head in the target and a heavy area, reporting acquire CPU time, FPS, 1% lows and frame times.@fixcan do L1 and L4.Checks: Failing on this head, which is behind its base, where it passes:
PR description / Title and description (pull_request_target).@rebase(or@fix) brings it up to date and runs it again; not held against it.More: does it help, other systems, switches, what was read
Does it help: Unproven. The reported Linux RTX 3090 runs compare main with this PR, not mod-api with this PR: median FPS is 139.2 versus 138.0, and median 1% low is 125.4 versus 117.0. The author estimates the cuts save 10–15 µs per frame from instrumented step timings, but did not measure the cuts against their base.
Other systems: The hook and timing paths run on Windows and Linux and are independent of GPU vendor; frame pacing can nevertheless vary by system. The supplied run covers Linux on NVIDIA; Windows, AMD and Steam Deck results are still needed for the affected paths.
Switches: HOS_FRAME_COST is added as an off-by-default diagnostic switch, with a switches.def row. Off is appropriate for its instrumentation overhead.
Reviewed:
cbd0742fe3againstcb37f5ab8a: Read the repository rules, PR template, standards, commit messages and diff; read the new cost module, timer service, hook chain and statistics code, and inspected the relevant runtime, host clock and retirement callers. Other changed files and surrounding code were inspected through the diff and targeted searches, not read in full. The requested review-checklist file and sibling Tooling checkout were absent. Recorded runs were read from the PR description; no run files were available.; nothing run (a code review).Checked and fine:
Testing: No code or tests were run, as requested. The PR reports Linux game runs and changed checks; Windows game testing and the remaining hardware runs are outstanding.
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.
@ -474,0 +482,4 @@// lives for the run: a C function, a `SiteFn`, never a closure)let plain_owner = match (wraps.as_slice(), core.as_slice()) {([], [only]) if only.answers => Some(only.handler.clone()),([h @ Handler::Fn(_)], []) => Some(h.clone()),L1 (blocking): A lone function handler now bypasses the readers count, so remove_retired can report that its grace period passed while that handler is still running.
When: A thread enters a Handler::Fn through the plain trampoline while another removes it with remove_retired. Reclaim sees no dispatcher readers and marks the guard passed, allowing the caller to release state the function uses while the first thread still accesses it.
Do: Keep handlers covered by the retirement readers, or provide an equivalent grace period for plain-handler calls and test removal while a function handler is in flight.
cbd0742fe3899cc67bdbL1 fixed (
899cc67b): a loneHandler::Fnon the plain trampoline is now counted in the site's readers (tagged inPLAIN, PLAIN reloaded once in, cleared on any publish off plain, null falls to the dispatcher), soremove_retired/remove_thenwait for it again; new test removes the handler from inside it and fails without the count.L4: Measurements now call the 1% low and p99 noisy and inconclusive and give the differences. L2: not re-measured — the user accepted this area's fps gap; the rebase onto mod-api @
75bcd270brought in nothing per frame (Measurements says why). L3 stays in Still to test (Windows via Beanstalk, the lab by hand).Landed on mod-api as
e8f8ca8c(one commit), after its review fixes and one batched build + game run of all six cleanup areas together. mod-api work now goes straight onto the branch once self-reviewed.Pull request closed