fix(host): the sync objects' table is compacted in place when few of its objects are live, so finalized objects cannot double it without end #2907
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!2907
Loading…
Reference in a new issue
No description provided.
Delete branch "HumanBean/Longshot:fix/sync-table-compact"
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
A latent bug in the host's sync objects, found during a RAM/VRAM leak study on this PC. The game does not hit it in a
17-minute session; it is fixed here for longer sessions and other access patterns, with log counters to see it.
Every guest mutex, event, semaphore or queue has a host object, found by its guest address in an open-addressing table
(
host/nn_os_sync.c). A finalized object stays in its slot as a tombstone until another address takes the slot.insert_lockedmade a new table twice the size every time half the slots were used, live objects and tombstonesalike, and kept the old table for the lookups that read it without the lock. Objects made and finalized at ever-new
addresses therefore doubled it without end:
tests/test_obj_table_bounded.py, 3,000,000 such objects beside 3,000 liveones, grows it to 4,194,304 slots and 743 MB on
main.What the game does (the new counters, a 10-minute tour): the table grows 2^16 → 2^20 slots while the first areas load,
with 131,067 of 131,072 used slots live at the 4th doubling and 194,551 of 262,144 at the 5th, then stays at 2^20 slots
for the rest of the tour, 0 compactions. The game keeps ~195k objects alive and finalizes few, so the table is sized by
them (~144-146 MB of the heap with the objects, in a jemalloc profile, on
mainand here alike).Now a half-full table with under a quarter of its slots live is rehashed in place, at its size (
compact_locked); itgrows when the live objects need it or the compaction allocation fails. A lookup without the lock that meets a slot emptied or refilled meanwhile either
finds its object (objects are never freed, and
obj_ischecks the identity) or misses, and the locked lookup answers amiss, as it does for a slot changing today.
HOS_SYNC_TABLE_COMPACT=0doubles as before. Thesync: object cachelogline (every 10 s) now also says the table's size, its live objects at the last resize and how often it grew or was
compacted, so a long session (the lab's) shows whether the path is ever taken.
Read first:
insert_lockedandcompact_lockedinhost/nn_os_sync.c,tests/test_obj_table_bounded.py.Testing
Tested: RTX 3090, NVIDIA 620.70.06, CachyOS Linux, 32 GB: four laps of Lost Woods → Zora's River → Hyrule Field →
Kakariko → Kokiri Forest (
memtour.py, headless, thekokiri-startsave, 40 s in each, ~13 min), onmainand here;every teleport and area played as on
main, and the game quit cleanly.tests/test_obj_table_bounded.py: the earlier fixture failed onmain(the test commit alone), passed here, and failed withHOS_SYNC_TABLE_COMPACT=0. The updated fixture explicitly checks for growth with the switch off; its run is pending.test_obj_cache_size.py,test_obj_guest_id.py,test_multiwait_wake.pypass.test_multiwait_wake.py's list of calls that keep the core now hasenv_on_or(theswitch's read: a
getenv, asenv_onalready listed).host/nn_os_sync.cchecked with-fsyntax-only -Wall -Wextrawith llvm-mingw (Windows) and clang (Linux): the samewarnings as
main, no new one; the game built (dev.py pack) and ran, its counters in the log line (the 10-minutetour in Measurements).
tests/run_all.py(all 916 checks): 767 passed, 37 failed, 112 skipped on this PC. All 37 also fail on a cleanmaincheckout here (missing Vulkan/SPIR-V headers and other tools in this environment); none is new. CI runs the suite.
Still to test:
sync: object cacheline's countersshow whether the table ever compacts or grows past 2^20 slots (by hand).
@Beanstalkon this pull request).Measurements
Verdict: a latent-bug fix, no change in the game: the compaction never runs in a 10-17 minute session (the game keeps
~195k objects alive), the sync objects' heap is the same on
mainand here, and fps is within the spread. The game-freereproduction of the unbounded doubling is fixed.
Setup: RTX 3090, NVIDIA 620.70.06, CachyOS Linux, 32 GB. Game-free:
tests/test_obj_table_bounded.py, 25 objects a frameat new addresses for 120,000 frames beside 3,000 live ones. In game:
memtour.pyfrom thekokiri-startsave (Lost Woods,Zora's River, Hyrule Field, Kakariko, Kokiri Forest, laps), a jemalloc heap profile (
LD_PRELOAD=libjemalloc.so.2,MALLOC_CONF=prof:true) of each side, the new log counters on this side; fps bydev.py ab --scene hyrule-field(3interleaved pairs, uncapped, 67 % render resolution, 1440p output).
28cb22b932df2b83obj_lookup), game, jemalloc, ~10 minmain)The compaction never ran in these runs, so the frame-time rows compare the same code path; the 1 % low difference is
the runs' own spread (A1 103.4, B1 117.0).
Risks
table_lockexclusively and walks the table (65,536 slots by default), as a doubling did; ithappens once every ~16,000 new addresses at most.
HOS_SYNC_TABLE_COMPACT=0, or a revert. Nothing changes after updating: no files, settings or saves.Checklist
Ready for review
main; the title is a Conventional Commit.mise run testpasses (any failure that also fails onmainis named). (37 fail here and on a cleanmainalike: this PC's missing headers and tools; see Testing)main, or Measurements says why there is nothing to measure.third_party/untouched; nothing GPL-incompatible.When it applies
mainand passes here.gpu/vk/switches.def.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.It should also be checked on the lab (RX 580, 16 GB): a long session there shows, with the new counters, whether the path is ever taken.
🤖 Generated with Claude Code
https://claude.ai/code/session_016o1k1SdGuww9Q4o1mvYD9c
Tested in game: RTX 3090 / NVIDIA 620.70.06 / Linux (CachyOS): four laps of Lost Woods, Zora's River, Hyrule Field, Kakariko and Kokiri Forest (memtour.py, headless, kokiri-start save, ~13 min); every area and teleport played as on main, clean quit.
Possibly related, for context:
864f5dbf8232df2b831bWIP: fix(host): the sync objects' table is compacted in place, so objects the game finalizes no longer grow it all sessionto WIP: fix(host): the sync objects' table is compacted in place when few of its objects are live, so finalized objects cannot double it without end32df2b831bc750b78a66Rebased onto main @
ba3f14df(headc750b78a; was32df2b83). Nothing on main since touches host/nn_os_sync.c, and the switches.def change there is elsewhere in the file, so the measurements still hold. After the rebase: test_obj_table_bounded, test_obj_cache_size, test_obj_guest_id and test_multiwait_wake pass. test_switch_table fails on main too (LONGSHOT_LAUNCHER_STARTUP has no row).WIP: fix(host): the sync objects' table is compacted in place when few of its objects are live, so finalized objects cannot double it without endto fix(host): the sync objects' table is compacted in place when few of its objects are live, so finalized objects cannot double it without endRecommendation: Request changes. The synthetic churn test shows that compaction bounds table growth, but the game runs did not exercise compaction. Its effect on synchronization and frame pacing therefore remains unmeasured. (It stands on L3: The check
CI / Third-party parts and guide screenshots (pull_request)fails on this head and passes on the base branch: Failing after 14s.)The change reuses the sync-object table when tombstones dominate it, avoiding repeated doubling for sustained churn. It adds an exclusive table scan and rehash, plus a kill switch and diagnostic counters.
Blocking (1): must change before merging.
CI / Third-party parts and guide screenshots (pull_request)fails on this head and passes on the base branch: Failing after 14s.Should fix (1): not blocking, but worth doing before merging.
tests/test_obj_table_bounded.py:131: The switch-off run accepts any nonzero exit as proof that the old growth behavior occurred. (more on the line) Do: Make the switch-off case assert the expected growth explicitly and require a successful exit, or verify a distinct expected failure result.Testing before merging (1) (runs on the systems it can change; it doesn't hold the recommendation)
host/nn_os_sync.c:208: The runs do not measure a compaction while game threads are active. (more on the line) Do: Exercise compaction during a representative long game session and record its duration and frame times, including the requested Windows and AMD coverage. (@fixdoes its part first: Add timing for compaction and its lock hold so the run can identify the pause.)@fixcan do L1, L2 and L3.Checks: Still running: 7 checks.
More: does it help, other systems, switches, what was read
Does it help: Yes for the synthetic case: the reported 3 million-object churn run reaches 65,536 slots and 31.9 MB, versus 4,194,304 slots and 743 MB on main. The reported game runs had zero compactions, so they do not show an in-game memory or timing effect.
Other systems: The table serves guest synchronization across game threads on both Windows and Linux. Lock-free readers can encounter slots while they are cleared and refilled; misses fall back to the locked lookup. The reported Linux game runs did not exercise this path, and Windows and the longer AMD run remain outstanding.
Switches: HOS_SYNC_TABLE_COMPACT is added as a kill switch, on by default; =0 retains doubling. Its table row is present. The default fixes the synthetic churn case, but its timing when compaction occurs has not been measured in the game.
Reviewed:
c750b78a66againstba3f14dff1: Read AGENTS.md, CONTRIBUTING.md, the pull request template, relevant standards, the diff and commits, the changed table code and its lookup, insertion, finalization and cache callers, and the new test and its shared harness. Skimmed the rest of the large sync source, switch table and multiwait test. docs/review-checklist.md and the neighboring Tooling checkout were absent. The supplied comments and CI status were reviewed.; nothing run (a code review).Checked and fine:
Testing: Read-only review; no commands from the project, builds or tests were run. The supplied CI status includes one head-only failure, which the bot handles separately, and several checks still running.
Overlaps and merge order: Not checked; the network is closed.
Automated code review by BeanBot (gpt-6.1-terra), asked for by BeanBot, as HumanBean took it out of WIP. Nothing was run; a maintainer decides.
@ -186,0 +205,4 @@else __atomic_store_n(&table_log_grown, table_log_grown + 1, __ATOMIC_RELAXED);}static int compact_locked(void) { /* 1: the tombstones buried and the live objects put back, the size kept */uint64_t live_n = 0;L2 (should fix): The runs do not measure a compaction while game threads are active.
When: When a long session reaches a half-used table with fewer than a quarter of its slots live, compaction scans and rebuilds the table while holding the exclusive lock; concurrent misses and insertions wait. The reported game runs performed zero compactions, so their frame times do not cover that pause.
Do: Exercise compaction during a representative long game session and record its duration and frame times, including the requested Windows and AMD coverage.
@ -0,0 +128,4 @@print("HOS_SYNC_TABLE_COMPACT=%s (as before: it should fail):" % compact)r = subprocess.run([exe, mode], capture_output=True, text=True, env=env, timeout=600)sys.stdout.write(r.stdout)if bool(r.returncode) != bool(compact):L1 (should fix): The switch-off run accepts any nonzero exit as proof that the old growth behavior occurred.
When: If the switch-off fixture crashes, fails an earlier live-object assertion, or exits for another error, the test reports success without checking that the table grew as expected.
Do: Make the switch-off case assert the expected growth explicitly and require a successful exit, or verify a distinct expected failure result.
@fix
Recommendation: Approve. The fix retains the table compaction and adds an explicit switch-off growth check. No defect was found in the changed lines. Recommend approval; not approved on the forge.
What
@fixchangedI changed this pull request: the new head is
774882d7f1. I edited its description to match the change.Changed
Changed in part (the rest is for the author)
Left for the author
Nothing was built or run: the checks run again on the new head.
Compaction bounds table growth under sustained churn of finalized synchronization objects; the fix adds pause logging and strengthens the switch-off fixture. It adds timing calls on exclusive table lookups.
Checks: they run again on this head (
CI / Third-party parts and guide screenshots (pull_request),CI / Host C for Windows (llvm-mingw, compile only) (pull_request),CI / Renderer build check (Linux, compile --only renderer, without and with FSR 4) (pull_request),CI / Renderer build check (Windows, compile --only renderer, without and with FSR 4) (pull_request),CI / Game-free checks (run_all.py, part 1/2) (pull_request)failed on the last one); a failure shows on the pull request.Also noticed (4; not asked for, not blocking)
More: does it help, other systems, switches, what was read
Does it help: Yes in the reported game-free reproduction: peak table size fell from 4,194,304 to 65,536 slots and large allocations from 743 MB to 31.9 MB. The reported game session did not trigger compaction, so its in-game pause cost remains unmeasured.
Other systems: The table serves host synchronization on Windows and Linux. The reported Linux game run completed cleanly; Windows play and a longer Linux session remain pending.
Switches: HOS_SYNC_TABLE_COMPACT defaults on and has a switches.def row; setting it to 0 restores doubling. The reported churn test supports the default, while active compaction pauses remain unmeasured.
Reviewed:
774882d7f1againstba3f14dff1: Read the repository rules, PR template, diff, changed test and relevant table, lookup, logging and fixture code. Skimmed the remaining host implementation and test harness; the full changed code and switches.def were not read in full. The neighboring Tooling rules and docs/review-checklist.md were unavailable.; nothing run (a code review).Checked and fine:
Testing: No commands that build or run project code were executed. The author reports the earlier fixture and Linux game run passed; CI has not run on this head.
Overlaps and merge order: Not checked; the network is closed.
Automated code review by BeanBot (gpt-6.1-terra), asked for by BeanBot, after its fix. Nothing was run; a maintainer decides.