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

Open
github-bot wants to merge 1 commit from github-bot/gh-3309 into main AGit
Owner

@⁠zmasi on GitHub · 2026-12-03 08:52 UTC · original
zmasi:fix/d3d12-thin-multi-worker-race → main · +143 −16 · 3 files · 1 commits · open

Refs #3264 (D3D12-THIN-MULTI-WORKER-RACE, claimed in #2570).

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).

**@⁠zmasi** on GitHub · 2026-12-03 08:52 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/3309) `zmasi:fix/d3d12-thin-multi-worker-race` → `main` · +143 −16 · 3 files · 1 commits · open Refs #3264 (`D3D12-THIN-MULTI-WORKER-RACE`, claimed in https://git.gtahub.st/github/ubiquitarianism--leonida/issues/2570). ### 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).
With LEONIDA_KEEP_BY_LIST (on), what a dynamic slot shows is kept by the
list that binds, once per resource, and each thread notes what it had a
list keep by the host list's place and its resets (KEPT_SEEN). A title
list's place takes another host list when the list is cut at a wait or
(LEONIDA_CUT_WRITES=1) at a value write, and when it is submitted
(list.rs cut, value_written, detach_parts, detach); new host lists start
at 0 resets, lists of ours go back for the next recording (list/thin.rs
BACKS), and a translating thread keeps its note while it waits for work.
The next host list in that place with as many resets was taken for the
one before: keep_once was skipped for what the note held, so such a
buffer or texture could be let go while the list still ran.

The note now also holds the list's epoch when this thread last stopped
binding on it (KeptSeen.ended, set when Keeping drops). An epoch is never
given twice and changes at every reset, so keeping() forgets the note
when the list in that place has another epoch. The key and the cache
within a bind are as before.

Refs #3264, not shown to be its cause: the reporter's VIctory build
(Belobug 4eb6cfdf) lost the device the same way without keeping by list.
docs/findings.md records it with what else was seen on the way: the
heap's buffer pass taken by the first list to ask before a list ahead
exists, the present's two-step look at the shown texture's state, the
removal context missing from the crash log (same code at b83ad5433),
and translating threads not waiting for page mappings done behind the
title's call.

Tests: descriptor::host::kept_seen_tests (one thread, nothing submitted):
a second host list put in the first's place with as many resets keeps
the buffer its slot shows once the first is dropped. Fails on d9b618f10
(1 reference, 2 expected), passes with the fix. scripts/red_green.py
against origin/main: red then green (that test), 716 pass on both.
leonida-gpu lib tests: list 42 passed, descriptor 95 passed; clippy (all
targets) no warnings.

AI-assisted: openai-codex/gpt-6.2-astra (implementation),
anthropic/claude-opus-5-5:max (scouts, advisor, reviewer).
github-bot locked as GitHub sync and limited conversation to collaborators 2026-12-03 08:52:37 +00:00
Author
Owner

@⁠fiestorra on GitHub · 2026-12-03 08:57 UTC · original

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.

**@⁠fiestorra** on GitHub · 2026-12-03 08:57 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/3309#issuecomment-7372971767) ## 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.**
Author
Owner

@⁠merzleckeier on GitHub · 2026-12-03 08:58 UTC · original

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.

**@⁠merzleckeier** on GitHub · 2026-12-03 08:58 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/3309#issuecomment-7372996206) 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.
Author
Owner

@⁠MoonEyes on GitHub · 2026-12-03 09:12 UTC · original

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).

**@⁠MoonEyes** on GitHub · 2026-12-03 09:12 UTC · [original](https://github.com/ProjectLeonida/mandy/pull/3309#issuecomment-7373332720) 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 can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/3309/head:github-bot/gh-3309'
git switch 'github-bot/gh-3309'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-3309'
git switch 'github-bot/gh-3309'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-3309'
git switch 'github-bot/gh-3309'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-3309'
git switch 'main'
git merge --squash 'github-bot/gh-3309'
git switch 'main'
git merge --ff-only 'github-bot/gh-3309'
git switch 'main'
git merge 'github-bot/gh-3309'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No reviewers
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.

Dependencies

No dependencies set

Reference
github/ubiquitarianism--leonida!3309
No description provided.