Skip to content

perf(agc): allocate storage CPU snapshots on demand - #3991

Merged
oneandonlydean merged 5 commits into
boykopovar:mainfrom
Sanjaysrinivas:perf/agc-lazy-storage-snapshot
Oct 13, 2026
Merged

oneandonlydean merged 5 commits into
boykopovar:mainfrom
Sanjaysrinivas:perf/agc-lazy-storage-snapshot

Conversation

@Sanjaysrinivas

@Sanjaysrinivas Sanjaysrinivas commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What

Watched GPU-direct storage uploads resize the full original CPU vector even though that path invalidates the snapshot and uploads from imported guest memory. Allocate the vector only when capturing guest bytes, uploading through the CPU, or using CPU write-back. The factory completes the initial upload before publishing the texture; watched direct uploads establish an invalid, empty CPU snapshot. The private field initializer follows main. The separate generation baseline is unchanged.

The CPU-fallback allocation sits immediately before the guest-byte read, after generation stamping. The CPU write-back allocation sits after the GPU-direct and unregistered-drop exits, before comparison-baseline handling. These locations avoid conflicts with #5024's per-unit CPU-write preservation; the initializer change is removed because the private factory establishes validity before publication. Both merge orders with #5024 head e5449936f succeed and produce the identical tree. Neither feature depends on the other. Earlier checks also verified both merge orders with #3949.

The regression checks zero retained original snapshot bytes for a watched shared-memory import, correct upload/refresh/write-back texels, comparison fallback after write tracking is removed, and import-disabled CPU upload/write-back.

The Windows fixture registers its test surfaces with gpu=true, matching the five-argument Mutation::Add API. Both fixture textures use the current public StorageTexture::Create factory; upstream made the constructor private, so direct make_shared calls no longer compile. The factory performs upload, view creation and live-image registration. The outer Windows guard remains. OriginalSnapshotBytes() reports retained vector capacity, including capacity left by earlier CPU fallbacks.

Tested

Windows 11, MinGW GCC 15.2 Release, RTX 4070 Laptop GPU:

  • Head 0612c181f, rebased onto main 4bb2c7f39: fresh Release configure and build of the linked native recorder fixture, depth/storage and resource-cache test targets, and all 125 runtime libraries (libs target). All 13 submodule checkouts match the current source pins; the cached pinned FFmpeg package is reused. This is not a build of every project target or a run of the whole test suite. The earlier clean pre-fix build reproduced the private-constructor/construct_at error; the two public factory calls remain in place.
  • ctest -R '^agc_storage_cpu_snapshot$' --output-on-failure --no-tests=error --timeout 30: passed in 1.14 s with Vulkan core validation enabled, no skips or validation errors. Watched GPU-direct original capacity is 0 bytes; untracked/comparison and CPU fallback capacities are 262,144 bytes. Refresh/write-back texels and tracking removal are checked by the fixture.
  • Isolated combined-tree verification with fix(agc): keep CPU writes when a pending storage result is stored over untracked memory #5024: the snapshot and eight related checks passed again. Its untracked-write fixture passed all five cases in default and APS5_WRITE_WATCH_IMPORTS=unwatch modes (0.68/0.41 s), with core validation and no skipped cases/errors. On Windows, the private test overlay uses the existing shared-memory mapping fixture instead of private committed backing so the left-watch case actually executes. The peer production code is unchanged; neither its feature nor this test overlay is included in this public PR. Local Ollama Qwen authored the isolated test adaptation; Codex reviewed/applied/tested it.
  • Same-base Silent Hill 2 startup A/B, three alternating-order pairs: median endpoint process resident memory 3875.0 -> 3736.8 MiB, observed reduction 138.2 MiB (3.57%). The control restores only the two production files to base 0a8b1d32b; all other runtime libraries, title executable/assets, settings and cache seed are identical. Samples use Windows WorkingSetSize at displayed startup-frame counters 251-256, with 0.25 s polling. Empty recompiled-shader cache; texture/staging caches 512/64 MiB and resource-cache entries 16. Both 8 GiB process guards and the available-RAM/commit-headroom guards remained enabled; none were hit. Full paired numbers and method are provided in my response to the resident-memory request.
  • Eight existing checks also passed on this public candidate and again on the isolated combined tree with fix(agc): keep CPU writes when a pending storage result is stored over untracked memory #5024: storage upload lifetime/failure, integer clear, settled baseline, unit shadow, depth/storage reuse, and resource-cache storage admission/clear. Both sets of nine checks used required native RTX 4070 Vulkan with core validation; none skipped or reported validation errors. Qwen was unloaded before the GPU tests. The final committed diff passes the conventions checker.
  • Earlier regression check: reintroducing the unconditional allocation caused the snapshot test to fail. The earlier overlap check verified both merge orders with perf(agc): upload a storage image spanning two host imports on the GPU #3949 after the upload-conflict follow-up.

The startup A/B above is historical evidence from the earlier public revision against base 0a8b1d32b; it was not repeated on this rebased head. The startup counters and dynamic image counts vary slightly because of asynchronous progress and polling (17-19 storage-image instances). The A/B covers early startup only, not steady-state memory, menu/gameplay correctness, or an 8 GiB fit throughout. Linux follow-up execution was not run locally. Independent contributor validation on the original head reports a clean Linux build, four existing tests and an Astro Bot check; these are the contributor's results. Raw title logs and proprietary assets remain local.

Checklist

  • Based on main; checked current main and relevant open PR changes for an equivalent allocation change
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw; no silent stubs added
  • No notes, investigation .md files or images added to the repository
  • New third-party code is a submodule built from source; none added
  • Generic behaviour, not specific to one title
  • Depends on: none
  • AI-assisted: yes; Codex authored the original change. Local Ollama Qwen wrote the upload-conflict and Windows fixture follow-ups. For the constructor correction and the allocation-overlap correction, a delegated subagent ran qwen3.8:27b as the coding worker. Each correction used one generation; Codex reviewed the exact patches and verified the builds/tests.

@Kikoarl

Kikoarl commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

Tested on Linux (CachyOS x86_64, GCC) with an NVIDIA GeForce RTX 5060 Ti (driver 615.78.08, Vulkan 1.4):

  • Clean upstream Linux build succeeds with zero errors across all targets.
  • Existing storage & texture test suite (agc_unit_shadow, agc_storage_baseline_settled, agc_driver_image_volume_address_planar_texture, texture_format_lookup) all pass 100%.
  • Verified in-game on Astro Bot (PPSA21567): storage textures upload and render correctly with no graphical artifacts or regression.

Regarding the test fixture: agc_storage_cpu_snapshot is guarded by #ifdef _WIN32 in CMakeLists.txt/Recorder.cpp because Block on Linux allocates via std::aligned_alloc outside of guest write tracking; the core StorageTexture logic itself works without issue on Linux.

Happy to report that the clean upstream Linux build validation limit mentioned in the description is verified! LGTM.

@Sanjaysrinivas
Sanjaysrinivas marked this pull request as ready for review October 11, 2026 21:05
@github-actions github-actions Bot added build agc libSceAgc* labels Oct 11, 2026
@TideOPL

TideOPL commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

Build failure on Windows: the new test doesn't compile on Windows:

core/libs/prx/libSceAgcDriver/tests/Recorder.cpp:4934:41: error: no matching function for call to
'GuestAllocations::Mutation::Add(void*&, const std::size_t&, bool, bool)'

Mutation::Add takes five arguments (pointer, bytes, readable, writable, gpu), on this branch's own head (cfd5257) as well as on main. The StorageCpuSnapshotTest block is inside #ifdef _WIN32, so the Linux jobs never compile it. The other tests pass the fifth argument, e.g. Mutation().Add(block, BlockBytes, true, true, true) in BdaSpanReads.cpp.

The change itself looks correct to me. I went through every reader of original on main:

  • equalsOriginal is guarded by originalValid.
  • compareUntracked returns early when it's invalid, and its Require(original.size() == guestBytes) comes after that check.
  • unchangedSinceBaseline checks the size.
  • writeBackLayers now resizes before its ReadCommitted.

So starting with originalValid = false is safe.

Nits:

  • The test is already inside #ifdef _WIN32, so the inner #ifdef _WIN32 ... #else std::aligned_alloc branch in Block is dead code.
  • OriginalSnapshotBytes() reports capacity(), which never shrinks once a CPU upload has happened. That's fine, just worth knowing when reading the test output.
  • Since this is a perf PR, a title-level number (resident memory before and after) would make the case beyond the unit test.

Tested by reviewer
Windows 11 (26200), WinLibs GCC 15.2.0 r7, Release, head cfd5257 merged onto main c5da823: the build stops at the error above, so I couldn't run the test or the games (Balatro, Minecraft Dungeons II) yet. Happy to rerun them on an RTX 5070 and the integrated Radeon of a 7800X3D once it builds.

AI-assisted: yes. Written with AI assistance (Claude Code), with the build run on my machine; I reviewed it.

@Sanjaysrinivas

Copy link
Copy Markdown
Contributor Author

Thanks for catching this, @TideOPL. Fixed in 70015bd55: the fixture now passes gpu=true as the fifth argument, and the redundant inner platform branches are removed. The outer Windows guard remains.

My earlier native checks used an older local integration with the four-argument API, so they missed this public-branch compile error. I reproduced the reported failure using the complete public Windows Recorder.cpp and this branch's own project headers. After the fix, both syntax checking and Release object compilation passed with MinGW GCC 15.2. This does not establish a complete clean linked build or execution of the public fixture; I've corrected the PR description to make that distinction explicit.

The description also now clarifies that OriginalSnapshotBytes() reports retained capacity, including allocations retained after CPU fallback. I don't yet have a reliable whole-process resident-memory before/after comparison; the fixture measures the watched storage image's CPU-vector allocation.

Qwen wrote this follow-up; I reviewed and validated it. Your rerun on the updated head would help close the remaining build and runtime validation.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

Could you measure a title's resident memory with and without this PR on the same base? A perf PR needs a number for the change itself (#218), and the fixture only counts one image's vector. Please also run agc_storage_cpu_snapshot on this head; so far it has only been compiled.

@Sanjaysrinivas

Copy link
Copy Markdown
Contributor Author

@oneandonlydean Both checks are now complete on public head 70015bd55.

Public Windows fixture: I configured a fresh Release build using this head's project sources/headers and independent dependency checkouts at its pinned revisions (reusing the pinned FFmpeg package), built and linked agc_driver_recorder_tests, and ran:

ctest --test-dir <fresh-build> -R '^agc_storage_cpu_snapshot$' --output-on-failure --no-tests=error --timeout 30
1/1 agc_storage_cpu_snapshot Passed (0.86 s)
watched snapshot fixture: direct 0 bytes, CPU fallback 262144 bytes
unwatched snapshot fixture: direct 262144 bytes, CPU fallback 262144 bytes
Storage CPU snapshot tests passed

RTX 4070 Laptop GPU, Vulkan core validation enabled; no validation errors or skips. This executes the public five-argument fixture, closing the compile-only limitation in my earlier reply.

Same-base title A/B: Silent Hill 2 startup, Windows 11, MinGW GCC 15.2, Release -O3 -DNDEBUG, same executable/assets/GPU/settings. Base is 0a8b1d32b; the with-PR build is 70015bd55. For the control I restored only the two production files (Texture.cpp/Texture.hpp) to their exact pre-PR contents and rebuilt the driver. All other runtime libraries were held identical, built from the public head; no older private integration libraries were used. I also built all 122 public runtime libraries successfully.

Three pairs alternated run order. Each run started with an empty recompiled-shader cache and the same copied Vulkan pipeline-cache seed. Settings were texture cache 512 MiB, staging pool 64 MiB, resource-cache entries 16. Resident memory is Windows GetProcessMemoryInfo.WorkingSetSize, sampled every 0.25 s at the first displayed startup-frame counter >=250; these are endpoint samples, not clipped peaks. The actual counters differ slightly because of polling:

Pair (order) Without PR: resident MiB / counter With PR: resident MiB / counter
1 (without, with) 3903.1 / 255 3706.3 / 251
2 (with, without) 3859.0 / 253 3736.8 / 251
3 (without, with) 3875.0 / 251 3749.4 / 256

Median resident memory: 3875.0 -> 3736.8 MiB, an observed 138.2 MiB (3.57%) reduction. Ranges: 3859.0-3903.1 MiB without; 3706.3-3749.4 MiB with. Median process private commit was 2635.9 -> 2501.6 MiB. All six runs reached the checkpoint without a recorded fatal error. Storage-image instances varied from 17 to 19, entirely from dynamic 1024x1024 images; other descriptor counts matched. This and the counter variation make the checkpoint approximate. I have not normalized or subtracted that difference from the measurements.

These numbers cover early startup only. They do not establish menu/gameplay correctness, steady-state memory, or that the title fits within 8 GiB throughout. Both 8 GiB process guards remained enabled, along with 4 GiB available-RAM and 8 GiB commit-headroom guards; no run hit them. Logs and proprietary assets remain local. I've updated the PR description with this validation and its scope.

AI-assisted: Codex prepared the comparison and checked the results. This validation required no production-code change or new push; the earlier fixture correction was written by Qwen and reviewed by Codex.

@Scramblrrrr

Copy link
Copy Markdown
Contributor

Preparing an independent 007 Windows/RTX 5070 Ti cross-test of your current #3991 head 70015bd. All three authored commits applied cleanly with attribution on our older integration stack: https://github.com/Scramblrrrr/AnyPS5/tree/codex/first-light-lazy-snapshot-cross-test head a33e1e5. Source only, not built/staged; your storage_cpu_snapshot fixture and related graphics/recorded tests are next after the currently running quiet host-window #290 control. This will compare 4e40830 against that same base plus your lazy snapshots, not claim current-main/full-suite coverage. No competing upstream implementation. AI-assisted: Codex. No title data uploaded.

@Mouhand-Kaddo

Copy link
Copy Markdown
Contributor

Linux follow-up for head 70015bd, ported locally onto public main c36fd0a with the external #757/#758/#4288 stack and two local shader fixes. This is combined integration evidence, not an isolated performance A/B. Hardware is i7-13700K / RX 6900 XT, RADV Mesa 26.2.4, 31 GiB RAM.

The patch applied cleanly. Built runtime libs and agc_driver_recorder_tests. Existing Linux checks agc_storage_baseline_settled, agc_storage_upload_lifetime and agc_storage_upload_failure pass. agc_unit_shadow exits successfully but explicitly reports that unit shadows were not tested because host imports are compared, so I do not count it as coverage. The new agc_storage_cpu_snapshot regression is Windows-only and was not run here.

Demon's Souls passes startup shader registration and reaches texture loading, but this combined run still stops at our available-RAM watchdog (2.53 GiB remaining), before a main menu. No memory reduction or menu fix from this PR is established. A separate disposable-buffer probe confirms that this host's udmabuf size_limit_mb=64 rejects a 64 MiB +4096-byte import with EINVAL while a 4096-byte control succeeds. The title's several much larger import requests therefore remain an independent constraint.

No game assets were copied or modified, and no kernel settings were changed for these results. Testing performed with AI assistance.

@Scramblrrrr

Copy link
Copy Markdown
Contributor

Windows port efcd899 (older 4e40830 integration base) now passes eight native tests, no skips: storage_cpu_snapshot, storage_baseline_settled, storage_upload_lifetime/failure, graphics, sampled_cache_budget, draw_cache_reuse ON/OFF. New snapshot fixture passes on real NVIDIA host imports. This older base has a private StorageTexture constructor, so I changed the fixture's two make_shared calls to StorageTexture::Create; production lazy-snapshot code is unchanged. Branch: https://github.com/Scramblrrrr/AnyPS5/tree/codex/first-light-lazy-snapshot-cross-test . Graphics SHA256 2D6144562ED06C779E803C690A3F21AE0A2DB730FB78068FE33C023F2F18C254. Game test next, no memory/performance gain claimed yet. AI-assisted: Codex. Not full current-main/full-suite coverage.

@Scramblrrrr

Copy link
Copy Markdown
Contributor

#3991 Windows follow-up efcd899/SHA2D614456: rendered title frame865 1.68 FPS, private19.45 decimal GB, versus preceding #290 title1.61/20.08. Not a clean A/B: previous title had effects On; current saved effects-Off settings expected, not rechecked in UI; cache warmer, camera/timing differ. No attributable FPS improvement claim.

Campaign Resume now reproduces the runtime-table unsupported operation at shader0x3001136900 stage4 pc0x54 (descriptor0x3f00080260 etc.). It then terminates, rather than the RAM guard firing, on: compute shader 0x3004eb3700: AGC graphics: vkAllocateMemory buffer: allocation=2359296000 memoryType=3 reclaimed=627897488 initialResult=-2 attempts=2: Vulkan result -2. Final sampled private20.34GB, working set6.15GB, free physical5.48GB after three bounded trims; GPU dedicated sample~7585MiB of16303MiB. Those samples do not prove simple dedicated-VRAM saturation. Investigating allocation origin/memory type before blaming capacity or a particular patch. Older controls ended sooner at free-RAM guard. No gameplay/playable-speed claim; no title data uploaded. IR-reclaim probe is now building, not staged. AI-assisted: Codex.

@Sanjaysrinivas

Copy link
Copy Markdown
Contributor Author

@Scramblrrrr @Mouhand-Kaddo Thanks for the independent follow-ups. The Windows port's eight native passes, including storage_cpu_snapshot on real host imports, add useful integration coverage. The Linux checks are useful too; I agree that the Windows-only fixture and the skipped shadow check should not be counted as Linux coverage.

The reported title runs use additional patches and different settings/cache states, so they do not isolate #3991's memory or FPS effect. The later 2,359,296,000-byte Vulkan buffer allocation failure also does not identify #3991 as its cause; allocation origin, memory type and lifetime need to be established first. I am keeping the PR's performance claim limited to the documented same-base early-startup A/B, with no menu, gameplay or whole-game memory claim. These reports do not currently call for a production-code change to this PR.

AI-assisted: Codex read the reports and prepared this response; no new code or model-worker inference was needed.

@Mouhand-Kaddo

Copy link
Copy Markdown
Contributor

Linux follow-up for the tested head 70015bd558ddb1c61943640443ef495404e351b1. Demon's Souls (PPSA01342) reached the main menu, with New Game and Settings visible in a native emulator frame and interaction confirmed by the user. Selecting New Game then produced a black screen; gameplay is not validated.

This was a combined integration stack: public-main snapshot c36fd0a0eb57c01866befd370c88329ca42df759, ported #757/#758, #4288, #3991, #4402, the descriptor-layout fix now in #4456, and a local split-descriptor-load correction. It is not an isolated success claim for this PR. The final menu run used GDB to investigate an earlier buffer descriptor uses an unsupported type abort. That earlier failure remains undiagnosed.

The earlier Linux storage baseline/upload lifetime/upload failure checks remain the focused evidence. I do not attribute the complete title result or a memory reduction to this PR alone.

Reproduction detail: the title run temporarily raised Linux udmabuf size_limit_mb from 64 to 2048 because larger GPU imports failed at the default limit. The user restored 64 afterward and readback confirmed it. Default shader optimization remained enabled. RX 6900 XT/RADV was receiving GPU work; CPU shader compilation was a major startup bottleneck. Game assets were accessed through an enforced read-only view of the Windows gaming drive, without copying the game or changing its inputs. Disposable test caches have now been removed. AI-assisted testing/report.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

The Windows job doesn't compile on 70015bd (https://github.com/boykopovar/AnyPS5/actions/runs/38259671911): tests/Recorder.cpp constructs a StorageTexture through std::construct_at, and the constructor StorageTexture(const Context&, TextureDetiler&, const GuestTextureResource&, uint32_t) is private. Linux built. Please fix that and rebase; the memory numbers and the snapshot test run are what was asked for.

@Mouhand-Kaddo

Copy link
Copy Markdown
Contributor

Retest on Linux using updated #4456 head 4f5f6d671cdb0ffd3a9c43eedbdf03e433e80ebe as the integration base. Its six focused PR checks pass three times each; the previous null-shader-module mock failure is reproduced on its parent and fixed on this head.

The title support stack remains #757/#758/#4288/#3991/#4402 plus the local grouped split-load correction. Five integration shader/graphics checks pass. Demon's Souls PPSA01342 rendered language/display settings and the online/offline prompt, then aborted with exit 134:

[videoout] presentation failed: compute shader 0x2489fbb00: runtime image descriptor is invalid

This run did not verify main menu. The earlier c36-based integration did reach it. I have not isolated which rebased-stack change causes the descriptor failure, so this is not a regression attribution to this PR. No memory guard/OOM event stopped the run. One brief debugger snapshot was taken during startup, then detached.

The temporary Linux udmabuf limit was again 2048 MiB for the title run and is now verified back at 64. Assets were read directly through an enforced read-only view of the Windows gaming drive, without copying the game. Original input hashes and timestamps are unchanged. AI-assisted testing/report.

@Sanjaysrinivas
Sanjaysrinivas force-pushed the perf/agc-lazy-storage-snapshot branch from 70015bd to d2ebb51 Compare October 12, 2026 21:48
@Sanjaysrinivas

Copy link
Copy Markdown
Contributor Author

Fixed in d2ebb51d2 and rebased onto main 584cc4c57. Both snapshot-fixture calls now use StorageTexture::Create.

Local Windows validation passed: the recorder fixture and 124 runtime libraries built successfully; nine Vulkan checks passed on RTX 4070 with core validation, no skips or validation errors. Conventions passed. The snapshot test confirms 0 retained bytes for watched direct uploads and 262,144 bytes for CPU fallback.

@github-actions

github-actions Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
#5211 core/libs/prx/libSceAgcDriver/CMakeLists.txt L971

@oneandonlydean
oneandonlydean merged commit d638e02 into boykopovar:main Oct 13, 2026
8 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agc libSceAgc* build

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants