Skip to content

fix(host): retain linked synchronization objects for later reclamation - #2858

Draft
Arkex-ai wants to merge 2 commits into
NotRexed:mainfrom
Arkex-ai:fix/v1zl-1-sync-retirement
Draft

Arkex-ai wants to merge 2 commits into
NotRexed:mainfrom
Arkex-ai:fix/v1zl-1-sync-retirement

Conversation

@Arkex-ai

@Arkex-ai Arkex-ai commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A finalized synchronization object can lose its retirement record while it is still linked to a multi-wait. After the link clears, its payload buffers then remain allocated and its node cannot be reused. Keeping the record fixes that lifecycle; the review followup also prevents the collector from reclaiming it before an unlink finishes its last access.

Fixes #2804. Draft: the source-level defects are reproduced, but no gameplay incidence, physical-RAM saving or FPS improvement has been measured. This is not an explanation of the reported multi-GiB growth.

Technical changes

  • Retain blocked retirement records for a later pass with the existing 30-second grace and eligibility rules; continue to eligible followers and bound the pass by its initial count.
  • Read retirement eligibility with atomic acquire loads. Link/unlink paths publish metadata with release stores; Unlink, UnlinkAll and MoveAll publish their final cleared reference/count only after their last object or links-array access. Unlink reads the holder's multi-wait under mw_lock.
  • Do not acquire mw_lock under table_lock: the existing reverse order remains valid. Preserve reusable-node policy and guest wait/signal semantics.
  • Explain that records unreachable by later unlink stay pending, and remove the unmeasured worklist row. docs/worklist.md is restored byte-for-byte to the PR base, including the unrelated text encoding.
  • Extend the actual table/link/unlink regression to seven scenarios, including two native-thread interleavings before and after the final publication.

Reviewed file overlaps change other paths, not the collector or this unlink ordering. Private investigation preceded the delivered claim.

Validation

Current source head: 9bba8f35ea087b8efa4cbba7f26e1b9c2b475578, a fast-forward followup to d09b08e7326fc7fa0b31d920147c90f6a4753622 (base de8192345086c7c79c115fff260163508bb19c43). The old head's passing sequential tests did not cover the race found in review; they are not proof of its safety.

  • Windows Clang 23.1.5: seven scenarios / 40 assertions pass in each of three runs. The newly exposed before-publication interleaving fails three assertions on published d09b08e7; the after-publication control fails one. Existing test_multiwait_wake.py passes, including watcher counts through Link, Unlink, UnlinkAll and MoveAll.
  • Linux focused source validation: three GCC 14, three Clang 17 and three Clang ASan/UBSan runs pass all seven scenarios on the committed source/test bytes, with leak detection. Both published-head negative controls fail as expected, and the existing multi-wait wake test passes with GCC and Clang. A Linux early-release semantic mutant is rejected by the after-publication control. An additional 100 controlled before/after-publication runs pass across GCC and Clang.
  • The thread fixture pauses metadata publication deterministically. Negative payload deallocation is quarantined and unsafe writes are intercepted, so the baseline defect is demonstrated without deliberately executing a use-after-free. The extracted source algorithms are otherwise unchanged; this is not a ThreadSanitizer result or a general race-freedom proof.
  • Complete base and fixed nn_os_sync.c pass strict Windows syntax checking with the actual host interface and retained local generic runtime headers. This is not a linked game.
  • Complete current-head Linux suite: python -I -B tests/run_all.py --jobs 2 on exact 9bba8f3 finished 425 passed, 4 failed, 71 skipped in 809 seconds. The exact tree and commit object are verified, with shallow history at the previous head, and source hashes remained unchanged. The failures are test_bake_portability.py, test_hookshot_ctl.py, test_mem_gate_children.py, and the concurrent-nightly test_release_scripts.py case. Their baseline controls and limitations are described below; this is not an all-green result. All local suite/stress children were absent on final inspection.

Historical full-suite results, explicitly not current-head certification: d09b08e7 Linux 425 passed / 4 failed / 71 skipped; earlier identical sequential-fix source on Windows 438 passed / 25 failed / 33 skipped. Three Linux failures also reproduced on unchanged 51da0464: missing zstandard (test_bake_portability), a missing runtime-directory prerequisite (test_hookshot_ctl), and child RSS below the expected accounting threshold (test_mem_gate_children). The fourth was the concurrent-nightly release-script mock HTTP404/checksum failure, also seen on #2823; it passed in another run of the same release files. Its cause is not established, and none of these results is labelled all-green. Not all Windows failures have clean-base controls.

Gameplay remains required: boot, scene changes and save/load, with temporary reclaimed-record/byte counts, then the uninstrumented fix. A later collection is still needed after links clear; permanently unreachable links keep their records pending. Independent review was COMMENTED, not approval. No game build or memory-saving measurement is claimed.

Current-head hosted checks: Game-free source regressions, Linux AppImage, PR title, Windows builder. Their live conclusions are separate from local tests.

Hosted integration status observed at 18:09 UTC: source jobs check synthetic merge bd40671590b4e0bda4c897ad188fae3779f9b1b3 (9bba8f3 plus main 65a4d874), whereas the local full-suite result above is standalone 9bba8f3. Linux 1/2 fails test_program_cache_one_variant.py with undeclared disk_zstd, kZstdHead and program_cache_payload; Windows 1/2 reports that failure and test_readme_menu_rows.py missing Skip opening from its README table. These files are outside this patch, but their cause on clean current main has not been reproduced here; the integration failures remain open. AppImage and Windows Vulkan builds passed; other checks were still pending.

Preserve existing lifetime eligibility and release resources only after successful
acquisition and their permitted finalization path. Include causal regressions.

Fixes NotRexed#2804

Assisted-by: GPT-6 Astra Pro
Co-Authored-By: GPT-6 Astra Pro <noreply@openai.com>

@ghost ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, and for being upfront in the description about what's measured and what isn't. The bug is real: on main, a tombstone that's still linked at its first pass loses its only record, so it can never get back to the spare list. Keeping it in the ring is the right fix, and it doesn't touch wait/signal or lock order. I checked against #2765, #2709, #2708 and #2487: none of them change the collector, so they don't care which order they merge in.

Some things to look at before it comes out of draft:

  1. A new race (inline). The collector reads d->mw / d->nlinks under table_lock, but Link/Unlink write them under mw_lock. On main that didn't matter. A multi-wait whose links were already clear at its first pass had no unlink left to run, and one that was still linked was dropped for good. This PR adds the case of an unlink on a buried object running while another thread runs bury_locked. If the collector sees nlinks == 0 partway through mw->links[i] = mw->links[--mw->nlinks], it can free links before the write into it lands, or put the object on spares while Unlink still holds it. The window is tiny, but this is exactly the path the PR opens. Taking mw_lock inside the collector would invert the existing mw_lock -> table_lock order (wait_any's lookups under mw_lock can take table_lock on a cache miss), so don't do that. Use atomic acquire loads in the check and have Unlink/UnlinkAll publish nlinks/mw last with a release store. Then the collector can't see zero before the unlink is done with the object.

  2. Which unlinks actually reach a buried object. Once a holder's slot is taken, UnlinkMultiWaitHolder(holder) looks the address up, misses the tombstone and makes a fresh holder, so the old one stays linked. A buried holder can only come back through UnlinkAllMultiWaitHolder on its multi-wait, and a buried multi-wait only through each holder's own Unlink. That's what your two linked cases test, which is good. Records that neither path reaches stay in the ring for the rest of the session. That costs 16 bytes and one revisit every 30 s each, and the object was leaked on main anyway, so it's bounded. Still worth one line in the comment above graves (which still says such tombstones are "freed 30 s later").

  3. Evidence (rule from #2712). That same comment notes that freeing still-linked objects "hung most boots" once. This PR only recycles them after unlink, but it reuses memory that main never reused, so it needs a real run in the game: a boot plus a long session through scene changes (and a save/load or two), with no hang or crash. It also needs the count of records this path actually reclaims (a temporary counter or log line is fine) and the bytes involved. Without that we don't know if this ever happens in OoT, and the worklist row's S2 is a guess.

  4. docs/worklist.md (inline). The diff re-encodes an unrelated line: instalaçao became instalaçao (UTF-8 read as Latin-1). Please restore it. I'd also hold the new row until there's an in-game number: it has no player report behind it, and "1.0 upper bound for host synchronization users" means every player.

Nits: remaining is redundant. A retained record gets now as its time, so the loop stops on its own when it comes back around. It's fine as a guard, though, if you'd rather keep it. The test is a good model of the single-threaded lifetime (real table, real Link/Unlink, real collision burial). It doesn't cover Unlink racing the collector, which is point 1.

CI was still running when I reviewed (Windows builder and AppImage pass), and the branch has no conflicts.

To come out of draft: point 1, the worklist line restored, and the in-game run with the reclaimed count from point 3.

Comment thread host/nn_os_sync.c
d->links = NULL;
d->spare = spares;
spares = d;
} else {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The eligibility check above (!d->kind && !d->mw && !d->nlinks) now runs while an unlink of the same object can be running on another thread under mw_lock (on main the record was already gone by then). Plain reads of mw/nlinks here can see nlinks == 0 before mw->links[i] = ... has stored, and then free(d->links) / the push onto spares races it. Suggest __atomic_load_n(..., __ATOMIC_ACQUIRE) in that check, with Unlink/UnlinkAll storing nlinks/mw last with __ATOMIC_RELEASE. Taking mw_lock here would invert the existing mw_lock -> table_lock order.

@Arkex-ai Arkex-ai Nov 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 9bba8f3. The collector now uses acquire loads of kind/mw/nlinks. Unlink reads mw inside mw_lock, finishes array/watch accesses, then release-publishes the cleared holder link and final count with no later access to those objects. UnlinkAll/MoveAll also publish their final cleared references/counts last. No mw_lock acquisition was added under table_lock.

Two native-thread controls pause before and after publication; published d09b08e fails 3 and 1 assertions respectively. The new seven scenarios (40 assertions) pass in 3 Windows Clang runs and 3 GCC + 3 Clang + 3 ASan/UBSan Linux runs. An early-publication mutant fails the after-publication control, and 100 additional controlled interleaving runs pass. Negative payload reclamation is quarantined, not deliberately executed as an invalid write. Existing watcher-count tests pass on Windows/Linux. The exact-head 9bba8f3 full Linux run finished: 425 passed, 4 failed, 71 skipped in 809 seconds. The four failures and baseline controls are recorded in the description; the suite is not all green. Gameplay and general race-freedom are not claimed.

Comment thread docs/worklist.md Outdated
| 2.1 | Low fps with low GPU use in Castle Town and Hyrule Field (CPU-bound), worse as adult Link; GTX 1660 Ti at about 20 fps in open areas with memory sync taking most of the frame (v2.1.0); RX 9070 under-used. Reported after v2.1.0 on Nov 10-11 (6 threads). Merged after v2.1.0: #2602; open: #2559, #2622, #2633, #2644 | S2 | 1.0 | 0.7 | | #995 (logs from 12 commenters); #bug-reporting "a lot of fps drop when get into hyrule castle town", "framerate getting extremely choppy in the hyrule citadelle since the recent updates", "Hyrule field as kid link runs better than as adult link", "about 20 fps in open areas on 1660 ti ... 2.1.0", "RX 9070 low fps", "Huge lag spike" |
| 2.1 | Invisible or see-through objects, walls and doors on v2.1.0: Kaepora Gaebora, doors in the Deku Tree and elsewhere, the Shadow Temple door after the Light Arrow (Linux AppImage), Lake Hylia after the owl cutscene. Merged after v2.1.0: #1573 (keep memory-writing draws while pipelines compile), #2382 (mesh fallback grass left out while its shaders build); retest | S2 | 1.0 | 0.7 | | #1002 (logs from 12 commenters); #bug-reporting [INVISIBLE KEPHORA](https://discord.com/channels/1568810484818378804/1568813928002224148/threads/1570246868443861104), [some transparent doors in some parts of the game](https://discord.com/channels/1568810484818378804/1568813928002224148/threads/1570272921132212224), "Linux, 2.1 AppImage, Ganandorfs castle - Shadow door missing textures.", "missing textures at lake hylia after owl cutscene"; before v2.1.0: "No walls inside Deku Tree.", "Invisible walls and invisible grabable things", "Water Temple missing most of the temple" |
| 2.0 | Antivirus flags HookshotBuilder.exe (Defender `Wacatac.H!ml` / `Wacatac.B!ml`, Chrome on v2.0.12): new unsigned exe, no reputation. Waiting on the SignPath open-source signing application; then sign in `windows-builder.yml` and publish the signed files | S1 | 0.57 | 0.7 | NotRexed (SignPath) | #1003, #525, #1620; checksums: #1307; still reported on v2.1.0 (Nov 10-11): #bug-reporting "Different Trojan Flag on defender", "problem updating" (updater flagged), "Cant download hookshot" (browser blocks the download); before: "Virus warning", "Trojan warning", "security concerns", "Virus deleting hookshot.exe", "I cant open the hook shotbuilder", "problema na instalaçao do game" |
| 2.0 | Antivirus flags HookshotBuilder.exe (Defender `Wacatac.H!ml` / `Wacatac.B!ml`, Chrome on v2.0.12): new unsigned exe, no reputation. Waiting on the SignPath open-source signing application; then sign in `windows-builder.yml` and publish the signed files | S1 | 0.57 | 0.7 | NotRexed (SignPath) | #1003, #525, #1620; checksums: #1307; still reported on v2.1.0 (Nov 10-11): #bug-reporting "Different Trojan Flag on defender", "problem updating" (updater flagged), "Cant download hookshot" (browser blocks the download); before: "Virus warning", "Trojan warning", "security concerns", "Virus deleting hookshot.exe", "I cant open the hook shotbuilder", "problema na instalaçao do game" |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line is otherwise unchanged, but instalaçao became instalaçao (an encoding round-trip). Please restore the original bytes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Restored docs/worklist.md byte-for-byte to the base in 9bba8f3, fixing the unrelated encoding change and removing the unmeasured ranking row. The graves comment now says recycling requires a later collection after the grace period, and explicitly notes that a blocked record remains pending when no unlink can reach it. #2804 is unranked until in-game record/payload counts establish incidence; the PR stays draft.

Address review on NotRexed#2858. Keep gameplay and reach unmeasured until
local hardware validation; restore the unrelated worklist bytes.

Assisted-by: GPT-6 Astra Pro
Co-Authored-By: GPT-6 Astra Pro <noreply@openai.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Retired synchronization objects are lost when multi-wait links outlive their first collection pass

1 participant