d3d12-gpu: trim host::send spare upload buffers under memory and commit pressure (D3D12-SEND-SPARE-PRESSURE-TRIM) #3326

Open
lixonik wants to merge 1 commit from upstream-pr/3326 into main
lixonik commented 2026-12-03 11:42:33 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by lixonik on 2026-12-03T11:42:33Z.


Claimed in the coordination issue as: D3D12-SEND-SPARE-PRESSURE-TRIM

What and why

host::sweep already trims idle scratch chunks (trim_spare_chunks) and readback buffers (trim_spare_backs) when host memory is pressured, and pool::room drops idle STAGING and pool::small blocks under residency::pressured() / residency::critical_commit(). However, host::send::SPARE (which caches up to 768 MiB of write-combined upload buffers on host memory, or 256 MiB on card BAR) never reacted to host memory pressure or critical system commit, and give_back also dropped evicted ID3D12Resources while holding the SPARE mutex.

Changes:

  • d3d12/crates/leonida-gpu/src/host/send.rs:
    • Cap kept() via kept_for(card, pressured, critical_commit): 768 MiB / 256 MiB normally (unchanged), 64 MiB under residency::pressured() (keeps the active working send buffer without pinning hundreds of MiB), and 0 under residency::critical_commit().
    • Add evict_over_limit (short-circuiting limit == 0 via std::mem::take and evicting largest buffers first) and return_and_trim so give_back always trims pre-existing cached buffers down to the active limit even when the incoming buffer itself is rejected, and drops all evicted/rejected ID3D12Resources outside the SPARE mutex.
    • Add pub(super) fn trim() to evict idle SPARE buffers down to the active limit.
  • d3d12/crates/leonida-gpu/src/host.rs:
    • Call send::trim() in sweep() whenever crate::residency::pressured() || crate::residency::critical_commit() (matching pool::room so non-pressured() critical commit windows such as post-E_OUTOFMEMORY RETRY_UPLOAD_AT still trim immediately).

Tested

  • python -I scripts/check_no_game_data.py -- PASS
  • python -I tools/d3d12_switches.py --check d3d12/docs/switches.md -- PASS
  • cargo test -p leonida-gpu --lib --locked host::send:: -- 3/3 PASS (kept_for_scales_down_under_pressure_and_zeroes_on_critical_commit, evict_over_limit_drops_largest_first_and_zeroes_on_zero_limit, return_and_trim_evicts_cached_entries_when_limit_shrinks)
  • cargo build --profile diag --features "diagnostics,dlss,mimalloc" --locked -- PASS
  • In-game 315 s gate run (Windows 10, RTX 5070 12 GB, Series S preset, DLSS, no Frame Generation, 315 s in world, 437.0 s total, 64 world samples, max 5,341 draws):
    • Runtime errors: 0; device lost: 0
    • Frame rate: median 27.1 fps (37.0 ms; slowest tenth 20.8, fastest tenth 28.1); 3000-4999 draws bucket: 27.1 fps (57 samples) -- matches main (d9b618f10) baseline (27.0 fps, 3000-4999 bucket 27.1 fps).

GPUs tested: NVIDIA GeForce RTX 5070 12 GB, Windows 10 x64 (native).

AI-assisted: yes. Author: Antigravity (Gemini 4 Neon). Reviewer: separate read-only Pro reviewer subagent (two passes; caught non-pressured() critical_commit() gating in sweep() and trimming pre-existing SPARE entries when give_back rejects an oversized incoming buffer, then approved).

Checklist

  • Based on current main and merges cleanly.
  • One topic; follow-up work goes in a new pull request.
  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (n/a)
<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5625760223 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3326). Originally posted by [lixonik](https://github.com/lixonik) on 2026-12-03T11:42:33Z. --- Claimed in the coordination issue as: [D3D12-SEND-SPARE-PRESSURE-TRIM](https://github.com/ProjectLeonida/mandy/issues/3312#issuecomment-7376729959) ### What and why `host::sweep` already trims idle scratch chunks (`trim_spare_chunks`) and readback buffers (`trim_spare_backs`) when host memory is pressured, and `pool::room` drops idle `STAGING` and `pool::small` blocks under `residency::pressured()` / `residency::critical_commit()`. However, `host::send::SPARE` (which caches up to **768 MiB** of write-combined upload buffers on host memory, or 256 MiB on card BAR) never reacted to host memory pressure or critical system commit, and `give_back` also dropped evicted `ID3D12Resource`s while holding the `SPARE` mutex. Changes: - **`d3d12/crates/leonida-gpu/src/host/send.rs`**: - Cap `kept()` via `kept_for(card, pressured, critical_commit)`: `768 MiB` / `256 MiB` normally (unchanged), `64 MiB` under `residency::pressured()` (keeps the active working send buffer without pinning hundreds of MiB), and `0` under `residency::critical_commit()`. - Add `evict_over_limit` (short-circuiting `limit == 0` via `std::mem::take` and evicting largest buffers first) and `return_and_trim` so `give_back` always trims pre-existing cached buffers down to the active limit even when the incoming buffer itself is rejected, and drops all evicted/rejected `ID3D12Resource`s **outside** the `SPARE` mutex. - Add `pub(super) fn trim()` to evict idle `SPARE` buffers down to the active limit. - **`d3d12/crates/leonida-gpu/src/host.rs`**: - Call `send::trim()` in `sweep()` whenever `crate::residency::pressured() || crate::residency::critical_commit()` (matching `pool::room` so non-`pressured()` critical commit windows such as post-`E_OUTOFMEMORY` `RETRY_UPLOAD_AT` still trim immediately). ### Tested - `python -I scripts/check_no_game_data.py` -- PASS - `python -I tools/d3d12_switches.py --check d3d12/docs/switches.md` -- PASS - `cargo test -p leonida-gpu --lib --locked host::send::` -- 3/3 PASS (`kept_for_scales_down_under_pressure_and_zeroes_on_critical_commit`, `evict_over_limit_drops_largest_first_and_zeroes_on_zero_limit`, `return_and_trim_evicts_cached_entries_when_limit_shrinks`) - `cargo build --profile diag --features "diagnostics,dlss,mimalloc" --locked` -- PASS - **In-game 315 s gate run (Windows 10, RTX 5070 12 GB, Series S preset, DLSS, no Frame Generation, 315 s in world, 437.0 s total, 64 world samples, max 5,341 draws):** - Runtime errors: 0; device lost: 0 - Frame rate: median **27.1 fps** (37.0 ms; slowest tenth 20.8, fastest tenth 28.1); `3000-4999` draws bucket: **27.1 fps** (57 samples) -- matches `main` (`d9b618f10`) baseline (`27.0 fps`, `3000-4999` bucket `27.1 fps`). GPUs tested: NVIDIA GeForce RTX 5070 12 GB, Windows 10 x64 (native). AI-assisted: yes. Author: Antigravity (Gemini 4 Neon). Reviewer: separate read-only Pro reviewer subagent (two passes; caught non-`pressured()` `critical_commit()` gating in `sweep()` and trimming pre-existing `SPARE` entries when `give_back` rejects an oversized incoming buffer, then approved). ### Checklist - [x] Based on current `main` and merges cleanly. - [x] One topic; follow-up work goes in a new pull request. - [x] No game data, keys or decryption (`CONTRIBUTING.md`), including in logs or reports quoted here. - [ ] A new translator rule is in the contract table of `docs/design.md`, with how it was confirmed. (n/a)
merzleckeier commented 2026-12-03 11:47:28 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by merzleckeier on 2026-12-03T11:47:28Z.


Independent check of 745a2ef2 on b053a181. On AMD RADV through Wine/vkd3d-proton, real D3D12 upload allocations left 88 MiB in the idle pool normally, 56 MiB after a simulated pressure transition, 0 MiB at critical commit, and 8 MiB after recovery. An active allocation retained its contents across the trim. The pool also stayed empty when an active buffer was returned during critical commit.

There is a single host::sweep merge conflict when combined with #3321 at 72f83d04. I resolved it locally by keeping the conditional send::trim() and #3321’s trim_idle_chunks(memory) before pool::room(memory). In the resulting build, a synthetic E_OUTOFMEMORY notification exercised the real retry window and sweep, emptying an idle D3D12 upload buffer. All five send tests, 13 scratch tests and 21 switch catalog tests passed on the combined tree.

AI-assisted with OpenAI Codex.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7377182140 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3326#issuecomment-7377182140). Originally posted by [merzleckeier](https://github.com/merzleckeier) on 2026-12-03T11:47:28Z. --- Independent check of `745a2ef2` on `b053a181`. On AMD RADV through Wine/vkd3d-proton, real D3D12 upload allocations left 88 MiB in the idle pool normally, 56 MiB after a simulated pressure transition, 0 MiB at critical commit, and 8 MiB after recovery. An active allocation retained its contents across the trim. The pool also stayed empty when an active buffer was returned during critical commit. There is a single `host::sweep` merge conflict when combined with #3321 at `72f83d04`. I resolved it locally by keeping the conditional `send::trim()` and #3321’s `trim_idle_chunks(memory)` before `pool::room(memory)`. In the resulting build, a synthetic `E_OUTOFMEMORY` notification exercised the real retry window and sweep, emptying an idle D3D12 upload buffer. All five send tests, 13 scratch tests and 21 switch catalog tests passed on the combined tree. AI-assisted with OpenAI Codex.
icdmkg2 commented 2026-12-03 11:59:33 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by icdmkg2 on 2026-12-03T11:59:33Z.


Verified on Windows 11 (Profile M laptop: NVIDIA GeForce RTX 5060 Laptop GPU 8 GB, driver 621.24, AMD Ryzen 7 H 260, 32 GB RAM) against \origin/main\ (\053a1813, PR head \745a2ef25):

Automated tests

  • \python -I scripts/red_green.py 3326: clean merge, 778/778 \leonida-gpu\ unit tests passed on green (
    ed does not build\ on base because the new tests reference \KEPT_PRESSURED).

Live in-game verification (Series S, -NoFrameGen -NoPrecompile -Adapter 5060, 150 s cold-cache load/entry)

  • Built \diag\ cleanly; 0 warnings / 0 errors / 0 allocation failures across the run.

  • esidency\ entered memory pressure (9/47 1 s ticks; least seen: 1691 MB free physical RAM, 7812 MB commit left).
  • \leonida_gpu::census\ confirmed \host/send.rs:204\ upload buffers trimmed live under pressure from 168 MB (5 buffers) → 40 MB (4 buffers) (out of 1192 MB allocated during load), staying at 40 MB for the rest of the pressured window.
  • End-of-run memory: dedicated VRAM 4602 / 7131 MB, shared GPU memory 4329 / 15238 MB. (Note: cold shader-compile window, so steady-state FPS was not measured.)

AI-assisted: Gemini 4 Neon (Antigravity).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7377455113 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3326#issuecomment-7377455113). Originally posted by [icdmkg2](https://github.com/icdmkg2) on 2026-12-03T11:59:33Z. --- Verified on Windows 11 (Profile M laptop: NVIDIA GeForce RTX 5060 Laptop GPU 8 GB, driver 621.24, AMD Ryzen 7 H 260, 32 GB RAM) against \origin/main\ (\053a1813\, PR head \745a2ef25\): ### Automated tests - \python -I scripts/red_green.py 3326\: clean merge, **778/778** \leonida-gpu\ unit tests passed on green (\ ed does not build\ on base because the new tests reference \KEPT_PRESSURED\). ### Live in-game verification (Series S, \-NoFrameGen -NoPrecompile -Adapter 5060\, 150 s cold-cache load/entry) - Built \diag\ cleanly; **0 warnings / 0 errors / 0 allocation failures** across the run. - \ esidency\ entered memory pressure (9/47 1 s ticks; least seen: 1691 MB free physical RAM, 7812 MB commit left). - \leonida_gpu::census\ confirmed \host/send.rs:204\ upload buffers trimmed live under pressure from **168 MB (5 buffers) → 40 MB (4 buffers)** (out of 1192 MB allocated during load), staying at 40 MB for the rest of the pressured window. - End-of-run memory: dedicated VRAM 4602 / 7131 MB, shared GPU memory 4329 / 15238 MB. (Note: cold shader-compile window, so steady-state FPS was not measured.) AI-assisted: Gemini 4 Neon (Antigravity).
fiestorra commented 2026-12-03 12:58:19 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by fiestorra on 2026-12-03T12:58:19Z.


VERIFY-3325 y 3326 — las dos aplican limpias y compilan, y sus tests nuevos son +1 y +3 contra el main de ahora

Lo primero fue medir la base, porque main se ha movido hoy 23 commits y restar contra el 715 de esta mañana sería comparar árboles distintos (el error que he cometido dos veces):

main en b053a1813   cargo test -p leonida-gpu --lib   715 passed; 1 failed; 59 ignored
                    el 1: views_are_made_beside_the_heap_and_copied_in  (la iGPU)

Y contra esa base, las dos PRs:

#3325  cherry-pick exit 0 · 716 passed; 1 failed; 59 ignored    → +1 test
#3326  cherry-pick exit 0 · 718 passed; 1 failed; 59 ignored    → +3 tests

Las dos compilan y el único rojo es el de siempre. Y el +1 y el +3 son de verdad ahora, porque la base está medida hoy y no heredada de la mañana.

Lo que cada una hace, en una línea:

  • #3325: registra la tarjeta, su driver y la memoria de vídeo al crear el dispositivo — 68 líneas en un fichero, y es de las que hacen que un informe de fallo sirva (lo que #3320 recoge y esta PR produce);
  • #3326: suelta los búferes de subida de reserva de host::send cuando la memoria y los contadores aprietan — 2 ficheros, +119/−7.

Y una coincidencia que vale la pena decir: #3326 y #3321 tocan lo mismo desde dos sitios (la scratch que nadie pide) — la primera en host::send, la segunda en la reserva de la tarjeta. Las dos aplican limpias por separado; juntas no las he probado. Y eso es exactamente el tipo de pareja que se pelea sin que merge-tree lo vea: dos reducciones de memoria que se suman pueden quitar más de lo que sobra.

Lo que no he verificado: que liberen de verdad donde dicen (necesita una tarjeta corta y el juego) ni la pareja #3321+#3326 junta.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7379119712 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/3326#issuecomment-7379119712). Originally posted by [fiestorra](https://github.com/fiestorra) on 2026-12-03T12:58:19Z. --- ## VERIFY-3325 y 3326 — las dos aplican limpias y compilan, y sus tests nuevos son **+1 y +3** contra el `main` de ahora **Lo primero fue medir la base, porque `main` se ha movido hoy 23 commits y restar contra el `715` de esta mañana sería comparar árboles distintos** (**el error que he cometido dos veces**): ``` main en b053a1813 cargo test -p leonida-gpu --lib 715 passed; 1 failed; 59 ignored el 1: views_are_made_beside_the_heap_and_copied_in (la iGPU) ``` **Y contra esa base, las dos PRs**: ``` #3325 cherry-pick exit 0 · 716 passed; 1 failed; 59 ignored → +1 test #3326 cherry-pick exit 0 · 718 passed; 1 failed; 59 ignored → +3 tests ``` **Las dos compilan y el único rojo es el de siempre.** **Y el `+1` y el `+3` son de verdad ahora**, **porque la base está medida hoy y no heredada de la mañana.** **Lo que cada una hace, en una línea**: - **`#3325`**: **registra la tarjeta, su driver y la memoria de vídeo al crear el dispositivo** — **68 líneas en un fichero, y es de las que hacen que un informe de fallo sirva** (**lo que `#3320` recoge y esta PR produce**); - **`#3326`**: **suelta los búferes de subida de reserva de `host::send` cuando la memoria y los contadores aprietan** — **2 ficheros, +119/−7**. **Y una coincidencia que vale la pena decir**: **`#3326` y `#3321` tocan lo mismo desde dos sitios** (**la *scratch* que nadie pide**) — **la primera en `host::send`, la segunda en la reserva de la tarjeta.** **Las dos aplican limpias por separado; juntas no las he probado.** **Y eso es exactamente el tipo de pareja que se pelea sin que `merge-tree` lo vea**: **dos reducciones de memoria que se suman pueden quitar más de lo que sobra.** **Lo que no he verificado**: **que liberen de verdad donde dicen** (**necesita una tarjeta corta y el juego**) **ni la pareja `#3321`+`#3326` junta.**
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/3326:upstream-pr/3326'
git switch 'upstream-pr/3326'

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/3326'
git switch 'upstream-pr/3326'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/3326'
git switch 'upstream-pr/3326'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/3326'
git switch 'main'
git merge --squash 'upstream-pr/3326'
git switch 'main'
git merge --ff-only 'upstream-pr/3326'
git switch 'main'
git merge 'upstream-pr/3326'
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!3326
No description provided.