Texture compaction: empty mostly empty pool blocks when the card or the PC is short of memory #4582

Closed
github-bot wants to merge 6 commits from github-bot/gh-4581 into main AGit
Owner

@⁠mcozcan on GitHub · 2026-11-30 23:12 UTC · original
mcozcan:pr/compact-sparse-blocks → main · +876 −1 · 5 files · 6 commits · closed without merging

What it changes

A 64 MiB texture block costs the card (and, on NVIDIA, the process's commit, see #4289) in full however little of it is taken. In a long session the blocks fill with holes: 1.0 to 1.5 GB free inside texture blocks all through a 50-minute run on a 12 GB card, while the card was over its budget. Letting textures go by age leaves those holes, so no memory comes back, and #4289's texture-line cut rightly stands still while the blocks hold that much free space.

What gives memory back is a block emptied whole. This adds a compaction step to resource::let_go_idle:

  • It runs only while the PC's commit left is under VICTORY_COMPACT_COMMIT_FLOOR_MB (4096 by default; the same floor as #4289's VICTORY_TEXTURE_COMMIT_FLOOR_MB, kept apart so either can land first) or the card's use is over its budget, and only with at least 512 MiB free in texture blocks; at most one look every 5 s. The commit is counted as #4289 counts it, without what the page file may still grow by (#3443).
  • It takes the blocks under 35 % full (50 % while the card is over its budget) from pool::sparse_texture_blocks, and lets go of the idle textures in them (idle for 3 s, held by their title texture alone: no list, no slot), exactly as the sweep lets an idle texture go (unstage, wanted, used, retire). Emptied blocks then go back through the pool's usual spare policy.
  • At most 384 MiB and 3 ms a look; a look resumes where the last one stopped.
  • pool::block_of names the block a resource was cut from through its Reclaim private data (GetPrivateData adds a reference, released at once; the resource keeps its own).
  • VICTORY_COMPACT_SPARSE=0 turns it off.

Whole blocks (VICTORY_COMPACT_WHOLE=1, off by default; 9fd549f8 and e6cac2f6)

@⁠CuteBooty's runs (below) showed the per-texture rule letting a lot go and giving little back: when one member of a sparse block cannot go (a slot or list holds it, it was read lately, the title wrote it), the block stays, and the members let go beside it are made and uploaded again at their next use. As @⁠Jesper-Andersson suggested, with this switch a block's members go only when every one of them can:

  • A round tallies, over one pass of the textures table (bounded to 3 ms a look, resuming where it stopped), the bytes of each candidate block's members that may go and of those that may not, by reason. A texture's block and piece size are noted once when its host copy is made (HostTexture::piece), so a round makes no D3D12 call for them.
  • When the round is whole, the blocks whose live bytes (held less resting) are all held by members that may go are emptied, emptiest first, at most 8 blocks and 384 MiB a round. Each member is checked again under its lock first (in the table, filled from title memory, used read again under the lock, not written by the title, references one, same block), and the block is taken only if the checked bytes are exactly what it holds now; otherwise it is given up and the next one is tried.
  • A block being emptied is marked for 10 s (pool::mark_draining): Pool::cut takes it after every other block with room (still before making a new block), so it is not filled again while its last pieces are retired and rest. Without marks the order is as before.
  • While it acts, and for 60 s after, the texture pools keep at most 2 empty blocks (pool::room), so what it empties goes back to Windows also below 85 % of the card's budget, where they would keep up to 64. VICTORY_COMPACT_SPARES=0 leaves the spares as they are, to measure the whole-block rule apart from this.
  • Its line (texture compaction, whole blocks) gives per round: looks and time, textures skipped because their lock was busy, candidate blocks, blocks with every member free to go, emptied and given up, and the MB held back in candidate blocks by reason (held by a slot or list / read lately / written by the title). Both compaction lines now also give the textures compaction let go that were made again since the start (COMPACT_COMEBACK), to compare the two rules' re-upload cost.

The decisions are pure functions in a new module, drain.rs (not Windows-only), with unit tests.

How it was tested

  • GPU and profile: RTX 5070 12 GB, Ryzen 5 9600X, 32 GB RAM, Windows 11 26300, driver 621.24. Series X, 2560x1440, DLSS Performance, DLSS frame generation 2x, ray tracing off.
  • Before: in the run above, 1.0 to 1.5 GB free in texture blocks from minute 10 to the end, the card at 10.9-12.0 GB of a 10.7 GB budget.
  • After: the same 6-minute run as in the sampled-eviction PR (with that change on, so the card stayed under its budget): compaction ran once, 231 idle textures (30 MB) from 34 sparse blocks, and the blocks still held 2.1 GB free at the end.
  • Runs by @⁠CuteBooty on an RTX 3070 8 GB (first two commits, cherry-picked onto v2026.11.30.01, Series S, DLSS Performance, DLSS frame generation x2, VICTORY_SAMPLED_EVICT=1):
    • 34 minutes of free roam with compaction forced to look every 5 s (VICTORY_COMPACT_COMMIT_FLOOR_MB=99999; card at 92-96 % of its budget): 5,514 idle textures (654 MB) let go; 12 texture blocks (768 MB) released to Windows, all in the first ~12 minutes (an upper bound: the counter includes blocks the sweep emptied); none in the last 22 minutes although ~330 MB more was let go; the texture blocks never shrank (43-46 blocks), and 6 to 17 blocks under a quarter full stayed all session. No cost seen in frame times.
    • 6 minutes, Series X 1080p, on its own trigger with the card 1.7-1.8 GB over budget: 239 MB let go, 8 blocks (512 MB) released (same upper bound).
    • A 28-minute campaign mission on its own trigger: the card stayed under budget; it acted twice near the end, 78 textures (11 MB), 2 blocks (128 MB) released.
  • Whole blocks (9fd549f8, e6cac2f6): not run in the game yet. Two arms on an 8 GB card would tell whether it helps: VICTORY_COMPACT_WHOLE=0 and =1, same route, 30 minutes each, VICTORY_POOL_STATS=1, VICTORY_LOG=info; compare blocks released, the texture block total over time, textures made again, and what holds the candidate blocks.
  • For shader changes: none.
  • cargo test -p victory-gpu --lib passed for the first two commits, with a new test (block_of_names_the_block_and_keeps_the_count: the block and pool named, the reference count unchanged after 1,000 calls, the piece back in the pool once the resource goes, None for a committed resource). The two failures list::thin::tests::bindings_record_no_work and shader_cache::tests::every_switch_of_the_translator_is_in_the_key fail on main too (#4297).
  • At e6cac2f6 (this branch's head; the same tree CI ran on before its commit messages were reworded), this repository's CI workflow passed on windows-latest: both clippy steps and cargo test --workspace --locked (run, run in my own repository because the runs here wait for approval). drain's 7 unit tests also pass on Linux.

Checked for overlap

  • I searched the open pull requests for the same issue and for the files this touches. Related: #4289 (texture line under the PC's commit; complementary: it lowers the line, this gives back what holes hold), #3475 (sweep under RAM pressure; touches let_go_idle near the card rule), #1562 (block-aware idle eviction, older and much larger), #4455 (first-upload admission scans), #4220 (index non-full pool blocks; touches Pool::cut), #4559 (the sweep on a thread of its own; this runs inside let_go_idle, so it would move with it).
**@⁠mcozcan** on GitHub · 2026-11-30 23:12 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581) `mcozcan:pr/compact-sparse-blocks` → `main` · +876 −1 · 5 files · 6 commits · closed without merging ## What it changes A 64 MiB texture block costs the card (and, on NVIDIA, the process's commit, see #4289) in full however little of it is taken. In a long session the blocks fill with holes: 1.0 to 1.5 GB free inside texture blocks all through a 50-minute run on a 12 GB card, while the card was over its budget. Letting textures go by age leaves those holes, so no memory comes back, and #4289's texture-line cut rightly stands still while the blocks hold that much free space. What gives memory back is a block emptied whole. This adds a compaction step to `resource::let_go_idle`: - It runs only while the PC's commit left is under `VICTORY_COMPACT_COMMIT_FLOOR_MB` (4096 by default; the same floor as #4289's `VICTORY_TEXTURE_COMMIT_FLOOR_MB`, kept apart so either can land first) or the card's use is over its budget, and only with at least 512 MiB free in texture blocks; at most one look every 5 s. The commit is counted as #4289 counts it, without what the page file may still grow by (#3443). - It takes the blocks under 35 % full (50 % while the card is over its budget) from `pool::sparse_texture_blocks`, and lets go of the idle textures in them (idle for 3 s, held by their title texture alone: no list, no slot), exactly as the sweep lets an idle texture go (`unstage`, `wanted`, `used`, `retire`). Emptied blocks then go back through the pool's usual spare policy. - At most 384 MiB and 3 ms a look; a look resumes where the last one stopped. - `pool::block_of` names the block a resource was cut from through its `Reclaim` private data (`GetPrivateData` adds a reference, released at once; the resource keeps its own). - `VICTORY_COMPACT_SPARSE=0` turns it off. ### Whole blocks (`VICTORY_COMPACT_WHOLE=1`, off by default; 9fd549f8 and e6cac2f6) @⁠CuteBooty's runs (below) showed the per-texture rule letting a lot go and giving little back: when one member of a sparse block cannot go (a slot or list holds it, it was read lately, the title wrote it), the block stays, and the members let go beside it are made and uploaded again at their next use. As @⁠Jesper-Andersson suggested, with this switch a block's members go only when every one of them can: - A round tallies, over one pass of the textures table (bounded to 3 ms a look, resuming where it stopped), the bytes of each candidate block's members that may go and of those that may not, by reason. A texture's block and piece size are noted once when its host copy is made (`HostTexture::piece`), so a round makes no D3D12 call for them. - When the round is whole, the blocks whose live bytes (held less resting) are all held by members that may go are emptied, emptiest first, at most 8 blocks and 384 MiB a round. Each member is checked again under its lock first (in the table, filled from title memory, `used` read again under the lock, not written by the title, references one, same block), and the block is taken only if the checked bytes are exactly what it holds now; otherwise it is given up and the next one is tried. - A block being emptied is marked for 10 s (`pool::mark_draining`): `Pool::cut` takes it after every other block with room (still before making a new block), so it is not filled again while its last pieces are retired and rest. Without marks the order is as before. - While it acts, and for 60 s after, the texture pools keep at most 2 empty blocks (`pool::room`), so what it empties goes back to Windows also below 85 % of the card's budget, where they would keep up to 64. `VICTORY_COMPACT_SPARES=0` leaves the spares as they are, to measure the whole-block rule apart from this. - Its line (`texture compaction, whole blocks`) gives per round: looks and time, textures skipped because their lock was busy, candidate blocks, blocks with every member free to go, emptied and given up, and the MB held back in candidate blocks by reason (held by a slot or list / read lately / written by the title). Both compaction lines now also give the textures compaction let go that were made again since the start (`COMPACT_COMEBACK`), to compare the two rules' re-upload cost. The decisions are pure functions in a new module, `drain.rs` (not Windows-only), with unit tests. ## How it was tested - GPU and profile: RTX 5070 12 GB, Ryzen 5 9600X, 32 GB RAM, Windows 11 26300, driver 621.24. Series X, 2560x1440, DLSS Performance, DLSS frame generation 2x, ray tracing off. - Before: in the run above, 1.0 to 1.5 GB free in texture blocks from minute 10 to the end, the card at 10.9-12.0 GB of a 10.7 GB budget. - After: the same 6-minute run as in the sampled-eviction PR (with that change on, so the card stayed under its budget): compaction ran once, 231 idle textures (30 MB) from 34 sparse blocks, and the blocks still held 2.1 GB free at the end. - Runs by @⁠CuteBooty on an RTX 3070 8 GB (first two commits, cherry-picked onto v2026.11.30.01, Series S, DLSS Performance, DLSS frame generation x2, `VICTORY_SAMPLED_EVICT=1`): - 34 minutes of free roam with compaction forced to look every 5 s (`VICTORY_COMPACT_COMMIT_FLOOR_MB=99999`; card at 92-96 % of its budget): 5,514 idle textures (654 MB) let go; 12 texture blocks (768 MB) released to Windows, all in the first ~12 minutes (an upper bound: the counter includes blocks the sweep emptied); none in the last 22 minutes although ~330 MB more was let go; the texture blocks never shrank (43-46 blocks), and 6 to 17 blocks under a quarter full stayed all session. No cost seen in frame times. - 6 minutes, Series X 1080p, on its own trigger with the card 1.7-1.8 GB over budget: 239 MB let go, 8 blocks (512 MB) released (same upper bound). - A 28-minute campaign mission on its own trigger: the card stayed under budget; it acted twice near the end, 78 textures (11 MB), 2 blocks (128 MB) released. - Whole blocks (9fd549f8, e6cac2f6): not run in the game yet. Two arms on an 8 GB card would tell whether it helps: `VICTORY_COMPACT_WHOLE=0` and `=1`, same route, 30 minutes each, `VICTORY_POOL_STATS=1`, `VICTORY_LOG=info`; compare blocks released, the texture block total over time, textures made again, and what holds the candidate blocks. - For shader changes: none. - `cargo test -p victory-gpu --lib` passed for the first two commits, with a new test (`block_of_names_the_block_and_keeps_the_count`: the block and pool named, the reference count unchanged after 1,000 calls, the piece back in the pool once the resource goes, `None` for a committed resource). The two failures `list::thin::tests::bindings_record_no_work` and `shader_cache::tests::every_switch_of_the_translator_is_in_the_key` fail on `main` too (#4297). - At e6cac2f6 (this branch's head; the same tree CI ran on before its commit messages were reworded), this repository's CI workflow passed on `windows-latest`: both clippy steps and `cargo test --workspace --locked` ([run](https://github.com/mcozcan/PortMC-VI/actions/runs/46615909760), run in my own repository because the runs here wait for approval). `drain`'s 7 unit tests also pass on Linux. ## Checked for overlap - [x] I searched the open pull requests for the same issue and for the files this touches. Related: #4289 (texture line under the PC's commit; complementary: it lowers the line, this gives back what holes hold), #3475 (sweep under RAM pressure; touches `let_go_idle` near the card rule), #1562 (block-aware idle eviction, older and much larger), #4455 (first-upload admission scans), #4220 (index non-full pool blocks; touches `Pool::cut`), #4559 (the sweep on a thread of its own; this runs inside `let_go_idle`, so it would move with it).
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-30 23:14:00 +00:00
Author
Owner

@⁠tyr0nsur on GitHub · 2026-11-30 23:21 UTC · original

There is a second trace that meets both gates for a useful test of this draft. The matched RTX 4050 Laptop 6 GiB run in #4310 has 723–799 MiB free in texture blocks while local use is 5,665–5,697 MiB against a 5,114–5,148 MiB budget. In its last 10 samples the dynamic sweep cap remains above its configured soft cap, so #4340 would leave the limit unchanged there. That makes this route a useful compaction-only comparison if the reporter can test a build.

One detail that would make the comparison easier to interpret: compact_sparse logs sparse.len() as the number of blocks the evictions came from. That is the size of the candidate set, including blocks the bounded scan never visited and blocks with no eligible texture. Could the line distinguish candidate blocks, blocks actually touched, and backing MiB returned once retirement drains? The last quantity is the result we care about here, and #3766 already instruments blocks released from both texture pools.

**@⁠tyr0nsur** on GitHub · 2026-11-30 23:21 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7295023834) There is a second trace that meets both gates for a useful test of this draft. The matched RTX 4050 Laptop 6 GiB run in #4310 has 723–799 MiB free in texture blocks while local use is 5,665–5,697 MiB against a 5,114–5,148 MiB budget. In its last 10 samples the dynamic sweep cap remains above its configured soft cap, so #4340 would leave the limit unchanged there. That makes this route a useful compaction-only comparison if the reporter can test a build. One detail that would make the comparison easier to interpret: `compact_sparse` logs `sparse.len()` as the number of blocks the evictions came from. That is the size of the candidate set, including blocks the bounded scan never visited and blocks with no eligible texture. Could the line distinguish candidate blocks, blocks actually touched, and backing MiB returned once retirement drains? The last quantity is the result we care about here, and #3766 already instruments blocks released from both texture pools.
Author
Owner

@⁠mcozcan on GitHub · 2026-11-30 23:48 UTC · original

Thanks, good catch. The line counted the candidate set, not what was touched or returned. Updated in 506c283e: it now reports candidate blocks, blocks a texture actually went from (and whether the scan stopped at its bound), and the texture blocks released to Windows since compaction first acted, in blocks and MiB, from a new texture-pools-only counter in pool.rs (TEXTURES_LET_GO; both texture pools share the SPARES budget, so staging releases are left out). Releases land after the textures' retirement drains, so a later line shows what an earlier look gave back; it counts every release since the first look, sweep included, so it is an upper bound on compaction's share. The #4310 trace sounds like the right comparison; I can't run it on that laptop, but if the reporter can test a build I'm happy to help read the log.

**@⁠mcozcan** on GitHub · 2026-11-30 23:48 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7295543710) Thanks, good catch. The line counted the candidate set, not what was touched or returned. Updated in 506c283e: it now reports candidate blocks, blocks a texture actually went from (and whether the scan stopped at its bound), and the texture blocks released to Windows since compaction first acted, in blocks and MiB, from a new texture-pools-only counter in `pool.rs` (`TEXTURES_LET_GO`; both texture pools share the `SPARES` budget, so staging releases are left out). Releases land after the textures' retirement drains, so a later line shows what an earlier look gave back; it counts every release since the first look, sweep included, so it is an upper bound on compaction's share. The #4310 trace sounds like the right comparison; I can't run it on that laptop, but if the reporter can test a build I'm happy to help read the log.
github-bot force-pushed github-bot/gh-4581 from e7ebbcfb38 to 09eecc8748 2026-12-01 00:05:18 +00:00 Compare
Author
Owner

@⁠Jesper-Andersson on GitHub · 2026-12-01 01:33 UTC · original

A data point from an 8 GB card, and a question, as promised in #4463.

Setup: RTX 2070 SUPER 8 GB, Series S, DLSS Performance, FSR 3 frame generation, no texture cap. Our fork's build, with this PR ported at e7ebbcfb (before 506c283e), so without the new TEXTURES_LET_GO line. Driver 621.40, ReBAR off, Ryzen 7 5800X, 32 GB RAM, Windows 11. One 35-minute session, not repeated; other cards and Series X not tested. The card was over its budget for almost all of it, so the 50 % line applied.

What we saw:

  • The compaction ran 150 looks and let 4,299 idle textures (557 MB) go.
  • Over the same time the texture blocks stayed at exactly 3968 MB in all 640 ledger samples, from minute 3 to the end. Free space inside them was up to 1.7 GB.
  • In the last block histogram about 1.0 GB of the 1.5 GB free was in blocks only 1–25 % full, well under the line. Earlier histograms had about 0.1–0.65 GB there, and most of the rest was in blocks 25–75 % full.

Since our port has no release counter, "no block came back" is read from the flat block total, not counted directly.

Reading the code (not measured), the candidates for what keeps a sparse block alive:

  1. A member held by a descriptor slot (reference count above one), which compaction skips by design.
  2. Placement refilling the block: what is let go is made again at its next use, and the pool cuts into the fullest block with room, which can be the sparse one.
  3. A live or host-written member, which only a move could take out.
  4. An emptied block kept as a spare.

We're adding a per-block count of what holds each block (slot, list, host-written, young, idle) to our build, and will post it here. Would a rule that lets a block's residents go only when all of them can go, sorted emptiest first, fit your design? If it helps, I can offer it as a small follow-up behind its own switch, after your counters show what our census shows. It's your design, so your call.

Drafted with AI assistance (Claude Code).

**@⁠Jesper-Andersson** on GitHub · 2026-12-01 01:33 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7297635327) A data point from an 8 GB card, and a question, as promised in #4463. **Setup:** RTX 2070 SUPER 8 GB, Series S, DLSS Performance, FSR 3 frame generation, no texture cap. Our fork's build, with this PR ported at e7ebbcfb (before 506c283e), so without the new `TEXTURES_LET_GO` line. Driver 621.40, ReBAR off, Ryzen 7 5800X, 32 GB RAM, Windows 11. One 35-minute session, not repeated; other cards and Series X not tested. The card was over its budget for almost all of it, so the 50 % line applied. **What we saw:** - The compaction ran 150 looks and let 4,299 idle textures (557 MB) go. - Over the same time the texture blocks stayed at exactly 3968 MB in all 640 ledger samples, from minute 3 to the end. Free space inside them was up to 1.7 GB. - In the last block histogram about 1.0 GB of the 1.5 GB free was in blocks only 1–25 % full, well under the line. Earlier histograms had about 0.1–0.65 GB there, and most of the rest was in blocks 25–75 % full. Since our port has no release counter, "no block came back" is read from the flat block total, not counted directly. **Reading the code (not measured), the candidates for what keeps a sparse block alive:** 1. A member held by a descriptor slot (reference count above one), which compaction skips by design. 2. Placement refilling the block: what is let go is made again at its next use, and the pool cuts into the fullest block with room, which can be the sparse one. 3. A live or host-written member, which only a move could take out. 4. An emptied block kept as a spare. We're adding a per-block count of what holds each block (slot, list, host-written, young, idle) to our build, and will post it here. Would a rule that lets a block's residents go only when all of them can go, sorted emptiest first, fit your design? If it helps, I can offer it as a small follow-up behind its own switch, after your counters show what our census shows. It's your design, so your call. Drafted with AI assistance (Claude Code).
Author
Owner

@⁠CuteBooty on GitHub · 2026-12-01 03:11 UTC · original

A short run of this PR on its own trigger, no forcing: card over budget. RTX 3070 8 GB, both commits cherry-picked onto v2026.11.30.01, Series X profile at 1080p, DLSS Performance, DLSS frame generation x2, upstream's play settings plus VICTORY_SAMPLED_EVICT=1. Six minutes in the world. Closed normally, no driver events.

  • The card was over its budget from minute 1: 8,692 / 7,029 MB at minute 5, 8,806 / 7,000 at minute 6. Render-target copies were 2.5 GB, against 1.2-1.5 GB on the Series S profile at the same point.
  • Compaction acted on its own: 239 MB of idle textures let go in 6 minutes, and 8 texture blocks (512 MB) released to Windows since the first look. That count includes blocks the sweep emptied, so it is an upper bound.
  • Texture blocks: 2,624 MB at minutes 5 and 6, with 1,029 and then 740 MB free inside.
  • Median frame 107 ms. Most of that is the card being 1.7-1.8 GB over budget, not compaction.

For comparison, the 34-minute forced session on the Series S profile is in #4463: 12 blocks (768 MB) released in the first 12 minutes, then none, and the texture blocks never shrank. Here, on the real trigger, the pace looks similar at the start. Six minutes is too short to say whether it keeps going.

**@⁠CuteBooty** on GitHub · 2026-12-01 03:11 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7299422827) A short run of this PR on its own trigger, no forcing: card over budget. RTX 3070 8 GB, both commits cherry-picked onto v2026.11.30.01, Series X profile at 1080p, DLSS Performance, DLSS frame generation x2, upstream's play settings plus `VICTORY_SAMPLED_EVICT=1`. Six minutes in the world. Closed normally, no driver events. - The card was over its budget from minute 1: 8,692 / 7,029 MB at minute 5, 8,806 / 7,000 at minute 6. Render-target copies were 2.5 GB, against 1.2-1.5 GB on the Series S profile at the same point. - Compaction acted on its own: 239 MB of idle textures let go in 6 minutes, and 8 texture blocks (512 MB) released to Windows since the first look. That count includes blocks the sweep emptied, so it is an upper bound. - Texture blocks: 2,624 MB at minutes 5 and 6, with 1,029 and then 740 MB free inside. - Median frame 107 ms. Most of that is the card being 1.7-1.8 GB over budget, not compaction. For comparison, the 34-minute forced session on the Series S profile is in #4463: 12 blocks (768 MB) released in the first 12 minutes, then none, and the texture blocks never shrank. Here, on the real trigger, the pace looks similar at the start. Six minutes is too short to say whether it keeps going.
Author
Owner

@⁠mcozcan on GitHub · 2026-12-01 06:51 UTC · original

@⁠Jesper-Andersson yes, that fits, and I'd welcome it as a follow-up behind its own switch. @⁠CuteBooty's runs make the case: in the 34-minute session compaction let go 654 MB, but blocks came back only in the first ~12 minutes (12 at most, 768 MB), and the last ~330 MB it let go returned nothing. As written, compact_sparse lets go of every idle texture in a sparse block whether or not the block can empty, so when a slot or list still holds one member, the rest are made again at their next use for no gain. Letting a block's members go only when all of them can, emptiest block first, should stop that.

On your candidates: 1 (slot-held) is skipped by design here; 4 (spare) goes through the pool's usual spare policy, so one emptied block can stay; 2 (placement refilling a sparse block) I haven't measured, and your per-block census would settle it.

@⁠CuteBooty thanks for both runs, and for the counter check. I'll fold the numbers into the PR description; it still says "ran once, 30 MB" from my 12 GB run.

**@⁠mcozcan** on GitHub · 2026-12-01 06:51 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7303360887) @⁠Jesper-Andersson yes, that fits, and I'd welcome it as a follow-up behind its own switch. @⁠CuteBooty's runs make the case: in the 34-minute session compaction let go 654 MB, but blocks came back only in the first ~12 minutes (12 at most, 768 MB), and the last ~330 MB it let go returned nothing. As written, compact_sparse lets go of every idle texture in a sparse block whether or not the block can empty, so when a slot or list still holds one member, the rest are made again at their next use for no gain. Letting a block's members go only when all of them can, emptiest block first, should stop that. On your candidates: 1 (slot-held) is skipped by design here; 4 (spare) goes through the pool's usual spare policy, so one emptied block can stay; 2 (placement refilling a sparse block) I haven't measured, and your per-block census would settle it. @⁠CuteBooty thanks for both runs, and for the counter check. I'll fold the numbers into the PR description; it still says "ran once, 30 MB" from my 12 GB run.
Author
Owner

@⁠mcozcan on GitHub · 2026-12-01 09:37 UTC · original · edited 2026-12-01 11:59 UTC

@⁠Jesper-Andersson I put the whole-block rule into this PR instead of leaving it for a follow-up, so there is no need for yours. It's in 9fd549f8 (and e6cac2f6, a clippy fix), behind VICTORY_COMPACT_WHOLE=1 (off by default; off, the per-texture rule runs as before):

  • A block's members go only when every one of them can, emptiest block first. Each member is checked again under its lock right before.
  • A block being emptied is placed in last for 10 s, so it isn't filled again while its last pieces rest.
  • While it acts, the texture pools keep at most 2 empty blocks (VICTORY_COMPACT_SPARES=0 turns that part off).
  • The line gives the MB held back in candidate blocks by reason: held by a slot or list, read lately, or written by the title. That is the per-block question from your census, from the compaction's side.

Not run in the game yet. The CI workflow passed at e6cac2f6 (clippy, both builds, and cargo test --workspace), run in my own repository since the runs here wait for approval. The description has the details and @⁠CuteBooty's numbers.

@⁠CuteBooty if you have time for it: two runs on the same route, 30 minutes each, with VICTORY_POOL_STATS=1 and VICTORY_LOG=info, one with VICTORY_COMPACT_WHOLE=0 and one with =1. Your forced setting (VICTORY_COMPACT_COMMIT_FLOOR_MB=99999) works for both. The lines to compare are blocks released to Windows, the texture block total over time, "let go by compaction and made again", and in the =1 run the "kept in candidate blocks" split.

**@⁠mcozcan** on GitHub · 2026-12-01 09:37 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7306975277) · edited 2026-12-01 11:59 UTC @⁠Jesper-Andersson I put the whole-block rule into this PR instead of leaving it for a follow-up, so there is no need for yours. It's in 9fd549f8 (and e6cac2f6, a clippy fix), behind `VICTORY_COMPACT_WHOLE=1` (off by default; off, the per-texture rule runs as before): - A block's members go only when every one of them can, emptiest block first. Each member is checked again under its lock right before. - A block being emptied is placed in last for 10 s, so it isn't filled again while its last pieces rest. - While it acts, the texture pools keep at most 2 empty blocks (`VICTORY_COMPACT_SPARES=0` turns that part off). - The line gives the MB held back in candidate blocks by reason: held by a slot or list, read lately, or written by the title. That is the per-block question from your census, from the compaction's side. Not run in the game yet. The CI workflow passed at e6cac2f6 (clippy, both builds, and `cargo test --workspace`), run in my own repository since the runs here wait for approval. The description has the details and @⁠CuteBooty's numbers. @⁠CuteBooty if you have time for it: two runs on the same route, 30 minutes each, with `VICTORY_POOL_STATS=1` and `VICTORY_LOG=info`, one with `VICTORY_COMPACT_WHOLE=0` and one with `=1`. Your forced setting (`VICTORY_COMPACT_COMMIT_FLOOR_MB=99999`) works for both. The lines to compare are blocks released to Windows, the texture block total over time, "let go by compaction and made again", and in the `=1` run the "kept in candidate blocks" split.
github-bot force-pushed github-bot/gh-4581 from 2f7887f75c to e6cac2f6b6 2026-12-01 12:04:30 +00:00 Compare
Author
Owner

@⁠tyr0nsur on GitHub · 2026-12-01 13:13 UTC · original
On crates/victory-gpu/src/resource.rs line 4474 (outdated):

@@ -3997,6 +4013,493 @@ fn record_frame_ring(frame: u64, now_ms: u64, idle_ms: u64) -> Option<u64> {
     frame_at(&ring, now_ms.saturating_sub(idle_ms))
 }
 
+// --- Compaction of sparse texture blocks under the PC's commit ---------------
+//
+// On NVIDIA the card's memory the layer holds counts in the process's commit
+// one to one (#4288), and a 64 MiB block of textures counts whole however
+// little of it is taken. A run on an RTX 5070 (12 GB), 32 GB of RAM, a 20 GB
+// page file, Series X 1440p with frame generation (2026-11-30): 47 GB
+// committed, 1.5 GB of RAM free, 2.8 GB free in texture blocks, and then the
+// device was removed. The texture line's cut (`commit_cut_tick`) stood still
+// all the while, rightly: with that much free in blocks, letting textures go
+// by age leaves holes and gives no commit back.
+//
+// What does give it back is a block emptied whole. So while the PC is short
+// of commit and the blocks hold holes, the idle textures of the blocks that
+// are mostly empty go (under a fill line, not sorted by it), a bounded amount a look:
+// their blocks then empty and the pool lets them go. A texture let go is made
+// and uploaded again at its next use, as after any sweep.
+
+/// Blocks under this many thousandths full are compacted.
+#[cfg(windows)]
+const COMPACT_SPARSE_PER_MILLE: u64 = 350;
+/// The least idle time of a texture compaction lets go.
+#[cfg(windows)]
+const COMPACT_IDLE_MS: u64 = 3000;
+/// The most compaction lets go at one look, and its time.
+#[cfg(windows)]
+const COMPACT_MOST: u64 = 384 << 20;
+#[cfg(windows)]
+const COMPACT_MOST_US: u128 = 3000;
+/// Free bytes in texture blocks under which there is nothing to compact.
+#[cfg(windows)]
+const COMPACT_HOLES: u64 = 512 << 20;
+
+/// The PC's commit left under which compaction runs
+/// (`VICTORY_COMPACT_COMMIT_FLOOR_MB`, 4096 by default, where the layer's
+/// own pressure starts (`crate::residency`); `0`: only for the card).
+#[cfg(windows)]
+fn compact_commit_floor() -> u64 {
+    static FLOOR: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
+    *FLOOR.get_or_init(|| {
+        std::env::var("VICTORY_COMPACT_COMMIT_FLOOR_MB")
+            .ok()
+            .and_then(|v| v.trim().parse::<u64>().ok())
+            .unwrap_or(4096)
+            << 20
+    })
+}
+
+/// Since the start: looks that compacted, textures let go, their bytes.
+#[cfg(windows)]
+static COMPACTED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
+
+/// `VICTORY_COMPACT_SPARSE=0` turns compaction off.
+#[cfg(windows)]
+fn compact_on() -> bool {
+    crate::toggled!("VICTORY_COMPACT_SPARSE")
+}
+
+/// The same while the card is over its budget.
+#[cfg(windows)]
+const COMPACT_SPARSE_PER_MILLE_CARD: u64 = 500;
+/// The least time between two compactions.
+#[cfg(windows)]
+const COMPACT_EVERY_MS: u64 = 5000;
+
+/// The sparse blocks to empty now, or `None`: compaction off, too little free
+/// in texture blocks, or neither the PC short of commit nor the card over its
+/// budget.
+///
+/// The card over its budget is the second reason (run of 2026-11-30, RTX 5070,
+/// Series X 1440p, frame generation 2x, 32 minutes): 12.0 GB in use of a
+/// budget of 10.7 from the tenth minute on, 1.8 GB of that free in texture
+/// blocks, 41 "out of VRAM" warnings of frame generation, frames of 900 ms
+/// and then the device removed. The queue's room takes the holes off the use,
+/// so nothing made it let them go; the card pays for them all the same. Over
+/// the budget the blocks under half full are compacted, a look in five
+/// seconds at most.
+#[cfg(windows)]
+fn compact_plan(memory: Option<[u64; 4]>) -> Option<std::collections::HashSet<(usize, usize)>> {
+    use std::sync::atomic::Ordering::Relaxed;
+    if !compact_on() || !crate::pool::on() || crate::pool::texture_room() < COMPACT_HOLES {
+        return None;
+    }
+    let floor = compact_commit_floor();
+    // The commit left of the moment, without what the page file may still
+    // grow by, as the texture line's floor counts it (`commit_floor`, #4288):
+    // a growing page file is what stalled 32 GB PCs (#3443), so compaction
+    // acts before it has to grow, not once it no longer can.
+    let short_of_commit =
+        floor != 0 && crate::residency::memory_status().is_some_and(|status| status.ullAvailPageFile < floor);
+    let card_over = memory.is_some_and(|[budget, used, ..]| used > budget);
+    if !short_of_commit && !card_over {
+        return None;
+    }
+    static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+    let now = crate::host::now_ms();
+    if now < LAST.load(Relaxed) + COMPACT_EVERY_MS {
+        return None;
+    }
+    LAST.store(now, Relaxed);
+    let per_mille = if card_over { COMPACT_SPARSE_PER_MILLE_CARD } else { COMPACT_SPARSE_PER_MILLE };
+    let sparse = crate::pool::sparse_texture_blocks(per_mille);
+    if !sparse.is_empty() {
+        COMPACT_ASKED_AT.store(now, Relaxed);
+    }
+    (!sparse.is_empty()).then_some(sparse)
+}
+
+/// Lets the idle textures of `sparse` blocks go ([`compact_plan`]), as the
+/// sweep lets an idle texture go: held by its title texture alone, no list
+/// and no slot on it.
+#[cfg(windows)]
+fn compact_sparse(all: &std::collections::BTreeSet<usize>, sparse: &std::collections::HashSet<(usize, usize)>) {
+    if compact_whole() {
+        compact_whole_blocks(all, sparse);
+        return;
+    }
+    use std::sync::atomic::Ordering::Relaxed;
+    const IDLE_FRAMES: u64 = 4;
+    let began = std::time::Instant::now();
+    let (mut went, mut bytes, mut looked) = (0u64, 0u64, 0usize);
+    // The candidate blocks a texture actually went from.
+    let mut touched = std::collections::HashSet::new();
+    // Where the last look stopped: a look bounded in time goes on from there,
+    // so the whole table is reached over a few looks (as the sweep's `FROM`).
+    static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+    let from = FROM.load(Relaxed);
+    let mut stopped_at = None;
+    for &at in all.range(from..).chain(all.range(..from)) {
+        if bytes >= COMPACT_MOST || (looked & 255) == 255 && began.elapsed().as_micros() >= COMPACT_MOST_US {
+            stopped_at = Some(at);
+            break;
+        }
+        looked += 1;
+        // SAFETY: a texture leaves the table before it is freed, under the
+        // table's lock, which the caller holds (`Drop for Resource`).
+        let r = unsafe { &*(at as *const Resource) };
+        let used = r.host.used.load(Relaxed);
+        if used == 0 || !fills(&r.desc) || !crate::host::long_ago(used, COMPACT_IDLE_MS, IDLE_FRAMES) || crate::texture::host_wrote(at) {
+            continue;
+        }
+        let Ok(mut made) = r.host.made.try_lock() else { continue };
+        let block = made.as_ref().and_then(|(host, _)| {
+            (crate::host::long_ago(r.host.used.load(Relaxed), COMPACT_IDLE_MS, IDLE_FRAMES)
+                && std::sync::Arc::strong_count(host) == 1
+                && crate::host::references(&host.texture) == 1)
+                .then(|| crate::pool::block_of(&host.texture))
+                .flatten()
+                .filter(|b| sparse.contains(b))
+        });
+        let Some(block) = block else {
+            continue;
+        };
+        touched.insert(block);
+        // As in `let_go_idle`: under the lock, the next use must not find the
+        // staging state of the texture let go, and it stamps `used` anew.
+        crate::texture::unstage(at as This);
+        r.host.wanted.store(u32::MAX, Relaxed);
+        r.host.used.store(0, Relaxed);
+        let gone = made.take();
+        drop(made);
+        if let Some((host, _)) = gone {
+            r.host.gone.store(true, Relaxed);
+            r.host.compacted.store(true, Relaxed);
+            KINDS[2].fetch_add(1, Relaxed);
+            KINDS[3].fetch_add(host.bytes, Relaxed);
+            went += 1;
+            bytes += host.bytes;
+            crate::host::retire(host);
+        }
+    }
+    FROM.store(stopped_at.unwrap_or(0), Relaxed);
+    // The texture blocks the pools had let go to Windows when compaction
+    // first acted: what they let go since is the memory actually returned
+    // (whatever let the last piece of a block go, compaction or the sweep;
+    // it comes once the textures' retirement has drained, so a later line
+    // shows what an earlier look gave back).
+    static BASE: std::sync::OnceLock<[u64; 2]> = std::sync::OnceLock::new();
+    if went == 0 && BASE.get().is_none() {
+        return;
+    }
+    let base = *BASE.get_or_init(crate::pool::textures_let_go);
+    let [blocks_now, bytes_now] = crate::pool::textures_let_go();
+    let looks = if went == 0 { COMPACTED[0].load(Relaxed) } else { COMPACTED[0].fetch_add(1, Relaxed) + 1 };
+    COMPACTED[1].fetch_add(went, Relaxed);
+    COMPACTED[2].fetch_add(bytes, Relaxed);
+    if went != 0 && (looks.is_power_of_two() || looks % 30 == 0) {
+        tracing::info!(
+            "texture compaction (VICTORY_COMPACT_SPARSE; the PC short of commit or the card over its budget): {went} idle \
+             textures ({} MB) let go from {} of {} candidate blocks (the scan stopped {}); since the start {} looks, {} \
+             textures, {} MB; let go by compaction and made again since the start: {} textures ({} MB); texture blocks \
+             released to Windows since the first look: {} ({} MB)",
+            bytes >> 20,
+            touched.len(),
+            sparse.len(),
+            if stopped_at.is_some() { "at its bound" } else { "after the whole table" },
+            looks,
+            COMPACTED[1].load(Relaxed),
+            COMPACTED[2].load(Relaxed) >> 20,
+            COMPACT_COMEBACK[0].load(Relaxed),
+            COMPACT_COMEBACK[1].load(Relaxed) >> 20,
+            blocks_now - base[0],
+            (bytes_now - base[1]) >> 20,
+        );
+    }
+}
+
+/// `VICTORY_COMPACT_WHOLE=1`: compaction lets a sparse block's textures go
+/// only when every one of them can, so the block empties whole
+/// (`crate::drain`); off, they go one by one as before.
+#[cfg(windows)]
+fn compact_whole() -> bool {
+    crate::asked_for!("VICTORY_COMPACT_WHOLE")
+}
+
+/// When [`compact_plan`] last asked for a compaction (ms).
+#[cfg(windows)]
+static COMPACT_ASKED_AT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// Whether the texture pools keep few empty blocks (`crate::pool::room`)
+/// because whole-block compaction asked to act within the last
+/// [`COMPACT_SPARES_HOLD_MS`], so that what it empties goes back to Windows.
+/// Below 85 % of the card's budget they would keep up to 64 otherwise.
+/// `VICTORY_COMPACT_SPARES=0` leaves the spares as they are, to measure the
+/// whole-block rule apart from this.
+#[cfg(windows)]
+pub(crate) fn compacting_whole() -> bool {
+    use std::sync::atomic::Ordering::Relaxed;
+    let at = COMPACT_ASKED_AT.load(Relaxed);
+    compact_whole()
+        && crate::toggled!("VICTORY_COMPACT_SPARES")
+        && at != 0
+        && crate::host::now_ms().saturating_sub(at) <= COMPACT_SPARES_HOLD_MS
+}
+
+/// How long the pools keep few spares after compaction last asked to act:
+/// longer than a round's gap, so that a PC at the commit floor does not
+/// switch between 2 and 64 spares (and blocks made ahead) every few seconds.
+#[cfg(windows)]
+const COMPACT_SPARES_HOLD_MS: u64 = 60_000;
+
+/// The most blocks one round empties.
+#[cfg(windows)]
+const COMPACT_WHOLE_BLOCKS: usize = 8;
+/// A round whose last look is older than this is dropped (compaction stopped
+/// being asked for): its tally would be stale. A round itself may take many
+/// looks; it is not bounded in time.
+#[cfg(windows)]
+const COMPACT_ROUND_GAP_MS: u64 = 20_000;
+/// How long a block being emptied is taken last by the pool's placement:
+/// longer than a retirement and a piece's rest.
+#[cfg(windows)]
+const COMPACT_DRAIN_MS: u64 = 10_000;
+
+/// Since the start: textures compaction let go that were made again, and
+/// their bytes (both modes): what letting them go cost in uploads.
+#[cfg(windows)]
+static COMPACT_COMEBACK: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
+
+/// What looks have tallied since the round began: a round is one pass over
+/// the whole table of textures, which a look bounded in time may not finish.
+#[cfg(windows)]
+struct Round {
+    /// Per candidate block: bytes (as cut from the block) of the members that
+    /// may go, and their addresses in the table.
+    may_go: std::collections::HashMap<(usize, usize), (u64, Vec<usize>)>,
+    /// Bytes of candidate blocks' members that may not go, by
+    /// [`crate::drain::Kept`].
+    kept: [u64; 3],
+    /// Textures skipped because their lock was busy (their block, unknown
+    /// without the lock, then falls short and is not taken this round).
+    busy: u64,
+    began: u64,
+    last: u64,
+    looks: u64,
+    /// Time the looks of the round took (µs).
+    spent: u64,
+}
+
+/// Since the start: rounds done, blocks emptied, blocks given up at the
+/// check before letting go.
+#[cfg(windows)]
+static COMPACT_ROUNDS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
+
+/// Whether the texture at `at` may go now: filled from title memory, read
+/// longer ago than the idle time, not written by the title, held by nothing
+/// but its title texture. `used` is read again under `made`'s lock, which
+/// `hosted_with` writes it under.
+#[cfg(windows)]
+fn compact_kept(at: usize, r: &Resource, host: &std::sync::Arc<HostTexture>) -> Option<crate::drain::Kept> {
+    use crate::drain::Kept;
+    use std::sync::atomic::Ordering::Relaxed;
+    const IDLE_FRAMES: u64 = 4;
+    let used = r.host.used.load(Relaxed);
+    if used == 0 || !crate::host::long_ago(used, COMPACT_IDLE_MS, IDLE_FRAMES) {
+        Some(Kept::Recent)
+    } else if crate::texture::host_wrote(at) {
+        Some(Kept::Written)
+    } else if std::sync::Arc::strong_count(host) != 1 || crate::host::references(&host.texture) != 1 {
+        Some(Kept::Referenced)
+    } else {
+        None
+    }
+}
+
+/// [`compact_sparse`] with `VICTORY_COMPACT_WHOLE=1`: tallies the members of
+/// `sparse` blocks over one pass of the table, then empties the blocks all of
+/// whose members may go ([`crate::drain::whole_blocks`]), each member checked
+/// again under its lock first.
+#[cfg(windows)]
+fn compact_whole_blocks(all: &std::collections::BTreeSet<usize>, sparse: &std::collections::HashSet<(usize, usize)>) {
+    use std::sync::atomic::Ordering::Relaxed;
+    static ROUND: std::sync::Mutex<Option<Round>> = std::sync::Mutex::new(None);
+    static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+    let now = crate::host::now_ms();
+    let mut round = ROUND.lock().unwrap_or_else(|e| e.into_inner());
+    if round.as_ref().is_some_and(|r| now.saturating_sub(r.last) > COMPACT_ROUND_GAP_MS) {
+        *round = None;
+        FROM.store(0, Relaxed);
+    }
+    let tally = round.get_or_insert_with(|| Round {
+        may_go: Default::default(),
+        kept: [0; 3],
+        busy: 0,
+        began: now,
+        last: now,
+        looks: 0,
+        spent: 0,
+    });
+
+    // Tally, bounded in time as the per-texture look is. No call into D3D12:
+    // the block of a texture is the one noted when it was made.
+    let began = std::time::Instant::now();
+    let from = FROM.load(Relaxed);
+    let mut stopped_at = None;
+    for (looked, &at) in all.range(from..).enumerate() {
+        if (looked & 255) == 255 && began.elapsed().as_micros() >= COMPACT_MOST_US {
+            stopped_at = Some(at);
+            break;
+        }
+        // SAFETY: as in `compact_sparse`: the caller holds the table's lock.
+        let r = unsafe { &*(at as *const Resource) };
+        if r.host.used.load(Relaxed) == 0 || !fills(&r.desc) {
+            continue;
+        }
+        let Ok(made) = r.host.made.try_lock() else {
+            tally.busy += 1;
+            continue;
+        };
+        let Some((host, _)) = made.as_ref() else { continue };
+        let Some((block, len)) = host.piece.filter(|(b, _)| sparse.contains(b)) else {
+            continue;
+        };
+        match compact_kept(at, r, host) {
+            Some(why) => tally.kept[why.index()] += len,
+            None => {
+                let entry = tally.may_go.entry(block).or_default();
+                entry.0 += len;
+                entry.1.push(at);
+            }
+        }
+    }
+    tally.looks += 1;
+    tally.last = now;
+    tally.spent += began.elapsed().as_micros() as u64;
+    FROM.store(stopped_at.unwrap_or(0), Relaxed);
+    if stopped_at.is_some() {
+        return;
+    }
+
+    // The round is whole: choose, check again, let go.
+    let Some(done) = round.take() else { return };
+    drop(round);
+    COMPACT_ROUNDS[0].fetch_add(1, Relaxed);
+    // Blocks no longer sparse are left out here, as are blocks that became
+    // sparse during the round (their tally then falls short).
+    let states = crate::pool::texture_block_states(sparse);
+    let may_go: std::collections::HashMap<(usize, usize), u64> = done.may_go.iter().map(|(&b, &(bytes, _))| (b, bytes)).collect();
+    // Every block whose members may all go, emptiest first; the caps count
+    // only the blocks actually emptied, so one given up makes room for the next.
+    let whole = crate::drain::whole_blocks(&states, &may_go, u64::MAX, usize::MAX);
+    let (mut went, mut bytes, mut emptied, mut given_up) = (0u64, 0u64, 0u64, 0u64);
+    let mut gone = Vec::new();
+    for block in whole.iter().copied() {
+        if emptied as usize >= COMPACT_WHOLE_BLOCKS || bytes >= COMPACT_MOST {
+            break;
+        }
+        let Some((_, members)) = done.may_go.get(&block) else { continue };
+        // Placement takes the block last from here on, so the check below is
+        // not undone by a new piece cut from it while its members go.
+        crate::pool::mark_draining(block, now + COMPACT_DRAIN_MS);
+        let mut guards = Vec::with_capacity(members.len());
+        let mut verified = 0u64;
+        let mut whole_still = true;
+        for &at in members {
+            // SAFETY: in the table (checked first), under its lock (the caller's).
+            let Some(r) = all.contains(&at).then(|| unsafe { &*(at as *const Resource) }) else {
+                whole_still = false;
+                break;
+            };
+            if !fills(&r.desc) {
+                whole_still = false;
+                break;
+            }
+            let Ok(made) = r.host.made.try_lock() else {
+                whole_still = false;
+                break;
+            };
+            let piece = made.as_ref().and_then(|(host, _)| compact_kept(at, r, host).is_none().then_some(host.piece).flatten());
+            match piece {
+                Some((b, len)) if b == block => verified += len,
+                _ => {
+                    whole_still = false;
+                    break;
+                }
+            }
+            guards.push((at, r, made));
+        }
+        let now_seen = crate::pool::texture_block_state(block).unwrap_or_default();
+        if !whole_still || !crate::drain::still_whole(verified, now_seen) {
+            // Placement may take it as before.
+            crate::pool::mark_draining(block, 0);
+            given_up += 1;
+            continue;
+        }
+        for (at, r, mut made) in guards {
+            // As in `compact_sparse` and `let_go_idle`: unstaged under the
+            // lock; retired once every lock of the block is let go.
+            crate::texture::unstage(at as This);
+            r.host.wanted.store(u32::MAX, Relaxed);
+            r.host.used.store(0, Relaxed);
+            if let Some((host, _)) = made.take() {
+                r.host.gone.store(true, Relaxed);
+                r.host.compacted.store(true, Relaxed);
+                KINDS[2].fetch_add(1, Relaxed);
+                KINDS[3].fetch_add(host.bytes, Relaxed);
+                went += 1;
+                bytes += host.bytes;
+                gone.push(host);
+            }
+        }
+        emptied += 1;
+    }
+    for host in gone {
+        crate::host::retire(host);
+    }
+    COMPACT_ROUNDS[1].fetch_add(emptied, Relaxed);
+    COMPACT_ROUNDS[2].fetch_add(given_up, Relaxed);
+    COMPACTED[1].fetch_add(went, Relaxed);
+    COMPACTED[2].fetch_add(bytes, Relaxed);
+    if went != 0 {
+        COMPACTED[0].fetch_add(1, Relaxed);
+    }
+    // As the per-texture line: blocks released to Windows since compaction
+    // first acted, once retirement has drained.
+    static BASE: std::sync::OnceLock<[u64; 2]> = std::sync::OnceLock::new();
+    let base = *BASE.get_or_init(crate::pool::textures_let_go);
+    let [blocks_now, bytes_now] = crate::pool::textures_let_go();
+    let rounds = COMPACT_ROUNDS[0].load(Relaxed);
+    if rounds.is_power_of_two() || rounds.is_multiple_of(12) {

The last successful drain can be invisible in the play log. The pool increments TEXTURES_LET_GO after retirement and the 2.5 s piece rest. If that release restores headroom, compact_plan stops scheduling rounds and this line never prints the new total. The throttle can also skip the successful round itself (e.g. round 13).

On e6cac2f6, a local synthetic D3D12 test on RTX 4060 confirmed the counter timing: with one texture still in the regular block, its count stayed flat. After the last texture went and the pool reclaimed, each of the regular and small texture blocks added 64 MiB. A separate 64 MiB staging release only increased the all-pools counter. The unchanged branch's pool and drain test selection also passed (38 passed, 3 ignored).

Could the existing periodic pool or memory line emit the texture-only cumulative count when it changes, even after compaction stops? This would let the #4310 retest tell whether the last drain returned a block. The count measures the pool dropping its block reference. The DXGI samples still measure the adapter's reported usage. The periodic reporting in #3766 is related.

**@⁠tyr0nsur** on GitHub · 2026-12-01 13:13 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#discussion_r4754614722) On `crates/victory-gpu/src/resource.rs` line 4474 (outdated): ```diff @@ -3997,6 +4013,493 @@ fn record_frame_ring(frame: u64, now_ms: u64, idle_ms: u64) -> Option<u64> { frame_at(&ring, now_ms.saturating_sub(idle_ms)) } +// --- Compaction of sparse texture blocks under the PC's commit --------------- +// +// On NVIDIA the card's memory the layer holds counts in the process's commit +// one to one (#4288), and a 64 MiB block of textures counts whole however +// little of it is taken. A run on an RTX 5070 (12 GB), 32 GB of RAM, a 20 GB +// page file, Series X 1440p with frame generation (2026-11-30): 47 GB +// committed, 1.5 GB of RAM free, 2.8 GB free in texture blocks, and then the +// device was removed. The texture line's cut (`commit_cut_tick`) stood still +// all the while, rightly: with that much free in blocks, letting textures go +// by age leaves holes and gives no commit back. +// +// What does give it back is a block emptied whole. So while the PC is short +// of commit and the blocks hold holes, the idle textures of the blocks that +// are mostly empty go (under a fill line, not sorted by it), a bounded amount a look: +// their blocks then empty and the pool lets them go. A texture let go is made +// and uploaded again at its next use, as after any sweep. + +/// Blocks under this many thousandths full are compacted. +#[cfg(windows)] +const COMPACT_SPARSE_PER_MILLE: u64 = 350; +/// The least idle time of a texture compaction lets go. +#[cfg(windows)] +const COMPACT_IDLE_MS: u64 = 3000; +/// The most compaction lets go at one look, and its time. +#[cfg(windows)] +const COMPACT_MOST: u64 = 384 << 20; +#[cfg(windows)] +const COMPACT_MOST_US: u128 = 3000; +/// Free bytes in texture blocks under which there is nothing to compact. +#[cfg(windows)] +const COMPACT_HOLES: u64 = 512 << 20; + +/// The PC's commit left under which compaction runs +/// (`VICTORY_COMPACT_COMMIT_FLOOR_MB`, 4096 by default, where the layer's +/// own pressure starts (`crate::residency`); `0`: only for the card). +#[cfg(windows)] +fn compact_commit_floor() -> u64 { + static FLOOR: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *FLOOR.get_or_init(|| { + std::env::var("VICTORY_COMPACT_COMMIT_FLOOR_MB") + .ok() + .and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(4096) + << 20 + }) +} + +/// Since the start: looks that compacted, textures let go, their bytes. +#[cfg(windows)] +static COMPACTED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// `VICTORY_COMPACT_SPARSE=0` turns compaction off. +#[cfg(windows)] +fn compact_on() -> bool { + crate::toggled!("VICTORY_COMPACT_SPARSE") +} + +/// The same while the card is over its budget. +#[cfg(windows)] +const COMPACT_SPARSE_PER_MILLE_CARD: u64 = 500; +/// The least time between two compactions. +#[cfg(windows)] +const COMPACT_EVERY_MS: u64 = 5000; + +/// The sparse blocks to empty now, or `None`: compaction off, too little free +/// in texture blocks, or neither the PC short of commit nor the card over its +/// budget. +/// +/// The card over its budget is the second reason (run of 2026-11-30, RTX 5070, +/// Series X 1440p, frame generation 2x, 32 minutes): 12.0 GB in use of a +/// budget of 10.7 from the tenth minute on, 1.8 GB of that free in texture +/// blocks, 41 "out of VRAM" warnings of frame generation, frames of 900 ms +/// and then the device removed. The queue's room takes the holes off the use, +/// so nothing made it let them go; the card pays for them all the same. Over +/// the budget the blocks under half full are compacted, a look in five +/// seconds at most. +#[cfg(windows)] +fn compact_plan(memory: Option<[u64; 4]>) -> Option<std::collections::HashSet<(usize, usize)>> { + use std::sync::atomic::Ordering::Relaxed; + if !compact_on() || !crate::pool::on() || crate::pool::texture_room() < COMPACT_HOLES { + return None; + } + let floor = compact_commit_floor(); + // The commit left of the moment, without what the page file may still + // grow by, as the texture line's floor counts it (`commit_floor`, #4288): + // a growing page file is what stalled 32 GB PCs (#3443), so compaction + // acts before it has to grow, not once it no longer can. + let short_of_commit = + floor != 0 && crate::residency::memory_status().is_some_and(|status| status.ullAvailPageFile < floor); + let card_over = memory.is_some_and(|[budget, used, ..]| used > budget); + if !short_of_commit && !card_over { + return None; + } + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let now = crate::host::now_ms(); + if now < LAST.load(Relaxed) + COMPACT_EVERY_MS { + return None; + } + LAST.store(now, Relaxed); + let per_mille = if card_over { COMPACT_SPARSE_PER_MILLE_CARD } else { COMPACT_SPARSE_PER_MILLE }; + let sparse = crate::pool::sparse_texture_blocks(per_mille); + if !sparse.is_empty() { + COMPACT_ASKED_AT.store(now, Relaxed); + } + (!sparse.is_empty()).then_some(sparse) +} + +/// Lets the idle textures of `sparse` blocks go ([`compact_plan`]), as the +/// sweep lets an idle texture go: held by its title texture alone, no list +/// and no slot on it. +#[cfg(windows)] +fn compact_sparse(all: &std::collections::BTreeSet<usize>, sparse: &std::collections::HashSet<(usize, usize)>) { + if compact_whole() { + compact_whole_blocks(all, sparse); + return; + } + use std::sync::atomic::Ordering::Relaxed; + const IDLE_FRAMES: u64 = 4; + let began = std::time::Instant::now(); + let (mut went, mut bytes, mut looked) = (0u64, 0u64, 0usize); + // The candidate blocks a texture actually went from. + let mut touched = std::collections::HashSet::new(); + // Where the last look stopped: a look bounded in time goes on from there, + // so the whole table is reached over a few looks (as the sweep's `FROM`). + static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let from = FROM.load(Relaxed); + let mut stopped_at = None; + for &at in all.range(from..).chain(all.range(..from)) { + if bytes >= COMPACT_MOST || (looked & 255) == 255 && began.elapsed().as_micros() >= COMPACT_MOST_US { + stopped_at = Some(at); + break; + } + looked += 1; + // SAFETY: a texture leaves the table before it is freed, under the + // table's lock, which the caller holds (`Drop for Resource`). + let r = unsafe { &*(at as *const Resource) }; + let used = r.host.used.load(Relaxed); + if used == 0 || !fills(&r.desc) || !crate::host::long_ago(used, COMPACT_IDLE_MS, IDLE_FRAMES) || crate::texture::host_wrote(at) { + continue; + } + let Ok(mut made) = r.host.made.try_lock() else { continue }; + let block = made.as_ref().and_then(|(host, _)| { + (crate::host::long_ago(r.host.used.load(Relaxed), COMPACT_IDLE_MS, IDLE_FRAMES) + && std::sync::Arc::strong_count(host) == 1 + && crate::host::references(&host.texture) == 1) + .then(|| crate::pool::block_of(&host.texture)) + .flatten() + .filter(|b| sparse.contains(b)) + }); + let Some(block) = block else { + continue; + }; + touched.insert(block); + // As in `let_go_idle`: under the lock, the next use must not find the + // staging state of the texture let go, and it stamps `used` anew. + crate::texture::unstage(at as This); + r.host.wanted.store(u32::MAX, Relaxed); + r.host.used.store(0, Relaxed); + let gone = made.take(); + drop(made); + if let Some((host, _)) = gone { + r.host.gone.store(true, Relaxed); + r.host.compacted.store(true, Relaxed); + KINDS[2].fetch_add(1, Relaxed); + KINDS[3].fetch_add(host.bytes, Relaxed); + went += 1; + bytes += host.bytes; + crate::host::retire(host); + } + } + FROM.store(stopped_at.unwrap_or(0), Relaxed); + // The texture blocks the pools had let go to Windows when compaction + // first acted: what they let go since is the memory actually returned + // (whatever let the last piece of a block go, compaction or the sweep; + // it comes once the textures' retirement has drained, so a later line + // shows what an earlier look gave back). + static BASE: std::sync::OnceLock<[u64; 2]> = std::sync::OnceLock::new(); + if went == 0 && BASE.get().is_none() { + return; + } + let base = *BASE.get_or_init(crate::pool::textures_let_go); + let [blocks_now, bytes_now] = crate::pool::textures_let_go(); + let looks = if went == 0 { COMPACTED[0].load(Relaxed) } else { COMPACTED[0].fetch_add(1, Relaxed) + 1 }; + COMPACTED[1].fetch_add(went, Relaxed); + COMPACTED[2].fetch_add(bytes, Relaxed); + if went != 0 && (looks.is_power_of_two() || looks % 30 == 0) { + tracing::info!( + "texture compaction (VICTORY_COMPACT_SPARSE; the PC short of commit or the card over its budget): {went} idle \ + textures ({} MB) let go from {} of {} candidate blocks (the scan stopped {}); since the start {} looks, {} \ + textures, {} MB; let go by compaction and made again since the start: {} textures ({} MB); texture blocks \ + released to Windows since the first look: {} ({} MB)", + bytes >> 20, + touched.len(), + sparse.len(), + if stopped_at.is_some() { "at its bound" } else { "after the whole table" }, + looks, + COMPACTED[1].load(Relaxed), + COMPACTED[2].load(Relaxed) >> 20, + COMPACT_COMEBACK[0].load(Relaxed), + COMPACT_COMEBACK[1].load(Relaxed) >> 20, + blocks_now - base[0], + (bytes_now - base[1]) >> 20, + ); + } +} + +/// `VICTORY_COMPACT_WHOLE=1`: compaction lets a sparse block's textures go +/// only when every one of them can, so the block empties whole +/// (`crate::drain`); off, they go one by one as before. +#[cfg(windows)] +fn compact_whole() -> bool { + crate::asked_for!("VICTORY_COMPACT_WHOLE") +} + +/// When [`compact_plan`] last asked for a compaction (ms). +#[cfg(windows)] +static COMPACT_ASKED_AT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether the texture pools keep few empty blocks (`crate::pool::room`) +/// because whole-block compaction asked to act within the last +/// [`COMPACT_SPARES_HOLD_MS`], so that what it empties goes back to Windows. +/// Below 85 % of the card's budget they would keep up to 64 otherwise. +/// `VICTORY_COMPACT_SPARES=0` leaves the spares as they are, to measure the +/// whole-block rule apart from this. +#[cfg(windows)] +pub(crate) fn compacting_whole() -> bool { + use std::sync::atomic::Ordering::Relaxed; + let at = COMPACT_ASKED_AT.load(Relaxed); + compact_whole() + && crate::toggled!("VICTORY_COMPACT_SPARES") + && at != 0 + && crate::host::now_ms().saturating_sub(at) <= COMPACT_SPARES_HOLD_MS +} + +/// How long the pools keep few spares after compaction last asked to act: +/// longer than a round's gap, so that a PC at the commit floor does not +/// switch between 2 and 64 spares (and blocks made ahead) every few seconds. +#[cfg(windows)] +const COMPACT_SPARES_HOLD_MS: u64 = 60_000; + +/// The most blocks one round empties. +#[cfg(windows)] +const COMPACT_WHOLE_BLOCKS: usize = 8; +/// A round whose last look is older than this is dropped (compaction stopped +/// being asked for): its tally would be stale. A round itself may take many +/// looks; it is not bounded in time. +#[cfg(windows)] +const COMPACT_ROUND_GAP_MS: u64 = 20_000; +/// How long a block being emptied is taken last by the pool's placement: +/// longer than a retirement and a piece's rest. +#[cfg(windows)] +const COMPACT_DRAIN_MS: u64 = 10_000; + +/// Since the start: textures compaction let go that were made again, and +/// their bytes (both modes): what letting them go cost in uploads. +#[cfg(windows)] +static COMPACT_COMEBACK: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// What looks have tallied since the round began: a round is one pass over +/// the whole table of textures, which a look bounded in time may not finish. +#[cfg(windows)] +struct Round { + /// Per candidate block: bytes (as cut from the block) of the members that + /// may go, and their addresses in the table. + may_go: std::collections::HashMap<(usize, usize), (u64, Vec<usize>)>, + /// Bytes of candidate blocks' members that may not go, by + /// [`crate::drain::Kept`]. + kept: [u64; 3], + /// Textures skipped because their lock was busy (their block, unknown + /// without the lock, then falls short and is not taken this round). + busy: u64, + began: u64, + last: u64, + looks: u64, + /// Time the looks of the round took (µs). + spent: u64, +} + +/// Since the start: rounds done, blocks emptied, blocks given up at the +/// check before letting go. +#[cfg(windows)] +static COMPACT_ROUNDS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Whether the texture at `at` may go now: filled from title memory, read +/// longer ago than the idle time, not written by the title, held by nothing +/// but its title texture. `used` is read again under `made`'s lock, which +/// `hosted_with` writes it under. +#[cfg(windows)] +fn compact_kept(at: usize, r: &Resource, host: &std::sync::Arc<HostTexture>) -> Option<crate::drain::Kept> { + use crate::drain::Kept; + use std::sync::atomic::Ordering::Relaxed; + const IDLE_FRAMES: u64 = 4; + let used = r.host.used.load(Relaxed); + if used == 0 || !crate::host::long_ago(used, COMPACT_IDLE_MS, IDLE_FRAMES) { + Some(Kept::Recent) + } else if crate::texture::host_wrote(at) { + Some(Kept::Written) + } else if std::sync::Arc::strong_count(host) != 1 || crate::host::references(&host.texture) != 1 { + Some(Kept::Referenced) + } else { + None + } +} + +/// [`compact_sparse`] with `VICTORY_COMPACT_WHOLE=1`: tallies the members of +/// `sparse` blocks over one pass of the table, then empties the blocks all of +/// whose members may go ([`crate::drain::whole_blocks`]), each member checked +/// again under its lock first. +#[cfg(windows)] +fn compact_whole_blocks(all: &std::collections::BTreeSet<usize>, sparse: &std::collections::HashSet<(usize, usize)>) { + use std::sync::atomic::Ordering::Relaxed; + static ROUND: std::sync::Mutex<Option<Round>> = std::sync::Mutex::new(None); + static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let now = crate::host::now_ms(); + let mut round = ROUND.lock().unwrap_or_else(|e| e.into_inner()); + if round.as_ref().is_some_and(|r| now.saturating_sub(r.last) > COMPACT_ROUND_GAP_MS) { + *round = None; + FROM.store(0, Relaxed); + } + let tally = round.get_or_insert_with(|| Round { + may_go: Default::default(), + kept: [0; 3], + busy: 0, + began: now, + last: now, + looks: 0, + spent: 0, + }); + + // Tally, bounded in time as the per-texture look is. No call into D3D12: + // the block of a texture is the one noted when it was made. + let began = std::time::Instant::now(); + let from = FROM.load(Relaxed); + let mut stopped_at = None; + for (looked, &at) in all.range(from..).enumerate() { + if (looked & 255) == 255 && began.elapsed().as_micros() >= COMPACT_MOST_US { + stopped_at = Some(at); + break; + } + // SAFETY: as in `compact_sparse`: the caller holds the table's lock. + let r = unsafe { &*(at as *const Resource) }; + if r.host.used.load(Relaxed) == 0 || !fills(&r.desc) { + continue; + } + let Ok(made) = r.host.made.try_lock() else { + tally.busy += 1; + continue; + }; + let Some((host, _)) = made.as_ref() else { continue }; + let Some((block, len)) = host.piece.filter(|(b, _)| sparse.contains(b)) else { + continue; + }; + match compact_kept(at, r, host) { + Some(why) => tally.kept[why.index()] += len, + None => { + let entry = tally.may_go.entry(block).or_default(); + entry.0 += len; + entry.1.push(at); + } + } + } + tally.looks += 1; + tally.last = now; + tally.spent += began.elapsed().as_micros() as u64; + FROM.store(stopped_at.unwrap_or(0), Relaxed); + if stopped_at.is_some() { + return; + } + + // The round is whole: choose, check again, let go. + let Some(done) = round.take() else { return }; + drop(round); + COMPACT_ROUNDS[0].fetch_add(1, Relaxed); + // Blocks no longer sparse are left out here, as are blocks that became + // sparse during the round (their tally then falls short). + let states = crate::pool::texture_block_states(sparse); + let may_go: std::collections::HashMap<(usize, usize), u64> = done.may_go.iter().map(|(&b, &(bytes, _))| (b, bytes)).collect(); + // Every block whose members may all go, emptiest first; the caps count + // only the blocks actually emptied, so one given up makes room for the next. + let whole = crate::drain::whole_blocks(&states, &may_go, u64::MAX, usize::MAX); + let (mut went, mut bytes, mut emptied, mut given_up) = (0u64, 0u64, 0u64, 0u64); + let mut gone = Vec::new(); + for block in whole.iter().copied() { + if emptied as usize >= COMPACT_WHOLE_BLOCKS || bytes >= COMPACT_MOST { + break; + } + let Some((_, members)) = done.may_go.get(&block) else { continue }; + // Placement takes the block last from here on, so the check below is + // not undone by a new piece cut from it while its members go. + crate::pool::mark_draining(block, now + COMPACT_DRAIN_MS); + let mut guards = Vec::with_capacity(members.len()); + let mut verified = 0u64; + let mut whole_still = true; + for &at in members { + // SAFETY: in the table (checked first), under its lock (the caller's). + let Some(r) = all.contains(&at).then(|| unsafe { &*(at as *const Resource) }) else { + whole_still = false; + break; + }; + if !fills(&r.desc) { + whole_still = false; + break; + } + let Ok(made) = r.host.made.try_lock() else { + whole_still = false; + break; + }; + let piece = made.as_ref().and_then(|(host, _)| compact_kept(at, r, host).is_none().then_some(host.piece).flatten()); + match piece { + Some((b, len)) if b == block => verified += len, + _ => { + whole_still = false; + break; + } + } + guards.push((at, r, made)); + } + let now_seen = crate::pool::texture_block_state(block).unwrap_or_default(); + if !whole_still || !crate::drain::still_whole(verified, now_seen) { + // Placement may take it as before. + crate::pool::mark_draining(block, 0); + given_up += 1; + continue; + } + for (at, r, mut made) in guards { + // As in `compact_sparse` and `let_go_idle`: unstaged under the + // lock; retired once every lock of the block is let go. + crate::texture::unstage(at as This); + r.host.wanted.store(u32::MAX, Relaxed); + r.host.used.store(0, Relaxed); + if let Some((host, _)) = made.take() { + r.host.gone.store(true, Relaxed); + r.host.compacted.store(true, Relaxed); + KINDS[2].fetch_add(1, Relaxed); + KINDS[3].fetch_add(host.bytes, Relaxed); + went += 1; + bytes += host.bytes; + gone.push(host); + } + } + emptied += 1; + } + for host in gone { + crate::host::retire(host); + } + COMPACT_ROUNDS[1].fetch_add(emptied, Relaxed); + COMPACT_ROUNDS[2].fetch_add(given_up, Relaxed); + COMPACTED[1].fetch_add(went, Relaxed); + COMPACTED[2].fetch_add(bytes, Relaxed); + if went != 0 { + COMPACTED[0].fetch_add(1, Relaxed); + } + // As the per-texture line: blocks released to Windows since compaction + // first acted, once retirement has drained. + static BASE: std::sync::OnceLock<[u64; 2]> = std::sync::OnceLock::new(); + let base = *BASE.get_or_init(crate::pool::textures_let_go); + let [blocks_now, bytes_now] = crate::pool::textures_let_go(); + let rounds = COMPACT_ROUNDS[0].load(Relaxed); + if rounds.is_power_of_two() || rounds.is_multiple_of(12) { ``` The last successful drain can be invisible in the play log. The pool increments `TEXTURES_LET_GO` after retirement and the 2.5 s piece rest. If that release restores headroom, `compact_plan` stops scheduling rounds and this line never prints the new total. The throttle can also skip the successful round itself (e.g. round 13). On `e6cac2f6`, a local synthetic D3D12 test on RTX 4060 confirmed the counter timing: with one texture still in the regular block, its count stayed flat. After the last texture went and the pool reclaimed, each of the regular and small texture blocks added 64 MiB. A separate 64 MiB staging release only increased the all-pools counter. The unchanged branch's pool and drain test selection also passed (38 passed, 3 ignored). Could the existing periodic pool or memory line emit the texture-only cumulative count when it changes, even after compaction stops? This would let the #4310 retest tell whether the last drain returned a block. The count measures the pool dropping its block reference. The DXGI samples still measure the adapter's reported usage. The periodic reporting in #3766 is related.
Author
Owner

@⁠mcozcan on GitHub · 2026-12-01 13:17 UTC · original
On crates/victory-gpu/src/resource.rs line 4474 (outdated):

@@ -3997,6 +4013,493 @@ fn record_frame_ring(frame: u64, now_ms: u64, idle_ms: u64) -> Option<u64> {
     frame_at(&ring, now_ms.saturating_sub(idle_ms))
 }
 
+// --- Compaction of sparse texture blocks under the PC's commit ---------------
+//
+// On NVIDIA the card's memory the layer holds counts in the process's commit
+// one to one (#4288), and a 64 MiB block of textures counts whole however
+// little of it is taken. A run on an RTX 5070 (12 GB), 32 GB of RAM, a 20 GB
+// page file, Series X 1440p with frame generation (2026-11-30): 47 GB
+// committed, 1.5 GB of RAM free, 2.8 GB free in texture blocks, and then the
+// device was removed. The texture line's cut (`commit_cut_tick`) stood still
+// all the while, rightly: with that much free in blocks, letting textures go
+// by age leaves holes and gives no commit back.
+//
+// What does give it back is a block emptied whole. So while the PC is short
+// of commit and the blocks hold holes, the idle textures of the blocks that
+// are mostly empty go (under a fill line, not sorted by it), a bounded amount a look:
+// their blocks then empty and the pool lets them go. A texture let go is made
+// and uploaded again at its next use, as after any sweep.
+
+/// Blocks under this many thousandths full are compacted.
+#[cfg(windows)]
+const COMPACT_SPARSE_PER_MILLE: u64 = 350;
+/// The least idle time of a texture compaction lets go.
+#[cfg(windows)]
+const COMPACT_IDLE_MS: u64 = 3000;
+/// The most compaction lets go at one look, and its time.
+#[cfg(windows)]
+const COMPACT_MOST: u64 = 384 << 20;
+#[cfg(windows)]
+const COMPACT_MOST_US: u128 = 3000;
+/// Free bytes in texture blocks under which there is nothing to compact.
+#[cfg(windows)]
+const COMPACT_HOLES: u64 = 512 << 20;
+
+/// The PC's commit left under which compaction runs
+/// (`VICTORY_COMPACT_COMMIT_FLOOR_MB`, 4096 by default, where the layer's
+/// own pressure starts (`crate::residency`); `0`: only for the card).
+#[cfg(windows)]
+fn compact_commit_floor() -> u64 {
+    static FLOOR: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
+    *FLOOR.get_or_init(|| {
+        std::env::var("VICTORY_COMPACT_COMMIT_FLOOR_MB")
+            .ok()
+            .and_then(|v| v.trim().parse::<u64>().ok())
+            .unwrap_or(4096)
+            << 20
+    })
+}
+
+/// Since the start: looks that compacted, textures let go, their bytes.
+#[cfg(windows)]
+static COMPACTED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
+
+/// `VICTORY_COMPACT_SPARSE=0` turns compaction off.
+#[cfg(windows)]
+fn compact_on() -> bool {
+    crate::toggled!("VICTORY_COMPACT_SPARSE")
+}
+
+/// The same while the card is over its budget.
+#[cfg(windows)]
+const COMPACT_SPARSE_PER_MILLE_CARD: u64 = 500;
+/// The least time between two compactions.
+#[cfg(windows)]
+const COMPACT_EVERY_MS: u64 = 5000;
+
+/// The sparse blocks to empty now, or `None`: compaction off, too little free
+/// in texture blocks, or neither the PC short of commit nor the card over its
+/// budget.
+///
+/// The card over its budget is the second reason (run of 2026-11-30, RTX 5070,
+/// Series X 1440p, frame generation 2x, 32 minutes): 12.0 GB in use of a
+/// budget of 10.7 from the tenth minute on, 1.8 GB of that free in texture
+/// blocks, 41 "out of VRAM" warnings of frame generation, frames of 900 ms
+/// and then the device removed. The queue's room takes the holes off the use,
+/// so nothing made it let them go; the card pays for them all the same. Over
+/// the budget the blocks under half full are compacted, a look in five
+/// seconds at most.
+#[cfg(windows)]
+fn compact_plan(memory: Option<[u64; 4]>) -> Option<std::collections::HashSet<(usize, usize)>> {
+    use std::sync::atomic::Ordering::Relaxed;
+    if !compact_on() || !crate::pool::on() || crate::pool::texture_room() < COMPACT_HOLES {
+        return None;
+    }
+    let floor = compact_commit_floor();
+    // The commit left of the moment, without what the page file may still
+    // grow by, as the texture line's floor counts it (`commit_floor`, #4288):
+    // a growing page file is what stalled 32 GB PCs (#3443), so compaction
+    // acts before it has to grow, not once it no longer can.
+    let short_of_commit =
+        floor != 0 && crate::residency::memory_status().is_some_and(|status| status.ullAvailPageFile < floor);
+    let card_over = memory.is_some_and(|[budget, used, ..]| used > budget);
+    if !short_of_commit && !card_over {
+        return None;
+    }
+    static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+    let now = crate::host::now_ms();
+    if now < LAST.load(Relaxed) + COMPACT_EVERY_MS {
+        return None;
+    }
+    LAST.store(now, Relaxed);
+    let per_mille = if card_over { COMPACT_SPARSE_PER_MILLE_CARD } else { COMPACT_SPARSE_PER_MILLE };
+    let sparse = crate::pool::sparse_texture_blocks(per_mille);
+    if !sparse.is_empty() {
+        COMPACT_ASKED_AT.store(now, Relaxed);
+    }
+    (!sparse.is_empty()).then_some(sparse)
+}
+
+/// Lets the idle textures of `sparse` blocks go ([`compact_plan`]), as the
+/// sweep lets an idle texture go: held by its title texture alone, no list
+/// and no slot on it.
+#[cfg(windows)]
+fn compact_sparse(all: &std::collections::BTreeSet<usize>, sparse: &std::collections::HashSet<(usize, usize)>) {
+    if compact_whole() {
+        compact_whole_blocks(all, sparse);
+        return;
+    }
+    use std::sync::atomic::Ordering::Relaxed;
+    const IDLE_FRAMES: u64 = 4;
+    let began = std::time::Instant::now();
+    let (mut went, mut bytes, mut looked) = (0u64, 0u64, 0usize);
+    // The candidate blocks a texture actually went from.
+    let mut touched = std::collections::HashSet::new();
+    // Where the last look stopped: a look bounded in time goes on from there,
+    // so the whole table is reached over a few looks (as the sweep's `FROM`).
+    static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+    let from = FROM.load(Relaxed);
+    let mut stopped_at = None;
+    for &at in all.range(from..).chain(all.range(..from)) {
+        if bytes >= COMPACT_MOST || (looked & 255) == 255 && began.elapsed().as_micros() >= COMPACT_MOST_US {
+            stopped_at = Some(at);
+            break;
+        }
+        looked += 1;
+        // SAFETY: a texture leaves the table before it is freed, under the
+        // table's lock, which the caller holds (`Drop for Resource`).
+        let r = unsafe { &*(at as *const Resource) };
+        let used = r.host.used.load(Relaxed);
+        if used == 0 || !fills(&r.desc) || !crate::host::long_ago(used, COMPACT_IDLE_MS, IDLE_FRAMES) || crate::texture::host_wrote(at) {
+            continue;
+        }
+        let Ok(mut made) = r.host.made.try_lock() else { continue };
+        let block = made.as_ref().and_then(|(host, _)| {
+            (crate::host::long_ago(r.host.used.load(Relaxed), COMPACT_IDLE_MS, IDLE_FRAMES)
+                && std::sync::Arc::strong_count(host) == 1
+                && crate::host::references(&host.texture) == 1)
+                .then(|| crate::pool::block_of(&host.texture))
+                .flatten()
+                .filter(|b| sparse.contains(b))
+        });
+        let Some(block) = block else {
+            continue;
+        };
+        touched.insert(block);
+        // As in `let_go_idle`: under the lock, the next use must not find the
+        // staging state of the texture let go, and it stamps `used` anew.
+        crate::texture::unstage(at as This);
+        r.host.wanted.store(u32::MAX, Relaxed);
+        r.host.used.store(0, Relaxed);
+        let gone = made.take();
+        drop(made);
+        if let Some((host, _)) = gone {
+            r.host.gone.store(true, Relaxed);
+            r.host.compacted.store(true, Relaxed);
+            KINDS[2].fetch_add(1, Relaxed);
+            KINDS[3].fetch_add(host.bytes, Relaxed);
+            went += 1;
+            bytes += host.bytes;
+            crate::host::retire(host);
+        }
+    }
+    FROM.store(stopped_at.unwrap_or(0), Relaxed);
+    // The texture blocks the pools had let go to Windows when compaction
+    // first acted: what they let go since is the memory actually returned
+    // (whatever let the last piece of a block go, compaction or the sweep;
+    // it comes once the textures' retirement has drained, so a later line
+    // shows what an earlier look gave back).
+    static BASE: std::sync::OnceLock<[u64; 2]> = std::sync::OnceLock::new();
+    if went == 0 && BASE.get().is_none() {
+        return;
+    }
+    let base = *BASE.get_or_init(crate::pool::textures_let_go);
+    let [blocks_now, bytes_now] = crate::pool::textures_let_go();
+    let looks = if went == 0 { COMPACTED[0].load(Relaxed) } else { COMPACTED[0].fetch_add(1, Relaxed) + 1 };
+    COMPACTED[1].fetch_add(went, Relaxed);
+    COMPACTED[2].fetch_add(bytes, Relaxed);
+    if went != 0 && (looks.is_power_of_two() || looks % 30 == 0) {
+        tracing::info!(
+            "texture compaction (VICTORY_COMPACT_SPARSE; the PC short of commit or the card over its budget): {went} idle \
+             textures ({} MB) let go from {} of {} candidate blocks (the scan stopped {}); since the start {} looks, {} \
+             textures, {} MB; let go by compaction and made again since the start: {} textures ({} MB); texture blocks \
+             released to Windows since the first look: {} ({} MB)",
+            bytes >> 20,
+            touched.len(),
+            sparse.len(),
+            if stopped_at.is_some() { "at its bound" } else { "after the whole table" },
+            looks,
+            COMPACTED[1].load(Relaxed),
+            COMPACTED[2].load(Relaxed) >> 20,
+            COMPACT_COMEBACK[0].load(Relaxed),
+            COMPACT_COMEBACK[1].load(Relaxed) >> 20,
+            blocks_now - base[0],
+            (bytes_now - base[1]) >> 20,
+        );
+    }
+}
+
+/// `VICTORY_COMPACT_WHOLE=1`: compaction lets a sparse block's textures go
+/// only when every one of them can, so the block empties whole
+/// (`crate::drain`); off, they go one by one as before.
+#[cfg(windows)]
+fn compact_whole() -> bool {
+    crate::asked_for!("VICTORY_COMPACT_WHOLE")
+}
+
+/// When [`compact_plan`] last asked for a compaction (ms).
+#[cfg(windows)]
+static COMPACT_ASKED_AT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// Whether the texture pools keep few empty blocks (`crate::pool::room`)
+/// because whole-block compaction asked to act within the last
+/// [`COMPACT_SPARES_HOLD_MS`], so that what it empties goes back to Windows.
+/// Below 85 % of the card's budget they would keep up to 64 otherwise.
+/// `VICTORY_COMPACT_SPARES=0` leaves the spares as they are, to measure the
+/// whole-block rule apart from this.
+#[cfg(windows)]
+pub(crate) fn compacting_whole() -> bool {
+    use std::sync::atomic::Ordering::Relaxed;
+    let at = COMPACT_ASKED_AT.load(Relaxed);
+    compact_whole()
+        && crate::toggled!("VICTORY_COMPACT_SPARES")
+        && at != 0
+        && crate::host::now_ms().saturating_sub(at) <= COMPACT_SPARES_HOLD_MS
+}
+
+/// How long the pools keep few spares after compaction last asked to act:
+/// longer than a round's gap, so that a PC at the commit floor does not
+/// switch between 2 and 64 spares (and blocks made ahead) every few seconds.
+#[cfg(windows)]
+const COMPACT_SPARES_HOLD_MS: u64 = 60_000;
+
+/// The most blocks one round empties.
+#[cfg(windows)]
+const COMPACT_WHOLE_BLOCKS: usize = 8;
+/// A round whose last look is older than this is dropped (compaction stopped
+/// being asked for): its tally would be stale. A round itself may take many
+/// looks; it is not bounded in time.
+#[cfg(windows)]
+const COMPACT_ROUND_GAP_MS: u64 = 20_000;
+/// How long a block being emptied is taken last by the pool's placement:
+/// longer than a retirement and a piece's rest.
+#[cfg(windows)]
+const COMPACT_DRAIN_MS: u64 = 10_000;
+
+/// Since the start: textures compaction let go that were made again, and
+/// their bytes (both modes): what letting them go cost in uploads.
+#[cfg(windows)]
+static COMPACT_COMEBACK: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
+
+/// What looks have tallied since the round began: a round is one pass over
+/// the whole table of textures, which a look bounded in time may not finish.
+#[cfg(windows)]
+struct Round {
+    /// Per candidate block: bytes (as cut from the block) of the members that
+    /// may go, and their addresses in the table.
+    may_go: std::collections::HashMap<(usize, usize), (u64, Vec<usize>)>,
+    /// Bytes of candidate blocks' members that may not go, by
+    /// [`crate::drain::Kept`].
+    kept: [u64; 3],
+    /// Textures skipped because their lock was busy (their block, unknown
+    /// without the lock, then falls short and is not taken this round).
+    busy: u64,
+    began: u64,
+    last: u64,
+    looks: u64,
+    /// Time the looks of the round took (µs).
+    spent: u64,
+}
+
+/// Since the start: rounds done, blocks emptied, blocks given up at the
+/// check before letting go.
+#[cfg(windows)]
+static COMPACT_ROUNDS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
+
+/// Whether the texture at `at` may go now: filled from title memory, read
+/// longer ago than the idle time, not written by the title, held by nothing
+/// but its title texture. `used` is read again under `made`'s lock, which
+/// `hosted_with` writes it under.
+#[cfg(windows)]
+fn compact_kept(at: usize, r: &Resource, host: &std::sync::Arc<HostTexture>) -> Option<crate::drain::Kept> {
+    use crate::drain::Kept;
+    use std::sync::atomic::Ordering::Relaxed;
+    const IDLE_FRAMES: u64 = 4;
+    let used = r.host.used.load(Relaxed);
+    if used == 0 || !crate::host::long_ago(used, COMPACT_IDLE_MS, IDLE_FRAMES) {
+        Some(Kept::Recent)
+    } else if crate::texture::host_wrote(at) {
+        Some(Kept::Written)
+    } else if std::sync::Arc::strong_count(host) != 1 || crate::host::references(&host.texture) != 1 {
+        Some(Kept::Referenced)
+    } else {
+        None
+    }
+}
+
+/// [`compact_sparse`] with `VICTORY_COMPACT_WHOLE=1`: tallies the members of
+/// `sparse` blocks over one pass of the table, then empties the blocks all of
+/// whose members may go ([`crate::drain::whole_blocks`]), each member checked
+/// again under its lock first.
+#[cfg(windows)]
+fn compact_whole_blocks(all: &std::collections::BTreeSet<usize>, sparse: &std::collections::HashSet<(usize, usize)>) {
+    use std::sync::atomic::Ordering::Relaxed;
+    static ROUND: std::sync::Mutex<Option<Round>> = std::sync::Mutex::new(None);
+    static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+    let now = crate::host::now_ms();
+    let mut round = ROUND.lock().unwrap_or_else(|e| e.into_inner());
+    if round.as_ref().is_some_and(|r| now.saturating_sub(r.last) > COMPACT_ROUND_GAP_MS) {
+        *round = None;
+        FROM.store(0, Relaxed);
+    }
+    let tally = round.get_or_insert_with(|| Round {
+        may_go: Default::default(),
+        kept: [0; 3],
+        busy: 0,
+        began: now,
+        last: now,
+        looks: 0,
+        spent: 0,
+    });
+
+    // Tally, bounded in time as the per-texture look is. No call into D3D12:
+    // the block of a texture is the one noted when it was made.
+    let began = std::time::Instant::now();
+    let from = FROM.load(Relaxed);
+    let mut stopped_at = None;
+    for (looked, &at) in all.range(from..).enumerate() {
+        if (looked & 255) == 255 && began.elapsed().as_micros() >= COMPACT_MOST_US {
+            stopped_at = Some(at);
+            break;
+        }
+        // SAFETY: as in `compact_sparse`: the caller holds the table's lock.
+        let r = unsafe { &*(at as *const Resource) };
+        if r.host.used.load(Relaxed) == 0 || !fills(&r.desc) {
+            continue;
+        }
+        let Ok(made) = r.host.made.try_lock() else {
+            tally.busy += 1;
+            continue;
+        };
+        let Some((host, _)) = made.as_ref() else { continue };
+        let Some((block, len)) = host.piece.filter(|(b, _)| sparse.contains(b)) else {
+            continue;
+        };
+        match compact_kept(at, r, host) {
+            Some(why) => tally.kept[why.index()] += len,
+            None => {
+                let entry = tally.may_go.entry(block).or_default();
+                entry.0 += len;
+                entry.1.push(at);
+            }
+        }
+    }
+    tally.looks += 1;
+    tally.last = now;
+    tally.spent += began.elapsed().as_micros() as u64;
+    FROM.store(stopped_at.unwrap_or(0), Relaxed);
+    if stopped_at.is_some() {
+        return;
+    }
+
+    // The round is whole: choose, check again, let go.
+    let Some(done) = round.take() else { return };
+    drop(round);
+    COMPACT_ROUNDS[0].fetch_add(1, Relaxed);
+    // Blocks no longer sparse are left out here, as are blocks that became
+    // sparse during the round (their tally then falls short).
+    let states = crate::pool::texture_block_states(sparse);
+    let may_go: std::collections::HashMap<(usize, usize), u64> = done.may_go.iter().map(|(&b, &(bytes, _))| (b, bytes)).collect();
+    // Every block whose members may all go, emptiest first; the caps count
+    // only the blocks actually emptied, so one given up makes room for the next.
+    let whole = crate::drain::whole_blocks(&states, &may_go, u64::MAX, usize::MAX);
+    let (mut went, mut bytes, mut emptied, mut given_up) = (0u64, 0u64, 0u64, 0u64);
+    let mut gone = Vec::new();
+    for block in whole.iter().copied() {
+        if emptied as usize >= COMPACT_WHOLE_BLOCKS || bytes >= COMPACT_MOST {
+            break;
+        }
+        let Some((_, members)) = done.may_go.get(&block) else { continue };
+        // Placement takes the block last from here on, so the check below is
+        // not undone by a new piece cut from it while its members go.
+        crate::pool::mark_draining(block, now + COMPACT_DRAIN_MS);
+        let mut guards = Vec::with_capacity(members.len());
+        let mut verified = 0u64;
+        let mut whole_still = true;
+        for &at in members {
+            // SAFETY: in the table (checked first), under its lock (the caller's).
+            let Some(r) = all.contains(&at).then(|| unsafe { &*(at as *const Resource) }) else {
+                whole_still = false;
+                break;
+            };
+            if !fills(&r.desc) {
+                whole_still = false;
+                break;
+            }
+            let Ok(made) = r.host.made.try_lock() else {
+                whole_still = false;
+                break;
+            };
+            let piece = made.as_ref().and_then(|(host, _)| compact_kept(at, r, host).is_none().then_some(host.piece).flatten());
+            match piece {
+                Some((b, len)) if b == block => verified += len,
+                _ => {
+                    whole_still = false;
+                    break;
+                }
+            }
+            guards.push((at, r, made));
+        }
+        let now_seen = crate::pool::texture_block_state(block).unwrap_or_default();
+        if !whole_still || !crate::drain::still_whole(verified, now_seen) {
+            // Placement may take it as before.
+            crate::pool::mark_draining(block, 0);
+            given_up += 1;
+            continue;
+        }
+        for (at, r, mut made) in guards {
+            // As in `compact_sparse` and `let_go_idle`: unstaged under the
+            // lock; retired once every lock of the block is let go.
+            crate::texture::unstage(at as This);
+            r.host.wanted.store(u32::MAX, Relaxed);
+            r.host.used.store(0, Relaxed);
+            if let Some((host, _)) = made.take() {
+                r.host.gone.store(true, Relaxed);
+                r.host.compacted.store(true, Relaxed);
+                KINDS[2].fetch_add(1, Relaxed);
+                KINDS[3].fetch_add(host.bytes, Relaxed);
+                went += 1;
+                bytes += host.bytes;
+                gone.push(host);
+            }
+        }
+        emptied += 1;
+    }
+    for host in gone {
+        crate::host::retire(host);
+    }
+    COMPACT_ROUNDS[1].fetch_add(emptied, Relaxed);
+    COMPACT_ROUNDS[2].fetch_add(given_up, Relaxed);
+    COMPACTED[1].fetch_add(went, Relaxed);
+    COMPACTED[2].fetch_add(bytes, Relaxed);
+    if went != 0 {
+        COMPACTED[0].fetch_add(1, Relaxed);
+    }
+    // As the per-texture line: blocks released to Windows since compaction
+    // first acted, once retirement has drained.
+    static BASE: std::sync::OnceLock<[u64; 2]> = std::sync::OnceLock::new();
+    let base = *BASE.get_or_init(crate::pool::textures_let_go);
+    let [blocks_now, bytes_now] = crate::pool::textures_let_go();
+    let rounds = COMPACT_ROUNDS[0].load(Relaxed);
+    if rounds.is_power_of_two() || rounds.is_multiple_of(12) {

Thanks, and for checking the counter's timing on the card. Done in b697bcba:

  • The frame-rate lines now carry texture compaction: texture blocks released to Windows since compaction first acted: N (MB ...) whenever the count changes, once compaction has acted at least once. It is printed whether or not compaction still asks to look, so a release that lands after the last round, and gives the room back that stops further rounds, still shows. It sits next to the slot eviction line (resource::compaction_released_line, called from the same place as slot_evict_line).
  • The two compaction lines used separate starting counts. Both now use one (COMPACT_BASE), so all three lines count from the same first look.
  • A whole-block round that emptied a block is always logged. Only the rounds that emptied nothing are thinned out, so round 13 is no longer skipped.

As you say, it counts both texture pools and the sweep's releases. The line says it is an upper bound on compaction's share, and it measures the pool letting its block go, not what DXGI reports. Not built on Windows or run in the game yet. For the #4310 retest, this line, the memory now: lines and the DXGI samples over the same minutes should show whether the last drain returned a block.

**@⁠mcozcan** on GitHub · 2026-12-01 13:17 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#discussion_r4754663031) On `crates/victory-gpu/src/resource.rs` line 4474 (outdated): ```diff @@ -3997,6 +4013,493 @@ fn record_frame_ring(frame: u64, now_ms: u64, idle_ms: u64) -> Option<u64> { frame_at(&ring, now_ms.saturating_sub(idle_ms)) } +// --- Compaction of sparse texture blocks under the PC's commit --------------- +// +// On NVIDIA the card's memory the layer holds counts in the process's commit +// one to one (#4288), and a 64 MiB block of textures counts whole however +// little of it is taken. A run on an RTX 5070 (12 GB), 32 GB of RAM, a 20 GB +// page file, Series X 1440p with frame generation (2026-11-30): 47 GB +// committed, 1.5 GB of RAM free, 2.8 GB free in texture blocks, and then the +// device was removed. The texture line's cut (`commit_cut_tick`) stood still +// all the while, rightly: with that much free in blocks, letting textures go +// by age leaves holes and gives no commit back. +// +// What does give it back is a block emptied whole. So while the PC is short +// of commit and the blocks hold holes, the idle textures of the blocks that +// are mostly empty go (under a fill line, not sorted by it), a bounded amount a look: +// their blocks then empty and the pool lets them go. A texture let go is made +// and uploaded again at its next use, as after any sweep. + +/// Blocks under this many thousandths full are compacted. +#[cfg(windows)] +const COMPACT_SPARSE_PER_MILLE: u64 = 350; +/// The least idle time of a texture compaction lets go. +#[cfg(windows)] +const COMPACT_IDLE_MS: u64 = 3000; +/// The most compaction lets go at one look, and its time. +#[cfg(windows)] +const COMPACT_MOST: u64 = 384 << 20; +#[cfg(windows)] +const COMPACT_MOST_US: u128 = 3000; +/// Free bytes in texture blocks under which there is nothing to compact. +#[cfg(windows)] +const COMPACT_HOLES: u64 = 512 << 20; + +/// The PC's commit left under which compaction runs +/// (`VICTORY_COMPACT_COMMIT_FLOOR_MB`, 4096 by default, where the layer's +/// own pressure starts (`crate::residency`); `0`: only for the card). +#[cfg(windows)] +fn compact_commit_floor() -> u64 { + static FLOOR: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *FLOOR.get_or_init(|| { + std::env::var("VICTORY_COMPACT_COMMIT_FLOOR_MB") + .ok() + .and_then(|v| v.trim().parse::<u64>().ok()) + .unwrap_or(4096) + << 20 + }) +} + +/// Since the start: looks that compacted, textures let go, their bytes. +#[cfg(windows)] +static COMPACTED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// `VICTORY_COMPACT_SPARSE=0` turns compaction off. +#[cfg(windows)] +fn compact_on() -> bool { + crate::toggled!("VICTORY_COMPACT_SPARSE") +} + +/// The same while the card is over its budget. +#[cfg(windows)] +const COMPACT_SPARSE_PER_MILLE_CARD: u64 = 500; +/// The least time between two compactions. +#[cfg(windows)] +const COMPACT_EVERY_MS: u64 = 5000; + +/// The sparse blocks to empty now, or `None`: compaction off, too little free +/// in texture blocks, or neither the PC short of commit nor the card over its +/// budget. +/// +/// The card over its budget is the second reason (run of 2026-11-30, RTX 5070, +/// Series X 1440p, frame generation 2x, 32 minutes): 12.0 GB in use of a +/// budget of 10.7 from the tenth minute on, 1.8 GB of that free in texture +/// blocks, 41 "out of VRAM" warnings of frame generation, frames of 900 ms +/// and then the device removed. The queue's room takes the holes off the use, +/// so nothing made it let them go; the card pays for them all the same. Over +/// the budget the blocks under half full are compacted, a look in five +/// seconds at most. +#[cfg(windows)] +fn compact_plan(memory: Option<[u64; 4]>) -> Option<std::collections::HashSet<(usize, usize)>> { + use std::sync::atomic::Ordering::Relaxed; + if !compact_on() || !crate::pool::on() || crate::pool::texture_room() < COMPACT_HOLES { + return None; + } + let floor = compact_commit_floor(); + // The commit left of the moment, without what the page file may still + // grow by, as the texture line's floor counts it (`commit_floor`, #4288): + // a growing page file is what stalled 32 GB PCs (#3443), so compaction + // acts before it has to grow, not once it no longer can. + let short_of_commit = + floor != 0 && crate::residency::memory_status().is_some_and(|status| status.ullAvailPageFile < floor); + let card_over = memory.is_some_and(|[budget, used, ..]| used > budget); + if !short_of_commit && !card_over { + return None; + } + static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let now = crate::host::now_ms(); + if now < LAST.load(Relaxed) + COMPACT_EVERY_MS { + return None; + } + LAST.store(now, Relaxed); + let per_mille = if card_over { COMPACT_SPARSE_PER_MILLE_CARD } else { COMPACT_SPARSE_PER_MILLE }; + let sparse = crate::pool::sparse_texture_blocks(per_mille); + if !sparse.is_empty() { + COMPACT_ASKED_AT.store(now, Relaxed); + } + (!sparse.is_empty()).then_some(sparse) +} + +/// Lets the idle textures of `sparse` blocks go ([`compact_plan`]), as the +/// sweep lets an idle texture go: held by its title texture alone, no list +/// and no slot on it. +#[cfg(windows)] +fn compact_sparse(all: &std::collections::BTreeSet<usize>, sparse: &std::collections::HashSet<(usize, usize)>) { + if compact_whole() { + compact_whole_blocks(all, sparse); + return; + } + use std::sync::atomic::Ordering::Relaxed; + const IDLE_FRAMES: u64 = 4; + let began = std::time::Instant::now(); + let (mut went, mut bytes, mut looked) = (0u64, 0u64, 0usize); + // The candidate blocks a texture actually went from. + let mut touched = std::collections::HashSet::new(); + // Where the last look stopped: a look bounded in time goes on from there, + // so the whole table is reached over a few looks (as the sweep's `FROM`). + static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let from = FROM.load(Relaxed); + let mut stopped_at = None; + for &at in all.range(from..).chain(all.range(..from)) { + if bytes >= COMPACT_MOST || (looked & 255) == 255 && began.elapsed().as_micros() >= COMPACT_MOST_US { + stopped_at = Some(at); + break; + } + looked += 1; + // SAFETY: a texture leaves the table before it is freed, under the + // table's lock, which the caller holds (`Drop for Resource`). + let r = unsafe { &*(at as *const Resource) }; + let used = r.host.used.load(Relaxed); + if used == 0 || !fills(&r.desc) || !crate::host::long_ago(used, COMPACT_IDLE_MS, IDLE_FRAMES) || crate::texture::host_wrote(at) { + continue; + } + let Ok(mut made) = r.host.made.try_lock() else { continue }; + let block = made.as_ref().and_then(|(host, _)| { + (crate::host::long_ago(r.host.used.load(Relaxed), COMPACT_IDLE_MS, IDLE_FRAMES) + && std::sync::Arc::strong_count(host) == 1 + && crate::host::references(&host.texture) == 1) + .then(|| crate::pool::block_of(&host.texture)) + .flatten() + .filter(|b| sparse.contains(b)) + }); + let Some(block) = block else { + continue; + }; + touched.insert(block); + // As in `let_go_idle`: under the lock, the next use must not find the + // staging state of the texture let go, and it stamps `used` anew. + crate::texture::unstage(at as This); + r.host.wanted.store(u32::MAX, Relaxed); + r.host.used.store(0, Relaxed); + let gone = made.take(); + drop(made); + if let Some((host, _)) = gone { + r.host.gone.store(true, Relaxed); + r.host.compacted.store(true, Relaxed); + KINDS[2].fetch_add(1, Relaxed); + KINDS[3].fetch_add(host.bytes, Relaxed); + went += 1; + bytes += host.bytes; + crate::host::retire(host); + } + } + FROM.store(stopped_at.unwrap_or(0), Relaxed); + // The texture blocks the pools had let go to Windows when compaction + // first acted: what they let go since is the memory actually returned + // (whatever let the last piece of a block go, compaction or the sweep; + // it comes once the textures' retirement has drained, so a later line + // shows what an earlier look gave back). + static BASE: std::sync::OnceLock<[u64; 2]> = std::sync::OnceLock::new(); + if went == 0 && BASE.get().is_none() { + return; + } + let base = *BASE.get_or_init(crate::pool::textures_let_go); + let [blocks_now, bytes_now] = crate::pool::textures_let_go(); + let looks = if went == 0 { COMPACTED[0].load(Relaxed) } else { COMPACTED[0].fetch_add(1, Relaxed) + 1 }; + COMPACTED[1].fetch_add(went, Relaxed); + COMPACTED[2].fetch_add(bytes, Relaxed); + if went != 0 && (looks.is_power_of_two() || looks % 30 == 0) { + tracing::info!( + "texture compaction (VICTORY_COMPACT_SPARSE; the PC short of commit or the card over its budget): {went} idle \ + textures ({} MB) let go from {} of {} candidate blocks (the scan stopped {}); since the start {} looks, {} \ + textures, {} MB; let go by compaction and made again since the start: {} textures ({} MB); texture blocks \ + released to Windows since the first look: {} ({} MB)", + bytes >> 20, + touched.len(), + sparse.len(), + if stopped_at.is_some() { "at its bound" } else { "after the whole table" }, + looks, + COMPACTED[1].load(Relaxed), + COMPACTED[2].load(Relaxed) >> 20, + COMPACT_COMEBACK[0].load(Relaxed), + COMPACT_COMEBACK[1].load(Relaxed) >> 20, + blocks_now - base[0], + (bytes_now - base[1]) >> 20, + ); + } +} + +/// `VICTORY_COMPACT_WHOLE=1`: compaction lets a sparse block's textures go +/// only when every one of them can, so the block empties whole +/// (`crate::drain`); off, they go one by one as before. +#[cfg(windows)] +fn compact_whole() -> bool { + crate::asked_for!("VICTORY_COMPACT_WHOLE") +} + +/// When [`compact_plan`] last asked for a compaction (ms). +#[cfg(windows)] +static COMPACT_ASKED_AT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Whether the texture pools keep few empty blocks (`crate::pool::room`) +/// because whole-block compaction asked to act within the last +/// [`COMPACT_SPARES_HOLD_MS`], so that what it empties goes back to Windows. +/// Below 85 % of the card's budget they would keep up to 64 otherwise. +/// `VICTORY_COMPACT_SPARES=0` leaves the spares as they are, to measure the +/// whole-block rule apart from this. +#[cfg(windows)] +pub(crate) fn compacting_whole() -> bool { + use std::sync::atomic::Ordering::Relaxed; + let at = COMPACT_ASKED_AT.load(Relaxed); + compact_whole() + && crate::toggled!("VICTORY_COMPACT_SPARES") + && at != 0 + && crate::host::now_ms().saturating_sub(at) <= COMPACT_SPARES_HOLD_MS +} + +/// How long the pools keep few spares after compaction last asked to act: +/// longer than a round's gap, so that a PC at the commit floor does not +/// switch between 2 and 64 spares (and blocks made ahead) every few seconds. +#[cfg(windows)] +const COMPACT_SPARES_HOLD_MS: u64 = 60_000; + +/// The most blocks one round empties. +#[cfg(windows)] +const COMPACT_WHOLE_BLOCKS: usize = 8; +/// A round whose last look is older than this is dropped (compaction stopped +/// being asked for): its tally would be stale. A round itself may take many +/// looks; it is not bounded in time. +#[cfg(windows)] +const COMPACT_ROUND_GAP_MS: u64 = 20_000; +/// How long a block being emptied is taken last by the pool's placement: +/// longer than a retirement and a piece's rest. +#[cfg(windows)] +const COMPACT_DRAIN_MS: u64 = 10_000; + +/// Since the start: textures compaction let go that were made again, and +/// their bytes (both modes): what letting them go cost in uploads. +#[cfg(windows)] +static COMPACT_COMEBACK: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// What looks have tallied since the round began: a round is one pass over +/// the whole table of textures, which a look bounded in time may not finish. +#[cfg(windows)] +struct Round { + /// Per candidate block: bytes (as cut from the block) of the members that + /// may go, and their addresses in the table. + may_go: std::collections::HashMap<(usize, usize), (u64, Vec<usize>)>, + /// Bytes of candidate blocks' members that may not go, by + /// [`crate::drain::Kept`]. + kept: [u64; 3], + /// Textures skipped because their lock was busy (their block, unknown + /// without the lock, then falls short and is not taken this round). + busy: u64, + began: u64, + last: u64, + looks: u64, + /// Time the looks of the round took (µs). + spent: u64, +} + +/// Since the start: rounds done, blocks emptied, blocks given up at the +/// check before letting go. +#[cfg(windows)] +static COMPACT_ROUNDS: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + +/// Whether the texture at `at` may go now: filled from title memory, read +/// longer ago than the idle time, not written by the title, held by nothing +/// but its title texture. `used` is read again under `made`'s lock, which +/// `hosted_with` writes it under. +#[cfg(windows)] +fn compact_kept(at: usize, r: &Resource, host: &std::sync::Arc<HostTexture>) -> Option<crate::drain::Kept> { + use crate::drain::Kept; + use std::sync::atomic::Ordering::Relaxed; + const IDLE_FRAMES: u64 = 4; + let used = r.host.used.load(Relaxed); + if used == 0 || !crate::host::long_ago(used, COMPACT_IDLE_MS, IDLE_FRAMES) { + Some(Kept::Recent) + } else if crate::texture::host_wrote(at) { + Some(Kept::Written) + } else if std::sync::Arc::strong_count(host) != 1 || crate::host::references(&host.texture) != 1 { + Some(Kept::Referenced) + } else { + None + } +} + +/// [`compact_sparse`] with `VICTORY_COMPACT_WHOLE=1`: tallies the members of +/// `sparse` blocks over one pass of the table, then empties the blocks all of +/// whose members may go ([`crate::drain::whole_blocks`]), each member checked +/// again under its lock first. +#[cfg(windows)] +fn compact_whole_blocks(all: &std::collections::BTreeSet<usize>, sparse: &std::collections::HashSet<(usize, usize)>) { + use std::sync::atomic::Ordering::Relaxed; + static ROUND: std::sync::Mutex<Option<Round>> = std::sync::Mutex::new(None); + static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let now = crate::host::now_ms(); + let mut round = ROUND.lock().unwrap_or_else(|e| e.into_inner()); + if round.as_ref().is_some_and(|r| now.saturating_sub(r.last) > COMPACT_ROUND_GAP_MS) { + *round = None; + FROM.store(0, Relaxed); + } + let tally = round.get_or_insert_with(|| Round { + may_go: Default::default(), + kept: [0; 3], + busy: 0, + began: now, + last: now, + looks: 0, + spent: 0, + }); + + // Tally, bounded in time as the per-texture look is. No call into D3D12: + // the block of a texture is the one noted when it was made. + let began = std::time::Instant::now(); + let from = FROM.load(Relaxed); + let mut stopped_at = None; + for (looked, &at) in all.range(from..).enumerate() { + if (looked & 255) == 255 && began.elapsed().as_micros() >= COMPACT_MOST_US { + stopped_at = Some(at); + break; + } + // SAFETY: as in `compact_sparse`: the caller holds the table's lock. + let r = unsafe { &*(at as *const Resource) }; + if r.host.used.load(Relaxed) == 0 || !fills(&r.desc) { + continue; + } + let Ok(made) = r.host.made.try_lock() else { + tally.busy += 1; + continue; + }; + let Some((host, _)) = made.as_ref() else { continue }; + let Some((block, len)) = host.piece.filter(|(b, _)| sparse.contains(b)) else { + continue; + }; + match compact_kept(at, r, host) { + Some(why) => tally.kept[why.index()] += len, + None => { + let entry = tally.may_go.entry(block).or_default(); + entry.0 += len; + entry.1.push(at); + } + } + } + tally.looks += 1; + tally.last = now; + tally.spent += began.elapsed().as_micros() as u64; + FROM.store(stopped_at.unwrap_or(0), Relaxed); + if stopped_at.is_some() { + return; + } + + // The round is whole: choose, check again, let go. + let Some(done) = round.take() else { return }; + drop(round); + COMPACT_ROUNDS[0].fetch_add(1, Relaxed); + // Blocks no longer sparse are left out here, as are blocks that became + // sparse during the round (their tally then falls short). + let states = crate::pool::texture_block_states(sparse); + let may_go: std::collections::HashMap<(usize, usize), u64> = done.may_go.iter().map(|(&b, &(bytes, _))| (b, bytes)).collect(); + // Every block whose members may all go, emptiest first; the caps count + // only the blocks actually emptied, so one given up makes room for the next. + let whole = crate::drain::whole_blocks(&states, &may_go, u64::MAX, usize::MAX); + let (mut went, mut bytes, mut emptied, mut given_up) = (0u64, 0u64, 0u64, 0u64); + let mut gone = Vec::new(); + for block in whole.iter().copied() { + if emptied as usize >= COMPACT_WHOLE_BLOCKS || bytes >= COMPACT_MOST { + break; + } + let Some((_, members)) = done.may_go.get(&block) else { continue }; + // Placement takes the block last from here on, so the check below is + // not undone by a new piece cut from it while its members go. + crate::pool::mark_draining(block, now + COMPACT_DRAIN_MS); + let mut guards = Vec::with_capacity(members.len()); + let mut verified = 0u64; + let mut whole_still = true; + for &at in members { + // SAFETY: in the table (checked first), under its lock (the caller's). + let Some(r) = all.contains(&at).then(|| unsafe { &*(at as *const Resource) }) else { + whole_still = false; + break; + }; + if !fills(&r.desc) { + whole_still = false; + break; + } + let Ok(made) = r.host.made.try_lock() else { + whole_still = false; + break; + }; + let piece = made.as_ref().and_then(|(host, _)| compact_kept(at, r, host).is_none().then_some(host.piece).flatten()); + match piece { + Some((b, len)) if b == block => verified += len, + _ => { + whole_still = false; + break; + } + } + guards.push((at, r, made)); + } + let now_seen = crate::pool::texture_block_state(block).unwrap_or_default(); + if !whole_still || !crate::drain::still_whole(verified, now_seen) { + // Placement may take it as before. + crate::pool::mark_draining(block, 0); + given_up += 1; + continue; + } + for (at, r, mut made) in guards { + // As in `compact_sparse` and `let_go_idle`: unstaged under the + // lock; retired once every lock of the block is let go. + crate::texture::unstage(at as This); + r.host.wanted.store(u32::MAX, Relaxed); + r.host.used.store(0, Relaxed); + if let Some((host, _)) = made.take() { + r.host.gone.store(true, Relaxed); + r.host.compacted.store(true, Relaxed); + KINDS[2].fetch_add(1, Relaxed); + KINDS[3].fetch_add(host.bytes, Relaxed); + went += 1; + bytes += host.bytes; + gone.push(host); + } + } + emptied += 1; + } + for host in gone { + crate::host::retire(host); + } + COMPACT_ROUNDS[1].fetch_add(emptied, Relaxed); + COMPACT_ROUNDS[2].fetch_add(given_up, Relaxed); + COMPACTED[1].fetch_add(went, Relaxed); + COMPACTED[2].fetch_add(bytes, Relaxed); + if went != 0 { + COMPACTED[0].fetch_add(1, Relaxed); + } + // As the per-texture line: blocks released to Windows since compaction + // first acted, once retirement has drained. + static BASE: std::sync::OnceLock<[u64; 2]> = std::sync::OnceLock::new(); + let base = *BASE.get_or_init(crate::pool::textures_let_go); + let [blocks_now, bytes_now] = crate::pool::textures_let_go(); + let rounds = COMPACT_ROUNDS[0].load(Relaxed); + if rounds.is_power_of_two() || rounds.is_multiple_of(12) { ``` Thanks, and for checking the counter's timing on the card. Done in b697bcba: - The frame-rate lines now carry `texture compaction: texture blocks released to Windows since compaction first acted: N (MB ...)` whenever the count changes, once compaction has acted at least once. It is printed whether or not compaction still asks to look, so a release that lands after the last round, and gives the room back that stops further rounds, still shows. It sits next to the slot eviction line (`resource::compaction_released_line`, called from the same place as `slot_evict_line`). - The two compaction lines used separate starting counts. Both now use one (`COMPACT_BASE`), so all three lines count from the same first look. - A whole-block round that emptied a block is always logged. Only the rounds that emptied nothing are thinned out, so round 13 is no longer skipped. As you say, it counts both texture pools and the sweep's releases. The line says it is an upper bound on compaction's share, and it measures the pool letting its block go, not what DXGI reports. Not built on Windows or run in the game yet. For the #4310 retest, this line, the `memory now:` lines and the DXGI samples over the same minutes should show whether the last drain returned a block.
Author
Owner

@⁠vi-tester-8gb on GitHub · 2026-12-01 15:33 UTC · original

Field report from an 8 GB laptop card, played by hand: one 79-minute session with the whole-block rule on, ending in a crash I haven't seen in any other run.

PC: RTX 5060 Laptop GPU 8 GB (driver 621.24), i7-13620H, 32 GB RAM, Windows 11.
Build: v2026.11.30.03 + #4207 + #4295, with this PR at cef63b9c and #4881 on top, local --release build. Series S profile, DLSS Performance, DLSS FG 2x, --fps 16, VICTORY_SAMPLED_EVICT=1, VICTORY_WAIT_RESIDENT=textures, VICTORY_VRAM_BUDGET_MB=6400 (so "over budget" means over 6400 MB, about 600 MB under the real ~7000 MB), VICTORY_COMPACT_WHOLE=1. Driving and walking around the city.

What compaction did in 79 minutes (from its own log lines):

  • 48+ rounds. Each round had 7 to 27 candidate blocks, and in nearly every round 0 of them had every member free to go. At round 48: since the start 2 emptied, 30 given up, 4 textures (6 MB) let go.
  • texture blocks released to Windows since compaction first acted: 1 (64 MB).
  • The candidates were mostly kept by "held by a slot or list" (~44 MB), "read lately" (~48 MB) and "written by the title" (~11 MB).
  • On this card, card use crept up anyway, from 5.5 GB at 5 min to 6.6 GB at 75 min. With the 6400 cap it never reached the real budget, so the cap is what kept the card safe, not compaction.

The end: that one block release was logged at 15:23:00. At 15:23:32 the process stopped with:

ERROR victory_gpu::host: a host command list did not close (0x80070057): a command recorded into it was invalid; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command

No DEVICE_HUNG, no nvlddmkm event, and the card had ~470 MB of real headroom. I searched all 22 session logs I have (VIctory forks, t30/t303 builds among them): this error appears only in this one. That isn't proof. It's one crash, and I don't have a debug-layer run. But the timing (32 s after the only block this PR ever handed back) makes me suspect a list still referencing something in the released block. If it helps, I can run a diagnostics build with VICTORY_D3D12_DEBUG=1.

For comparison, without the cap and without this PR (otherwise the same settings), two long sessions crept up to the real budget at roughly 70-90 min, and one ended in DEVICE_HUNG. Next we'll play with the cap alone (no compaction) to see whether the cap is enough on its own.

Written up with help from Claude (AI); numbers are from our own logs.

**@⁠vi-tester-8gb** on GitHub · 2026-12-01 15:33 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7316125279) Field report from an 8 GB laptop card, played by hand: one 79-minute session with the whole-block rule on, ending in a crash I haven't seen in any other run. **PC:** RTX 5060 Laptop GPU 8 GB (driver 621.24), i7-13620H, 32 GB RAM, Windows 11. **Build:** `v2026.11.30.03` + #4207 + #4295, with this PR at `cef63b9c` and #4881 on top, local `--release` build. Series S profile, DLSS Performance, DLSS FG 2x, `--fps 16`, `VICTORY_SAMPLED_EVICT=1`, `VICTORY_WAIT_RESIDENT=textures`, `VICTORY_VRAM_BUDGET_MB=6400` (so "over budget" means over 6400 MB, about 600 MB under the real ~7000 MB), `VICTORY_COMPACT_WHOLE=1`. Driving and walking around the city. **What compaction did in 79 minutes (from its own log lines):** - 48+ rounds. Each round had 7 to 27 candidate blocks, and in nearly every round **0 of them had every member free to go**. At round 48: `since the start 2 emptied, 30 given up, 4 textures (6 MB) let go`. - `texture blocks released to Windows since compaction first acted: 1 (64 MB)`. - The candidates were mostly kept by "held by a slot or list" (~44 MB), "read lately" (~48 MB) and "written by the title" (~11 MB). - On this card, card use crept up anyway, from 5.5 GB at 5 min to 6.6 GB at 75 min. With the 6400 cap it never reached the real budget, so the cap is what kept the card safe, not compaction. **The end:** that one block release was logged at `15:23:00`. At `15:23:32` the process stopped with: ``` ERROR victory_gpu::host: a host command list did not close (0x80070057): a command recorded into it was invalid; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command ``` No `DEVICE_HUNG`, no nvlddmkm event, and the card had ~470 MB of real headroom. I searched all 22 session logs I have (VIctory forks, t30/t303 builds among them): this error appears only in this one. That isn't proof. It's one crash, and I don't have a debug-layer run. But the timing (32 s after the only block this PR ever handed back) makes me suspect a list still referencing something in the released block. If it helps, I can run a diagnostics build with `VICTORY_D3D12_DEBUG=1`. For comparison, without the cap and without this PR (otherwise the same settings), two long sessions crept up to the real budget at roughly 70-90 min, and one ended in `DEVICE_HUNG`. Next we'll play with the cap alone (no compaction) to see whether the cap is enough on its own. _Written up with help from Claude (AI); numbers are from our own logs._
Author
Owner

@⁠mcozcan on GitHub · 2026-12-01 16:01 UTC · original

Thanks, this is exactly the kind of run the rule needed. Two things stand out.

0 of N blocks with every member free matches what Remorce saw in #4774 and your breakdown says why: the candidates are kept by "held by a slot or list" and "read lately", not by the rule itself. So on its own the whole-block rule mostly gives up, as designed; what could change that is #4581 (sampled eviction) freeing the index-picked textures first. I'm running three forced arms tonight on an RTX 5070 12 GB (per-texture, whole, whole with VICTORY_SAMPLED_EVICT=0) to separate the two, and will post the numbers here.

The crash 32 s after the only block release is the part I take most seriously. One crash isn't proof, but a released block followed by an invalid command is the failure the rule must never cause. Yes please: a diagnostics build with VICTORY_D3D12_DEBUG=1 (and VICTORY_D3D12_DRED=light if you can afford it) with VICTORY_COMPACT_WHOLE=1 would tell us whether the command names a resource in that block. In the meantime I'll go through the release path again (texture retirement vs the block's heap going back to Windows, and anything that can still name a view into it) and report what I find.

**@⁠mcozcan** on GitHub · 2026-12-01 16:01 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7316911477) Thanks, this is exactly the kind of run the rule needed. Two things stand out. **0 of N blocks with every member free** matches what Remorce saw in #4774 and your breakdown says why: the candidates are kept by "held by a slot or list" and "read lately", not by the rule itself. So on its own the whole-block rule mostly gives up, as designed; what could change that is #4581 (sampled eviction) freeing the index-picked textures first. I'm running three forced arms tonight on an RTX 5070 12 GB (per-texture, whole, whole with `VICTORY_SAMPLED_EVICT=0`) to separate the two, and will post the numbers here. **The crash 32 s after the only block release** is the part I take most seriously. One crash isn't proof, but a released block followed by an invalid command is the failure the rule must never cause. Yes please: a diagnostics build with `VICTORY_D3D12_DEBUG=1` (and `VICTORY_D3D12_DRED=light` if you can afford it) with `VICTORY_COMPACT_WHOLE=1` would tell us whether the command names a resource in that block. In the meantime I'll go through the release path again (texture retirement vs the block's heap going back to Windows, and anything that can still name a view into it) and report what I find.
Author
Owner

@⁠mcozcan on GitHub · 2026-12-01 16:12 UTC · original

@⁠vi-tester-8gb as promised, I went through the release path on cef63b9c (code reading only, nothing run). I found no way for it to leave a host list naming a texture that is gone. Here is the path:

  • Textures. Whole-block compaction lets a texture go only if compact_kept passes it (resource.rs:4333-4347): idle, not written by the title, no Arc held by a list, and a D3D12 reference count of 1. It checks this again for every member under that member's lock just before letting go (resource.rs:4446-4461). Then it hands the copies to crate::host::retire (resource.rs:4487-4489), the same call the sweep uses. retire (host.rs:990-1003) drops an object only after every submission started or queued at that moment has finished, plus bury_lag (host.rs:1028, 64 submissions by default). That lag is there for lists that are recorded but not yet sent.
  • Pieces. A piece goes back to its pool only when the texture's last reference goes (give_back_to, pool.rs:1329). It then rests for REST = 2.5 s (pool.rs:171).
  • Blocks. reclaim lets a block go only when it is wholly free (pool.rs:508-540), so only after all of the above has happened for every piece in it.

The one thing VICTORY_COMPACT_WHOLE=1 changes on that path is the spares cap (pool.rs:59). While compaction is asking to act, the texture pools keep at most 2 empty blocks instead of up to 64. So blocks the sweep emptied also go back to Windows, and new blocks are made more often. Your "1 (64 MB)" counts those releases as well (the counter is an upper bound on compaction's share). And in your run compaction itself let only 4 textures (6 MB) go in 79 minutes.

What the error says: 0x80070057 from Close (host.rs:11206) means the runtime refused the arguments of a command recorded into that list. It is not a page fault or a device removal. The cases of it this code has met before were copies into a level that a remade host copy doesn't hold (list.rs:1889-1895, the test at resource.rs:9791-9795). Neither of those is on the release path. That fits the crash not coming from the block release, but it doesn't rule it out. One crash and no debug layer can't settle it either way, so the VICTORY_D3D12_DEBUG=1 run is still the way to find out, and the command it names will say whether a resource from a released block is involved. If it is, that's a bug here, and I'll fix it in this PR.

**@⁠mcozcan** on GitHub · 2026-12-01 16:12 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7317217697) @⁠vi-tester-8gb as promised, I went through the release path on `cef63b9c` (code reading only, nothing run). I found no way for it to leave a host list naming a texture that is gone. Here is the path: - **Textures.** Whole-block compaction lets a texture go only if `compact_kept` passes it (`resource.rs:4333-4347`): idle, not written by the title, no `Arc` held by a list, and a D3D12 reference count of 1. It checks this again for every member under that member's lock just before letting go (`resource.rs:4446-4461`). Then it hands the copies to `crate::host::retire` (`resource.rs:4487-4489`), the same call the sweep uses. `retire` (`host.rs:990-1003`) drops an object only after every submission started or queued at that moment has finished, plus `bury_lag` (`host.rs:1028`, 64 submissions by default). That lag is there for lists that are recorded but not yet sent. - **Pieces.** A piece goes back to its pool only when the texture's last reference goes (`give_back_to`, `pool.rs:1329`). It then rests for `REST` = 2.5 s (`pool.rs:171`). - **Blocks.** `reclaim` lets a block go only when it is wholly free (`pool.rs:508-540`), so only after all of the above has happened for every piece in it. The one thing `VICTORY_COMPACT_WHOLE=1` changes on that path is the spares cap (`pool.rs:59`). While compaction is asking to act, the texture pools keep at most 2 empty blocks instead of up to 64. So blocks the sweep emptied also go back to Windows, and new blocks are made more often. Your "1 (64 MB)" counts those releases as well (the counter is an upper bound on compaction's share). And in your run compaction itself let only 4 textures (6 MB) go in 79 minutes. What the error says: `0x80070057` from `Close` (`host.rs:11206`) means the runtime refused the arguments of a command recorded into that list. It is not a page fault or a device removal. The cases of it this code has met before were copies into a level that a remade host copy doesn't hold (`list.rs:1889-1895`, the test at `resource.rs:9791-9795`). Neither of those is on the release path. That fits the crash not coming from the block release, but it doesn't rule it out. One crash and no debug layer can't settle it either way, so the `VICTORY_D3D12_DEBUG=1` run is still the way to find out, and the command it names will say whether a resource from a released block is involved. If it is, that's a bug here, and I'll fix it in this PR.
Author
Owner

@⁠CuteBooty on GitHub · 2026-12-01 16:23 UTC · original

@⁠mcozcan thanks for folding the numbers in and for the whole-block rule. I can't do supervised route runs today, so the two 30-minute runs will have to wait for another day. I'll post them here if I get to them.

Standing still wouldn't answer your question: on my runs, all the blocks compaction released came out in the first ~12 minutes of driving, and a stationary session loads almost nothing new after the first minute.

**@⁠CuteBooty** on GitHub · 2026-12-01 16:23 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7317530294) @⁠mcozcan thanks for folding the numbers in and for the whole-block rule. I can't do supervised route runs today, so the two 30-minute runs will have to wait for another day. I'll post them here if I get to them. Standing still wouldn't answer your question: on my runs, all the blocks compaction released came out in the first ~12 minutes of driving, and a stationary session loads almost nothing new after the first minute.
Author
Owner

@⁠Jesper-Andersson on GitHub · 2026-12-01 16:35 UTC · original

A short one from an 8 GB card at cef63b9c: compaction never acted, so this run says nothing about the whole-block rule yet. It also ended in a crash. I can't tell whether it relates to this PR; no block was released before it, unlike vi-tester-8gb's run.

Setup: our fork's diagnostics build with this PR (to cef63b9c) and #4581 (to 732ee452) cherry-picked onto it, not your branch on main. VICTORY_COMPACT_SPARSE=1, VICTORY_COMPACT_WHOLE=1, VICTORY_SAMPLED_EVICT=pressure, victory play's memory defaults otherwise. RTX 2070 SUPER 8 GB (driver 621.40, ReBAR off), Ryzen 7 5800X, 32 GB RAM, Windows 11 Pro Insider 10.0.26320. Series S, DLSS Performance, FSR 3 frame generation. One free-play session, 24 minutes in the world before the crash. GPU clocks locked at 1890 MHz.

Compaction: no compaction line in the whole log, and the frame-rate lines never printed "released to Windows since compaction first acted". The card never went over its budget (closest -341 MB of 7,048 MB; #4581 was on, numbers there), so the card trigger never fired, and no line shows the commit trigger firing either. No log line shows either the whole-block rule or the spares cap acting (spare empty blocks: at most 2 in this run and in the census run without it).

The crash: at world + 24.2 min the device hung (0x887A0006, DEVICE_HUNG), and Windows then stopped with bugcheck 0x10E (VIDEO_MEMORY_MANAGEMENT_INTERNAL, parameter 1 = 0x2e); no dump was written. Our own line at the loss says the submitting thread was between submissions, nothing of ours on the card, for 38,023 ms before the device went. The cause isn't isolated:

  • the clocks were locked, and this PC has crashed before while locked at 1890 MHz;
  • no debug layer;
  • it isn't vi-tester-8gb's error (theirs was a list that would not close, 0x80070057, with no device hang);
  • compaction never acted, so no block release came before it.

No storahci or disk events around the crash.

If 8 GB is still an open question after your 12 GB arms, we'll rerun with compaction forced (VICTORY_COMPACT_COMMIT_FLOOR_MB=99999) on a debug-layer build (VICTORY_D3D12_DEBUG=1), with GPU clocks unlocked.

Spec dependence:

  • Likely general: compaction never reaching its trigger while the card stays just under its budget.
  • May depend on our specs: 8 GB card near its budget, Turing, ReBAR off, Series S; clocks locked for this run.
  • Untested elsewhere: other GPUs, AMD, 12-16 GB, Series X, frame generation off, ray tracing.

Not tested: compaction acting (per-texture or whole blocks); VICTORY_COMPACT_SPARES=0; release build; Series X; other cards; DLSS frame generation; a second session.

Drafted with AI assistance (Claude Code).

**@⁠Jesper-Andersson** on GitHub · 2026-12-01 16:35 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7317865840) A short one from an 8 GB card at cef63b9c: compaction never acted, so this run says nothing about the whole-block rule yet. It also ended in a crash. I can't tell whether it relates to this PR; no block was released before it, unlike vi-tester-8gb's run. **Setup:** our fork's diagnostics build with this PR (to cef63b9c) and #4581 (to 732ee452) cherry-picked onto it, not your branch on main. `VICTORY_COMPACT_SPARSE=1`, `VICTORY_COMPACT_WHOLE=1`, `VICTORY_SAMPLED_EVICT=pressure`, `victory play`'s memory defaults otherwise. RTX 2070 SUPER 8 GB (driver 621.40, ReBAR off), Ryzen 7 5800X, 32 GB RAM, Windows 11 Pro Insider 10.0.26320. Series S, DLSS Performance, FSR 3 frame generation. One free-play session, 24 minutes in the world before the crash. GPU clocks locked at 1890 MHz. **Compaction:** no compaction line in the whole log, and the frame-rate lines never printed "released to Windows since compaction first acted". The card never went over its budget (closest -341 MB of 7,048 MB; #4581 was on, numbers there), so the card trigger never fired, and no line shows the commit trigger firing either. No log line shows either the whole-block rule or the spares cap acting (spare empty blocks: at most 2 in this run and in the census run without it). **The crash:** at world + 24.2 min the device hung (`0x887A0006`, DEVICE_HUNG), and Windows then stopped with bugcheck 0x10E (VIDEO_MEMORY_MANAGEMENT_INTERNAL, parameter 1 = 0x2e); no dump was written. Our own line at the loss says the submitting thread was between submissions, nothing of ours on the card, for 38,023 ms before the device went. The cause isn't isolated: - the clocks were locked, and this PC has crashed before while locked at 1890 MHz; - no debug layer; - it isn't vi-tester-8gb's error (theirs was a list that would not close, `0x80070057`, with no device hang); - compaction never acted, so no block release came before it. No storahci or disk events around the crash. If 8 GB is still an open question after your 12 GB arms, we'll rerun with compaction forced (`VICTORY_COMPACT_COMMIT_FLOOR_MB=99999`) on a debug-layer build (`VICTORY_D3D12_DEBUG=1`), with GPU clocks unlocked. **Spec dependence:** - Likely general: compaction never reaching its trigger while the card stays just under its budget. - May depend on our specs: 8 GB card near its budget, Turing, ReBAR off, Series S; clocks locked for this run. - Untested elsewhere: other GPUs, AMD, 12-16 GB, Series X, frame generation off, ray tracing. **Not tested:** compaction acting (per-texture or whole blocks); `VICTORY_COMPACT_SPARES=0`; release build; Series X; other cards; DLSS frame generation; a second session. Drafted with AI assistance (Claude Code).
Author
Owner

@⁠mcozcan on GitHub · 2026-12-01 17:03 UTC · original

@⁠Jesper-Andersson thanks. I agree it says nothing about the whole-block rule, and the code confirms that more strongly than "it never logged". On cef63b9c, compact_plan returns early unless the card is over its budget or the commit is under the floor (resource.rs:4106), and it sets COMPACT_ASKED_AT only after that (:4118). The spares cap (pool.rs:59) depends on compacting_whole() (resource.rs:4270-4277), which needs COMPACT_ASKED_AT. compact_whole_blocks runs only from a plan. So in your run, VICTORY_COMPACT_SPARSE=1 / VICTORY_COMPACT_WHOLE=1 did nothing beyond that check. The spares you saw (at most 2) are the pool's usual policy, and the hang can't come from a block this PR released or a cap it set.

Before the forced run on a debug-layer build, one thing to know. A local review found an issue in whole-block mode. compact_whole_blocks took the texture pool locks with a blocking lock and ran its check phase without a time bound while holding the texture table. With the sweep on its own low-priority thread (VICTORY_SWEEP_OFF_THREAD=1, #4559), that could make a title thread wait. The fix uses pool::lock_now (try-lock) in texture_block_state / mark_draining / texture_block_states and bounds the check loop by COMPACT_MOST_US. It's in testing here and I'll push it to this PR after that. If you're not in a hurry, the forced run is most useful on that head. I'll say here when it's up.

**@⁠mcozcan** on GitHub · 2026-12-01 17:03 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7318675139) @⁠Jesper-Andersson thanks. I agree it says nothing about the whole-block rule, and the code confirms that more strongly than "it never logged". On `cef63b9c`, `compact_plan` returns early unless the card is over its budget or the commit is under the floor (`resource.rs:4106`), and it sets `COMPACT_ASKED_AT` only after that (`:4118`). The spares cap (`pool.rs:59`) depends on `compacting_whole()` (`resource.rs:4270-4277`), which needs `COMPACT_ASKED_AT`. `compact_whole_blocks` runs only from a plan. So in your run, `VICTORY_COMPACT_SPARSE=1` / `VICTORY_COMPACT_WHOLE=1` did nothing beyond that check. The spares you saw (at most 2) are the pool's usual policy, and the hang can't come from a block this PR released or a cap it set. Before the forced run on a debug-layer build, one thing to know. A local review found an issue in whole-block mode. `compact_whole_blocks` took the texture pool locks with a blocking lock and ran its check phase without a time bound while holding the texture table. With the sweep on its own low-priority thread (`VICTORY_SWEEP_OFF_THREAD=1`, #4559), that could make a title thread wait. The fix uses `pool::lock_now` (try-lock) in `texture_block_state` / `mark_draining` / `texture_block_states` and bounds the check loop by `COMPACT_MOST_US`. It's in testing here and I'll push it to this PR after that. If you're not in a hurry, the forced run is most useful on that head. I'll say here when it's up.
Author
Owner

@⁠trustno1-coder on GitHub · 2026-12-01 18:36 UTC · original

Closing this as part of moving main to the texture and video-memory rework (v2026.12.01.01-test). A lot of the code changed, and this pull request no longer applies cleanly to it; it would need to be rewritten against the new main rather than rebased. Thank you for the work. If the change is still needed, please open a new pull request based on the current main.

**@⁠trustno1-coder** on GitHub · 2026-12-01 18:36 UTC · [original](https://github.com/trustno1-coder/VIctory-NVIDIA/pull/4581#issuecomment-7321222396) Closing this as part of moving main to the texture and video-memory rework (v2026.12.01.01-test). A lot of the code changed, and this pull request no longer applies cleanly to it; it would need to be rewritten against the new main rather than rebased. Thank you for the work. If the change is still needed, please open a new pull request based on the current main.
github-bot closed this pull request 2026-12-01 18:43:00 +00:00

Pull request closed

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/trustno1-coder--VIctory-NVIDIA!4582
No description provided.