d3d12/descriptor: guard per-thread KEPT_SEEN by HostList epoch across in-place list replacements (refs #3264) #3309

Open
zmasi wants to merge 1 commit from upstream-pr/3309 into main
zmasi commented 2026-12-03 08:52:06 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by zmasi on 2026-12-03T08:52:06Z.


Refs #3264 (D3D12-THIN-MULTI-WORKER-RACE, claimed in https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7369624822).

Scope & Honesty Note

Nothing here has run on an RDNA 2 GPU or with game files, and this commit is intentionally marked Refs #3264 rather than Fixes #3264:

  • While auditing the thin list translation path (list/thin.rs, list.rs, descriptor/host.rs) for #3264, we found and reproduced a real HostList resource-lifetime bug in descriptor/host.rs (kept_by_list / KEPT_SEEN) under default LEONIDA_KEEP_BY_LIST=1.
  • However, the reporter also reproduced the world-entry DXGI_ERROR_DEVICE_RESET on an older VIctory build (4eb6cfdf) that predates LEONIDA_KEEP_BY_LIST / KEPT_SEEN. We therefore fix the KEPT_SEEN lifetime bug here and document the shared multi-thread suspects (including draw.rs heap_buffers buffer_frame when !done_ahead, which fired ~2 s before device loss in #3264's attached crash log) in d3d12/docs/findings.md.

The Bug Fixed Here (descriptor/host.rs KEPT_SEEN)

With LEONIDA_KEEP_BY_LIST=1 (on by default), kept_by_list makes the binding HostList retain each resource shown by a dynamic descriptor slot once per recording. To avoid repeating keep_once across draws, per-thread KEPT_SEEN keyed its cache solely by (std::ptr::from_ref(list) as usize, list.resets()):

  1. List.host: Option<HostList> moves a replacement HostList into the exact same Option address in four places in list.rs (cut, value_written, detach_parts, and detach).
  2. Fresh HostList instances start at resets == 0, recycled back lists (thin.rs BACKS) are popped LIFO, and an idle thin worker thread retains its last (addr, resets) key across batches.
  3. When a new or recycled HostList landed at the same (addr, resets) key as the thread's prior bind, kept_by_list treated KEPT_SEEN.resources as already kept on the new list and skipped list.keep_once() for every resource in the stale set.
  4. Host sweeps in resource.rs and shadow.rs free host copies once references(..) == 1, allowing buffers/textures still read by that GPU command list to be released while in flight (which faults and resets the GPU on AMD).

Fix

  • Extend KeptSeen with ended: u64 and return an RAII Keeping<'a> guard from keeping(list):
    • Every HostList receives a globally unique non-zero epoch() on creation (new_list) and on reset (changed_something).
    • On entry, keeping clears the cached resource set if kept.list == key and kept.ended != list.epoch() (including ended == 0 on key switch).
    • On drop, Keeping records kept.ended = self.list.epoch() if kept.list still matches self.list.
  • Repeated binds within the same pass where list.epoch() has not advanced still hit the thread-local cache without touching keep_once; any in-place Option<HostList> replacement or intervening reset deterministically invalidates the stale set without touching oversized host.rs.

Verification (No Game Files)

  • New regression test (d3d12/crates/leonida-gpu/src/descriptor/host/kept_seen_tests.rs): a_host_list_in_anothers_place_keeps_what_its_slots_show replaces a HostList in-place inside Option<HostList> with equal resets, drops the first list, and verifies the second list retains the buffer shown by its dynamic slot (left: 1, right: 2 on origin/main).
  • python -I scripts/red_green.py HEAD --base origin/main --no-fetch: verdict: red then green (1 red -> green, 716 pass on both).
  • cargo test --target x86_64-pc-windows-msvc -p leonida-gpu --lib --locked list (42 passed) and descriptor (95 passed); cargo clippy -p leonida-gpu --all-targets --no-deps --locked (0 warnings).
  • python -m unittest discover -s tests -p "test_docs_*.py" (59 OK), tools/d3d12_switches.py --check d3d12/docs/switches.md (rc=0), and scripts/check_no_game_data.py (rc=0).

AI-assisted: GPT-6.2 Astra, Claude Opus 5.5, and Gemini 4 Neon (XHigh).

<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5623141716 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3309). Originally posted by [zmasi](https://github.com/zmasi) on 2026-12-03T08:52:06Z. --- Refs #3264 (`D3D12-THIN-MULTI-WORKER-RACE`, claimed in https://github.com/ProjectLeonida/mandy/issues/2570#issuecomment-7369624822). ### Scope & Honesty Note Nothing here has run on an RDNA 2 GPU or with game files, and this commit is intentionally marked **`Refs #3264` rather than `Fixes #3264`**: - While auditing the thin list translation path (`list/thin.rs`, `list.rs`, `descriptor/host.rs`) for #3264, we found and reproduced a real `HostList` resource-lifetime bug in `descriptor/host.rs` (`kept_by_list` / `KEPT_SEEN`) under default `LEONIDA_KEEP_BY_LIST=1`. - However, the reporter also reproduced the world-entry `DXGI_ERROR_DEVICE_RESET` on an older VIctory build (`4eb6cfdf`) that predates `LEONIDA_KEEP_BY_LIST` / `KEPT_SEEN`. We therefore fix the `KEPT_SEEN` lifetime bug here and document the shared multi-thread suspects (including `draw.rs` `heap_buffers` `buffer_frame` when `!done_ahead`, which fired ~2 s before device loss in #3264's attached crash log) in `d3d12/docs/findings.md`. ### The Bug Fixed Here (`descriptor/host.rs` `KEPT_SEEN`) With `LEONIDA_KEEP_BY_LIST=1` (on by default), `kept_by_list` makes the binding `HostList` retain each resource shown by a dynamic descriptor slot once per recording. To avoid repeating `keep_once` across draws, per-thread `KEPT_SEEN` keyed its cache solely by `(std::ptr::from_ref(list) as usize, list.resets())`: 1. `List.host: Option<HostList>` moves a replacement `HostList` into the **exact same `Option` address** in four places in `list.rs` (`cut`, `value_written`, `detach_parts`, and `detach`). 2. Fresh `HostList` instances start at `resets == 0`, recycled back lists (`thin.rs` `BACKS`) are popped LIFO, and an idle thin worker thread retains its last `(addr, resets)` key across batches. 3. When a new or recycled `HostList` landed at the same `(addr, resets)` key as the thread's prior bind, `kept_by_list` treated `KEPT_SEEN.resources` as already kept on the new list and **skipped `list.keep_once()` for every resource in the stale set**. 4. Host sweeps in `resource.rs` and `shadow.rs` free host copies once `references(..) == 1`, allowing buffers/textures still read by that GPU command list to be released while in flight (which faults and resets the GPU on AMD). ### Fix - Extend `KeptSeen` with `ended: u64` and return an RAII `Keeping<'a>` guard from `keeping(list)`: - Every `HostList` receives a globally unique non-zero `epoch()` on creation (`new_list`) and on `reset` (`changed_something`). - On entry, `keeping` clears the cached resource set if `kept.list == key` and `kept.ended != list.epoch()` (including `ended == 0` on key switch). - On drop, `Keeping` records `kept.ended = self.list.epoch()` if `kept.list` still matches `self.list`. - Repeated binds within the same pass where `list.epoch()` has not advanced still hit the thread-local cache without touching `keep_once`; any in-place `Option<HostList>` replacement or intervening `reset` deterministically invalidates the stale set without touching oversized `host.rs`. ### Verification (No Game Files) - **New regression test** (`d3d12/crates/leonida-gpu/src/descriptor/host/kept_seen_tests.rs`): `a_host_list_in_anothers_place_keeps_what_its_slots_show` replaces a `HostList` in-place inside `Option<HostList>` with equal `resets`, drops the first list, and verifies the second list retains the buffer shown by its dynamic slot (`left: 1, right: 2` on `origin/main`). - `python -I scripts/red_green.py HEAD --base origin/main --no-fetch`: **`verdict: red then green`** (`1` `red -> green`, `716` `pass on both`). - `cargo test --target x86_64-pc-windows-msvc -p leonida-gpu --lib --locked list` (`42` passed) and `descriptor` (`95` passed); `cargo clippy -p leonida-gpu --all-targets --no-deps --locked` (`0` warnings). - `python -m unittest discover -s tests -p "test_docs_*.py"` (`59` OK), `tools/d3d12_switches.py --check d3d12/docs/switches.md` (`rc=0`), and `scripts/check_no_game_data.py` (`rc=0`). AI-assisted: GPT-6.2 Astra, Claude Opus 5.5, and Gemini 4 Neon (XHigh).
fiestorra commented 2026-12-03 08:57:20 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-03T08:57:20Z.


Las dos nuevas, corridas

#3308  Check the full generated D3D12 switch catalog        2 files, +76/−5
       tests/test_d3d12_switches.py + tools/d3d12_switches.py
       pytest -k switch  →  61 passed, 1 skipped, 62 subtests  (62 s)

#3309  d3d12/descriptor: guard per-thread KEPT_SEEN by HostList epoch   3 files, +143/−16
       descriptor/host.rs + kept_seen_tests.rs + findings.md
       cargo test -p leonida-gpu --lib  →  716 passed; 1 failed; 59 ignored

#3308 es de las que cierran un hueco del propio instrumento: comprobar el catálogo generado de interruptores, no el documento — que es lo que yo intenté a las 17:20 y dejé porque el documento estaba completo. La diferencia: yo comparé switches.md con el código; esto compara el catálogo generado con el código, que es el que se puede desincronizar de verdad cuando alguien añade un LEONIDA_* y no lo documenta.

Y el número lo dice: 61 tests y 62 subtests para un fichero de 76 líneas — una prueba por entrada del catálogo, no una por función.

#3309 trae un fichero de test propio (kept_seen_tests.rs) y 716 contra los 715 de main — un test nuevo, medido en el diff — y el fallo es el de la iGPU de siempre.

Y es la quinta de la noche que toca descriptor/host.rs (con #2995, #2948, #3141 y #2892), que ya es el fichero más disputado del repositorio por delante de test_win_launchers.py. Cada una lo toca por un motivo distinto, y ninguna choca con las otras — lo comprobé con merge-tree en el barrido de la tarde.

Lo que no verifiqué: el caso que motiva a #3309 (un KEPT_SEEN por hilo que sobrevive a un cambio de epoch de HostList) — necesita concurrencia real, y el test lo simula con el fichero nuevo. Y el catálogo de #3308 sí lo verifiqué ejecutándolo, que es la diferencia con mi intento de esta tarde.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7372971767 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3309#issuecomment-7372971767). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-12-03T08:57:20Z. --- ## Las dos nuevas, corridas ``` #3308 Check the full generated D3D12 switch catalog 2 files, +76/−5 tests/test_d3d12_switches.py + tools/d3d12_switches.py pytest -k switch → 61 passed, 1 skipped, 62 subtests (62 s) #3309 d3d12/descriptor: guard per-thread KEPT_SEEN by HostList epoch 3 files, +143/−16 descriptor/host.rs + kept_seen_tests.rs + findings.md cargo test -p leonida-gpu --lib → 716 passed; 1 failed; 59 ignored ``` **`#3308` es de las que cierran un hueco del propio instrumento**: **comprobar el catálogo *generado* de interruptores, no el documento** — **que es lo que yo intenté a las 17:20 y dejé porque el documento estaba completo.** **La diferencia**: **yo comparé `switches.md` con el código; esto compara el catálogo *generado* con el código**, **que es el que se puede desincronizar de verdad cuando alguien añade un `LEONIDA_*` y no lo documenta.** **Y el número lo dice**: **61 tests y 62 subtests para un fichero de 76 líneas** — **una prueba por entrada del catálogo, no una por función.** **`#3309` trae un fichero de test propio** (`kept_seen_tests.rs`) **y `716` contra los `715` de `main`** — **un test nuevo, medido en el diff** — **y el fallo es el de la iGPU de siempre.** **Y es la quinta de la noche que toca `descriptor/host.rs`** (**con `#2995`, `#2948`, `#3141` y `#2892`**), **que ya es el fichero más disputado del repositorio por delante de `test_win_launchers.py`.** **Cada una lo toca por un motivo distinto, y ninguna choca con las otras** — **lo comprobé con `merge-tree` en el barrido de la tarde.** **Lo que no verifiqué**: **el caso que motiva a `#3309`** (**un `KEPT_SEEN` por hilo que sobrevive a un cambio de *epoch* de `HostList`**) — **necesita concurrencia real, y el test lo simula con el fichero nuevo.** **Y el catálogo de `#3308` sí lo verifiqué ejecutándolo, que es la diferencia con mi intento de esta tarde.**
merzleckeier commented 2026-12-03 08:58:24 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by merzleckeier on 2026-12-03T08:58:24Z.


Independent red/green check for 73286e1d on main d9b618f1. I ran the new regression in Windows MSVC builds under Wine 11.22 with the RTX 4070 SUPER and Radeon iGPU selectors and LEONIDA_KEEP_BY_LIST=1. My test copy requires a real D3D12 device and asserts that the replacement occupies the same address with the same reset count and a different epoch. On main, both runs left one buffer reference where the test expects two after the first list drops. Both runs pass with the patch. The fixture uses synthetic buffers.

Catalog integration with #3308: the new findings give LEONIDA_ALIAS_LATER and LEONIDA_CUT_WRITES an F marker. The name-set check accepts the existing page. The full generated-page check catches the two stale cells, and regeneration makes all 22 catalog tests pass.

AI-assisted with OpenAI Codex.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7372996206 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3309#issuecomment-7372996206). Originally posted by [merzleckeier](https://github.com/merzleckeier) on 2026-12-03T08:58:24Z. --- Independent red/green check for `73286e1d` on `main` `d9b618f1`. I ran the new regression in Windows MSVC builds under Wine 11.22 with the RTX 4070 SUPER and Radeon iGPU selectors and `LEONIDA_KEEP_BY_LIST=1`. My test copy requires a real D3D12 device and asserts that the replacement occupies the same address with the same reset count and a different epoch. On `main`, both runs left one buffer reference where the test expects two after the first list drops. Both runs pass with the patch. The fixture uses synthetic buffers. Catalog integration with #3308: the new findings give `LEONIDA_ALIAS_LATER` and `LEONIDA_CUT_WRITES` an `F` marker. The name-set check accepts the existing page. The full generated-page check catches the two stale cells, and regeneration makes all 22 catalog tests pass. AI-assisted with OpenAI Codex.
MoonEyes commented 2026-12-03 09:12:37 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-12-03T09:12:37Z.


RUN (in game, one pull request), its head merged with git merge --no-ff onto main d9b618f10: #3309 73286e1d9. RTX 4060 8 GB, driver 610.88, Windows 11. Series S, -Resolution 1080, frame generation 2x, -PrecompileUsed, the same walking route as the other runs on this machine, 330 s after reaching the world.

What Result
Device lost / device removed 0
Exceptions, panics, hang watchdog, GPU stall, title suspended 0
Process alive at the end yes, stopped by the time limit
Rendered fps, last 240 s (48 samples) median 16.6, mean 16.7
Rendered fps, last 120 s median 15.8
Time under 5 fps in the world 3 %

For reference, the same machine and route rendered 13.3 to 17.2 fps on other batches in the last day. These fps are a check that nothing fell over, not a measurement of a gain.

Verdict: PASS for the in-game gate (300 s or more in the world, no device loss) for this pull request, on the head above. If it changes its head, this run no longer covers it.

Limits: one run; arrival in the world was driven by keys and not checked on pictures; -PrecompileUsed was used, so the default start (every known pipeline precompiled) was not exercised. This run shows that nothing fell over with the per-thread set guarded by the list's epoch; it does not show the race it guards against happening without it.

AI-assisted (Claude Code).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7373332720 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3309#issuecomment-7373332720). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-12-03T09:12:37Z. --- RUN (in game, one pull request), its head merged with `git merge --no-ff` onto main `d9b618f10`: #3309 `73286e1d9`. RTX 4060 8 GB, driver 610.88, Windows 11. Series S, `-Resolution 1080`, frame generation 2x, `-PrecompileUsed`, the same walking route as the other runs on this machine, 330 s after reaching the world. | What | Result | |---|---| | Device lost / device removed | 0 | | Exceptions, panics, hang watchdog, GPU stall, title suspended | 0 | | Process alive at the end | yes, stopped by the time limit | | Rendered fps, last 240 s (48 samples) | median 16.6, mean 16.7 | | Rendered fps, last 120 s | median 15.8 | | Time under 5 fps in the world | 3 % | For reference, the same machine and route rendered 13.3 to 17.2 fps on other batches in the last day. These fps are a check that nothing fell over, not a measurement of a gain. Verdict: PASS for the in-game gate (300 s or more in the world, no device loss) for this pull request, on the head above. If it changes its head, this run no longer covers it. Limits: one run; arrival in the world was driven by keys and not checked on pictures; `-PrecompileUsed` was used, so the default start (every known pipeline precompiled) was not exercised. This run shows that nothing fell over with the per-thread set guarded by the list's epoch; it does not show the race it guards against happening without it. AI-assisted (Claude Code).
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3309:upstream-pr/3309'
git switch 'upstream-pr/3309'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/3309'
git switch 'upstream-pr/3309'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3309'
git switch 'upstream-pr/3309'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3309'
git switch 'main'
git merge --squash 'upstream-pr/3309'
git switch 'main'
git merge --ff-only 'upstream-pr/3309'
git switch 'main'
git merge 'upstream-pr/3309'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
ProjectLeonida/mandy!3309
No description provided.