Prebuilding Architecture V2 - Phase 1 and Phase 2 #20

Open
github-bot wants to merge 20 commits from github-bot/gh-20 into main AGit
Owner

@⁠VictoryX-dev on GitHub · 2026-12-03 09:43 UTC · original
VictoryX-dev:arch/prebuilding-overhaul → main · +9846 −291 · 38 files · 20 commits · draft

Pull Request: Prebuilding Architecture Overhaul (VICTORY_PREBUILD_V2)

Branch: arch/prebuilding-overhaul (isolated from main; preserves existing public implementation as rollback baseline via VICTORY_PREBUILD_V2=0 default)
License: GPL-3.0-or-later (upstream attribution preserved)


Summary

This PR investigates VictoryX's existing command-list prebuilding and resource preparation subsystem (victory-gpu) and introduces Prebuilding Architecture v2 (victory-prebuild + reversible victory-gpu/src/prebuild_v2.rs integration behind VICTORY_PREBUILD_V2=1).

Root Causes Confirmed in Existing main Implementation

  1. Tight coupling of persistent command recordings with dynamic backing & mutable execution state (list.rs, host.rs, draw.rs):
    • list::submitted_recording retains HostList and RecordingMemory (RootSlots, _uploads) until explicit Reset()/Release() because concrete host GPU VAs are eagerly baked at recording time.
    • HostList bundles immutable translated commands with mutable per-submission state (prelude, scratch, budget, backs, last_late), forcing replay::execute_repeated to split batches and replay::prepare to stall the submission lane waiting for landed_through().
  2. Overlapping loose window allocations & ~42% duplicated page copies (shadow.rs, host.rs):
    • shadow::loose keys loose windows by (start, len). Overlapping sized windows and staggered root-view tails (TAIL_STEP = 256 KiB) create multiple independent committed buffers and Copied::pages tables over the same 4 MiB guest cells.
    • Host::submit keys refresh spans by Arc::as_ptr(shadow), copying the same dirty 64 KiB pages once per overlapping window and walking ~28,000 raw Steps/frame across 4–5 passes.
  3. Geometry corruption / stale draw inputs (host/draw_inputs.rs, shadow.rs, host.rs):
    • host/draw_inputs.rs stores only a single latest: Option<ExactWrite> per list (same-list place_copy only), missing multiple disjoint copies and all cross-list / cross-submission GPU producers.
    • shadow::copy_stale stamps copied.pages[i] = now before take_all, permanently caching zeros whenever copy_mapped falls back to read_unread during a concurrent remap or unmapped hole (VICTORY_SOURCE_RETRY defaults off).

Architectural Changes

1. New Internal Crate: runtime/crates/victory-prebuild

  • page_store.rs (PageStore / CanonicalSegment / ExecutionLease):
    • Canonical non-overlapping 4 MiB aligned loose segments (SegmentKey, canonical_loose_span) with per-64 KiB CanonicalPageState and 16-bit 4 KiB subpage bitmasks.
    • Monotonic ABA-free BackingId + backing_gen + mapping_gen.
    • PageValidity::TransientZero: failed/unmapped reads substitute zeros for the current draw only and are never stamped fresh.
    • Fence-scoped ExecutionLease handles: idle closed templates hold zero strong leases, allowing full reclamation of unleased segments via reclaim_idle().
  • coherence.rs (CoherenceTracker):
    • Interval-partitioned BTreeMap<u64, AuthoritativeWrite> tracking multiple simultaneous ExactGpuCopy and GpuShaderUav producers across within-list, cross-list, and cross-submission boundaries.
    • Clean interval splitting on partial overwrites, superseding on CPU copies (record_cpu_overwrite), immediate invalidation on guest remaps (invalidate_remap), and fence-based retirement (retire_through).
    • Explicit InputResolution::RequiresSync when partial GPU overwrites prevent safe whole-range aliasing.
  • template.rs (CompiledCommandTemplate / TemplateBuilder):
    • Compiled at Close() off the submitting thread into hazard-ordered PrepPhases and pre-sorted, coalesced all_read_pages: Box<[CanonicalPageRange]>.
    • Stores dynamic bindings with non-owning BackingHints (zero idle backing retention) and classifies ReplayCapability::ConcurrentSafe vs SerializedSharedTarget.
  • planner.rs (SubmissionPlanner / EphemeralSlotPool / SubmitSnapshot / LeaseManager):
    • Single-pass linear merge across templates using reusable PlannerScratch buffers to produce minimal coalesced write-watch queries and strictly deduplicated canonical page refresh jobs.
    • Per-execution EphemeralSlotPool eliminates stalls on repeated concurrent-safe template executions.
    • Per-submission SubmitSnapshot isolates dynamic CPU ring overwrites without poisoning PageStore.
    • LeaseManager drops all strong leases and returns ephemeral slots immediately on GPU fence retirement.

2. Reversible Windows D3D12 Integration in victory-gpu (VICTORY_PREBUILD_V2)

Gated behind VICTORY_PREBUILD_V2=1 (off by default, A/B-capable in diagnostics builds, documented in docs/RUNTIME_SWITCHES.md):

  • prebuild_v2.rs: bridges PrebuildRuntime into victory-gpu using Weak<Shadow> (no extra retention).
  • shadow.rs: routes loose() onto canonical 4 MiB keys (canonical_loose_key), propagates guest remaps (in_place_let_go → on_guest_remap), and guards copy_stale against permanently caching transient zero reads.
  • host.rs: compiles CompiledCommandTemplate at HostList::close(), uses single-pass merge_watch_ranges in Host::submit(), enables source_retry and tracks SOURCE_ZEROS, notifies CoherenceTracker on Step::Copy and Step::GpuWrite, and retires fences in bury().
  • host/place.rs & host/draw_inputs.rs: publishes exact GPU copies into CoherenceTracker and resolves multi-write and cross-list draw-input aliases.
  • host/replay.rs: skips the replay::prepare lane stall for immutable ConcurrentSafe lists with no mutable prelude/readback/budget state.

Verification & Measured Results

Executed Tests & Checks (Linux host + Windows cross-check)

  • cargo test -p victory-prebuild: 8 / 8 passed (memory ownership & zero idle retention + post-eviction rebind, repeated concurrent & serialized execution, overlapping views & 4 KiB subpage tracking, multi-copy & cross-list aliasing + partial sync + CPU split + remap, 8-thread concurrent stress test, isolated submit snapshots & TransientZero recovery, 2,000-round randomized coalesce_page_ranges oracle test, overflow bounds & cross-submission coherence).
  • cargo clippy -p victory-prebuild --all-targets -- -D warnings: 0 warnings.
  • cargo check -p victory-gpu --target x86_64-pc-windows-gnu --tests (default & --features diagnostics): passed with 0 errors and 0 new warnings.
  • cargo test -p xtask: 0 violations on any new/modified switch or file (VICTORY_PREBUILD_V2 passes switch-doc check; all new victory-prebuild and doc files pass asset policy; 2 pre-existing upstream main failures remain untouched: host.rs pre-existing size > 640 KiB and 6 pre-existing undocumented switches in unrelated docs).

Reproducible Synthetic Benchmarks (cargo run --release -p victory-prebuild --example prebuild_bench)

Important: These are measured Linux CPU synthetic benchmark results, NOT Windows or GPU hardware gameplay measurements.

Synthetic Workload (calibrated to VictoryX telemetry) Legacy Model Prebuild V2 Measured Delta
Heavy-scene frame prep (200 lists, 28,000 steps, 1,105 dirty pages) 10.134 ms 4.160 ms 2.44× faster (0.705 ms/worker close-time across 8 workers)
Dirty page copies / frame 2,568 1,105 57.0% duplicate copies eliminated
Write-watch query spans / frame 512 64 87.5% fewer query spans
Overlapping loose window memory (658 × 4 MiB guest cells) 5,390 MiB (53.9% overlap) 2,632 MiB (0.0% overlap) 51.2% less allocated memory
Idle retention (200 closed lists never reset, post-fence) 1,644 MiB pinned 0 MiB segments (106.5 KiB metadata) 100% idle backing reclaimable
Repeated execution (100 runs of 20 closed lists) 4 splits + 4 stalls 0 splits, 80 concurrent replays (45.4 µs) Zero stalls on concurrent-safe replays
Traversal burst + cross-list GPU aliasing (64 areas) 128 / 128 missed 128 / 128 resolved (0.562 ms) 100% cross-list draw-input coherence

Remaining Windows & GPU Hardware Validation Requirements

No Windows or GPU hardware tests were executed in this Linux environment. Before flipping VICTORY_PREBUILD_V2 on by default:

  1. Run native cargo test --workspace on Windows (x86_64-pc-windows-msvc).
  2. Run D3D12 hardware/WARP fixtures (draw::geometry_alias_tests, host::prep_pipeline::tests::hardware_refresh_wave_*, shadow_tail_tests, host::refresh_tests) with VICTORY_PREBUILD_V2=0 and =1.
  3. Validate with VICTORY_D3D12_DEBUG=1 and VICTORY_PREBUILD_V2=1 (zero D3D12 debug-layer lifetime/state errors).
  4. Run controlled gameplay A/B sessions (VICTORY_AB, VICTORY_XFER=2, VICTORY_FRAME_METRICS=1, VICTORY_STALE_DRAWS=1, VICTORY_MEM_LINE_S=10) across AMD RDNA, NVIDIA, and Intel GPUs.
  5. Follow-up Phase 2 on Windows: retain compact thin::Recording word streams on SubmittedRecording so evicted idle Windows D3D12 command lists can re-materialize after RootSlots release (unlocking the full idle D3D12 window eviction already verified in victory-prebuild).
**@⁠VictoryX-dev** on GitHub · 2026-12-03 09:43 UTC · [original](https://github.com/VictoryX-dev/VictoryX/pull/20) `VictoryX-dev:arch/prebuilding-overhaul` → `main` · +9846 −291 · 38 files · 20 commits · draft # Pull Request: Prebuilding Architecture Overhaul (`VICTORY_PREBUILD_V2`) **Branch:** `arch/prebuilding-overhaul` (isolated from `main`; preserves existing public implementation as rollback baseline via `VICTORY_PREBUILD_V2=0` default) **License:** GPL-3.0-or-later (upstream attribution preserved) --- ## Summary This PR investigates VictoryX's existing command-list prebuilding and resource preparation subsystem (`victory-gpu`) and introduces **Prebuilding Architecture v2** (`victory-prebuild` + reversible `victory-gpu/src/prebuild_v2.rs` integration behind `VICTORY_PREBUILD_V2=1`). ### Root Causes Confirmed in Existing `main` Implementation 1. **Tight coupling of persistent command recordings with dynamic backing & mutable execution state (`list.rs`, `host.rs`, `draw.rs`):** - `list::submitted_recording` retains `HostList` and `RecordingMemory` (`RootSlots`, `_uploads`) until explicit `Reset()`/`Release()` because concrete host GPU VAs are eagerly baked at recording time. - `HostList` bundles immutable translated commands with mutable per-submission state (`prelude`, `scratch`, `budget`, `backs`, `last_late`), forcing `replay::execute_repeated` to split batches and `replay::prepare` to stall the submission lane waiting for `landed_through()`. 2. **Overlapping loose window allocations & ~42% duplicated page copies (`shadow.rs`, `host.rs`):** - `shadow::loose` keys loose windows by `(start, len)`. Overlapping sized windows and staggered root-view tails (`TAIL_STEP = 256 KiB`) create multiple independent committed buffers and `Copied::pages` tables over the same 4 MiB guest cells. - `Host::submit` keys refresh spans by `Arc::as_ptr(shadow)`, copying the same dirty 64 KiB pages once per overlapping window and walking ~28,000 raw `Step`s/frame across 4–5 passes. 3. **Geometry corruption / stale draw inputs (`host/draw_inputs.rs`, `shadow.rs`, `host.rs`):** - `host/draw_inputs.rs` stores only a single `latest: Option<ExactWrite>` per list (same-list `place_copy` only), missing multiple disjoint copies and all cross-list / cross-submission GPU producers. - `shadow::copy_stale` stamps `copied.pages[i] = now` *before* `take_all`, permanently caching zeros whenever `copy_mapped` falls back to `read_unread` during a concurrent remap or unmapped hole (`VICTORY_SOURCE_RETRY` defaults off). --- ## Architectural Changes ### 1. New Internal Crate: `runtime/crates/victory-prebuild` - **`page_store.rs` (`PageStore` / `CanonicalSegment` / `ExecutionLease`):** - Canonical non-overlapping 4 MiB aligned loose segments (`SegmentKey`, `canonical_loose_span`) with per-64 KiB `CanonicalPageState` and 16-bit 4 KiB subpage bitmasks. - Monotonic ABA-free `BackingId` + `backing_gen` + `mapping_gen`. - `PageValidity::TransientZero`: failed/unmapped reads substitute zeros for the current draw only and are **never** stamped fresh. - Fence-scoped `ExecutionLease` handles: idle closed templates hold zero strong leases, allowing full reclamation of unleased segments via `reclaim_idle()`. - **`coherence.rs` (`CoherenceTracker`):** - Interval-partitioned `BTreeMap<u64, AuthoritativeWrite>` tracking multiple simultaneous `ExactGpuCopy` and `GpuShaderUav` producers across within-list, cross-list, and cross-submission boundaries. - Clean interval splitting on partial overwrites, superseding on CPU copies (`record_cpu_overwrite`), immediate invalidation on guest remaps (`invalidate_remap`), and fence-based retirement (`retire_through`). - Explicit `InputResolution::RequiresSync` when partial GPU overwrites prevent safe whole-range aliasing. - **`template.rs` (`CompiledCommandTemplate` / `TemplateBuilder`):** - Compiled at `Close()` off the submitting thread into hazard-ordered `PrepPhase`s and pre-sorted, coalesced `all_read_pages: Box<[CanonicalPageRange]>`. - Stores dynamic bindings with non-owning `BackingHint`s (zero idle backing retention) and classifies `ReplayCapability::ConcurrentSafe` vs `SerializedSharedTarget`. - **`planner.rs` (`SubmissionPlanner` / `EphemeralSlotPool` / `SubmitSnapshot` / `LeaseManager`):** - Single-pass linear merge across templates using reusable `PlannerScratch` buffers to produce minimal coalesced write-watch queries and strictly deduplicated canonical page refresh jobs. - Per-execution `EphemeralSlotPool` eliminates stalls on repeated concurrent-safe template executions. - Per-submission `SubmitSnapshot` isolates dynamic CPU ring overwrites without poisoning `PageStore`. - `LeaseManager` drops all strong leases and returns ephemeral slots immediately on GPU fence retirement. ### 2. Reversible Windows D3D12 Integration in `victory-gpu` (`VICTORY_PREBUILD_V2`) Gated behind `VICTORY_PREBUILD_V2=1` (off by default, A/B-capable in diagnostics builds, documented in `docs/RUNTIME_SWITCHES.md`): - `prebuild_v2.rs`: bridges `PrebuildRuntime` into `victory-gpu` using `Weak<Shadow>` (no extra retention). - `shadow.rs`: routes `loose()` onto canonical 4 MiB keys (`canonical_loose_key`), propagates guest remaps (`in_place_let_go` → `on_guest_remap`), and guards `copy_stale` against permanently caching transient zero reads. - `host.rs`: compiles `CompiledCommandTemplate` at `HostList::close()`, uses single-pass `merge_watch_ranges` in `Host::submit()`, enables `source_retry` and tracks `SOURCE_ZEROS`, notifies `CoherenceTracker` on `Step::Copy` and `Step::GpuWrite`, and retires fences in `bury()`. - `host/place.rs` & `host/draw_inputs.rs`: publishes exact GPU copies into `CoherenceTracker` and resolves multi-write and cross-list draw-input aliases. - `host/replay.rs`: skips the `replay::prepare` lane stall for immutable `ConcurrentSafe` lists with no mutable prelude/readback/budget state. --- ## Verification & Measured Results ### Executed Tests & Checks (Linux host + Windows cross-check) - `cargo test -p victory-prebuild`: **8 / 8 passed** (memory ownership & zero idle retention + post-eviction rebind, repeated concurrent & serialized execution, overlapping views & 4 KiB subpage tracking, multi-copy & cross-list aliasing + partial sync + CPU split + remap, 8-thread concurrent stress test, isolated submit snapshots & `TransientZero` recovery, 2,000-round randomized `coalesce_page_ranges` oracle test, overflow bounds & cross-submission coherence). - `cargo clippy -p victory-prebuild --all-targets -- -D warnings`: **0 warnings**. - `cargo check -p victory-gpu --target x86_64-pc-windows-gnu --tests` (default & `--features diagnostics`): **passed with 0 errors and 0 new warnings**. - `cargo test -p xtask`: **0 violations** on any new/modified switch or file (`VICTORY_PREBUILD_V2` passes switch-doc check; all new `victory-prebuild` and doc files pass asset policy; 2 pre-existing upstream `main` failures remain untouched: `host.rs` pre-existing size > 640 KiB and 6 pre-existing undocumented switches in unrelated docs). ### Reproducible Synthetic Benchmarks (`cargo run --release -p victory-prebuild --example prebuild_bench`) > **Important:** These are **measured Linux CPU synthetic benchmark results**, NOT Windows or GPU hardware gameplay measurements. | Synthetic Workload (calibrated to VictoryX telemetry) | Legacy Model | Prebuild V2 | Measured Delta | | :--- | ---: | ---: | :--- | | Heavy-scene frame prep (200 lists, 28,000 steps, 1,105 dirty pages) | `10.134 ms` | `4.160 ms` | **`2.44×` faster** (`0.705 ms`/worker close-time across 8 workers) | | Dirty page copies / frame | `2,568` | `1,105` | **`57.0%` duplicate copies eliminated** | | Write-watch query spans / frame | `512` | `64` | **`87.5%` fewer query spans** | | Overlapping loose window memory (658 × 4 MiB guest cells) | `5,390 MiB` (`53.9%` overlap) | `2,632 MiB` (`0.0%` overlap) | **`51.2%` less allocated memory** | | Idle retention (200 closed lists never reset, post-fence) | `1,644 MiB` pinned | `0 MiB` segments (`106.5 KiB` metadata) | **`100%` idle backing reclaimable** | | Repeated execution (100 runs of 20 closed lists) | `4` splits + `4` stalls | `0` splits, `80` concurrent replays (`45.4 µs`) | **Zero stalls on concurrent-safe replays** | | Traversal burst + cross-list GPU aliasing (64 areas) | `128 / 128` missed | `128 / 128` resolved (`0.562 ms`) | **100% cross-list draw-input coherence** | --- ## Remaining Windows & GPU Hardware Validation Requirements **No Windows or GPU hardware tests were executed in this Linux environment.** Before flipping `VICTORY_PREBUILD_V2` on by default: 1. Run native `cargo test --workspace` on Windows (`x86_64-pc-windows-msvc`). 2. Run D3D12 hardware/WARP fixtures (`draw::geometry_alias_tests`, `host::prep_pipeline::tests::hardware_refresh_wave_*`, `shadow_tail_tests`, `host::refresh_tests`) with `VICTORY_PREBUILD_V2=0` and `=1`. 3. Validate with `VICTORY_D3D12_DEBUG=1` and `VICTORY_PREBUILD_V2=1` (zero D3D12 debug-layer lifetime/state errors). 4. Run controlled gameplay A/B sessions (`VICTORY_AB`, `VICTORY_XFER=2`, `VICTORY_FRAME_METRICS=1`, `VICTORY_STALE_DRAWS=1`, `VICTORY_MEM_LINE_S=10`) across AMD RDNA, NVIDIA, and Intel GPUs. 5. Follow-up Phase 2 on Windows: retain compact `thin::Recording` word streams on `SubmittedRecording` so evicted idle Windows D3D12 command lists can re-materialize after `RootSlots` release (unlocking the full idle D3D12 window eviction already verified in `victory-prebuild`).
github-bot locked as GitHub sync and limited conversation to collaborators 2026-12-06 00:21:13 +00:00
This pull request can be merged automatically.
You are not authorized to merge this pull request.
View command line instructions

Checkout

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

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-20'
git switch 'github-bot/gh-20'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-20'
git switch 'github-bot/gh-20'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-20'
git switch 'main'
git merge --squash 'github-bot/gh-20'
git switch 'main'
git merge --ff-only 'github-bot/gh-20'
git switch 'main'
git merge 'github-bot/gh-20'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No reviewers
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/VictoryX-dev--VictoryX!20
No description provided.