From 04a6c5a01cfbd18018f4a207aaaad4d34c8dd653 Mon Sep 17 00:00:00 2001 From: wish131400 <2898869317@qq.com> Date: Sat, 28 Nov 2026 17:25:46 +0800 Subject: [PATCH 1/3] gpu: trace descriptor provenance with a GPU-written Mesh fixture Integrate the original contribution from PR #3321, including the author's subsequent conflict resolution, onto main 158ef79422f296c48873bfe8123e1e040125dc0a. Original authored commit: 42a185536bfd5e9df81d786d55fceb48046f1b32 Original resolved PR head: 029dfefef4c273b5d9c5565fbff1ee2acfd9a3ca Refs #3310 and #3321. --- CMakePresets.json | 2 +- docs/experiments/mesh-argument-provenance.md | 206 ++++++++++++++ docs/startup-runtime.md | 1 + src/startup_stubs/d3d12_capture.inl | 57 ++++ tests/cmake/mesh_argument_provenance.cmake | 10 + tests/startup_indirect_draw_indexed.cpp | 7 +- tests/startup_mesh_argument_provenance.inl | 268 ++++++++++++++++++ .../startup_mesh_argument_provenance_check.py | 136 +++++++++ 8 files changed, 685 insertions(+), 2 deletions(-) create mode 100644 docs/experiments/mesh-argument-provenance.md create mode 100644 tests/cmake/mesh_argument_provenance.cmake create mode 100644 tests/startup_mesh_argument_provenance.inl create mode 100644 tests/startup_mesh_argument_provenance_check.py diff --git a/CMakePresets.json b/CMakePresets.json index 6bd4804f08..47adfbbcf4 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -50,7 +50,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" + "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_mesh_argument_provenance_warp|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" } } }, diff --git a/docs/experiments/mesh-argument-provenance.md b/docs/experiments/mesh-argument-provenance.md new file mode 100644 index 0000000000..1666ee712c --- /dev/null +++ b/docs/experiments/mesh-argument-provenance.md @@ -0,0 +1,206 @@ +# GPU-written Mesh arguments and descriptor history + +Refs [#3310](https://github.com/R0Y00/Xbox2Windows/issues/3310). +This adds a source-built reproducer and an opt-in descriptor diagnostic. It +does not establish the issue's matched integration acceptance or repair the +zero launch count observed there. + +## What the fixture measures + +`startup_mesh_argument_provenance_hardware` uses the existing +`startup_indirect_draw_indexed` executable in `mesh-provenance` mode. All shader +and buffer inputs come from repository source. No external capture, shader +cache, game content or fitted parameters are required. + +The fixture follows this chain: + +1. Create a raw buffer SRV in a CPU-only guest descriptor heap. Copy it to a + shader-visible heap, overwrite the source SRV, then copy the updated view. + The guest token and desktop shadow record have different identities. +2. A source-built Compute dispatch writes the scalar input: `2` at byte 16 + and `0` at byte 32. Copy those bytes to readback before the updater. After + fence 1 completes, verify that this GPU write supplied the nonzero input. +3. A second Compute dispatch reads `launch.Load(0)` through the copied SRV + and writes `(X,1,1)` into the argument buffer at byte 4. Copy the argument + buffer to a separate readback allocation and complete fence 1. +4. In a separate submission on the same DIRECT queue, copy that buffer again + immediately before the guest command-list slot 61 `ExecuteIndirect` call. + Complete fence 2 before mapping the second snapshot. Report the exact + consumed 12-byte interval, backing resource and byte offset. +5. Read back the scene-color target after fence 3. The positive case checks + every pixel of the 4 by 2 RGBA8 target: left red, right green. No compositor + participates. Check the argument buffer's leading, trailing and neighboring + record guards, device-removal status and debug-layer errors too. + +The positive oracle requires the same resource **and** offset, identical +12-byte records with X greater than zero, intact guards and all eight expected +pixels. Each negative control must fail that same oracle while satisfying its +own expected record and pixel results: + +| Case | Post-write record at byte 4 | Pre-consume record | Changed pixels | +|---|---|---|---| +| `positive` | `(2,1,1)` | byte 4: `(2,1,1)` | 8/8 | +| `missing-copy` | `(0,1,1)` | byte 4: `(0,1,1)` | 0/8 | +| `stale-copy` | `(0,1,1)` | byte 4: `(0,1,1)` | 0/8 | +| `wrong-srv-offset` | `(0,1,1)` | byte 4: `(0,1,1)` | 0/8 | +| `wrong-argument-offset` | `(2,1,1)` | byte 20: `(0,1,1)` | 0/8 | + +The missing-copy destination is explicitly initialized with a null SRV. The +stale-copy case copies the original view at byte 32, then overwrites the source +to byte 16 without copying again. The wrong-SRV case copies a view still +pointing at byte 32. The wrong-argument case consumes a valid zero record in +the same resource, so a same-resource-only comparison would miss the error. +The Python driver also repeats the positive case with history tracing disabled +and requires the same argument and pixel results without history lines. + +## Runtime diagnostic + +Set `X2W_D3D12_DESCRIPTOR_HISTORY=1` **before process startup**. The setting is +cached. Output follows the usual trap logger, stderr unless `X2W_TRAP_LOG` is +set. It emits `x2w-descriptor-history` lines for intercepted view creation into +tracked shadow slots and intercepted descriptor copies: + +| Field | Meaning | +|---|---| +| `seq` | CPU shadow-publication order, serialized by `note_lock`; not GPU execution order | +| `op` | `create` or `copy`; a create with a different `old`/`new` ID is an overwrite | +| `guest`, `desktop`, `source` | Destination guest address, destination desktop handle, and source guest address for a copy | +| `old`, `new` | Shadow IDs before and after publication; 0 means unknown, otherwise the view-record index plus 1 | +| `slot` | Recorded device view-creation slot, for example 18 for SRV | +| `resource`, `backing` | Recorded guest resource identity and its unwrapped desktop backing resource | +| `first`, `stride` | Buffer SRV `FirstElement` and `StructureByteStride`; raw SRV byte offset is `first * 4` | +| `materialized` | Whether the recorded view was materialized on the desktop | +| `guest_bytes`, `guest_read`, `guest_before` | Requested token sample size, successful complete read flag, and up to eight hexadecimal DWORDs **before this operation writes the guest token** | + +SRV tokens occupy 32 bytes. Sampler tokens use the shorter sampler stride; the +remaining printed words are zero padding. Only a sample with `guest_read=1` +can be interpreted. Guest token word 1 is a zero-based view-record index, +whereas `old`/`new` use one-based IDs. Native desktop descriptor bytes are +opaque and are not read as guest tokens. + +This diagnostic is intended for the fixture and short startup reproductions +only. It is not a complete-history capture for a real integration run: +initialization can exhaust its 8,192-event process budget, and each copied +descriptor counts as one event, so a large copy can consume the budget by +itself. It emits one `truncated limit=8192` line at that limit. Later producer +history needs a separately targeted diagnostic; no filter, delayed start or +rolling history is implemented here. With +`X2W_D3D12_VIEW_CONTENT_TOKENS=1`, parked view records are reused, so the same +`old`/`new` ID can refer to different views at different sequence points. +Arbitrary guest CPU stores or `memcpy` operations are not intercepted. View creations +without a tracked desktop shadow slot and view-record allocation failures do +not produce creation events. The sequence describes shadow updates; guest +token memory writes occur afterward and concurrently reused slots still +require the caller's synchronization. + +This switch adds no GPU commands, barriers, readbacks or waits. The source-built +fixture supplies its own fenced GPU snapshots. When the switch is unset, it +does not sample guest memory or add the per-descriptor history loop. The +diagnostic changes neither descriptor-copy policy nor the rendering path. + +The fixture prints `provenance debug info_queue=present` or +`info_queue=absent` for each process. Only a present `ID3D12InfoQueue` supports +the debug-message check; an absent queue leaves pixel/argument checks active +but provides no evidence that the debug layer reported no errors. + +## Reproduce + +Use the ordinary Windows build prerequisites in +[CONTRIBUTING.md](../../CONTRIBUTING.md#build-and-test), including DXC and Python. +Mesh requires a capable adapter/runtime. On an older Windows installation, +configure the existing `OFFSCREEN_AGILITY_620_DIR` option with a local directory +containing the public Agility 620 `D3D12Core.dll` and `d3d12SDKLayers.dll`. +Neither DLL is part of this contribution. + +```powershell +. .\tools\dev.ps1 +cmake --preset dev +cmake --build --preset dev --target startup_indirect_draw_indexed startup_compute_binding_trace startup_view_alloc startup_view_census +ctest --preset dev --no-tests=error -j 1 -V -R '^startup_(mesh_argument_provenance_(warp|hardware)|indirect_mesh_(warp|hardware)|view_alloc_.*|view_census_.*|compute_binding_trace_warp)$' + +cmake --preset release +cmake --build --preset release --target startup_indirect_draw_indexed startup_compute_binding_trace startup_view_alloc startup_view_census +ctest --preset release --no-tests=error -j 1 -V -R '^startup_(mesh_argument_provenance_(warp|hardware)|indirect_mesh_(warp|hardware)|view_alloc_.*|view_census_.*|compute_binding_trace_warp)$' +``` + +To inspect the unfiltered diagnostic for one case: + +```powershell +$env:X2W_D3D12_DESCRIPTOR_HISTORY = '1' +$env:X2W_MESH_PROVENANCE_CASE = 'positive' +.\out\build\dev\startup_indirect_draw_indexed.exe hardware mesh-provenance +``` + +`startup_mesh_argument_provenance_warp` is included in the PR smoke-test preset. +Capability skips return 77 and must be reported separately from passes. + +## Local result and remaining integration work + +Tested on 28 November 2026, Windows 10 Pro build 19045, NVIDIA GeForce RTX +4070 Ti SUPER, driver `32.0.15.7270`, MSVC `19.43.34810`, DXC `1.9.2609`, +Agility SDK 620, D3D12 debug layer enabled. Build: this change on base +`32dc3d7c3cdc4be79afdad4cc04709e76d99a795`. + +Debug and Release each ran the 23 selected tests: 21 passed, zero failed, +and two capability skips (`startup_indirect_mesh_warp` and +`startup_mesh_argument_provenance_warp`, Mesh shaders unavailable on local +WARP). The hardware provenance test runs six processes: the positive case, +four negative controls and the positive case without tracing. All had the +expected records, pixel readback and descriptor history, with no debug-layer +ERROR/CORRUPTION messages or device removal. + +### Merge refresh verification, 30 November 2026 + +Retested the tree after merging main +`44a3ad5aa9c679cc039b8cb8275738dd6e4405d2` into PR head +`42a185536bfd5e9df81d786d55fceb48046f1b32`, using the same hardware, +driver, OS and toolchain above. The merge preserves both the provenance +fixture and main's native fixed-Mesh/MRT fixture, together with all current +PR smoke selections. + +Debug and Release builds of the four targets in the reproduction commands +passed. In each configuration the 23-test group again produced 21 passes, +zero failures and the same two WARP Mesh capability skips. All six hardware +provenance processes reported `info_queue=present`; the pixel, argument, +history and debug-message checks passed without device removal. + +The additional conflict-specific regression command was run in both presets: + +```powershell +ctest --preset dev --no-tests=error -j 1 -V -R '^native_fixed_mesh57(_mrt)?_(warp|hardware)$' +ctest --preset release --no-tests=error -j 1 -V -R '^native_fixed_mesh57(_mrt)?_(warp|hardware)$' +``` + +Each selected four tests: two hardware passes, zero failures and two WARP +Mesh capability skips. + +A local mutation changed the copy-history call in +`src/startup_stubs/d3d12_capture.inl` from +`trace_descriptor_history("copy", ...)` to +`trace_descriptor_history("create", ...)`. The Debug build succeeded and +the previously passing hardware provenance test failed its descriptor-copy +history assertion while the positive pixel check still observed 8/8 pixels. +The mutation was restored, the target rebuilt, and the hardware provenance +test passed again. No mutation is included in this change. + +Documentation links, bidirectional-control checks, Python AST syntax, CMake +preset JSON, PR-regex selection and diff whitespace checks also passed. + +### Remaining integration work + +The producers use desktop source-built HLSL on a native command list. View +creation/copy and the indirect Mesh consumer use the guest wrappers; queue +execution and fences are native. This does not exercise a translated gfx1013 +producer, guest queue preprocessing, XMem argument refresh, or the real +integration's root/attachment state. + +Issue #3310 remains open until a matched integration run identifies the actual +scalar-input write and descriptor history, reads identical nonzero records at +the same resource and offset after production and before consumption, and +observes a real Mesh submission changing scene color before composition. The +issue's reported 48 zero records were not reproduced by this fixture. No +matched integration configuration or capture is included in this change. +The native integration work in +[#3091](https://github.com/R0Y00/Xbox2Windows/pull/3091) and +[#3094](https://github.com/R0Y00/Xbox2Windows/pull/3094) was still open when this +result was recorded; it has not been substituted for a test of `main`. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 976e2f80ee..9bd9262103 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1871,6 +1871,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_D3D12_VIEW_DEFAULTS=all` or `=off` | `all` is experimental: UAV, RTV and DSV descriptions with `ViewDimension` 0 also get the resource's default view, which drops their requested format and component mapping. `off` skips the measured SRV case too. Unset, only SRVs of typed non-depth textures get the default view ([details](#unknown-and-mismatched-view-dimensions)) | | `X2W_DIAG_PLACED_INPUT=1` | For a refused draw input in a non-aliasing placed buffer, logs up to four lines per shader key and SRV index: resource, width, requested range, same-list copy tracking status, recorded ranges, up to 64 recorded buffer copies per resource, and observed translated UAV bindings and accepted UAV clears. Same-list tracking requires `X2W_TRANSLATED_INDIRECT_COPY_RANGES=1` and retains at most 64 ranges per list. UAV observations cover translated compute buffer outputs, translated pixel UAVs and accepted UAV clears, not all possible bindings or writes. Records are bounded to 4096 resources and 4096 shader/index pairs; resource pointer reuse may conflate observations. Recorded commands and bindings do not prove GPU execution or a write. | | `X2W_D3D12_VIEW_CENSUS=1` | diagnostic only: counts new distinct view records by device slot (a heartbeat line), and logs the record vector capacity and hash bucket count before either grows ([details](#d3d12-view-census)). Unset, nothing is counted or logged | +| `X2W_D3D12_DESCRIPTOR_HISTORY=1` | fixture/short-startup diagnostic only: logs the first 8,192 descriptor events, then truncates; it cannot establish a complete later integration history. Records guest token bytes, shadow IDs and backing identities. IDs can be reused with `X2W_D3D12_VIEW_CONTENT_TOKENS=1`; CPU order is separate from GPU execution ([fixture, controls and limits](experiments/mesh-argument-provenance.md)) | | `X2W_D3D12_VIEW_CONTENT_TOKENS=1` | opt-in: constant buffer views and buffer shader-resource views are written into title descriptor memory as tokens that carry the view itself instead of a record id, and their records are freed and reused once no shadow slot names them, so the record count stays bounded ([details](#d3d12-view-content-tokens)). Off under `X2W_D3D12_CAPTURE`. Unset, every view keeps an id token and records are never removed | | `X2W_D3D12_TABLE_LOCK=1` | opt-in: the resource, slot 133 placement and descriptor heap tables get their own lock, so the four lookups that read only them stop queueing on the view-record lock behind view creation and descriptor copies ([details](#d3d12-table-lock)). Unset, they take that lock as before | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 9e181eb612..a096fb6fef 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -701,6 +701,51 @@ void drop_unrecorded_view(const ViewRecord& record, bool materialized, const cha container, record.slot); } +// Opt-in, bounded descriptor provenance. Called with note_lock held: sequence is +// the order in which shadow updates are published, not GPU execution order. +// Guest bytes are sampled BEFORE this operation publishes its token/copy. +bool descriptor_history_enabled() +{ + static const bool enabled = x2w_local::env_on("X2W_D3D12_DESCRIPTOR_HISTORY"); + return enabled; +} +void trace_descriptor_history(const char* operation, u64 title, u64 desktop, u64 source, + std::uint32_t previous, std::uint32_t next, UINT token_bytes) +{ + if (!descriptor_history_enabled()) return; + static u64 sequence; + const u64 event = ++sequence; + if (event > 8192) { + if (event == 8193) log("x2w-descriptor-history truncated limit=8192"); + return; + } + const DWORD saved_error = GetLastError(); + std::uint32_t guest[8]{}; + const UINT guest_bytes = (std::min)(token_bytes, UINT{sizeof(guest)}); + SIZE_T copied = 0; + const bool readable = guest_bytes && title != desktop && ReadProcessMemory(GetCurrentProcess(), + reinterpret_cast(title), guest, guest_bytes, &copied) && copied == guest_bytes; + const ViewRecord* view = next && next - 1 < view_records().size() ? &view_records()[next - 1] : nullptr; + u64 first = 0; + UINT stride = 0; + if (view && view->slot == 18 && view->desc_bytes >= sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)) { + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + std::memcpy(&srv, view->desc, sizeof(srv)); + if (srv.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { + first = srv.Buffer.FirstElement; + stride = srv.Buffer.StructureByteStride; + } + } + log("x2w-descriptor-history seq=%llu op=%s guest=%llx desktop=%llx source=%llx old=%u new=%u " + "slot=%u resource=%llx backing=%llx first=%llu stride=%u materialized=%u guest_bytes=%u guest_read=%u " + "guest_before=%08x,%08x,%08x,%08x,%08x,%08x,%08x,%08x", + event, operation, title, desktop, source, previous, next, view ? view->slot : 0, + view ? view->resource : 0, view ? unwrap(view->resource) : 0, first, stride, + view && view_materialized()[next - 1] ? 1 : 0, guest_bytes, readable ? 1 : 0, + guest[0], guest[1], guest[2], guest[3], guest[4], guest[5], guest[6], guest[7]); + SetLastError(saved_error); +} + // A view is created: remembered by id; the id is also written into title-owned descriptor memory so // that copies the title makes there itself can be followed. void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_t desc_bytes, u64 dest_title, u64 dest_desktop, @@ -773,6 +818,8 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ } if (std::uint32_t* slot_ptr = shadow_slot(dest_desktop)) { const std::uint32_t prev = *slot_ptr; + trace_descriptor_history("create", dest_title, dest_desktop, 0, prev, record.id + 1, + slot == 22 ? x2w_startup::title_sampler_stride : 32u); *slot_ptr = record.id + 1; // The same view written to the same slot again keeps its id and changes no reference count. A different view // takes over the slot: the new record adds its refs, the previous materialized record drops its own. @@ -805,11 +852,21 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ } void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, UINT count, UINT increment) { + const bool history = descriptor_history_enabled(); + const UINT dest_stride = history ? title_descriptor_stride(dest_title, increment) : 0; + const UINT src_stride = history ? title_descriptor_stride(src_title, increment) : 0; AcquireSRWLockExclusive(¬e_lock); descriptors_copied += count; std::uint32_t dest_room = 0, src_room = 0; std::uint32_t* to = shadow_slot(dest_desktop, &dest_room); const std::uint32_t* from = shadow_slot(src_desktop, &src_room); + if (history) + for (UINT i = 0; i < count; ++i) { + const auto previous = to && i < dest_room ? to[i] : 0; + const auto next = to && count <= dest_room ? (from && count <= src_room ? from[i] : 0) : previous; + trace_descriptor_history("copy", dest_title + u64{i} * dest_stride, dest_desktop + u64{i} * increment, + src_title + u64{i} * src_stride, previous, next, dest_stride); + } if (to && count <= dest_room) { if (from && count <= src_room) { // Every copied-in view is now named by one more tracked slot; every view the destination named before is diff --git a/tests/cmake/mesh_argument_provenance.cmake b/tests/cmake/mesh_argument_provenance.cmake new file mode 100644 index 0000000000..1eedb0aff5 --- /dev/null +++ b/tests/cmake/mesh_argument_provenance.cmake @@ -0,0 +1,10 @@ +# Reuse the existing source-built mesh executable and its generated DXIL. +if(EXISTS "${INTAKE_PYTHON}") + foreach(adapter IN ITEMS warp hardware) + add_test(NAME startup_mesh_argument_provenance_${adapter} + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_mesh_argument_provenance_check.py" + "$" ${adapter}) + set_tests_properties(startup_mesh_argument_provenance_${adapter} PROPERTIES + TIMEOUT 120 SKIP_RETURN_CODE 77) + endforeach() +endif() diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 02b7c56c32..17529e29d9 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -2512,6 +2512,7 @@ bool fixed_mesh_create_contract(ID3D12Device* guest) #include "startup_mesh57_runtime.inl" } // namespace +#include "startup_mesh_argument_provenance.inl" static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* writer, const std::wstring& log_path) { @@ -3126,7 +3127,8 @@ int main(int argc, char** argv) try const bool count_control = argc == 3 && std::strcmp(argv[2], "count-control") == 0; if ((translated && !translated_indexed) || (argc == 3 && std::strcmp(argv[2], "draw") == 0)) kind = DrawKind::vertices; else if (argc == 3 && std::strcmp(argv[2], "rect") == 0) kind = DrawKind::rect; - else if (lease_arguments || console_mesh || desktop_as || runtime_mesh57 || (argc == 3 && std::strcmp(argv[2], "mesh") == 0)) + else if (lease_arguments || console_mesh || desktop_as || runtime_mesh57 || (argc == 3 && + (std::strcmp(argv[2], "mesh") == 0 || std::strcmp(argv[2], "mesh-provenance") == 0))) kind = DrawKind::mesh; else if (rect) kind = DrawKind::indexed_rect; else if (argc != 2 && !count_control && !translated_indexed && !lease_writer && !bucket_case && !stream_key_case && @@ -3850,6 +3852,9 @@ int main(int argc, char** argv) try ComPtr signature; check(guest->CreateCommandSignature(&signature_desc, nullptr, IID_PPV_ARGS(&signature)), "create guest draw signature"); + if (argc == 3 && std::strcmp(argv[2], "mesh-provenance") == 0) + return check_mesh_argument_provenance(device.Get(), guest.Get(), graphics.Get(), pso.Get(), signature.Get()) ? 0 : 1; + if (lease_arguments) { if (!lease_fixture) return 2; return check_mesh_indirect_xmem(device.Get(), guest.Get(), lease_xmem, info.Get(), log_path, diff --git a/tests/startup_mesh_argument_provenance.inl b/tests/startup_mesh_argument_provenance.inl new file mode 100644 index 0000000000..a51866f278 --- /dev/null +++ b/tests/startup_mesh_argument_provenance.inl @@ -0,0 +1,268 @@ +// Source-built descriptor -> compute writer -> indirect Mesh chain (Refs #3310). +// Included in startup_indirect_draw_indexed.cpp to reuse its real guest wrapper, +// placed-resource helper, Mesh shaders and complete pixel oracle. +bool check_mesh_argument_provenance(ID3D12Device* device, ID3D12Device* guest, + ID3D12RootSignature* graphics_root, IUnknown* graphics, ID3D12CommandSignature* signature) +{ + char setting[64]{}; + GetEnvironmentVariableA("X2W_MESH_PROVENANCE_CASE", setting, sizeof(setting)); + const std::string scenario = setting; + const bool missing = scenario == "missing-copy"; + const bool stale = scenario == "stale-copy"; + const bool wrong_srv = scenario == "wrong-srv-offset"; + const bool wrong_argument = scenario == "wrong-argument-offset"; + if (!scenario.empty() && scenario != "positive" && !missing && !stale && !wrong_srv && !wrong_argument) + return false; + const char* label = scenario.empty() ? "positive" : scenario.c_str(); + constexpr UINT64 input_offset = 16; + constexpr UINT64 written_offset = 4; + const UINT64 consumed_offset = wrong_argument ? 20 : written_offset; + const UINT expected_x = missing || stale || wrong_srv ? 0 : 2; + const UINT consumed_x = wrong_argument ? 0 : expected_x; + const Words seed{0xa5a5a5a5, 0, 1, 1, 0x5a5a5a5a, 0, 1, 1, 0x12345678}; + PlacedBuffer arguments(device, guest, sizeof(seed), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + PlacedBuffer input(device, guest, 64, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + const auto upload = make_buffer(device, sizeof(seed), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + void* memory = nullptr; + const D3D12_RANGE none{0, 0}; + check(upload->Map(0, &none, &memory), "map provenance seed"); + std::memcpy(memory, seed.data(), sizeof(seed)); + upload->Unmap(0, &none); + + constexpr char producer[] = R"( +ByteAddressBuffer launch : register(t0); +RWByteAddressBuffer data : register(u0); +[numthreads(1,1,1)] void seed_input() { data.Store(16, 2); data.Store(32, 0); } +[numthreads(1,1,1)] void update_args() { data.Store3(4, uint3(launch.Load(0), 1, 1)); } +)"; + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER parameters[2]{}; + parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + parameters[0].DescriptorTable = {1, &range}; + parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + const auto writer_root = create_root(device, {2, parameters}); + const auto pipeline = [&](const char* entry) { + ComPtr code, errors; + const HRESULT hr = D3DCompile(producer, sizeof(producer) - 1, nullptr, nullptr, nullptr, + entry, "cs_5_1", 0, 0, &code, &errors); + if (FAILED(hr) && errors) std::fprintf(stderr, "%s\n", static_cast(errors->GetBufferPointer())); + check(hr, entry); + D3D12_COMPUTE_PIPELINE_STATE_DESC desc{}; + desc.pRootSignature = writer_root.Get(); + desc.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + ComPtr result; + check(device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&result)), entry); + return result; + }; + const auto seed_pipeline = pipeline("seed_input"), update_pipeline = pipeline("update_args"); + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + ComPtr heap, source_heap; + check(guest->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap)), "create provenance descriptor heap"); + const D3D12_DESCRIPTOR_HEAP_DESC source_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1}; + check(guest->CreateDescriptorHeap(&source_desc, IID_PPV_ARGS(&source_heap)), "create CPU copy-source heap"); + const auto native_heap = native_object(device, guest, heap.Get()); + using Handle = UINT64 (WINAPI*)(IUnknown*, void*); + const UINT64 guest_cpu = slot(source_heap.Get(), 9)(source_heap.Get(), nullptr); + const UINT64 bound_cpu = slot(heap.Get(), 9)(heap.Get(), nullptr); + const UINT64 desktop_cpu = native_heap->GetCPUDescriptorHandleForHeapStart().ptr; + using View = void (WINAPI*)(IUnknown*, IUnknown*, const D3D12_SHADER_RESOURCE_VIEW_DESC*, UINT64, UINT64); + using Copy = void (WINAPI*)(IUnknown*, UINT, UINT64, UINT64, D3D12_DESCRIPTOR_HEAP_TYPE); + D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; + srv.Format = DXGI_FORMAT_R32_TYPELESS; + srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + srv.Buffer.NumElements = 1; + srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + const auto create_srv = [&](UINT index, UINT64 byte_offset, bool null_resource = false) { + srv.Buffer.FirstElement = byte_offset / 4; + slot(guest, 18)(guest, null_resource ? nullptr : input.wrapped.Get(), &srv, + index ? bound_cpu : guest_cpu, 0); + }; + // A known null destination makes the missing-copy control deterministic. + create_srv(1, 0, true); + create_srv(0, input_offset + 16); + if (!missing) slot(guest, 24)(guest, 1, bound_cpu, guest_cpu, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + create_srv(0, wrong_srv ? input_offset + 16 : input_offset); // overwrite the source + if (!missing && !stale) slot(guest, 24)(guest, 1, bound_cpu, guest_cpu, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + std::uint32_t tokens[2][8]{}; + std::memcpy(tokens[0], reinterpret_cast(guest_cpu), 32); + std::memcpy(tokens[1], reinterpret_cast(bound_cpu), 32); + std::printf("provenance descriptor case=%s guest=%llx desktop=%llx source=%llx " + "input=%p input_offset=%llu token_source=%08x,%u token_bound=%08x,%u\n", label, + bound_cpu, desktop_cpu, guest_cpu, + static_cast(input.native.Get()), wrong_srv || stale ? input_offset + 16 : missing ? 0 : input_offset, + tokens[0][0], tokens[0][1], tokens[1][0], tokens[1][1]); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + ComPtr queue; + ComPtr completion; + check(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue)), "create provenance DIRECT queue"); + check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&completion)), "create provenance fence"); + ComPtr snapshots[2]; + const auto input_snapshot = make_buffer(device, 64, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + Words observed[2]{}; + Words expected = seed; + expected[1] = expected_x; + const auto read_record = [&](UINT i) { + const D3D12_RANGE read{0, sizeof(seed)}; + check(snapshots[i]->Map(0, &read, &memory), "map provenance argument snapshot"); + std::memcpy(observed[i].data(), memory, sizeof(seed)); + snapshots[i]->Unmap(0, &none); + const UINT index = static_cast((i ? consumed_offset : written_offset) / 4); + std::printf("provenance record phase=%s resource=%p offset=%llu tuple=%u,%u,%u guards=%s\n", + i ? "pre-consume" : "post-write", static_cast(arguments.native.Get()), + i ? consumed_offset : written_offset, observed[i][index], observed[i][index + 1], observed[i][index + 2], + observed[i] == expected ? "intact" : "BAD"); + return observed[i] == expected; + }; + const auto wait = [&](UINT64 value, const char* phase) { + check(queue->Signal(completion.Get(), value), "signal provenance fence"); + const auto deadline = GetTickCount64() + 10000; + while (completion->GetCompletedValue() < value && GetTickCount64() < deadline) Sleep(1); + check(device->GetDeviceRemovedReason(), "provenance device completion"); + check(completion->GetCompletedValue() >= value ? S_OK : E_FAIL, "wait provenance fence"); + std::printf("provenance fence phase=%s queue=%p fence=%p value=%llu completed=%llu\n", + phase, static_cast(queue.Get()), static_cast(completion.Get()), value, + completion->GetCompletedValue()); + }; + { + ComputeCommands commands(device, queue.Get(), nullptr); + auto* list = commands.list.Get(); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(arguments.native.Get(), 0, upload.Get(), 0, sizeof(seed)); + transition(list, input.native.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list->SetComputeRootSignature(writer_root.Get()); + list->SetPipelineState(seed_pipeline.Get()); + list->SetComputeRootUnorderedAccessView(1, input.native->GetGPUVirtualAddress()); + std::printf("provenance input-write queue=%p resource=%p offset=%llu value=2 dispatch=1,1,1\n", + static_cast(queue.Get()), static_cast(input.native.Get()), input_offset); + list->Dispatch(1, 1, 1); + transition(list, input.native.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(input_snapshot.Get(), 0, input.native.Get(), 0, 64); + transition(list, input.native.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + ID3D12DescriptorHeap* heaps[]{native_heap.Get()}; + list->SetDescriptorHeaps(1, heaps); + auto bound = native_heap->GetGPUDescriptorHandleForHeapStart(); + list->SetComputeRootDescriptorTable(0, bound); + list->SetComputeRootUnorderedAccessView(1, arguments.native->GetGPUVirtualAddress()); + list->SetPipelineState(update_pipeline.Get()); + std::printf("provenance producer queue=%p resource=%p offset=%llu bytes=12 dispatch=1,1,1\n", + static_cast(queue.Get()), static_cast(arguments.native.Get()), written_offset); + list->Dispatch(1, 1, 1); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + snapshots[0] = make_buffer(device, sizeof(seed), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(snapshots[0].Get(), 0, arguments.native.Get(), 0, sizeof(seed)); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + transition(list, input.native.Get(), D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON); + check(list->Close(), "close provenance writer"); + ID3D12CommandList* lists[]{list}; + queue->ExecuteCommandLists(1, lists); + wait(1, "post-write"); + } + const D3D12_RANGE input_range{input_offset, input_offset + 20}; + check(input_snapshot->Map(0, &input_range, &memory), "map provenance scalar input"); + UINT launch = 0, adjacent = 0; + std::memcpy(&launch, static_cast(memory) + input_offset, sizeof(launch)); + std::memcpy(&adjacent, static_cast(memory) + input_offset + 16, sizeof(adjacent)); + input_snapshot->Unmap(0, &none); + std::printf("provenance input-record resource=%p offset=%llu value=%u adjacent_offset=%llu adjacent_value=%u\n", + static_cast(input.native.Get()), input_offset, launch, input_offset + 16, adjacent); + if (launch != 2 || adjacent != 0 || !read_record(0)) return false; + // Separate consumer submission. The second copy is immediately before the + // guest ExecuteIndirect and uses the exact resource/offset being consumed. + const D3D12_RESOURCE_DESC target_desc{D3D12_RESOURCE_DIMENSION_TEXTURE2D, 0, width, height, 1, 1, + format, {1, 0}, D3D12_TEXTURE_LAYOUT_UNKNOWN, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET}; + const D3D12_CLEAR_VALUE clear_value{format, {0, 0, 0, 1}}; + const auto target = resource(device, target_desc, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, &clear_value); + ComPtr rtv_heap; + const D3D12_DESCRIPTOR_HEAP_DESC rtv_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1}; + check(device->CreateDescriptorHeap(&rtv_desc, IID_PPV_ARGS(&rtv_heap)), "create provenance RTV heap"); + const auto rtv = rtv_heap->GetCPUDescriptorHandleForHeapStart(); + guest->CreateRenderTargetView(target.Get(), nullptr, rtv); + ComPtr allocator; + check(guest->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator)), "create provenance allocator"); + const auto wrapped = begin_guest_list(guest, allocator.Get()); + const auto native_list = native_object(device, guest, wrapped.Get()); + auto* list = native_list.Get(); + using Bind = void (WINAPI*)(IUnknown*, IUnknown*); + using Targets = void (WINAPI*)(IUnknown*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL, const D3D12_CPU_DESCRIPTOR_HANDLE*); + using Clear = void (WINAPI*)(IUnknown*, SIZE_T, const float*, UINT, const D3D12_RECT*); + const float clear[]{0, 0, 0, 1}; + slot(wrapped.Get(), 52)(wrapped.Get(), rtv.ptr, clear, 0, nullptr); + slot(wrapped.Get(), 50)(wrapped.Get(), 1, &rtv, FALSE, nullptr); + slot(wrapped.Get(), 34)(wrapped.Get(), graphics_root); + slot(wrapped.Get(), 25)(wrapped.Get(), graphics); + const D3D12_VIEWPORT viewport{0, 0, width, height, 0, 1}; + const D3D12_RECT scissor{0, 0, width, height}; + slot(wrapped.Get(), 21)(wrapped.Get(), 1, &viewport); + slot(wrapped.Get(), 22)(wrapped.Get(), 1, &scissor); + // Snapshot all guard words too; report only the consumed 12-byte interval. + snapshots[1] = make_buffer(device, sizeof(seed), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(snapshots[1].Get(), 0, arguments.native.Get(), 0, sizeof(seed)); + transition(list, arguments.native.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + std::printf("provenance consumer queue=%p resource=%p offset=%llu bytes=12\n", + static_cast(queue.Get()), static_cast(arguments.native.Get()), consumed_offset); + using Execute = void (WINAPI*)(IUnknown*, IUnknown*, UINT, IUnknown*, UINT64, IUnknown*, UINT64); + slot(wrapped.Get(), 61)(wrapped.Get(), signature, 1, arguments.wrapped.Get(), consumed_offset, nullptr, 0); + check(slot(wrapped.Get(), 9)(wrapped.Get()), "close provenance consumer"); + ID3D12CommandList* lists[]{list}; + queue->ExecuteCommandLists(1, lists); + wait(2, "pre-consume-copy-and-mesh"); + if (!read_record(1) || observed[0] != observed[1]) return false; + D3D12_PLACED_SUBRESOURCE_FOOTPRINT footprint{}; + UINT64 bytes = 0; + device->GetCopyableFootprints(&target_desc, 0, 1, 0, &footprint, nullptr, nullptr, &bytes); + const auto pixels = make_buffer(device, bytes, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + ComputeCommands capture(device, queue.Get(), nullptr); + transition(capture.list.Get(), target.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + D3D12_TEXTURE_COPY_LOCATION source{target.Get(), D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + D3D12_TEXTURE_COPY_LOCATION destination{pixels.Get(), D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + destination.PlacedFootprint = footprint; + capture.list->CopyTextureRegion(&destination, 0, 0, 0, &source, nullptr); + check(capture.list->Close(), "close provenance pixel capture"); + ID3D12CommandList* captures[]{capture.list.Get()}; + queue->ExecuteCommandLists(1, captures); + wait(3, "scene-color-readback"); + const D3D12_RANGE pixel_range{0, static_cast(bytes)}; + check(pixels->Map(0, &pixel_range, &memory), "map provenance pixels"); + UINT changed = 0; + bool correct = true; + for (UINT y = 0; y < height; ++y) for (UINT x = 0; x < width; ++x) { + UINT actual = 0; + std::memcpy(&actual, static_cast(memory) + footprint.Offset + y * footprint.Footprint.RowPitch + 4 * x, 4); + const UINT wanted = consumed_x ? (x < width / 2 ? red : green) : black; + changed += actual != black; + if (actual != wanted) { + std::fprintf(stderr, "provenance pixel %u,%u: %08x != %08x\n", x, y, actual, wanted); + correct = false; + } + } + pixels->Unmap(0, &none); + std::printf("provenance result case=%s changed=%u total=%u writer_x=%u consumer_x=%u\n", + label, changed, width * height, expected_x, consumed_x); + ComPtr messages; + const bool has_info_queue = SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&messages))); + std::printf("provenance debug info_queue=%s\n", has_info_queue ? "present" : "absent"); + if (has_info_queue) { + for (UINT64 i = 0; i < messages->GetNumStoredMessagesAllowedByRetrievalFilter(); ++i) { + SIZE_T size = 0; + check(messages->GetMessage(i, nullptr, &size), "size provenance debug message"); + std::vector storage(size); + auto* message = reinterpret_cast(storage.data()); + check(messages->GetMessage(i, message, &size), "read provenance debug message"); + if (message->Severity == D3D12_MESSAGE_SEVERITY_ERROR || + message->Severity == D3D12_MESSAGE_SEVERITY_CORRUPTION) { + std::fprintf(stderr, "provenance debug error: %s\n", message->pDescription); + correct = false; + } + } + } + return correct; +} diff --git a/tests/startup_mesh_argument_provenance_check.py b/tests/startup_mesh_argument_provenance_check.py new file mode 100644 index 0000000000..6d599f2ea1 --- /dev/null +++ b/tests/startup_mesh_argument_provenance_check.py @@ -0,0 +1,136 @@ +"""Observe the source-built SRV -> GPU writer -> indirect Mesh chain. + +The positive oracle requires matching resource AND byte interval, X > 0 and +the expected scene-color pixels. Controls must fail that same positive oracle. +""" +from pathlib import Path +import os +import subprocess +import sys + + +CASES = ("positive", "missing-copy", "stale-copy", "wrong-srv-offset", "wrong-argument-offset") + + +def fields(line): + return dict(part.split("=", 1) for part in line.split() if "=" in part) + + +def observations(stdout, prefix): + return [fields(line) for line in stdout.splitlines() if line.startswith(prefix)] + + +def positive_oracle(records, result): + before, after = records + return (before["resource"].lower() == after["resource"].lower() + and before["offset"] == after["offset"] + and before["tuple"] == after["tuple"] + and int(before["tuple"].split(",")[0]) > 0 + and before["guards"] == after["guards"] == "intact" + and int(result["changed"]) == int(result["total"]) == 8) + + +def check_history(stdout, stderr, scenario): + descriptor, = observations(stdout, "provenance descriptor ") + history = observations(stderr, "x2w-descriptor-history seq=") + assert history, "missing descriptor history" + sequences = [int(event["seq"]) for event in history] + assert sequences == list(range(1, len(history) + 1)), sequences + destination = descriptor["guest"] + source = descriptor["source"] + source_writes = [event for event in history if event["guest"] == source and event["op"] == "create"] + assert len(source_writes) == 2, source_writes + initial, overwrite = source_writes + assert initial["first"] == "8", initial + assert overwrite["first"] == ("8" if scenario == "wrong-srv-offset" else "4"), overwrite + assert overwrite["old"] == initial["new"], overwrite + bound = [event for event in history if event["guest"] == destination] + assert bound[0]["op"] == "create" and bound[0]["resource"] == "0", bound + if scenario == "missing-copy": + assert len(bound) == 1, bound + else: + assert bound[1]["op"] == "copy" and bound[1]["source"] == source, bound + assert bound[1]["new"] == initial["new"], bound + if scenario == "stale-copy": + assert len(bound) == 2 and bound[-1]["new"] != overwrite["new"], bound + else: + assert bound[-1]["op"] == "copy" and bound[-1]["new"] == overwrite["new"], bound + assert int(bound[-1]["seq"]) > int(overwrite["seq"]), bound + final = bound[-1] + assert final["desktop"] == descriptor["desktop"], final + assert int(final["guest"], 16) != int(final["desktop"], 16), final + magic, token = descriptor["token_bound"].split(",") + assert magic == "56573258" and int(token) + 1 == int(final["new"]), descriptor + for event in history: + assert event["slot"] == "18" and event["materialized"] == "1", event + assert event["guest_read"] == "1" and event["guest_bytes"] == "32", event + if event["resource"] != "0": + assert int(event["backing"], 16) == int(descriptor["input"], 16), event + if event["old"] != "0": + previous = event["guest_before"].split(",") + assert previous[0] == "56573258" and int(previous[1], 16) + 1 == int(event["old"]), event + + +def check(executable, adapter, scenario, trace=True): + env = dict(os.environ) + env["X2W_MESH_PROVENANCE_CASE"] = scenario + if trace: + env["X2W_D3D12_DESCRIPTOR_HISTORY"] = "1" + else: + env.pop("X2W_D3D12_DESCRIPTOR_HISTORY", None) + # Always inspect this process's stderr, not a caller's persistent trap log. + env.pop("X2W_TRAP_LOG", None) + result = subprocess.run([str(executable), adapter, "mesh-provenance"], env=env, + capture_output=True, text=True, timeout=45) + if result.returncode == 77: + print(result.stdout, end="") + return False + print(result.stdout, end="") + assert result.returncode == 0, (scenario, result.returncode, result.stdout, result.stderr) + assert "DEVICE REMOVED" not in result.stderr and "ExecuteIndirect refused" not in result.stderr, result.stderr + debug, = observations(result.stdout, "provenance debug ") + assert debug["info_queue"] in ("present", "absent"), debug + records = observations(result.stdout, "provenance record ") + assert len(records) == 2 and [r["phase"] for r in records] == ["post-write", "pre-consume"], records + summary, = observations(result.stdout, "provenance result ") + assert positive_oracle(records, summary) == (scenario == "positive"), (scenario, records, summary) + assert summary["changed"] == ("8" if scenario == "positive" else "0"), summary + fences = observations(result.stdout, "provenance fence ") + assert [event["value"] for event in fences] == ["1", "2", "3"], fences + assert len({event["queue"] for event in fences}) == len({event["fence"] for event in fences}) == 1, fences + assert all(int(event["completed"]) >= int(event["value"]) for event in fences), fences + producer, = observations(result.stdout, "provenance producer ") + consumer, = observations(result.stdout, "provenance consumer ") + assert producer["queue"] == consumer["queue"] == fences[0]["queue"], (producer, consumer) + assert producer["resource"] == consumer["resource"] == records[0]["resource"] == records[1]["resource"], records + assert producer["offset"] == records[0]["offset"] == "4", records + assert consumer["offset"] == records[1]["offset"] == ("20" if scenario == "wrong-argument-offset" else "4"), records + assert producer["bytes"] == consumer["bytes"] == "12", (producer, consumer) + write, = observations(result.stdout, "provenance input-write ") + scalar, = observations(result.stdout, "provenance input-record ") + descriptor, = observations(result.stdout, "provenance descriptor ") + assert write["queue"] == producer["queue"], write + assert int(write["resource"], 16) == int(scalar["resource"], 16) == int(descriptor["input"], 16), scalar + assert write["offset"] == scalar["offset"] == "16" and write["value"] == scalar["value"] == "2", scalar + assert scalar["adjacent_offset"] == "32" and scalar["adjacent_value"] == "0", scalar + assert result.stdout.index("provenance record phase=post-write") < result.stdout.index("provenance consumer ") + if trace: + check_history(result.stdout, result.stderr, scenario) + else: + assert "x2w-descriptor-history " not in result.stderr, result.stderr + return True + + +def main(): + executable = Path(sys.argv[1]).resolve() + adapter = sys.argv[2] + for scenario in CASES: + if not check(executable, adapter, scenario): + return 77 + assert check(executable, adapter, "positive", trace=False) + print("Mesh argument provenance: positive, four negative controls and trace opt-out passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From 390f5c1d1e1f460422fcf8ff3d78da8a8aa27877 Mon Sep 17 00:00:00 2001 From: Vilify-13 <109003055+Vilify-13@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:32:17 -0500 Subject: [PATCH 2/3] gpu: add targeted descriptor history filtering Select heap-relative descriptor ranges before consuming the diagnostic event budget. Match copies by source or destination, validate retained mapping and shadow identity, and bound diagnostic traversal after truncation. Add source-built model and Mesh regression checks for filtering, exhaustion, and sparse copy windows. Document selection syntax, conservative attribution, and completeness limits. Builds on wish131400's provenance work in #3321 and the review findings of Leyukaka and Jess-Doit. Refs #3310 and #3321. AI-assisted implementation, testing and verification. --- CMakePresets.json | 4 +- README.md | 1 + docs/experiments.md | 4 + docs/experiments/descriptor-history-filter.md | 106 ++++++ docs/experiments/mesh-argument-provenance.md | 8 +- docs/startup-runtime.md | 3 +- src/startup_stubs/d3d12_capture.inl | 167 +++++++-- src/startup_stubs/d3d12_xs_device.cpp | 83 ++++- .../descriptor_history_config.h | 109 ++++++ .../descriptor_history_config_win.h | 27 ++ .../descriptor_history/heap_shape.h | 51 +++ .../descriptor_history/history_admission.h | 83 +++++ .../descriptor_history/history_budget.h | 64 ++++ .../descriptor_history/history_filter.h | 32 ++ .../descriptor_history/history_runtime.inl | 182 +++++++++ .../descriptor_history/range_selection.h | 32 ++ .../descriptor_history/retained_registry.h | 183 +++++++++ .../descriptor_history/shadow_identity.h | 65 ++++ tests/cmake/startup_descriptor_history.cmake | 15 + tests/startup_descriptor_history_check.cpp | 352 ++++++++++++++++++ tests/startup_descriptor_history_check.py | 144 +++++++ tests/startup_mesh_argument_provenance.inl | 62 +++ .../startup_mesh_argument_provenance_check.py | 10 +- 23 files changed, 1726 insertions(+), 61 deletions(-) create mode 100644 docs/experiments/descriptor-history-filter.md create mode 100644 src/startup_stubs/descriptor_history/descriptor_history_config.h create mode 100644 src/startup_stubs/descriptor_history/descriptor_history_config_win.h create mode 100644 src/startup_stubs/descriptor_history/heap_shape.h create mode 100644 src/startup_stubs/descriptor_history/history_admission.h create mode 100644 src/startup_stubs/descriptor_history/history_budget.h create mode 100644 src/startup_stubs/descriptor_history/history_filter.h create mode 100644 src/startup_stubs/descriptor_history/history_runtime.inl create mode 100644 src/startup_stubs/descriptor_history/range_selection.h create mode 100644 src/startup_stubs/descriptor_history/retained_registry.h create mode 100644 src/startup_stubs/descriptor_history/shadow_identity.h create mode 100644 tests/cmake/startup_descriptor_history.cmake create mode 100644 tests/startup_descriptor_history_check.cpp create mode 100644 tests/startup_descriptor_history_check.py diff --git a/CMakePresets.json b/CMakePresets.json index 47adfbbcf4..e760f6ad0a 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -29,7 +29,7 @@ "d3d12_sdk_check", "era_heap_check", "xmem_shim", "offscreen_check", "startup_list_copy", "startup_list_copy_check", "cpu_fuzz_lifted", "cpu_fuzz_lifted_o2", "pe_map", "intake_candidate", "archive_gpu_reader", "archive_codec_gpu", "archive_texture_gpu_lifted", "startup_launch_probe", - "compile_dxil", "startup_indirect_dispatch", "startup_indirect_draw_indexed", "startup_present_readback_check", + "compile_dxil", "startup_indirect_dispatch", "startup_indirect_draw_indexed", "startup_descriptor_history_check", "startup_present_readback_check", "startup_present_planes", "startup_present_composite_warp", "xmem_shim_test_controls", "startup_stub_xcrdapi", "startup_stub_xcrdapi_break_window_control", "xmem_run_break_readers_check", "xmem_run_break_readers_control", "xmem_cross_call_merge_check", @@ -50,7 +50,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_mesh_argument_provenance_warp|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" + "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_mesh_argument_provenance_warp|startup_descriptor_history_(model|(filter|exhaustion)_warp)|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" } } }, diff --git a/README.md b/README.md index d87c8ed601..0794515e9b 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,7 @@ The control-flow CPU translator supports [source-built string memory transfers]( | gfx1030 formatted UINT buffer reads | Lower [indexed `buffer_load_format_*` with caller-declared RGBA32 UINT](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-reads) and verify one to four channels in the UAV readback. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_format_'` | | gfx1030 formatted D16 UINT writes | Lower [indexed packed `buffer_store_format_d16_x/xy/xyzw`](docs/experiments.md#indexed-gfx1030-formatted-d16-uint-buffer-writes) and verify the untouched halfword and record padding. The experimental `xyz` form requires a caller-verified W-preservation contract. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | | gfx1030 formatted UINT buffer writes | Lower [indexed `buffer_store_format_*` with matching caller-declared UINT texels](docs/experiments.md#indexed-gfx1030-formatted-uint-buffer-writes) and compare full UAV readback with a CPU reference. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_mubuf_store_format_'` | +| Targeted descriptor history | [Select descriptor heap-relative ranges and verify history budget controls](docs/experiments/descriptor-history-filter.md) with source-built Mesh fixtures. | `ctest --preset dev --no-tests=error -j 1 -V -R '^startup_descriptor_history_'` | | Descriptor-format buffer loads | Lower [gfx1013 indexed `buffer_load_format_x/xy/xyz/xyzw` and the d16 forms](docs/experiments.md#descriptor-format-buffer-loads), reading the GFX10 or legacy format from V# word 3 at run time with integer-exact conversions. An unsupported format or opcode width leaves the output unwritten. The descriptor itself is still static. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_descriptor_load_format_'` | | Heap-view buffer loads | Lower [gfx1013 indexed `buffer_load_format_xy/xyzw` from a run-time view record](docs/experiments.md#heap-view-buffer-loads): base, stride, `num_records` and format come from the record at a chosen slot. An index past `num_records` reads zero; a view that is not live, a bad slot or a bad format leaves the output unwritten. The record table is a side table inside t0; the SM 6.6 heap lookup is not wired yet. | `ctest --preset dev --no-tests=error -R '^compute_(store_aot_heap_view_load_\|heap_view_controls$)'` | | Descriptor-format buffer stores | Lower [indexed `buffer_store_format_x/xy/xyz/xyzw` and the d16 forms](docs/experiments.md#descriptor-format-buffer-stores), reading the GFX10 or legacy format from V# word 3. Unknown formats are refused. | `ctest --preset dev --no-tests=error -R '^compute_store_aot_descriptor_store_format_'` | diff --git a/docs/experiments.md b/docs/experiments.md index 8506dfdc05..ddb1b477ad 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2,6 +2,10 @@ New notes go in `docs/experiments/.md` (see [the folder guide](experiments/README.md)); this file keeps the older notes. +## Targeted descriptor history + +[Selector grammar, attribution limits and source-built regression commands](experiments/descriptor-history-filter.md) + ## First native graphics draw through the stand-in Set `X2W_NATIVE_SHADERS` to the desktop DXC directory and `X2W_SHADER_CACHE` to a writable cache. diff --git a/docs/experiments/descriptor-history-filter.md b/docs/experiments/descriptor-history-filter.md new file mode 100644 index 0000000000..c56f706563 --- /dev/null +++ b/docs/experiments/descriptor-history-filter.md @@ -0,0 +1,106 @@ +# Targeted descriptor history + +This extends the [GPU-written Mesh argument provenance fixture](mesh-argument-provenance.md) +associated with [PR #3321](https://github.com/R0Y00/Xbox2Windows/pull/3321) and +[issue #3310](https://github.com/R0Y00/Xbox2Windows/issues/3310). It selects +intercepted descriptor operations before they consume the existing history +budget. It does not change rendering, native descriptor copies, resource +retirement, GPU submission or synchronization. + +## Enable and select + +Set both environment variables before starting the process; the configuration +is cached. For the source-built Mesh provenance fixture: + +```powershell +$env:X2W_D3D12_DESCRIPTOR_HISTORY = '1' +$env:X2W_D3D12_DESCRIPTOR_HISTORY_FILTER = 'view:cpu:0:1:1:0:1;view:visible:0:1:1:0:1' +``` + +Each selector is `TYPE:VISIBILITY:NODE_MASK:CAPACITY:ORDINAL:FIRST:COUNT`. +Use one or two selectors separated by a semicolon (at most 256 characters in +total). Types are `view`, `sampler`, `rtv`, and `dsv`; visibility is +`cpu` or `visible` (RTV and DSV must be CPU-only). Numeric fields are +canonical unsigned 32-bit decimal values, without whitespace, signs or +leading zeroes. Capacity, ordinal and count must be positive. The zero-based +slot interval must fit within the requested logical capacity. An ordinal is +one-based among successful logical heap registrations of the exact type, +visibility, requested node mask and logical capacity. Selectors must identify +distinct heap keys (including ordinal). + +The master switch being off ignores the filter. A missing or empty filter +preserves legacy unfiltered recording. Invalid nonempty input disables the +diagnostic and logs one configuration error, without a legacy fallback. + +## Attribution and budget + +A creation matches its destination. A copy matches the union of source and +destination slot intervals, with each copy index counted once. The arithmetic +produces at most two nonoverlapping windows. Only admitted indices are sampled +and logged; the budget is 8,192 records per process. Reaching exactly 8,192 +is not by itself truncation; the first additional admissible matching record +emits the marker. No further history traversal or guest-token sampling is +performed after truncation. + +With filtering enabled, registration lines show generation, mapping index, +heap shape, guest and desktop handle starts, strides, prefix, tail and +mirror information, and a selector bit mask. Bit 0 represents the first +selector and bit 1 the second. Discovery emits the first 256 registrations +and a discovery-truncation notice; a later selected registration is still +reported. The registry retains at most 1,024 logical registrations, not +1,024 live COM references. Exceeding its capacity or encountering an invalid +registration faults attribution and reports an incomplete trace. Mirrors +are companions of their logical heap, not additional selector ordinals. + +Use actual same-run mapping and shadow identity to confirm selections. +Ordinals can change across executions, configurations, adapters or concurrent +registrations; they are not stable title identifiers. A selector may never +become available. No end-of-process completeness receipt is supplied. Zero +records or absence of a truncation marker is not proof of a complete history. + +Attribution is conservative. Ambiguous overlapping mappings, stale mapping +publication, untracked or opaque endpoints, untracked CPU tails and selected +view allocation failures can omit operations and report an incomplete trace. +A selected copy must validate both endpoints and the admitted rows in the +shadow snapshot; rejecting a chunk does not consume budget or gate the native +copy. Registration lookup is bounded by the retained registry size, and +selected-row shadow checks by the event budget; this is not a constant-time +end-to-end lookup claim. + +Trace fields describe CPU shadow publication and a pre-token-write guest +sample, not native descriptor bytes, guest copy completion, arbitrary guest +CPU stores or GPU execution order. View IDs can be reused. Filtered SRV +decoding uses the fixed guest record width; legacy decoding is unchanged. +The fixture supplies its own fences and pixel readback. This diagnostic +alone does not satisfy the remaining integration criteria of issue #3310. + +## Reproduce + +With the ordinary Windows prerequisites (including DXC and Python), build +both configurations and run the GPU tests serially: + +```powershell +foreach ($preset in @('dev', 'release')) { + cmake --build --preset $preset --target startup_descriptor_history_check startup_indirect_draw_indexed + ctest --preset $preset --no-tests=error -j 1 -V -R '^startup_(descriptor_history_(model|(filter|exhaustion)_(warp|hardware))|mesh_argument_provenance_(warp|hardware))$' +} +``` + +The model check covers parsing, retained mappings, mirror/tail identities, +ambiguous endpoints, transactional admission, bounded secondary lookups, +publication changes and capacity boundaries. The GPU check uses the original +provenance oracle, including positive pixels and four negative controls, +with source-only, destination-only, and combined filters. The exhaustion +check adds unrelated null SRV creation and bulk copies, checks the exact +admitted event sequence and truncation marker, and verifies that selecting +only the later Mesh heaps preserves their history. A sparse case checks +disjoint copy windows. Capability skips are reported separately. These +fixtures do not establish full-game behavior. + +## Credits + +The underlying history and Mesh provenance fixture are from wish131400's +[PR #3321](https://github.com/R0Y00/Xbox2Windows/pull/3321). The event-budget +and post-truncation traversal findings discussed in that PR motivate this +follow-up. Original measured results remain tied to their original revisions; +current-branch verification is reported separately. diff --git a/docs/experiments/mesh-argument-provenance.md b/docs/experiments/mesh-argument-provenance.md index 1666ee712c..595a86f49b 100644 --- a/docs/experiments/mesh-argument-provenance.md +++ b/docs/experiments/mesh-argument-provenance.md @@ -78,13 +78,13 @@ can be interpreted. Guest token word 1 is a zero-based view-record index, whereas `old`/`new` use one-based IDs. Native desktop descriptor bytes are opaque and are not read as guest tokens. -This diagnostic is intended for the fixture and short startup reproductions +Unfiltered history is intended for the fixture and short startup reproductions only. It is not a complete-history capture for a real integration run: initialization can exhaust its 8,192-event process budget, and each copied descriptor counts as one event, so a large copy can consume the budget by -itself. It emits one `truncated limit=8192` line at that limit. Later producer -history needs a separately targeted diagnostic; no filter, delayed start or -rolling history is implemented here. With +itself. It emits one `truncated limit=8192` line on the first event omitted by that limit. +For later producer history, use the optional [targeted descriptor history filter](descriptor-history-filter.md). +No delayed start or rolling history is provided. With `X2W_D3D12_VIEW_CONTENT_TOKENS=1`, parked view records are reused, so the same `old`/`new` ID can refer to different views at different sequence points. Arbitrary guest CPU stores or `memcpy` operations are not intercepted. View creations diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 9bd9262103..b9f282096c 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1871,7 +1871,8 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_D3D12_VIEW_DEFAULTS=all` or `=off` | `all` is experimental: UAV, RTV and DSV descriptions with `ViewDimension` 0 also get the resource's default view, which drops their requested format and component mapping. `off` skips the measured SRV case too. Unset, only SRVs of typed non-depth textures get the default view ([details](#unknown-and-mismatched-view-dimensions)) | | `X2W_DIAG_PLACED_INPUT=1` | For a refused draw input in a non-aliasing placed buffer, logs up to four lines per shader key and SRV index: resource, width, requested range, same-list copy tracking status, recorded ranges, up to 64 recorded buffer copies per resource, and observed translated UAV bindings and accepted UAV clears. Same-list tracking requires `X2W_TRANSLATED_INDIRECT_COPY_RANGES=1` and retains at most 64 ranges per list. UAV observations cover translated compute buffer outputs, translated pixel UAVs and accepted UAV clears, not all possible bindings or writes. Records are bounded to 4096 resources and 4096 shader/index pairs; resource pointer reuse may conflate observations. Recorded commands and bindings do not prove GPU execution or a write. | | `X2W_D3D12_VIEW_CENSUS=1` | diagnostic only: counts new distinct view records by device slot (a heartbeat line), and logs the record vector capacity and hash bucket count before either grows ([details](#d3d12-view-census)). Unset, nothing is counted or logged | -| `X2W_D3D12_DESCRIPTOR_HISTORY=1` | fixture/short-startup diagnostic only: logs the first 8,192 descriptor events, then truncates; it cannot establish a complete later integration history. Records guest token bytes, shadow IDs and backing identities. IDs can be reused with `X2W_D3D12_VIEW_CONTENT_TOKENS=1`; CPU order is separate from GPU execution ([fixture, controls and limits](experiments/mesh-argument-provenance.md)) | +| `X2W_D3D12_DESCRIPTOR_HISTORY=1` | opt-in diagnostic: records at most 8,192 descriptor events per process; the first omitted matching event emits a truncation marker. Records guest token samples, shadow IDs and backing identities. IDs can be reused with `X2W_D3D12_VIEW_CONTENT_TOKENS=1`; CPU order is separate from GPU execution ([fixture, controls and limits](experiments/mesh-argument-provenance.md)) | +| `X2W_D3D12_DESCRIPTOR_HISTORY_FILTER` | optional heap-relative selector(s) with descriptor history enabled; select creation by destination and copies by either endpoint before consuming the event budget. Absent or empty retains legacy history; malformed nonempty input disables history. See [selector grammar, discovery and completeness limits](experiments/descriptor-history-filter.md). | | `X2W_D3D12_VIEW_CONTENT_TOKENS=1` | opt-in: constant buffer views and buffer shader-resource views are written into title descriptor memory as tokens that carry the view itself instead of a record id, and their records are freed and reused once no shadow slot names them, so the record count stays bounded ([details](#d3d12-view-content-tokens)). Off under `X2W_D3D12_CAPTURE`. Unset, every view keeps an id token and records are never removed | | `X2W_D3D12_TABLE_LOCK=1` | opt-in: the resource, slot 133 placement and descriptor heap tables get their own lock, so the four lookups that read only them stop queueing on the view-record lock behind view creation and descriptor copies ([details](#d3d12-table-lock)). Unset, they take that lock as before | | `X2W_DRAW_NULL_IDENTITY=1` | null descriptors read as identity values instead of zero | diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index a096fb6fef..4e676fbebf 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -252,7 +252,7 @@ void view_allocation_gate(ViewAllocation site) } // The shadow entry for a desktop CPU descriptor handle (note_lock held), or null. -std::uint32_t* shadow_slot(u64 desktop_handle, std::uint32_t* room = nullptr) +std::uint32_t* shadow_slot(u64 desktop_handle, std::uint32_t* room = nullptr, history_shadow::Match* observation = nullptr, bool count_statistics = true) { // Desktop CPU handles need not be addresses: interleaved tagged handles, released heaps and the two cases the // handle cannot settle are described in descriptor_heap_match.h. The counters show whether either case occurs. @@ -263,13 +263,33 @@ std::uint32_t* shadow_slot(u64 desktop_handle, std::uint32_t* room = nullptr) span = {heaps[i].desktop_cpu, heaps[i].increment, heaps[i].count}; return true; }); + if (observation) { + *observation = {}; + observation->lookup = match; + } if (!match.found()) return nullptr; - if (match.boundary_matches > 1) InterlockedIncrement64(&descriptor_heap_shared_boundary); - if (match.off_boundary) InterlockedIncrement64(&descriptor_heap_off_boundary); + if (count_statistics && match.boundary_matches > 1) InterlockedIncrement64(&descriptor_heap_shared_boundary); + if (count_statistics && match.off_boundary) InterlockedIncrement64(&descriptor_heap_off_boundary); const HeapInfo& heap = heaps[match.heap]; + if (observation) { + observation->owner = heap.wrapper; + observation->guest_base = heap.title_cpu; + observation->desktop_base = heap.desktop_cpu; + observation->type = static_cast(heap.type); + observation->stride = heap.increment; + observation->physical = heap.count; + observation->logical = heap.logical_count; + observation->room = static_cast(heap.count - match.index); + } if (room) *room = static_cast(heap.count - match.index); return heap.shadow + match.index; } +bool history_shadow_observe(const HistoryExpected* expected) +{ + return expected && expected->attribution != history_retained::Attribution::inactive && + history_filtered() && !history_truncated.load(std::memory_order_relaxed) && + expected->plan.status == history_filter::Status::filtered && expected->plan.size; +} std::uint32_t shadow_id(u64 desktop_handle) { AcquireSRWLockShared(¬e_lock); @@ -675,13 +695,76 @@ const char* store_view(const ViewRecord& record, std::uint8_t created, u64 hash, return nullptr; } +// Diagnostic reservation only. The actual native/shadow/token operations below +// do not depend on this result. All budget access is under note_lock. +history_budget::Batch history_reserve(history_admission::Operation op, UINT count, + const HistoryExpected* source, const HistoryExpected* destination, + const history_shadow::Match& src_match, const history_shadow::Match& dest_match, + u64 src_desktop, u64 dest_desktop, UINT increment, bool allocation_failed = false) +{ + if (history_truncated.load(std::memory_order_relaxed)) return {history_budget::Decision::stopped}; + history_filter::Plan plan{}; + if (history_legacy_enabled()) { + plan.status = history_filter::Status::unfiltered; + if (count) { plan.windows[0] = {0, count}; plan.size = 1; } + } else if (history_filtered() && destination) { + plan = destination->plan; + } + if (plan.status == history_filter::Status::off) return {}; + const DWORD saved = GetLastError(); + static history_budget::Budget budget; + const history_admission::Endpoint a{source ? static_cast(*source) : + history_shadow::Expected{}, src_match}; + const history_admission::Endpoint b{destination ? static_cast(*destination) : + history_shadow::Expected{}, dest_match}; + const auto result = history_admission::admit(budget, plan, count, op, a, b, allocation_failed, + [&](bool from_source, u64 i) noexcept { + history_shadow::Match row{}; + shadow_slot((from_source ? src_desktop : dest_desktop) + i * increment, nullptr, &row, false); + return row; + }, []() noexcept { return history_publication.load(std::memory_order_acquire); }); + using Failure = history_admission::Failure; + using Verdict = history_shadow::Verdict; + switch (result.failure) { + case Failure::none: break; + case Failure::plan: history_incomplete(op == history_admission::Operation::view ? "view-attribution" : "copy-attribution"); break; + case Failure::allocation: history_incomplete("selected-view-allocation-failed"); break; + case Failure::publication: history_incomplete("registration-changed-before-note"); break; + case Failure::source: + case Failure::destination: + if (result.verdict == Verdict::stale) history_incomplete("registration-changed-before-note"); + else if (result.verdict == Verdict::shared_boundary || result.verdict == Verdict::off_boundary) + history_incomplete("selected-shadow-ambiguous"); + else if (result.verdict == Verdict::opaque || result.verdict == Verdict::tail || result.verdict == Verdict::missing) + history_incomplete(op == history_admission::Operation::view ? "selected-view-untracked" : "selected-copy-untracked"); + else history_incomplete("selected-shadow-identity"); + break; + } + SetLastError(saved); + return result.batch; +} +void history_finish(const history_budget::Batch& batch) +{ + if (!batch.truncate) return; + const DWORD saved = GetLastError(); + log("x2w-descriptor-history truncated limit=%llu", static_cast(history_budget::limit)); + history_truncated.store(true, std::memory_order_relaxed); + SetLastError(saved); +} + // A new view could not be recorded. The desktop descriptor already holds it, so the destination must stop naming the // view it held before: the slot and its title token are cleared, and a draw refuses the descriptor instead of binding // the old view. Nothing records the new view's use of its resource, so the resource leaves the retire class and is not // released early. Allocates nothing. Enters with note_lock held and releases it. -void drop_unrecorded_view(const ViewRecord& record, bool materialized, const char* container) +void drop_unrecorded_view(const ViewRecord& record, bool materialized, const char* container, + const HistoryExpected* expected = nullptr) { - if (std::uint32_t* slot_ptr = shadow_slot(record.dest_desktop)) { + history_shadow::Match match{}; + std::uint32_t* slot_ptr = shadow_slot(record.dest_desktop, nullptr, history_shadow_observe(expected) ? &match : nullptr); + if (history_filtered()) + history_reserve(history_admission::Operation::view, 1, nullptr, expected, {}, match, + 0, record.dest_desktop, 0, true); + if (slot_ptr) { const std::uint32_t prev = *slot_ptr; *slot_ptr = 0; if (prev && prev - 1 < view_records().size() && view_materialized()[prev - 1]) @@ -704,21 +787,9 @@ void drop_unrecorded_view(const ViewRecord& record, bool materialized, const cha // Opt-in, bounded descriptor provenance. Called with note_lock held: sequence is // the order in which shadow updates are published, not GPU execution order. // Guest bytes are sampled BEFORE this operation publishes its token/copy. -bool descriptor_history_enabled() -{ - static const bool enabled = x2w_local::env_on("X2W_D3D12_DESCRIPTOR_HISTORY"); - return enabled; -} -void trace_descriptor_history(const char* operation, u64 title, u64 desktop, u64 source, +void trace_descriptor_history(u64 event, const char* operation, u64 title, u64 desktop, u64 source, std::uint32_t previous, std::uint32_t next, UINT token_bytes) { - if (!descriptor_history_enabled()) return; - static u64 sequence; - const u64 event = ++sequence; - if (event > 8192) { - if (event == 8193) log("x2w-descriptor-history truncated limit=8192"); - return; - } const DWORD saved_error = GetLastError(); std::uint32_t guest[8]{}; const UINT guest_bytes = (std::min)(token_bytes, UINT{sizeof(guest)}); @@ -728,9 +799,17 @@ void trace_descriptor_history(const char* operation, u64 title, u64 desktop, u64 const ViewRecord* view = next && next - 1 < view_records().size() ? &view_records()[next - 1] : nullptr; u64 first = 0; UINT stride = 0; - if (view && view->slot == 18 && view->desc_bytes >= sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC)) { + // Keep legacy decoding unchanged; filtered history uses the fixed guest + // record width (the desktop SDK may add fields after that record). + static_assert(sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) >= ViewRecord::srv_desc_bytes); + static_assert(offsetof(D3D12_SHADER_RESOURCE_VIEW_DESC, ViewDimension) == 4); + static_assert(offsetof(D3D12_SHADER_RESOURCE_VIEW_DESC, Buffer) == 16); + static_assert(offsetof(D3D12_BUFFER_SRV, FirstElement) == 0); + static_assert(offsetof(D3D12_BUFFER_SRV, StructureByteStride) == 12); + const std::size_t srv_bytes = history_filtered() ? ViewRecord::srv_desc_bytes : sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC); + if (view && view->slot == 18 && view->desc_bytes >= srv_bytes) { D3D12_SHADER_RESOURCE_VIEW_DESC srv{}; - std::memcpy(&srv, view->desc, sizeof(srv)); + std::memcpy(&srv, view->desc, srv_bytes); if (srv.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { first = srv.Buffer.FirstElement; stride = srv.Buffer.StructureByteStride; @@ -749,7 +828,7 @@ void trace_descriptor_history(const char* operation, u64 title, u64 desktop, u64 // A view is created: remembered by id; the id is also written into title-owned descriptor memory so // that copies the title makes there itself can be followed. void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_t desc_bytes, u64 dest_title, u64 dest_desktop, - bool materialized = true) + bool materialized = true, const HistoryExpected* expected = nullptr) { ViewRecord record{}; record.slot = static_cast(slot); @@ -806,7 +885,7 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ } if (const char* container = store_view(record, created, hash, freeable)) { if (taken) park_view_record(record.id); // emptied, not in view_ids: never found, taken again later - drop_unrecorded_view(record, materialized, container); + drop_unrecorded_view(record, materialized, container, expected); return; } ++views_distinct; @@ -816,10 +895,18 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ view_census.missed += !ids_full && view_ids().bucket_count() != buckets_before; } } - if (std::uint32_t* slot_ptr = shadow_slot(dest_desktop)) { + history_shadow::Match match{}; + std::uint32_t* slot_ptr = shadow_slot(dest_desktop, nullptr, history_shadow_observe(expected) ? &match : nullptr); + if (slot_ptr || history_filtered()) { + const auto batch = history_reserve(history_admission::Operation::view, 1, nullptr, expected, {}, match, + 0, dest_desktop, 0); + if (batch.count()) + trace_descriptor_history(batch.first_sequence, "create", dest_title, dest_desktop, 0, + slot_ptr ? *slot_ptr : 0, record.id + 1, slot == 22 ? x2w_startup::title_sampler_stride : 32u); + history_finish(batch); + } + if (slot_ptr) { const std::uint32_t prev = *slot_ptr; - trace_descriptor_history("create", dest_title, dest_desktop, 0, prev, record.id + 1, - slot == 22 ? x2w_startup::title_sampler_stride : 32u); *slot_ptr = record.id + 1; // The same view written to the same slot again keeps its id and changes no reference count. A different view // takes over the slot: the new record adds its refs, the previous materialized record drops its own. @@ -850,23 +937,33 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ std::memcpy(reinterpret_cast(dest_title), token, token_bytes); } } -void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, UINT count, UINT increment) +void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, UINT count, UINT increment, + const HistoryCopyExpected* expected = nullptr) { - const bool history = descriptor_history_enabled(); - const UINT dest_stride = history ? title_descriptor_stride(dest_title, increment) : 0; - const UINT src_stride = history ? title_descriptor_stride(src_title, increment) : 0; + const bool legacy_history = history_legacy_enabled(); + const UINT dest_stride = legacy_history ? title_descriptor_stride(dest_title, increment) : + expected ? expected->destination.guest_stride : 0; + const UINT src_stride = legacy_history ? title_descriptor_stride(src_title, increment) : + expected ? expected->source.guest_stride : 0; AcquireSRWLockExclusive(¬e_lock); descriptors_copied += count; std::uint32_t dest_room = 0, src_room = 0; - std::uint32_t* to = shadow_slot(dest_desktop, &dest_room); - const std::uint32_t* from = shadow_slot(src_desktop, &src_room); - if (history) - for (UINT i = 0; i < count; ++i) { + history_shadow::Match dest_match{}, src_match{}; + const auto* dest_expected = expected ? &expected->destination : nullptr; + const auto* src_expected = expected ? &expected->source : nullptr; + std::uint32_t* to = shadow_slot(dest_desktop, &dest_room, history_shadow_observe(dest_expected) ? &dest_match : nullptr); + const std::uint32_t* from = shadow_slot(src_desktop, &src_room, history_shadow_observe(src_expected) ? &src_match : nullptr); + const auto batch = history_reserve(history_admission::Operation::copy, count, src_expected, dest_expected, + src_match, dest_match, src_desktop, dest_desktop, increment); + u64 sequence = batch.first_sequence; + for (unsigned j = 0; j < batch.size; ++j) + for (u64 i = batch.windows[j].begin; i < batch.windows[j].end; ++i) { const auto previous = to && i < dest_room ? to[i] : 0; const auto next = to && count <= dest_room ? (from && count <= src_room ? from[i] : 0) : previous; - trace_descriptor_history("copy", dest_title + u64{i} * dest_stride, dest_desktop + u64{i} * increment, - src_title + u64{i} * src_stride, previous, next, dest_stride); + trace_descriptor_history(sequence++, "copy", dest_title + i * dest_stride, dest_desktop + i * increment, + src_title + i * src_stride, previous, next, dest_stride); } + history_finish(batch); if (to && count <= dest_room) { if (from && count <= src_room) { // Every copied-in view is now named by one more tracked slot; every view the destination named before is diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 0a3ddf5832..9be7912cd4 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -94,6 +94,10 @@ #include "present_view_format.h" #include "state_block_blend.h" #include "title_heap_memory.h" +#include "descriptor_history/descriptor_history_config_win.h" +#include "descriptor_history/retained_registry.h" +#include "descriptor_history/shadow_identity.h" +#include "descriptor_history/history_admission.h" #include "startup_stubs/xmem_section_buffer.h" #include "native_buffer_store_view.h" #include "native_compute_output.h" @@ -326,6 +330,7 @@ struct DescriptorRange { }; SRWLOCK descriptor_lock = SRWLOCK_INIT; std::vector descriptor_ranges; +#include "descriptor_history/history_runtime.inl" // Desktop rejects a shader-visible CBV/SRV/UAV heap above a driver-specific descriptor count: the // API documents 1,048,576, but a driver may accept fewer (1,000,000 on the GTX 1660 SUPER here), so @@ -340,17 +345,28 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo std::uint64_t accepted_view_heap_descriptors(ID3D12Device* device, UINT node_mask); std::uint64_t desktop_cpu_handle(std::uint64_t handle, UINT* contiguous = nullptr, UINT* available = nullptr, - std::uint64_t* mirror = nullptr) + std::uint64_t* mirror = nullptr, HistoryObservation* observation = nullptr) { std::uint64_t result = handle, mirrored = 0; UINT room = UINT_MAX, remaining = UINT_MAX; bool past_end = false; AcquireSRWLockShared(&descriptor_lock); + if (observation) { + *observation = {}; + observation->epoch = history_registry().epoch(); + observation->mapping_count = static_cast(descriptor_ranges.size()); + observation->guest = handle; + } for (const auto& r : descriptor_ranges) { if (handle < r.title) continue; const u64 offset = handle - r.title; if (offset == r.bytes && r.tail_cpu) past_end = true; if (offset >= r.bytes) continue; + if (observation) { + observation->mapping_index = static_cast(&r - descriptor_ranges.data()) + 1; + observation->guest_stride = r.title_stride; + observation->desktop_stride = r.desktop_stride; + } const u64 index = offset / r.title_stride; const u64 limit = r.bytes / r.title_stride; remaining = static_cast(limit - index); @@ -371,6 +387,10 @@ std::uint64_t desktop_cpu_handle(std::uint64_t handle, UINT* contiguous = nullpt ReleaseSRWLockShared(&descriptor_lock); if (past_end) { result = 0; room = 0; } if (!result) mirrored = 0; + if (observation) { + observation->desktop = result; + observation->mirror = mirrored; + } if (mirror) *mirror = mirrored; if (contiguous) *contiguous = room; if (available) *available = result ? remaining : 0; @@ -6172,15 +6192,22 @@ HRESULT __stdcall device_create_descriptor_heap(Wrapper* self, const D3D12_DESCR heap->Release(); return E_OUTOFMEMORY; } - if (title_memory) { - w->own().title_cpu = title_memory; + const bool history_tracking = history_filtered(); + HistoryRegistrationReceipt history_registration{}; + if (title_memory) w->own().title_cpu = title_memory; + if (title_memory || history_tracking) { AcquireSRWLockExclusive(&descriptor_lock); - descriptor_ranges.push_back({title_memory, bytes, desktop, title_stride, desktop_stride, - static_cast(request->NumDescriptors), - tail ? tail->GetCPUDescriptorHandleForHeapStart().ptr : 0, - mirror ? mirror->GetCPUDescriptorHandleForHeapStart().ptr : 0}); + const u64 tail_cpu = tail ? tail->GetCPUDescriptorHandleForHeapStart().ptr : 0; + const u64 mirror_cpu = mirror ? mirror->GetCPUDescriptorHandleForHeapStart().ptr : 0; + if (title_memory) + descriptor_ranges.push_back({title_memory, bytes, desktop, title_stride, desktop_stride, + static_cast(request->NumDescriptors), tail_cpu, mirror_cpu}); + if (history_tracking) + history_registration = history_register_heap(*desc, title_memory, title_stride, desktop, + desktop_stride, request->NumDescriptors, tail_cpu, mirror_cpu, reinterpret_cast(w)); ReleaseSRWLockExclusive(&descriptor_lock); } + if (history_tracking) history_report_registration(history_registration); const u64 sampler_cpu = raw_samplers ? title_memory : 0; note_heap(w, desc->Type, request->NumDescriptors, desc->NumDescriptors, desktop_stride, title_memory, desktop, @@ -6235,8 +6262,15 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) Timed timed(time_view); u64 args[4] = {unwrap(a), unwrap(b), unwrap(c), unwrap(d)}; const u64 title_dest = args[D]; + const bool history_tracking = history_planning_enabled(); + HistoryObservation history_observation{}; u64 mirror = 0; - args[D] = desktop_cpu_handle(args[D], nullptr, nullptr, &mirror); + args[D] = desktop_cpu_handle(args[D], nullptr, nullptr, &mirror, history_tracking ? &history_observation : nullptr); + HistoryExpected history_expected_view{}; + if (history_tracking) + history_expected_view = history_plan_view(history_observation, device_of(self), + N == 20 ? D3D12_DESCRIPTOR_HEAP_TYPE_RTV : N == 21 ? D3D12_DESCRIPTOR_HEAP_TYPE_DSV : + N == 22 ? D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER : D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); constexpr D3D12_DESCRIPTOR_HEAP_TYPE view_heap_type = N == 22 ? D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER : D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; // Slots 18-21 name a resource in a descriptor slot. While shadow_slot() tracks the destination, note_view() owns the @@ -6267,7 +6301,7 @@ __declspec(noinline) u64 view_slot(Wrapper* self, u64 a, u64 b, u64 c, u64 d) N == 19 ? ViewRecord::uav_desc_bytes : N == 20 ? sizeof(D3D12_RENDER_TARGET_VIEW_DESC) : sizeof(D3D12_DEPTH_STENCIL_VIEW_DESC); note_view(N, (N >= 18 && N <= 21) ? raw[0] : 0, N == 19 ? raw[1] : 0, reinterpret_cast(raw[described]), - described_bytes, title_dest, args[D], materialized); + described_bytes, title_dest, args[D], materialized, &history_expected_view); }; const char* skip = nullptr; bool default_view = false; @@ -6464,11 +6498,16 @@ void copy_descriptor_run(Wrapper* self, UINT count, u64 dest, u64 src, D3D12_DES const UINT src_stride = title_descriptor_stride(src, increment); while (count) { UINT dest_room, src_room, dest_total, src_total; + const bool history_tracking = history_planning_enabled(); + HistoryObservation history_dest{}, history_src{}; u64 dest_mirror = 0, src_mirror = 0; - const auto d = desktop_cpu_handle(dest, &dest_room, &dest_total, &dest_mirror); - const auto s = desktop_cpu_handle(src, &src_room, &src_total, &src_mirror); + const auto d = desktop_cpu_handle(dest, &dest_room, &dest_total, &dest_mirror, history_tracking ? &history_dest : nullptr); + const auto s = desktop_cpu_handle(src, &src_room, &src_total, &src_mirror, history_tracking ? &history_src : nullptr); if (count > dest_total || count > src_total || !d || !s) return; const UINT chunk = (std::min)(count, (std::min)(dest_room, src_room)); + HistoryCopyExpected history_expected_copy{}; + if (history_tracking) + history_expected_copy = history_plan_copy(history_src, history_dest, chunk, src_stride, dest_stride, increment, type); // A visible source is read from its mirror. A visible destination is written to its mirror and copied // from there, so a later copy out of it reads what this one wrote. const u64 source = src_mirror ? src_mirror : s; @@ -6478,7 +6517,7 @@ void copy_descriptor_run(Wrapper* self, UINT count, u64 dest, u64 src, D3D12_DES } else { device_of(self)->CopyDescriptorsSimple(chunk, {static_cast(d)}, {static_cast(source)}, type); } - note_copy(dest, src, d, s, chunk, increment); + note_copy(dest, src, d, s, chunk, increment, &history_expected_copy); dest += u64{chunk} * dest_stride; src += u64{chunk} * src_stride; count -= chunk; @@ -6499,8 +6538,13 @@ void __stdcall device_copy_descriptors_simple(Wrapper* self, UINT count, u64 des void __stdcall device_console_sampler(Wrapper* self, const UINT* words, u64 destination) { if (!words || !x2w_local::readable(words, 27 * sizeof(UINT))) return; + const bool history_tracking = history_planning_enabled(); + HistoryObservation history_observation{}; u64 mirror = 0; - const auto handle = desktop_cpu_handle(destination, nullptr, nullptr, &mirror); + const auto handle = desktop_cpu_handle(destination, nullptr, nullptr, &mirror, history_tracking ? &history_observation : nullptr); + HistoryExpected history_expected_view{}; + if (history_tracking) + history_expected_view = history_plan_view(history_observation, device_of(self), D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); if (!handle) return; const auto create = [&](const D3D12_SAMPLER_DESC& sampler) { write_descriptor(device_of(self), handle, mirror, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, [&](u64 at) { @@ -6515,7 +6559,7 @@ void __stdcall device_console_sampler(Wrapper* self, const UINT* words, u64 dest words[16] > D3D12_COMPARISON_FUNC_ALWAYS || !std::all_of(words + 6, words + 9, address_valid)) { sampler = x2w_startup::border_sampler(); create(sampler); - note_view(22, 0, 0, &sampler, sizeof(sampler), destination, handle); + note_view(22, 0, 0, &sampler, sizeof(sampler), destination, handle, true, &history_expected_view); static LONG refused; if (first_calls(refused, 4)) log("x2w-d3d12 unsupported console sampler fields; using border sampler"); return; @@ -6537,7 +6581,7 @@ void __stdcall device_console_sampler(Wrapper* self, const UINT* words, u64 dest std::memcpy(&sampler.MipLODBias, words + 11, sizeof(float)); std::memcpy(sampler.BorderColor, words + 17, sizeof(sampler.BorderColor)); create(sampler); - note_view(22, 0, 0, &sampler, sizeof(sampler), destination, handle); + note_view(22, 0, 0, &sampler, sizeof(sampler), destination, handle, true, &history_expected_view); } // Device slot 23, desktop CopyDescriptors(destCount, destStarts, destSizes, srcCount, srcStarts, srcSizes, type). @@ -7670,9 +7714,14 @@ extern "C" __declspec(dllexport) BOOL x2w_d3d12_record_uncreated_buffer_srv(void { if (!resource || !desc || desc_bytes < ViewRecord::srv_desc_bytes || !title_cpu) return FALSE; if (!x2w_local::readable(desc, ViewRecord::srv_desc_bytes)) return FALSE; - const u64 desktop = desktop_cpu_handle(title_cpu); + const bool history_tracking = history_planning_enabled(); + HistoryObservation history_observation{}; + const u64 desktop = desktop_cpu_handle(title_cpu, nullptr, nullptr, nullptr, history_tracking ? &history_observation : nullptr); + HistoryExpected history_expected_view{}; + if (history_tracking) + history_expected_view = history_plan_view(history_observation, nullptr, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); if (!desktop || desktop == title_cpu) return FALSE; - note_view(18, reinterpret_cast(resource), 0, desc, ViewRecord::srv_desc_bytes, title_cpu, desktop, false); + note_view(18, reinterpret_cast(resource), 0, desc, ViewRecord::srv_desc_bytes, title_cpu, desktop, false, &history_expected_view); return TRUE; } diff --git a/src/startup_stubs/descriptor_history/descriptor_history_config.h b/src/startup_stubs/descriptor_history/descriptor_history_config.h new file mode 100644 index 0000000000..f51d166327 --- /dev/null +++ b/src/startup_stubs/descriptor_history/descriptor_history_config.h @@ -0,0 +1,109 @@ +#pragma once +#include +#include +#include + +namespace descriptor_history_config { +using U = std::uint32_t; +inline constexpr U max_u = (std::numeric_limits::max)(); +inline constexpr std::size_t max_text = 256; +inline constexpr unsigned max_selectors = 2; + +enum class Mode { off, unfiltered, filtered, invalid }; +enum class Error { none, length, syntax, heap_type, visibility, number, + range, duplicate_heap, too_many, environment }; +enum class HeapType { view, sampler, rtv, dsv }; + +struct HeapKey { + HeapType type{}; + bool visible{}; + U node_mask{}, capacity{}, ordinal{}; +}; +struct Selector { + HeapKey heap{}; + U first{}, count{}; +}; +struct Config { + Mode mode{Mode::off}; + Error error{Error::none}; + Selector selectors[max_selectors]{}; + unsigned size{}; +}; + +constexpr bool same_heap(HeapKey a, HeapKey b) noexcept { + return a.type == b.type && a.visible == b.visible && + a.node_mask == b.node_mask && a.capacity == b.capacity && a.ordinal == b.ordinal; +} +constexpr Config invalid(Error error) noexcept { return {Mode::invalid, error}; } + +// Canonical unsigned decimal, with explicit overflow checking; no allocation. +constexpr bool number(std::string_view text, U& out) noexcept { + if (text.empty() || (text.size() > 1 && text.front() == '0')) return false; + U value = 0; + for (char c : text) { + if (c < '0' || c > '9') return false; + const U digit = static_cast(c - '0'); + if (value > (max_u - digit) / 10) return false; + value = value * 10 + digit; + } + out = value; + return true; +} + +constexpr Error parse_selector(std::string_view text, Selector& out) noexcept { + std::string_view fields[7]{}; + for (unsigned i = 0; i < 7; ++i) { + const auto pos = text.find(':'); + if ((i < 6 && pos == std::string_view::npos) || + (i == 6 && pos != std::string_view::npos)) return Error::syntax; + fields[i] = text.substr(0, pos); + if (fields[i].empty()) return Error::syntax; + if (i < 6) text.remove_prefix(pos + 1); + } + Selector candidate{}; + if (fields[0] == "view") candidate.heap.type = HeapType::view; + else if (fields[0] == "sampler") candidate.heap.type = HeapType::sampler; + else if (fields[0] == "rtv") candidate.heap.type = HeapType::rtv; + else if (fields[0] == "dsv") candidate.heap.type = HeapType::dsv; + else return Error::heap_type; + if (fields[1] == "cpu") candidate.heap.visible = false; + else if (fields[1] == "visible") candidate.heap.visible = true; + else return Error::visibility; + if (candidate.heap.visible && + (candidate.heap.type == HeapType::rtv || candidate.heap.type == HeapType::dsv)) + return Error::visibility; + if (!number(fields[2], candidate.heap.node_mask) || + !number(fields[3], candidate.heap.capacity) || + !number(fields[4], candidate.heap.ordinal) || + !number(fields[5], candidate.first) || + !number(fields[6], candidate.count)) return Error::number; + const auto& h = candidate.heap; + if (!h.capacity || !h.ordinal || !candidate.count || + candidate.first >= h.capacity || + candidate.count > h.capacity - candidate.first) return Error::range; + out = candidate; + return Error::none; +} + +// Off ignores the selector entirely. Empty is legacy unfiltered mode. +// Any nonempty malformed input rejects the whole diagnostic configuration. +constexpr Config parse(bool trace_enabled, std::string_view text) noexcept { + if (!trace_enabled) return {}; + if (text.empty()) return {Mode::unfiltered}; + if (text.size() > max_text) return invalid(Error::length); + Config result{Mode::filtered}; + for (;;) { + if (result.size == max_selectors) return invalid(Error::too_many); + const auto pos = text.find(';'); + Selector selector{}; + const auto error = parse_selector(text.substr(0, pos), selector); + if (error != Error::none) return invalid(error); + for (unsigned i = 0; i < result.size; ++i) + if (same_heap(result.selectors[i].heap, selector.heap)) + return invalid(Error::duplicate_heap); + result.selectors[result.size++] = selector; + if (pos == std::string_view::npos) return result; + text.remove_prefix(pos + 1); + } +} +} // namespace descriptor_history_config diff --git a/src/startup_stubs/descriptor_history/descriptor_history_config_win.h b/src/startup_stubs/descriptor_history/descriptor_history_config_win.h new file mode 100644 index 0000000000..55b7d4db60 --- /dev/null +++ b/src/startup_stubs/descriptor_history/descriptor_history_config_win.h @@ -0,0 +1,27 @@ +#pragma once +#include "descriptor_history_config.h" +#include + +namespace descriptor_history_config { +inline constexpr char variable[] = "X2W_D3D12_DESCRIPTOR_HISTORY_FILTER"; + +// Called only with the existing master-switch decision; no environment read when off. +// A runtime caller can cache this result at startup, log invalid configuration once, +// and leave ordinary D3D12 behavior untouched. +inline Config read_environment(bool trace_enabled) noexcept { + if (!trace_enabled) return {}; + const DWORD saved = GetLastError(); + char buffer[max_text + 1]{}; + SetLastError(ERROR_SUCCESS); + const DWORD length = GetEnvironmentVariableA(variable, buffer, static_cast(sizeof(buffer))); + const DWORD error = GetLastError(); + SetLastError(saved); + if (!length) { + if (error == ERROR_ENVVAR_NOT_FOUND || error == ERROR_SUCCESS) + return parse(true, {}); + return invalid(Error::environment); + } + if (length >= sizeof(buffer)) return invalid(Error::length); + return parse(true, std::string_view(buffer, length)); +} +} // namespace descriptor_history_config diff --git a/src/startup_stubs/descriptor_history/heap_shape.h b/src/startup_stubs/descriptor_history/heap_shape.h new file mode 100644 index 0000000000..52f7a81105 --- /dev/null +++ b/src/startup_stubs/descriptor_history/heap_shape.h @@ -0,0 +1,51 @@ +#pragma once +#include "descriptor_history_config.h" +#include +#include +#include + +// Logical heap shapes and checked guest byte spans. +// Only logical guest CPU handle mappings are considered, not desktop/GPU aliases. +namespace descriptor_history_heap { +namespace cfg = descriptor_history_config; +using U = std::uint32_t; +using V = std::uint64_t; +inline constexpr V max_v = (std::numeric_limits::max)(); +inline constexpr V discovery_limit = 256; + +struct Shape { + cfg::HeapType type{}; + bool visible{}; + U node_mask{}, capacity{}; +}; +constexpr bool same_shape(Shape a, Shape b) noexcept { + return a.type == b.type && a.visible == b.visible && + a.node_mask == b.node_mask && a.capacity == b.capacity; +} +constexpr Shape shape_of(cfg::HeapKey k) noexcept { + return {k.type,k.visible,k.node_mask,k.capacity}; +} +constexpr bool valid_shape(Shape s) noexcept { + if (!s.capacity) return false; + switch (s.type) { + case cfg::HeapType::view: case cfg::HeapType::sampler: return true; + case cfg::HeapType::rtv: case cfg::HeapType::dsv: return !s.visible; + } + return false; +} +struct Mapping { V base{}; U stride{}; }; // both zero = explicitly no guest mapping +struct Span { V first{}, last{}; }; // inclusive byte span, not descriptor selection +constexpr bool mapped(Mapping m) noexcept { return m.base != 0; } +constexpr bool valid_mapping(Shape s, Mapping m) noexcept { + if (!m.base || !m.stride) return !m.base && !m.stride; + // Both factors are uint32, so the product fits in uint64. + const V bytes = V{s.capacity} * m.stride; + return bytes && bytes - 1 <= max_v - m.base; +} +constexpr Span span(Shape s, Mapping m) noexcept { + return {m.base,m.base + (V{s.capacity} * m.stride - 1)}; +} +constexpr bool overlaps(Span a, Span b) noexcept { + return a.first <= b.last && b.first <= a.last; +} +} // namespace descriptor_history_heap diff --git a/src/startup_stubs/descriptor_history/history_admission.h b/src/startup_stubs/descriptor_history/history_admission.h new file mode 100644 index 0000000000..fede601081 --- /dev/null +++ b/src/startup_stubs/descriptor_history/history_admission.h @@ -0,0 +1,83 @@ +#pragma once +#include "history_budget.h" +#include "shadow_identity.h" + +// Caller holds note_lock throughout admission, +// sampling and logging; lookup must be a pure observation of that snapshot. +// No native descriptor operation is gated by this result. +namespace descriptor_history_admission { +namespace budget=descriptor_history_budget; +namespace shadow=descriptor_history_shadow; +namespace filter=descriptor_history_filter; +using budget::U; +enum class Operation { view, copy }; +enum class Failure { none, plan, allocation, publication, source, destination }; +struct Endpoint { + shadow::Expected expected{}; + shadow::Match start{}; +}; +struct Result { + budget::Batch batch{}; + Failure failure{}; + shadow::Verdict verdict{}; +}; +inline Result reject(Failure failure,shadow::Verdict verdict=shadow::Verdict::verified) noexcept { + return {{budget::Decision::rejected},failure,verdict}; +} +// A selected operation is all-or-nothing for the admitted prefix. Unselected +// and over-budget rows are never probed. At full budget a valid nonempty plan +// and verified starting spans establish a capacity omission, not verification +// of the omitted rows. Rejected attribution or allocation does not truncate. +template +Result admit(budget::Budget& live,const filter::Plan& plan,U count, + Operation op,const Endpoint& source,const Endpoint& destination, + bool allocation_failed,Lookup lookup,Publication publication) noexcept { + auto preview=live; + const auto batch=preview.take(plan,count); + if(batch.decision==budget::Decision::rejected|| + batch.decision==budget::Decision::invalid_plan) + return {batch,Failure::plan}; + if(batch.decision!=budget::Decision::admitted)return {batch}; + if(!batch.count()&&!batch.truncate)return {batch}; + if(op==Operation::view && count!=1)return reject(Failure::plan); + if(allocation_failed) { + if(plan.status==filter::Status::unfiltered)return {}; + return reject(Failure::allocation); + } + if(plan.status==filter::Status::unfiltered){ + live=preview;return {batch}; + } + // Both starts must belong to the same publication and operation extent. + const auto current=publication(); + const auto check_start=[&](const Endpoint& ep,Failure failure) noexcept -> Result { + if(ep.expected.publication!=current)return reject(Failure::publication,shadow::Verdict::stale); + if(ep.expected.count!=count)return reject(failure,shadow::Verdict::short_span); + const auto v=shadow::validate(ep.expected,ep.start,current); + return v==shadow::Verdict::verified?Result{}:reject(failure,v); + }; + if(op==Operation::copy){ + auto result=check_start(source,Failure::source); + if(result.failure!=Failure::none)return result; + } + auto result=check_start(destination,Failure::destination); + if(result.failure!=Failure::none)return result; + for(unsigned j=0;j(i),current); + if(v!=shadow::Verdict::verified)return reject(Failure::source,v); + } + const auto v=shadow::validate_selected(destination.expected,destination.start, + lookup(false,i),static_cast(i),current); + if(v!=shadow::Verdict::verified)return reject(Failure::destination,v); + } + } + // Publication may change while the bounded pure lookups execute. + // This is the reservation point, not a claim of later GPU/guest ordering. + if(publication()!=current)return reject(Failure::publication,shadow::Verdict::stale); + live=preview; + return {batch}; +} +} // namespace descriptor_history_admission diff --git a/src/startup_stubs/descriptor_history/history_budget.h b/src/startup_stubs/descriptor_history/history_budget.h new file mode 100644 index 0000000000..ee1fdf50e2 --- /dev/null +++ b/src/startup_stubs/descriptor_history/history_budget.h @@ -0,0 +1,64 @@ +#pragma once +#include "history_filter.h" + +// One budget per diagnostic process; caller serializes +// planning, reservation, sampling and logging under its existing note lock. +// Never use this budget to gate actual descriptor operations. +namespace descriptor_history_budget { +namespace filter = descriptor_history_filter; +namespace range = descriptor_selection; +using U = range::U; +inline constexpr U limit = 8192; +enum class Decision { inactive, rejected, invalid_plan, admitted, stopped }; +struct Batch { + Decision decision{Decision::inactive}; + range::Window windows[2]{}; + unsigned size{}; + U first_sequence{}; // zero when no records admitted + bool truncate{}; // emit marker AFTER all admitted records + U count() const noexcept { + U n=0; + for (unsigned i=0;i2) return {Decision::invalid_plan}; + // Validate the entire plan before consuming any budget. + for (unsigned i=0;i=w.end || w.end>operation_count || + (i && plan.windows[i-1].end>=w.begin)) + return {Decision::invalid_plan}; + } + Batch out{Decision::admitted}; + for (unsigned i=0;ia.end) p.windows[0].end=b.end; + } else p.windows[p.size++]=b; + } +} +} // namespace descriptor_history_filter diff --git a/src/startup_stubs/descriptor_history/history_runtime.inl b/src/startup_stubs/descriptor_history/history_runtime.inl new file mode 100644 index 0000000000..6e4a3202a4 --- /dev/null +++ b/src/startup_stubs/descriptor_history/history_runtime.inl @@ -0,0 +1,182 @@ +// Optional targeted descriptor history. +// Registry access and mapping publication use descriptor_lock, never note_lock. +namespace history_cfg = descriptor_history_config; +namespace history_retained = descriptor_history_retained; +using HistoryObservation = history_retained::Observation; +namespace history_shadow = descriptor_history_shadow; +namespace history_filter = descriptor_history_filter; +namespace history_budget = descriptor_history_budget; +namespace history_admission = descriptor_history_admission; +struct HistoryExpected : history_shadow::Expected { + history_filter::Plan plan{}; + UINT guest_stride{}; +}; +std::atomic history_truncated{}; +void history_incomplete(const char* reason) +{ + const DWORD saved = GetLastError(); + static LONG reported; + if (x2w_local::first_calls(reported, 1)) + x2w_local::logf("x2w-descriptor-history incomplete reason=%s", reason); + SetLastError(saved); +} +// Access these records only while holding descriptor_lock. Generation indexes +// this array, never the independently published shadow table. +std::array history_owners{}; +std::atomic history_publication{}; + +static_assert(static_cast(history_cfg::HeapType::view) == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); +static_assert(static_cast(history_cfg::HeapType::sampler) == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); +static_assert(static_cast(history_cfg::HeapType::rtv) == D3D12_DESCRIPTOR_HEAP_TYPE_RTV); +static_assert(static_cast(history_cfg::HeapType::dsv) == D3D12_DESCRIPTOR_HEAP_TYPE_DSV); + +const history_cfg::Config& history_configuration() +{ + static const auto config = [] { + const DWORD saved = GetLastError(); + const auto c = history_cfg::read_environment(x2w_local::env_on("X2W_D3D12_DESCRIPTOR_HISTORY")); + if (c.mode == history_cfg::Mode::filtered) + x2w_local::logf("x2w-descriptor-registry mode=filtered selectors=%u retained_limit=%u", + c.size, history_retained::capacity); + else if (c.mode == history_cfg::Mode::invalid) + x2w_local::logf("x2w-descriptor-registry mode=invalid error=%u history_disabled=1", + static_cast(c.error)); + SetLastError(saved); + return c; + }(); + return config; +} +bool history_filtered() +{ + return history_configuration().mode == history_cfg::Mode::filtered; +} +bool history_planning_enabled() +{ + return history_filtered() && !history_truncated.load(std::memory_order_relaxed); +} +bool history_legacy_enabled() +{ + return history_configuration().mode == history_cfg::Mode::unfiltered && + !history_truncated.load(std::memory_order_relaxed); +} +history_retained::Registry& history_registry() +{ + static history_retained::Registry registry(history_configuration()); + return registry; +} +struct HistoryRegistrationReceipt { + history_retained::Registration record{}; + history_retained::Receipt receipt{}; + unsigned selected_mask{}; + u64 owner{}; +}; +// Caller holds descriptor_lock exclusively and has already inserted the mapping. +HistoryRegistrationReceipt history_register_heap(const D3D12_DESCRIPTOR_HEAP_DESC& requested, + u64 title, UINT title_stride, u64 desktop, UINT desktop_stride, UINT prefix, u64 tail, u64 mirror, u64 wrapper) +{ + auto& registry = history_registry(); + HistoryRegistrationReceipt result{}; + result.record = {{static_cast(requested.Type), + (requested.Flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) != 0, + requested.NodeMask, requested.NumDescriptors}, {title, title ? title_stride : 0}, + title ? static_cast(descriptor_ranges.size()) : 0, desktop, tail, desktop_stride, prefix, mirror}; + result.owner = wrapper; + result.receipt = registry.append(result.record); + if (result.receipt.generation) + history_owners[result.receipt.generation - 1] = wrapper; + // Publish even on a fault: previously captured expectations must become stale. + history_publication.fetch_add(1, std::memory_order_release); + if (result.receipt.generation) + for (unsigned i = 0; i < history_cfg::max_selectors; ++i) + if (registry.selected_generation(i) == result.receipt.generation) + result.selected_mask |= 1u << i; + return result; +} +void history_report_registration(const HistoryRegistrationReceipt& result) +{ + const DWORD saved = GetLastError(); + const auto& a = result.record; + const auto& r = result.receipt; + if (r.fault != history_retained::Fault::none) { + static LONG reported; + if (x2w_local::first_calls(reported, 1)) { + x2w_local::logf("x2w-descriptor-registry fault=%u history_incomplete=1", + static_cast(r.fault)); + if (!history_truncated.load(std::memory_order_relaxed)) + history_incomplete("registry-fault"); + } + } else { + if (r.discover || result.selected_mask) + x2w_local::logf("x2w-descriptor-registry generation=%llu mapping=%llu type=%u visible=%u node=%u " + "logical=%u guest=%llx guest_stride=%u desktop=%llx desktop_stride=%u prefix=%u tail=%llx mirror=%llx selected=%u discovery=%u owner=%llx", + r.generation, a.mapping_index, static_cast(a.shape.type), a.shape.visible ? 1u : 0u, + a.shape.node_mask, a.shape.capacity, a.guest.base, a.guest.stride, a.desktop, + a.desktop_stride, a.prefix, a.tail, a.mirror, result.selected_mask, r.discover ? 1u : 0u, result.owner); + if (r.discovery_truncated) + x2w_local::logf("x2w-descriptor-registry discovery_truncated limit=%llu", + descriptor_history_heap::discovery_limit); + } + SetLastError(saved); +} + +void history_complete_observation(HistoryObservation& o, UINT count, UINT guest_stride, + UINT desktop_stride, D3D12_DESCRIPTOR_HEAP_TYPE type) +{ + o.count = count; + o.guest_stride = guest_stride; + o.desktop_stride = desktop_stride; + o.type = static_cast(type); +} +// Caller holds descriptor_lock. Copy values, never pointers into the table. +HistoryExpected history_expected(history_retained::Endpoint endpoint) +{ + const u64 publication = history_publication.load(std::memory_order_relaxed); + if (endpoint.status == history_retained::Attribution::mapped && + endpoint.generation && endpoint.generation <= history_retained::capacity) { + history_retained::Registration record{}; + if (history_registry().registration(endpoint.generation, record)) + { + HistoryExpected result{}; + static_cast(result) = + history_shadow::expected(record, endpoint, history_owners[endpoint.generation - 1], publication); + return result; + } + } + HistoryExpected result{}; + result.attribution = endpoint.status; + result.publication = publication; + result.count = endpoint.count; + return result; +} +HistoryExpected history_plan_view(HistoryObservation o, ID3D12Device* device, D3D12_DESCRIPTOR_HEAP_TYPE type) +{ + const DWORD saved = GetLastError(); + const UINT stride = device ? device->GetDescriptorHandleIncrementSize(type) : o.desktop_stride; + history_complete_observation(o, 1, o.mapping_index ? o.guest_stride : stride, stride, type); + AcquireSRWLockShared(&descriptor_lock); + const auto endpoint = history_registry().attribute(o); + auto result = history_expected(endpoint); + result.plan = history_registry().plan(endpoint, endpoint); + result.guest_stride = o.guest_stride; + ReleaseSRWLockShared(&descriptor_lock); + SetLastError(saved); + return result; +} +struct HistoryCopyExpected { HistoryExpected source{}, destination{}; }; +HistoryCopyExpected history_plan_copy(HistoryObservation s, HistoryObservation d, UINT count, UINT src_stride, + UINT dest_stride, UINT increment, D3D12_DESCRIPTOR_HEAP_TYPE type) +{ + const DWORD saved = GetLastError(); + history_complete_observation(s, count, src_stride, increment, type); + history_complete_observation(d, count, dest_stride, increment, type); + AcquireSRWLockShared(&descriptor_lock); + const auto a = history_registry().attribute(s), b = history_registry().attribute(d); + HistoryCopyExpected result{history_expected(a), history_expected(b)}; + result.destination.plan = history_registry().plan(a, b); + result.source.plan = result.destination.plan; + result.source.guest_stride = src_stride; + result.destination.guest_stride = dest_stride; + ReleaseSRWLockShared(&descriptor_lock); + SetLastError(saved); + return result; +} diff --git a/src/startup_stubs/descriptor_history/range_selection.h b/src/startup_stubs/descriptor_history/range_selection.h new file mode 100644 index 0000000000..8a3586bb80 --- /dev/null +++ b/src/startup_stubs/descriptor_history/range_selection.h @@ -0,0 +1,32 @@ +#pragma once +#include +#include + +namespace descriptor_selection { +using U = std::uint64_t; +inline constexpr U max_u = (std::numeric_limits::max)(); + +struct Run { U base, stride, count; }; +struct Target { U first, last; }; // inclusive handle-start addresses +struct Window { U begin{}, end{}; }; // half-open copy-index interval + +constexpr bool valid(Run r) noexcept { + return !r.count || (r.stride && r.count - 1 <= (max_u - r.base) / r.stride); +} +constexpr bool valid(Target t) noexcept { return t.first <= t.last; } + +// Return the copy indices whose handle starts fall within the target. +// No descriptor-byte overlap semantics; no address dereferences. +constexpr Window intersect(Run r, Target t) noexcept { + if (!valid(r) || !valid(t) || !r.count || t.last < r.base) return {}; + const U lo = t.first > r.base ? t.first - r.base : 0; + const U hi = t.last - r.base; + const U begin = lo / r.stride + (lo % r.stride != 0); + if (begin >= r.count) return {}; + // Clamp before adding one, including hi == UINT64_MAX and stride == 1. + const U last = hi / r.stride; + const U end = last >= r.count - 1 ? r.count : last + 1; + return begin < end ? Window{begin, end} : Window{}; +} + +} // namespace descriptor_selection diff --git a/src/startup_stubs/descriptor_history/retained_registry.h b/src/startup_stubs/descriptor_history/retained_registry.h new file mode 100644 index 0000000000..30684ca239 --- /dev/null +++ b/src/startup_stubs/descriptor_history/retained_registry.h @@ -0,0 +1,183 @@ +#pragma once +#include "history_budget.h" +#include + +// All registry operations require external synchronization. +// Registration and the runtime mapping insertion must share a publication lock. +// No production mapping or COM lifetime changes. Desktop handles are opaque. +namespace descriptor_history_retained { +namespace cfg=descriptor_history_config; +namespace heap=descriptor_history_heap; +namespace filter=descriptor_history_filter; +namespace range=descriptor_selection; +using U=std::uint32_t; +using V=std::uint64_t; +inline constexpr unsigned capacity=1024; // retained registrations, not live references +inline constexpr V max_v=heap::max_v; +enum class Fault { none, invalid_config, invalid_registration, capacity, publication_order }; +enum class Attribution { inactive, empty, mapped, opaque, stale, ambiguous, invalid, faulted }; +struct Registration { + heap::Shape shape{}; + heap::Mapping guest{}; + V mapping_index{}; // 1-based position in existing append-only descriptor_ranges; 0 if absent + V desktop{}, tail{}; + U desktop_stride{}, prefix{}; + V mirror{}; // CPU-only companion of the canonical visible prefix; no separate logical identity +}; +struct Receipt { V generation{}; bool discover{}, discovery_truncated{}; Fault fault{}; }; +struct Observation { + V epoch{}, mapping_count{}, mapping_index{}; // captured by actual resolver, NOT guessed later + V guest{}, desktop{}; + U count{}, guest_stride{}, desktop_stride{}; + cfg::HeapType type{}; + V mirror{}; // actual optional mirror handle returned by the same resolver +}; +struct Endpoint { + Attribution status{Attribution::inactive}; + V generation{}; + U slot{},count{}; +}; +constexpr bool checked_last(V base,V stride,V count) noexcept { + return base && stride && count && count-1 <= (max_v-base)/stride; +} +constexpr bool valid_registration(Registration r) noexcept { + if (!heap::valid_shape(r.shape) || !heap::valid_mapping(r.shape,r.guest) || + !r.prefix || r.prefix>r.shape.capacity || + !checked_last(r.desktop,r.desktop_stride,r.prefix)) return false; + const U tail_count=r.shape.capacity-r.prefix; + if (tail_count ? !checked_last(r.tail,r.desktop_stride,tail_count) : r.tail!=0) return false; + if(r.mirror && (!r.shape.visible || !heap::mapped(r.guest) || + !checked_last(r.mirror,r.desktop_stride,r.prefix)))return false; + return (r.mapping_index!=0)==heap::mapped(r.guest) && + (heap::mapped(r.guest)||!tail_count); +} +class Registry { + struct Selected { U seen{}; V generation{}; }; + cfg::Config config_; + std::array records_{}; + std::array selected_{}; + V size_{}, mapped_count_{}; + Fault fault_{Fault::none}; + bool active() const noexcept {return config_.mode==cfg::Mode::filtered && fault_==Fault::none;} + Receipt reject(Fault f) noexcept {fault_=f;return {0,false,false,f};} +public: + explicit Registry(cfg::Config c) noexcept:config_(c) { + if(c.mode!=cfg::Mode::filtered)return; + if(!c.size||c.size>cfg::max_selectors){fault_=Fault::invalid_config;return;} + for(unsigned i=0;i=s.heap.capacity||s.count>s.heap.capacity-s.first){ + fault_=Fault::invalid_config;return; + } + for(unsigned j=0;jsize_)return false; + out=records_[generation-1]; + return true; + } + bool selected_unmapped() const noexcept { + if(!active())return false; + for(unsigned i=0;imax_v-o.guest)return {Attribution::invalid}; + const heap::Span run{o.guest,o.guest+bytes-1}; + V chosen=0;unsigned intersections=0; + for(V i=0;i=s.first&&o.guest<=s.last)chosen=i+1; + } + // Preserve actual first-containing mapping; do not infer intent from it. + // Even an overlap beginning halfway through the run is ambiguous. + if(intersections>1)return {Attribution::ambiguous,chosen}; + if(!chosen){ + if(intersections||o.mapping_index||o.desktop!=o.guest|| + o.guest_stride!=o.desktop_stride||o.mirror)return {Attribution::invalid}; + return {Attribution::opaque,0,0,o.count}; + } + const auto& r=records_[chosen-1]; + if(o.mapping_index!=r.mapping_index||o.type!=r.shape.type|| + o.guest_stride!=r.guest.stride||o.desktop_stride!=r.desktop_stride) + return {Attribution::invalid,chosen}; + const V offset=o.guest-r.guest.base; + if(offset%r.guest.stride)return {Attribution::invalid,chosen}; + const V slot=offset/r.guest.stride; + if(o.count>r.shape.capacity-slot)return {Attribution::invalid,chosen}; + const bool tail=slot>=r.prefix; + const V end=tail?r.shape.capacity:r.prefix; + if(o.count>end-slot)return {Attribution::invalid,chosen}; // runtime must split at prefix/tail + const V index=tail?slot-r.prefix:slot; + const V expected=(tail?r.tail:r.desktop)+index*r.desktop_stride; + const V expected_mirror=!tail&&r.mirror?r.mirror+index*r.desktop_stride:0; + if(o.desktop!=expected||o.mirror!=expected_mirror)return {Attribution::invalid,chosen}; + return {Attribution::mapped,chosen,static_cast(slot),o.count}; + } + bool usable(Endpoint e) const noexcept { + return e.status==Attribution::mapped||e.status==Attribution::opaque|| + e.status==Attribution::empty; + } + range::Window window(Endpoint e) const noexcept { + if(e.status!=Attribution::mapped)return {}; + for(unsigned i=0;ie.logical||e.slot>=e.logical|| + e.count>e.logical-e.slot)return Verdict::uncertain_mapping; + if(e.slot>=e.prefix)return Verdict::tail; + if(e.count>e.prefix-e.slot)return Verdict::short_span; + if(m.lookup.heap==x2w_startup::DescriptorHeapMatch::none)return Verdict::missing; + if(m.lookup.off_boundary)return Verdict::off_boundary; + if(m.lookup.boundary_matches!=1)return Verdict::shared_boundary; + if(m.owner!=e.owner)return Verdict::wrong_owner; + if(m.guest_base!=e.guest_base||m.desktop_base!=e.desktop_base||m.type!=e.type|| + m.stride!=e.stride||m.physical!=e.prefix||m.logical!=e.logical)return Verdict::wrong_heap; + if(m.lookup.index!=e.slot)return Verdict::wrong_slot; + if(m.room!=e.prefix-e.slot||e.count>m.room)return Verdict::short_span; + return Verdict::verified; +} +// An additional selected-row boundary check is not the original copy lookup. +// It can only establish uniqueness for that row in the same note-lock snapshot. +// Caller may bound this work by the admitted event budget, not the original run length. +constexpr Verdict validate_selected(const Expected& e,const Match& start,const Match& row, + U offset,V current_publication) noexcept { + const auto v=validate(e,start,current_publication); + if(v!=Verdict::verified)return v; + if(offset>=e.count)return Verdict::short_span; + auto single=e;single.slot+=offset;single.count=1; + return validate(single,row,current_publication); +} +} // namespace descriptor_history_shadow diff --git a/tests/cmake/startup_descriptor_history.cmake b/tests/cmake/startup_descriptor_history.cmake new file mode 100644 index 0000000000..a42a2a397e --- /dev/null +++ b/tests/cmake/startup_descriptor_history.cmake @@ -0,0 +1,15 @@ +# Targeted descriptor history: pure range/registry/admission checks and source-built Mesh controls. +add_executable(startup_descriptor_history_check tests/startup_descriptor_history_check.cpp) +target_include_directories(startup_descriptor_history_check PRIVATE src) +target_compile_features(startup_descriptor_history_check PRIVATE cxx_std_17) +add_test(NAME startup_descriptor_history_model COMMAND startup_descriptor_history_check) +if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_indirect_draw_indexed) + foreach(adapter IN ITEMS warp hardware) + foreach(family IN ITEMS filter exhaustion) + add_test(NAME startup_descriptor_history_${family}_${adapter} + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_descriptor_history_check.py" + "$" ${adapter} ${family}) + set_tests_properties(startup_descriptor_history_${family}_${adapter} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) + endforeach() + endforeach() +endif() diff --git a/tests/startup_descriptor_history_check.cpp b/tests/startup_descriptor_history_check.cpp new file mode 100644 index 0000000000..31e4fd34c2 --- /dev/null +++ b/tests/startup_descriptor_history_check.cpp @@ -0,0 +1,352 @@ +// Source-built checks for the same filtering, attribution and admission code used by the shim. +#include "startup_stubs/descriptor_history/history_admission.h" +#include +#include +#include +#include +#include +#include + +namespace admission_checks { +using namespace descriptor_history_admission; +using shadow::Verdict; +using filter::Status; +using budget::Decision; +static U checks{}; +void require(bool ok,const char* why){ + ++checks;if(!ok){std::cerr<<"FAIL "<; +shadow::Match observe(const Heaps& h,U handle){ + shadow::Match m{}; + m.lookup=x2w_startup::match_descriptor_heap(h.size(),handle,[&](std::size_t i,x2w_startup::DescriptorHeapSpan& s){ + s={h[i].base,h[i].stride,h[i].capacity};return true; + }); + if(m.lookup.found()){ + const auto& a=h[m.lookup.heap]; + m.owner=a.owner;m.guest_base=a.guest;m.desktop_base=a.base;m.stride=a.stride; + m.physical=m.logical=a.capacity;m.room=a.capacity-static_cast(m.lookup.index); + } + return m; +} +Endpoint endpoint(const Heap& h,shadow::U slot,shadow::U count,const Heaps& all,U gen){ + const shadow::retained::Registration r{{shadow::cfg::HeapType::view,false,0,h.capacity},{h.guest,h.stride},gen,h.base,0,h.stride,h.capacity,0}; + return {shadow::expected(r,{shadow::Attribution::mapped,gen,slot,count},h.owner,2),observe(all,h.base+U{slot}*h.stride)}; +} +struct Fixture { + Heap s{101,0x100000,3,32,1000000},d{202,0x4000000,4,32,1000000}; + Heaps heaps{s,d}; + Endpoint src{},dst{}; + U reads{},queries{},change_at{},epoch=2; + std::vector> visits; + bool corrupt_source=false,corrupt_dest=false; + U corrupt_offset=0; + explicit Fixture(shadow::U count=8){ + src=endpoint(s,0,count,heaps,1);dst=endpoint(d,0,count,heaps,2); + } + Result run(budget::Budget& b,filter::Plan p,U n,Operation op=Operation::copy,bool failed=false){ + return admit(b,p,n,op,src,dst,failed,[&](bool source,U i){ + ++reads;visits.emplace_back(source,i); + auto m=observe(heaps,(source?s.base:d.base)+i*32); + if(i==corrupt_offset && (source?corrupt_source:corrupt_dest))++m.lookup.boundary_matches; + return m; + },[&]{++queries;return change_at&&queries>=change_at?epoch+1:epoch;}); + } +}; +void prefill(budget::Budget& b,U n){ + auto t=b.take(plan(0,n,0,0,Status::unfiltered),n); + require(t.count()==n&&!b.stopped(),"prefill"); +} +void exact(const Result& r,U count,U first,bool marker,const char* why){ + require(r.failure==Failure::none&&r.batch.decision==Decision::admitted&& + r.batch.count()==count&&r.batch.first_sequence==first&&r.batch.truncate==marker,why); +} +void rejected(const Result& r,const budget::Budget& b,U used,Failure reason,Verdict v,const char* why){ + require(r.failure==reason&&r.verdict==v&&!r.batch.count()&&!r.batch.truncate&&b.used()==used&&!b.stopped(),why); +} +void directed(){ + budget::Budget b;Fixture f; + exact(f.run(b,plan(0,1,4,6),8),3,1,false,"two windows"); + require(f.visits==std::vector>{{true,4},{false,4},{true,5},{false,5}},"selected visits only and start reused"); + require(b.used()==3&&f.queries==2,"committed exactly once"); + Fixture a; a.heaps.push_back({303,0x8000000,a.s.base+2*32,32,1}); + a.src=endpoint(a.s,0,8,a.heaps,1); + require(shadow::validate(a.src.expected,a.src.start,2)==Verdict::verified,"actual unique start with later overlap"); + rejected(a.run(b,plan(1,4),8),b,3,Failure::source,Verdict::shared_boundary,"source later row rollback"); + require(a.reads==3,"stop at first failed source row"); + Fixture d;d.heaps.push_back({303,0x8000000,d.d.base+3*32,32,1}); + d.dst=endpoint(d.d,0,8,d.heaps,2); + rejected(d.run(b,plan(1,4),8),b,3,Failure::destination,Verdict::shared_boundary,"destination later row rollback"); + require(d.reads==6,"stop at failed destination row"); + Fixture skip;skip.heaps=a.heaps; + exact(skip.run(b,plan(3,4),8),1,4,false,"unselected ambiguity not probed"); + require(skip.reads==2,"unselected traversal avoided"); + Fixture stale;stale.change_at=2; + rejected(stale.run(b,plan(1,4),8),b,4,Failure::publication,Verdict::stale,"publication changes during row checks"); + Fixture initial;initial.epoch=3; + rejected(initial.run(b,plan(1,4),8),b,4,Failure::publication,Verdict::stale,"initial stale publication"); + require(initial.reads==0,"stale no row probes"); + Fixture opaque;opaque.src.expected.attribution=shadow::Attribution::opaque; + rejected(opaque.run(b,plan(0,1),8),b,4,Failure::source,Verdict::opaque,"opaque source rejected"); + Fixture missing;missing.dst.start={}; + rejected(missing.run(b,plan(0,1),8),b,4,Failure::destination,Verdict::missing,"missing destination rejected"); + Fixture wrong;wrong.dst.expected.count=7; + rejected(wrong.run(b,plan(0,1),8),b,4,Failure::destination,Verdict::short_span,"extent mismatch"); + Fixture v(1); + rejected(v.run(b,plan(0,1),1,Operation::view,true),b,4,Failure::allocation,Verdict::verified,"selected allocation failure"); + require(!v.reads&&!v.queries,"allocation failure no probes"); + exact(v.run(b,plan(0,0),1,Operation::view,true),0,0,false,"unselected allocation ignored"); + exact(v.run(b,plan(0,1),1,Operation::view),1,5,false,"fresh recovery view"); + require(!v.reads&&v.queries==2,"view start reused"); + Fixture legacy; + legacy.src.start={};legacy.dst.start={};legacy.epoch=9; + exact(legacy.run(b,plan(0,8,0,0,Status::unfiltered),8),8,6,false,"legacy bypass identity"); + require(!legacy.reads&&!legacy.queries,"legacy no attribution"); + auto fail=legacy.run(b,plan(0,1,0,0,Status::unfiltered),1,Operation::view,true); + require(fail.batch.decision==Decision::inactive&&b.used()==13,"legacy allocation omitted"); + Fixture invalid; + auto malformed=plan(0,2,3,9); + auto r=invalid.run(b,malformed,8); + require(r.failure==Failure::plan&&r.batch.decision==Decision::invalid_plan&&b.used()==13,"invalid plan"); + r=invalid.run(b,{Status::uncertain_endpoint},8); + require(r.failure==Failure::plan&&r.batch.decision==Decision::rejected&&b.used()==13,"uncertain plan"); + r=invalid.run(b,{Status::off},8); + require(r.batch.decision==Decision::inactive&&!invalid.reads&&!invalid.queries,"off and invalid no probes"); +} +void cap(){ + budget::Budget b;prefill(b,budget::limit-2); + Fixture f;f.corrupt_dest=true;f.corrupt_offset=5; + rejected(f.run(b,plan(1,2,5,8),8),b,budget::limit-2,Failure::destination,Verdict::shared_boundary,"partial-cap rollback no premature marker"); + Fixture g(1000000);g.corrupt_source=true;g.corrupt_offset=6; + exact(g.run(b,plan(1,2,5,1000000),1000000),2,budget::limit-1,true,"million clipped and overbudget not probed"); + require(g.visits==std::vector>{{true,1},{false,1},{true,5},{false,5}}&&b.stopped(),"only admitted rows probed"); + Fixture after; + for(unsigned i=0;i<10000;++i){ + auto r=after.run(b,plan(0,8),8); + require(r.batch.decision==Decision::stopped&&!r.batch.count()&&!r.batch.truncate,"post stop"); + } + require(!after.reads&&!after.queries,"post stop zero work"); + budget::Budget full;prefill(full,budget::limit); + Fixture no; + exact(no.run(full,plan(0,0),8),0,0,false,"full empty not stopped"); + require(!no.reads&&!no.queries&&!full.stopped(),"empty full no work"); + Fixture bad;bad.dst.start={}; + rejected(bad.run(full,plan(0,1),8),full,budget::limit,Failure::destination,Verdict::missing,"full invalid start no marker"); + Fixture alloc(1); + rejected(alloc.run(full,plan(0,1),1,Operation::view,true),full,budget::limit,Failure::allocation,Verdict::verified,"full allocation no marker"); + Fixture race;race.change_at=2; + rejected(race.run(full,plan(0,1),8),full,budget::limit,Failure::publication,Verdict::stale,"full stale no marker"); + Fixture valid; + exact(valid.run(full,plan(2,4),8),0,0,true,"full valid selected omission"); + require(!valid.reads&&valid.queries==2&&full.stopped(),"full marker no row probes"); + budget::Budget one;prefill(one,budget::limit-1); + Fixture only;only.corrupt_source=true;only.corrupt_offset=5; + exact(only.run(one,plan(1,2,5,8),8),1,budget::limit,true,"whole omitted window skipped"); + require(only.reads==2&&one.stopped(),"omitted window no probes"); + budget::Budget legacy;prefill(legacy,budget::limit-1); + Fixture l; + exact(l.run(legacy,plan(0,8,0,0,Status::unfiltered),8),1,budget::limit,true,"legacy cap"); + require(!l.reads&&!l.queries&&legacy.stopped(),"legacy no checks"); +} +void randomized(){ + std::mt19937_64 rng(0x56c13321); + for(unsigned t=0;t<20000;++t){ + const auto count=static_cast(1+rng()%64); + const U remaining=rng()%65,used=budget::limit-remaining; + budget::Budget b;prefill(b,used); + Fixture f(count); + const U a=rng()%(count+1),z=a+rng()%(count-a+1),c=z+rng()%(count-z+1),d=c+rng()%(count-c+1); + auto p=plan(a,z,c,d); + if(p.size==2&&p.windows[0].end==p.windows[1].begin){p.windows[0].end=p.windows[1].end;p.size=1;} + std::vector selected; + for(U i=0;i=a&&i=c&&i((std::min)(remaining,static_cast(selected.size()))); + const bool marker=selected.size()>admitted; + unsigned kind=t%6; + const U off=rng()%count; + f.corrupt_offset=off;f.corrupt_source=kind==1;f.corrupt_dest=kind==2; + if(kind==3)f.change_at=2; + if(kind==4)f.src.start={}; + const bool allocation=kind==5; + Failure failure=Failure::none;Verdict verdict=Verdict::verified; + std::vector> visits; + if(!selected.empty()){ + if(allocation)failure=Failure::allocation; + else if(kind==4){failure=Failure::source;verdict=Verdict::missing;} + else{ + for(std::size_t i=0;i indices; + for(unsigned j=0;j(selected.begin(),selected.begin()+admitted),"random exact admitted prefix"); + } + require(f.visits==visits,"random exact probe sequence"); + } +} +void run(){ + directed();cap();randomized(); + std::cout<<"PASS transactional admission assertions="<(rng()%64),gs=t%2?64:32,ds=t%3?32:16; + const V base=0x10000+(rng()%100000)*0x10000; + const V native=3,mirror=t%5?5:0,tailbase=prefix<64?0x1000:0; + require(m.append(reg(visible,base,1,native,prefix,tailbase,mirror,gs,ds)).generation==1,"random registration"); + const U slot=static_cast(rng()%64),count=1+static_cast(rng()%65); + const bool tail_slot=slot>=prefix; + const V canonical=(tail_slot?tailbase:native)+V{tail_slot?slot-prefix:slot}*ds; + const V companion=tail_slot||!mirror?0:mirror+V{slot}*ds; + auto o=obs(m,1,base+V{slot}*gs,canonical,count,companion,gs,ds); + const bool valid=V{slot}+count<=(tail_slot?64:prefix); + expect(m,o,valid?Attribution::mapped:Attribution::invalid,"random chunk oracle"); + if(valid){ + auto e=m.attribute(o); + require(e.generation==1&&e.slot==slot&&e.count==count,"random logical identity"); + auto p=m.plan(e,e); + unsigned want=0; + for(U i=0;i=16&&slot+i<24)++want; + require(p.status==filter::Status::filtered&&selected_count(p)==want,"random selected interval"); + o.mirror=companion?companion-1:1; + expect(m,o,Attribution::invalid,"random corrupt mirror"); + } + } + std::cout<<"PASS mirror registry assertions="<=32 and nstep>0 and ns!=nd and nsd!=ndd + src,dst,dd=[hx(raw,k) for k in ("source","guest","desktop")] + heaps=records(s,"x2w-d3d12 Device::CreateDescriptorHeap ") + assert len(heaps)==4 and [hx(x,"desktop") for x in heaps[:3]]==[nsd,ndd,dd] + sd=hx(heaps[3],"desktop") + assert all(not base<=v8192 + assert [(h["op"],hx(h,"guest"),hx(h,"source"),hx(h,"desktop")) for h in hist]==expected[:8192] + markers=[l for l in s.splitlines() if l.startswith("x2w-descriptor-history truncated")] + assert markers==(["x2w-descriptor-history truncated limit=8192"] if truncated else []) + if markers:assert s.rindex("x2w-descriptor-history seq=")0 + assert h["guest_before"]=="00000000,"*7+"00000000" + regs=records(s,"x2w-descriptor-registry generation=") + if mode in ("target","noise","mixed","sparse"): + assert [dec(h,"generation") for h in regs]==[1,2,3,4] + assert [hx(h,"guest") for h in regs]==[ns,nd,dst,src] + assert [dec(h,"selected") for h in regs]=={ + "target":[0,0,2,1],"noise":[1,0,0,0],"mixed":[1,0,2,0],"sparse":[1,2,0,0]}[mode] + else:assert not regs + if mode=="target":check_history(o,s,case) + print(f"descriptor history exhaustion: slots={slots} mode={mode} records={len(hist)} truncated={int(truncated)}",flush=True) + +def main(): + exe,adapter,family=Path(sys.argv[1]).resolve(),sys.argv[2],sys.argv[3] + assert family in ("filter","exhaustion") + if family=="filter": + selectors={"both":SOURCE+";"+DESTINATION,"source":SOURCE,"destination":DESTINATION, + "empty":"","off":"invalid","invalid":"invalid","unmatched":"view:cpu:0:1:2:0:1"} + cases=[(case,mode) for case in CASES for mode in ("both","source","destination")] + cases += [("positive",mode) for mode in ("empty","off","invalid","unmatched")] + for case,mode in cases: + if not check(exe,adapter,case,trace=mode!="off",settings={"X2W_D3D12_DESCRIPTOR_HISTORY_FILTER":selectors[mode]}, + history_check=lambda o,s,c:check_filtered(o,s,c,mode)):return 77 + else: + cases=[(4093,"legacy"),(4094,"legacy"),(5000,"legacy"),(5000,"target"),(5000,"off"), + (4096,"noise"),(5000,"noise"),(4095,"mixed"),(5000,"sparse")] + for slots,mode in cases: + settings={"X2W_MESH_PROVENANCE_NOISE_SLOTS":str(slots)} + noise=f"view:cpu:0:{slots}:1:0:{slots}" + selector={"target":SOURCE+";"+DESTINATION,"noise":noise,"mixed":noise+";"+DESTINATION, + "sparse":f"view:cpu:0:{slots}:1:2:3;view:cpu:0:{slots}:2:8:2"}.get(mode) + if selector is not None:settings["X2W_D3D12_DESCRIPTOR_HISTORY_FILTER"]=selector + if not check(exe,adapter,"positive",trace=mode!="off",settings=settings, + history_check=lambda o,s,c:check_exhaustion(o,s,c,slots,mode)):return 77 + print(f"PASS descriptor history {family}: {len(cases)} cases") + return 0 + +if __name__=="__main__": + sys.exit(main()) diff --git a/tests/startup_mesh_argument_provenance.inl b/tests/startup_mesh_argument_provenance.inl index a51866f278..75c0c5b88a 100644 --- a/tests/startup_mesh_argument_provenance.inl +++ b/tests/startup_mesh_argument_provenance.inl @@ -55,6 +55,68 @@ RWByteAddressBuffer data : register(u0); return result; }; const auto seed_pipeline = pipeline("seed_input"), update_pipeline = pipeline("update_args"); + // Optional unrelated CPU-only heaps before the Mesh provenance operations. + // Two events per slot: source creation, followed by one bulk descriptor copy. + char noise_setting[16]{}; + const DWORD noise_length = GetEnvironmentVariableA("X2W_MESH_PROVENANCE_NOISE_SLOTS", noise_setting, sizeof(noise_setting)); + UINT noise_slots = 0; + if (noise_length) { + if (noise_length >= sizeof(noise_setting)) return false; + const std::string noise_value = noise_setting; + if (noise_value == "4093") noise_slots = 4093; + else if (noise_value == "4094") noise_slots = 4094; + else if (noise_value == "4095") noise_slots = 4095; + else if (noise_value == "4096") noise_slots = 4096; + else if (noise_value == "5000") noise_slots = 5000; + else if (noise_value != "0") return false; + } + // Keep both heaps alive through the positive fixture so their ranges cannot be reused. + ComPtr noise_source, noise_destination; + if (noise_slots) { + struct ExtendedHeapDesc { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 address, bytes; + }; + const ExtendedHeapDesc noise_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, noise_slots, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}, 0, 0}; + check(guest->CreateDescriptorHeap(&noise_desc.desc, IID_PPV_ARGS(&noise_source)), "provenance noise source heap"); + check(guest->CreateDescriptorHeap(&noise_desc.desc, IID_PPV_ARGS(&noise_destination)), "provenance noise destination heap"); + using NoiseHandle = UINT64 (WINAPI*)(IUnknown*, void*); + using NoiseView = void (WINAPI*)(IUnknown*, IUnknown*, const D3D12_SHADER_RESOURCE_VIEW_DESC*, UINT64, UINT64); + using NoiseCopy = void (WINAPI*)(IUnknown*, UINT, UINT64, UINT64, D3D12_DESCRIPTOR_HEAP_TYPE); + const UINT64 src = slot(noise_source.Get(), 9)(noise_source.Get(), nullptr); + const UINT64 dst = slot(noise_destination.Get(), 9)(noise_destination.Get(), nullptr); + const UINT step = guest->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (!src || !dst || src == dst || step < 32) return false; + D3D12_SHADER_RESOURCE_VIEW_DESC noise_srv{}; + noise_srv.Format = DXGI_FORMAT_R32_TYPELESS; + noise_srv.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + noise_srv.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + noise_srv.Buffer.NumElements = 1; + noise_srv.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + for (UINT i = 0; i < noise_slots; ++i) + slot(guest, 18)(guest, nullptr, &noise_srv, src + UINT64{i} * step, 0); + slot(guest, 24)(guest, noise_slots, dst, src, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + for (UINT i = 0; i < noise_slots; ++i) { + const auto* s = reinterpret_cast(src + UINT64{i} * step); + const auto* d = reinterpret_cast(dst + UINT64{i} * step); + UINT magic = 0; + std::memcpy(&magic, s, sizeof(magic)); + if (magic != 0x56573258 || std::memcmp(s, d, 32) != 0) return false; + } + const auto native_src = native_object(device, guest, noise_source.Get()); + const auto native_dst = native_object(device, guest, noise_destination.Get()); + if (!native_src || !native_dst) return false; + const auto src_desktop = native_src->GetCPUDescriptorHandleForHeapStart().ptr; + const auto dst_desktop = native_dst->GetCPUDescriptorHandleForHeapStart().ptr; + const UINT native_stride = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if (!src_desktop || !dst_desktop || src_desktop == dst_desktop || !native_stride || + native_src->GetDesc().NumDescriptors != noise_slots || native_dst->GetDesc().NumDescriptors != noise_slots) + return false; + std::printf("provenance noise slots=%u events=%u src=%llx dst=%llx stride=%u src_desktop=%llx dst_desktop=%llx desktop_stride=%u tokens=verified\n", + noise_slots, 2 * noise_slots, src, dst, step, static_cast(src_desktop), + static_cast(dst_desktop), native_stride); + } const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; ComPtr heap, source_heap; diff --git a/tests/startup_mesh_argument_provenance_check.py b/tests/startup_mesh_argument_provenance_check.py index 6d599f2ea1..cebc61d5f7 100644 --- a/tests/startup_mesh_argument_provenance_check.py +++ b/tests/startup_mesh_argument_provenance_check.py @@ -71,13 +71,17 @@ def check_history(stdout, stderr, scenario): assert previous[0] == "56573258" and int(previous[1], 16) + 1 == int(event["old"]), event -def check(executable, adapter, scenario, trace=True): +def check(executable, adapter, scenario, trace=True, *, settings=None, history_check=None): env = dict(os.environ) + env.pop("X2W_D3D12_DESCRIPTOR_HISTORY_FILTER", None) + env.pop("X2W_MESH_PROVENANCE_NOISE_SLOTS", None) env["X2W_MESH_PROVENANCE_CASE"] = scenario if trace: env["X2W_D3D12_DESCRIPTOR_HISTORY"] = "1" else: env.pop("X2W_D3D12_DESCRIPTOR_HISTORY", None) + if settings: + env.update(settings) # Always inspect this process's stderr, not a caller's persistent trap log. env.pop("X2W_TRAP_LOG", None) result = subprocess.run([str(executable), adapter, "mesh-provenance"], env=env, @@ -114,7 +118,9 @@ def check(executable, adapter, scenario, trace=True): assert write["offset"] == scalar["offset"] == "16" and write["value"] == scalar["value"] == "2", scalar assert scalar["adjacent_offset"] == "32" and scalar["adjacent_value"] == "0", scalar assert result.stdout.index("provenance record phase=post-write") < result.stdout.index("provenance consumer ") - if trace: + if history_check is not None: + history_check(result.stdout, result.stderr, scenario) + elif trace: check_history(result.stdout, result.stderr, scenario) else: assert "x2w-descriptor-history " not in result.stderr, result.stderr From e2609c0eff8403e284aa026b8ef83eafa9cb829a Mon Sep 17 00:00:00 2001 From: Vilify-13 <109003055+Vilify-13@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:41:15 -0500 Subject: [PATCH 3/3] gpu: refine targeted descriptor history after review --- CMakePresets.json | 2 +- docs/experiments.md | 4 - docs/experiments/descriptor-history-filter.md | 100 ++++++++++--- src/startup_stubs/d3d12_capture.inl | 111 ++++++++------- src/startup_stubs/d3d12_xs_device.cpp | 1 + .../descriptor_history/heap_shape.h | 1 - .../descriptor_history/history_omissions.h | 76 ++++++++++ .../descriptor_history/history_runtime.inl | 30 ++-- .../descriptor_history/retained_registry.h | 9 +- tests/cmake/startup_descriptor_history.cmake | 2 +- tests/startup_descriptor_history_check.cpp | 131 +++++++++++++++++- tests/startup_descriptor_history_check.py | 66 ++++++++- tests/startup_mesh_argument_provenance.inl | 72 +++++++++- .../startup_mesh_argument_provenance_check.py | 1 + 14 files changed, 506 insertions(+), 100 deletions(-) create mode 100644 src/startup_stubs/descriptor_history/history_omissions.h diff --git a/CMakePresets.json b/CMakePresets.json index e760f6ad0a..b1b1419079 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -50,7 +50,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_mesh_argument_provenance_warp|startup_descriptor_history_(model|(filter|exhaustion)_warp)|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" + "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_mesh_argument_provenance_warp|startup_descriptor_history_(model|(filter|exhaustion|incomplete)_warp)|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run)$" } } }, diff --git a/docs/experiments.md b/docs/experiments.md index ddb1b477ad..8506dfdc05 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -2,10 +2,6 @@ New notes go in `docs/experiments/.md` (see [the folder guide](experiments/README.md)); this file keeps the older notes. -## Targeted descriptor history - -[Selector grammar, attribution limits and source-built regression commands](experiments/descriptor-history-filter.md) - ## First native graphics draw through the stand-in Set `X2W_NATIVE_SHADERS` to the desktop DXC directory and `X2W_SHADER_CACHE` to a writable cache. diff --git a/docs/experiments/descriptor-history-filter.md b/docs/experiments/descriptor-history-filter.md index c56f706563..3f63422646 100644 --- a/docs/experiments/descriptor-history-filter.md +++ b/docs/experiments/descriptor-history-filter.md @@ -45,17 +45,21 @@ performed after truncation. With filtering enabled, registration lines show generation, mapping index, heap shape, guest and desktop handle starts, strides, prefix, tail and mirror information, and a selector bit mask. Bit 0 represents the first -selector and bit 1 the second. Discovery emits the first 256 registrations -and a discovery-truncation notice; a later selected registration is still -reported. The registry retains at most 1,024 logical registrations, not -1,024 live COM references. Exceeding its capacity or encountering an invalid -registration faults attribution and reports an incomplete trace. Mirrors -are companions of their logical heap, not additional selector ordinals. - -Use actual same-run mapping and shadow identity to confirm selections. -Ordinals can change across executions, configurations, adapters or concurrent -registrations; they are not stable title identifiers. A selector may never -become available. No end-of-process completeness receipt is supplied. Zero +selector and bit 1 the second. Discovery emits one line for every successfully +retained registration, including selected registrations, up to the registry +capacity of 1,024 logical registrations (not live COM references). There is +no independent discovery cutoff. Exceeding capacity or encountering an invalid +registration faults attribution and reports an incomplete trace; failed +registrations do not emit discovery lines. Mirrors are companions of their +logical heap, not additional selector ordinals. + +Use the registration lines to identify the heap shape and count successful +registrations of that exact shape in generation order to obtain its ordinal. +Generation is a global registration number, not the per-shape ordinal. +Confirm the selected bit mask, mapping and shadow identity on the targeted +run. Ordinals can change across executions, configurations, adapters or +concurrent registrations; they are not stable title identifiers. A selector may +never become available. No end-of-process completeness receipt is supplied. Zero records or absence of a truncation marker is not proof of a complete history. Attribution is conservative. Ambiguous overlapping mappings, stale mapping @@ -67,6 +71,23 @@ copy. Registration lookup is bounded by the retained registry size, and selected-row shadow checks by the event budget; this is not a constant-time end-to-end lookup claim. +Incomplete-history messages retain their reason and add a cumulative +`count=` for that reason. Each process counts refused operations by reason +(not omitted descriptor rows), or failed registrations for `registry-fault`. +Messages are emitted at counts 1, 2, 4, 8 and successive powers of two. +Counters saturate at the maximum 64-bit value, limiting each reason to 64 +messages (576 across all nine reasons); they do not consume the +descriptor-record budget. The separate registry fault marker remains one-time. +Concurrent messages may appear out of count order. The highest reported +count is a lower bound, not a final total; +no shutdown summary is promised. Disabled or invalid history does not count +omissions; after truncation, history admission stops and registration failures +are not counted once truncation is observed. + +With history disabled, the cached active check bypasses history-specific +shadow observations, reservation and sampling. This is a structural change +to the disabled path, not a claim of zero overhead or performance parity. + Trace fields describe CPU shadow publication and a pre-token-write guest sample, not native descriptor bytes, guest copy completion, arbitrary guest CPU stores or GPU execution order. View IDs can be reused. Filtered SRV @@ -76,26 +97,71 @@ alone does not satisfy the remaining integration criteria of issue #3310. ## Reproduce -With the ordinary Windows prerequisites (including DXC and Python), build -both configurations and run the GPU tests serially: +Use the ordinary Windows prerequisites in +[CONTRIBUTING.md](../../CONTRIBUTING.md#build-and-test), including DXC and the +Python environment prepared before configuring. Use a non-elevated x64 +Windows PowerShell from the repository root. See the +[Mesh fixture prerequisites](mesh-argument-provenance.md#reproduce) for +adapter/runtime capability requirements. Configure and build both +configurations and run the GPU tests serially: ```powershell +. .\tools\dev.ps1 +$env:X2W_D3D12_DEBUG = '1' +$selection = '^startup_(descriptor_history_(model|(filter|exhaustion|incomplete)_(warp|hardware))|mesh_argument_provenance_(warp|hardware))$' foreach ($preset in @('dev', 'release')) { + cmake --preset $preset + if ($LASTEXITCODE -ne 0) { throw "Configure failed: $preset" } cmake --build --preset $preset --target startup_descriptor_history_check startup_indirect_draw_indexed - ctest --preset $preset --no-tests=error -j 1 -V -R '^startup_(descriptor_history_(model|(filter|exhaustion)_(warp|hardware))|mesh_argument_provenance_(warp|hardware))$' + if ($LASTEXITCODE -ne 0) { throw "Build failed: $preset" } + ctest --preset $preset -N -R $selection + ctest --preset $preset --no-tests=error -j 1 -V -R $selection + if ($LASTEXITCODE -ne 0) { throw "Tests failed: $preset" } } ``` +With all fixtures registered, the selection contains nine CTest tests: +the model, the filter/exhaustion/incomplete families on each adapter, and +the two Mesh argument provenance tests. Check the inventory printed by +`ctest -N` rather than interpreting a smaller registered subset as a pass. The model check covers parsing, retained mappings, mirror/tail identities, ambiguous endpoints, transactional admission, bounded secondary lookups, -publication changes and capacity boundaries. The GPU check uses the original +publication changes, full-capacity discovery and independent omission counters, +including concurrent increments and saturation. The GPU check uses the original provenance oracle, including positive pixels and four negative controls, with source-only, destination-only, and combined filters. The exhaustion check adds unrelated null SRV creation and bulk copies, checks the exact admitted event sequence and truncation marker, and verifies that selecting only the later Mesh heaps preserves their history. A sparse case checks -disjoint copy windows. Capability skips are reported separately. These -fixtures do not establish full-game behavior. +disjoint copy windows. The incomplete-history check runs three cases per +adapter: + +| Case | Descriptor records | Incomplete messages | Discovery records | +|---|---:|---:|---:| +| Native CPU-only SRV source | 4 | 3 | 2 | +| Same native operations, history off | 0 | 0 | 0 | +| Full registry and overflow | 5 | 5 | 1,024 | + +The native-source case copies five times from outside the guest registry. +The expected refusal reason is `selected-copy-untracked` at counts 1, 2 +and 4. The GPU still reads the intended scalar, consumes the matching +`(2,1,1)` record and produces all eight expected pixels. A later valid +creation retains a contiguous history sequence. The guest token is unchanged +for the native-source copy, so this does not establish guest-token provenance. + +The discovery case selects the final two of 1,024 real heap registrations +and checks their positive GPU oracle before overflow. Five further allocations +succeed natively, with one registry fault marker and `registry-fault` counts +1, 2 and 4. Subsequent view and copy operations exercise independent +`view-attribution` and `copy-attribution` counts; neither adds descriptor +records. Token equality and device status are checked after overflow, not +another GPU draw. + +Report capability skips (77) separately. Record the adapter, driver, Windows +build, configuration, exact source revision and per-test result. A +`provenance debug info_queue=present` line supports the ERROR/CORRUPTION check; +an absent queue is not evidence of error-free debug output. These fixtures +do not establish full-game behavior. ## Credits diff --git a/src/startup_stubs/d3d12_capture.inl b/src/startup_stubs/d3d12_capture.inl index 4e676fbebf..4795e1c7c1 100644 --- a/src/startup_stubs/d3d12_capture.inl +++ b/src/startup_stubs/d3d12_capture.inl @@ -723,23 +723,9 @@ history_budget::Batch history_reserve(history_admission::Operation op, UINT coun shadow_slot((from_source ? src_desktop : dest_desktop) + i * increment, nullptr, &row, false); return row; }, []() noexcept { return history_publication.load(std::memory_order_acquire); }); - using Failure = history_admission::Failure; - using Verdict = history_shadow::Verdict; - switch (result.failure) { - case Failure::none: break; - case Failure::plan: history_incomplete(op == history_admission::Operation::view ? "view-attribution" : "copy-attribution"); break; - case Failure::allocation: history_incomplete("selected-view-allocation-failed"); break; - case Failure::publication: history_incomplete("registration-changed-before-note"); break; - case Failure::source: - case Failure::destination: - if (result.verdict == Verdict::stale) history_incomplete("registration-changed-before-note"); - else if (result.verdict == Verdict::shared_boundary || result.verdict == Verdict::off_boundary) - history_incomplete("selected-shadow-ambiguous"); - else if (result.verdict == Verdict::opaque || result.verdict == Verdict::tail || result.verdict == Verdict::missing) - history_incomplete(op == history_admission::Operation::view ? "selected-view-untracked" : "selected-copy-untracked"); - else history_incomplete("selected-shadow-identity"); - break; - } + const auto reason = history_omissions::reason_for(op, result.failure, result.verdict); + if (reason != history_omissions::Reason::count) + history_incomplete(reason); SetLastError(saved); return result.batch; } @@ -757,13 +743,17 @@ void history_finish(const history_budget::Batch& batch) // the old view. Nothing records the new view's use of its resource, so the resource leaves the retire class and is not // released early. Allocates nothing. Enters with note_lock held and releases it. void drop_unrecorded_view(const ViewRecord& record, bool materialized, const char* container, - const HistoryExpected* expected = nullptr) + bool active, const HistoryExpected* expected) { - history_shadow::Match match{}; - std::uint32_t* slot_ptr = shadow_slot(record.dest_desktop, nullptr, history_shadow_observe(expected) ? &match : nullptr); - if (history_filtered()) + std::uint32_t* slot_ptr; + if (active && history_filtered()) { + history_shadow::Match match{}; + slot_ptr = shadow_slot(record.dest_desktop, nullptr, history_shadow_observe(expected) ? &match : nullptr); history_reserve(history_admission::Operation::view, 1, nullptr, expected, {}, match, 0, record.dest_desktop, 0, true); + } else { + slot_ptr = shadow_slot(record.dest_desktop); + } if (slot_ptr) { const std::uint32_t prev = *slot_ptr; *slot_ptr = 0; @@ -851,6 +841,7 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ const bool freeable = view_content_tokens() && x2w_startup::encode_view_content(view_token_magic, record.slot, resource, counter, record.desc, record.desc_bytes, materialized, content); + const bool active = history_active(); AcquireSRWLockExclusive(¬e_lock); ++views_noted; const auto found = view_ids().find(hash); @@ -885,7 +876,7 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ } if (const char* container = store_view(record, created, hash, freeable)) { if (taken) park_view_record(record.id); // emptied, not in view_ids: never found, taken again later - drop_unrecorded_view(record, materialized, container, expected); + drop_unrecorded_view(record, materialized, container, active, expected); return; } ++views_distinct; @@ -895,15 +886,20 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ view_census.missed += !ids_full && view_ids().bucket_count() != buckets_before; } } - history_shadow::Match match{}; - std::uint32_t* slot_ptr = shadow_slot(dest_desktop, nullptr, history_shadow_observe(expected) ? &match : nullptr); - if (slot_ptr || history_filtered()) { - const auto batch = history_reserve(history_admission::Operation::view, 1, nullptr, expected, {}, match, - 0, dest_desktop, 0); - if (batch.count()) - trace_descriptor_history(batch.first_sequence, "create", dest_title, dest_desktop, 0, - slot_ptr ? *slot_ptr : 0, record.id + 1, slot == 22 ? x2w_startup::title_sampler_stride : 32u); - history_finish(batch); + std::uint32_t* slot_ptr; + if (active) { + history_shadow::Match match{}; + slot_ptr = shadow_slot(dest_desktop, nullptr, history_shadow_observe(expected) ? &match : nullptr); + if (slot_ptr || history_filtered()) { + const auto batch = history_reserve(history_admission::Operation::view, 1, nullptr, expected, {}, match, + 0, dest_desktop, 0); + if (batch.count()) + trace_descriptor_history(batch.first_sequence, "create", dest_title, dest_desktop, 0, + slot_ptr ? *slot_ptr : 0, record.id + 1, slot == 22 ? x2w_startup::title_sampler_stride : 32u); + history_finish(batch); + } + } else { + slot_ptr = shadow_slot(dest_desktop); } if (slot_ptr) { const std::uint32_t prev = *slot_ptr; @@ -940,30 +936,41 @@ void note_view(int slot, u64 resource, u64 counter, const void* desc, std::size_ void note_copy(u64 dest_title, u64 src_title, u64 dest_desktop, u64 src_desktop, UINT count, UINT increment, const HistoryCopyExpected* expected = nullptr) { - const bool legacy_history = history_legacy_enabled(); - const UINT dest_stride = legacy_history ? title_descriptor_stride(dest_title, increment) : - expected ? expected->destination.guest_stride : 0; - const UINT src_stride = legacy_history ? title_descriptor_stride(src_title, increment) : - expected ? expected->source.guest_stride : 0; + const bool active = history_active(); + UINT dest_stride = 0, src_stride = 0; + if (active) { + const bool legacy_history = history_legacy_enabled(); + dest_stride = legacy_history ? title_descriptor_stride(dest_title, increment) : + expected ? expected->destination.guest_stride : 0; + src_stride = legacy_history ? title_descriptor_stride(src_title, increment) : + expected ? expected->source.guest_stride : 0; + } AcquireSRWLockExclusive(¬e_lock); descriptors_copied += count; std::uint32_t dest_room = 0, src_room = 0; - history_shadow::Match dest_match{}, src_match{}; - const auto* dest_expected = expected ? &expected->destination : nullptr; - const auto* src_expected = expected ? &expected->source : nullptr; - std::uint32_t* to = shadow_slot(dest_desktop, &dest_room, history_shadow_observe(dest_expected) ? &dest_match : nullptr); - const std::uint32_t* from = shadow_slot(src_desktop, &src_room, history_shadow_observe(src_expected) ? &src_match : nullptr); - const auto batch = history_reserve(history_admission::Operation::copy, count, src_expected, dest_expected, - src_match, dest_match, src_desktop, dest_desktop, increment); - u64 sequence = batch.first_sequence; - for (unsigned j = 0; j < batch.size; ++j) - for (u64 i = batch.windows[j].begin; i < batch.windows[j].end; ++i) { - const auto previous = to && i < dest_room ? to[i] : 0; - const auto next = to && count <= dest_room ? (from && count <= src_room ? from[i] : 0) : previous; - trace_descriptor_history(sequence++, "copy", dest_title + i * dest_stride, dest_desktop + i * increment, - src_title + i * src_stride, previous, next, dest_stride); - } - history_finish(batch); + std::uint32_t* to; + const std::uint32_t* from; + if (active) { + history_shadow::Match dest_match{}, src_match{}; + const auto* dest_expected = expected ? &expected->destination : nullptr; + const auto* src_expected = expected ? &expected->source : nullptr; + to = shadow_slot(dest_desktop, &dest_room, history_shadow_observe(dest_expected) ? &dest_match : nullptr); + from = shadow_slot(src_desktop, &src_room, history_shadow_observe(src_expected) ? &src_match : nullptr); + const auto batch = history_reserve(history_admission::Operation::copy, count, src_expected, dest_expected, + src_match, dest_match, src_desktop, dest_desktop, increment); + u64 sequence = batch.first_sequence; + for (unsigned j = 0; j < batch.size; ++j) + for (u64 i = batch.windows[j].begin; i < batch.windows[j].end; ++i) { + const auto previous = to && i < dest_room ? to[i] : 0; + const auto next = to && count <= dest_room ? (from && count <= src_room ? from[i] : 0) : previous; + trace_descriptor_history(sequence++, "copy", dest_title + i * dest_stride, dest_desktop + i * increment, + src_title + i * src_stride, previous, next, dest_stride); + } + history_finish(batch); + } else { + to = shadow_slot(dest_desktop, &dest_room); + from = shadow_slot(src_desktop, &src_room); + } if (to && count <= dest_room) { if (from && count <= src_room) { // Every copied-in view is now named by one more tracked slot; every view the destination named before is diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 9be7912cd4..e625aebe4b 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -98,6 +98,7 @@ #include "descriptor_history/retained_registry.h" #include "descriptor_history/shadow_identity.h" #include "descriptor_history/history_admission.h" +#include "descriptor_history/history_omissions.h" #include "startup_stubs/xmem_section_buffer.h" #include "native_buffer_store_view.h" #include "native_compute_output.h" diff --git a/src/startup_stubs/descriptor_history/heap_shape.h b/src/startup_stubs/descriptor_history/heap_shape.h index 52f7a81105..6a5e03d33d 100644 --- a/src/startup_stubs/descriptor_history/heap_shape.h +++ b/src/startup_stubs/descriptor_history/heap_shape.h @@ -11,7 +11,6 @@ namespace cfg = descriptor_history_config; using U = std::uint32_t; using V = std::uint64_t; inline constexpr V max_v = (std::numeric_limits::max)(); -inline constexpr V discovery_limit = 256; struct Shape { cfg::HeapType type{}; diff --git a/src/startup_stubs/descriptor_history/history_omissions.h b/src/startup_stubs/descriptor_history/history_omissions.h new file mode 100644 index 0000000000..d57c5d20d7 --- /dev/null +++ b/src/startup_stubs/descriptor_history/history_omissions.h @@ -0,0 +1,76 @@ +#pragma once +#include "history_admission.h" +#include +#include +#include +#include + +// Omission reporting is independent of the descriptor-record budget. +// Each reason has a fixed-size process-wide counter; log only at powers of two. +namespace descriptor_history_omissions { +namespace admission = descriptor_history_admission; +using Count = std::uint64_t; +enum class Reason { + registry_fault, view_attribution, copy_attribution, view_allocation, + stale_publication, ambiguous_shadow, untracked_view, untracked_copy, + shadow_identity, count +}; +inline constexpr auto reason_count = static_cast(Reason::count); +inline constexpr std::array names{{ + "registry-fault", "view-attribution", "copy-attribution", + "selected-view-allocation-failed", "registration-changed-before-note", + "selected-shadow-ambiguous", "selected-view-untracked", + "selected-copy-untracked", "selected-shadow-identity" +}}; +constexpr Reason reason_for(admission::Operation op, admission::Failure failure, + admission::shadow::Verdict verdict) noexcept { + using Failure = admission::Failure; + using Verdict = admission::shadow::Verdict; + const bool view = op == admission::Operation::view; + switch (failure) { + case Failure::none: return Reason::count; + case Failure::plan: return view ? Reason::view_attribution : Reason::copy_attribution; + case Failure::allocation: return Reason::view_allocation; + case Failure::publication: return Reason::stale_publication; + case Failure::source: + case Failure::destination: + if (verdict == Verdict::stale) return Reason::stale_publication; + if (verdict == Verdict::shared_boundary || verdict == Verdict::off_boundary) + return Reason::ambiguous_shadow; + if (verdict == Verdict::opaque || verdict == Verdict::tail || verdict == Verdict::missing) + return view ? Reason::untracked_view : Reason::untracked_copy; + return Reason::shadow_identity; + } + return Reason::count; +} +constexpr bool milestone(Count n) noexcept { + return n && !(n & (n - 1)); +} +// Saturation avoids wraparound and a second sequence of milestone messages. +// Return zero once saturated; otherwise return the unique new count. +inline Count increment(std::atomic& counter) noexcept { + auto old = counter.load(std::memory_order_relaxed); + while (old != (std::numeric_limits::max)()) { + if (counter.compare_exchange_weak(old, old + 1, std::memory_order_relaxed)) + return old + 1; + } + return 0; +} +class Counters { + std::array, reason_count> counts_; +public: + Counters() noexcept { + for (auto& counter : counts_) std::atomic_init(&counter, Count{0}); + } + Count record(Reason reason) noexcept { + const auto index = static_cast(reason); + if (index >= reason_count) return 0; + const auto n = increment(counts_[index]); + return milestone(n) ? n : 0; + } + Count total(Reason reason) const noexcept { + const auto index = static_cast(reason); + return index < reason_count ? counts_[index].load(std::memory_order_relaxed) : 0; + } +}; +} // namespace descriptor_history_omissions diff --git a/src/startup_stubs/descriptor_history/history_runtime.inl b/src/startup_stubs/descriptor_history/history_runtime.inl index 6e4a3202a4..b95fb53853 100644 --- a/src/startup_stubs/descriptor_history/history_runtime.inl +++ b/src/startup_stubs/descriptor_history/history_runtime.inl @@ -7,17 +7,19 @@ namespace history_shadow = descriptor_history_shadow; namespace history_filter = descriptor_history_filter; namespace history_budget = descriptor_history_budget; namespace history_admission = descriptor_history_admission; +namespace history_omissions = descriptor_history_omissions; struct HistoryExpected : history_shadow::Expected { history_filter::Plan plan{}; UINT guest_stride{}; }; std::atomic history_truncated{}; -void history_incomplete(const char* reason) +void history_incomplete(history_omissions::Reason reason) { const DWORD saved = GetLastError(); - static LONG reported; - if (x2w_local::first_calls(reported, 1)) - x2w_local::logf("x2w-descriptor-history incomplete reason=%s", reason); + static history_omissions::Counters counters; + if (const auto count = counters.record(reason)) + x2w_local::logf("x2w-descriptor-history incomplete reason=%s count=%llu", + history_omissions::names[static_cast(reason)], static_cast(count)); SetLastError(saved); } // Access these records only while holding descriptor_lock. Generation indexes @@ -46,6 +48,16 @@ const history_cfg::Config& history_configuration() }(); return config; } +// Configuration is immutable for the process. Keep the disabled note path +// separate from live truncation, which is checked during admission. +bool history_active() +{ + static const bool active = [] { + const auto mode = history_configuration().mode; + return mode == history_cfg::Mode::unfiltered || mode == history_cfg::Mode::filtered; + }(); + return active; +} bool history_filtered() { return history_configuration().mode == history_cfg::Mode::filtered; @@ -102,19 +114,17 @@ void history_report_registration(const HistoryRegistrationReceipt& result) if (x2w_local::first_calls(reported, 1)) { x2w_local::logf("x2w-descriptor-registry fault=%u history_incomplete=1", static_cast(r.fault)); - if (!history_truncated.load(std::memory_order_relaxed)) - history_incomplete("registry-fault"); } + // Count failed registrations separately from refused descriptor operations. + if (!history_truncated.load(std::memory_order_relaxed)) + history_incomplete(history_omissions::Reason::registry_fault); } else { - if (r.discover || result.selected_mask) + if (r.discover) x2w_local::logf("x2w-descriptor-registry generation=%llu mapping=%llu type=%u visible=%u node=%u " "logical=%u guest=%llx guest_stride=%u desktop=%llx desktop_stride=%u prefix=%u tail=%llx mirror=%llx selected=%u discovery=%u owner=%llx", r.generation, a.mapping_index, static_cast(a.shape.type), a.shape.visible ? 1u : 0u, a.shape.node_mask, a.shape.capacity, a.guest.base, a.guest.stride, a.desktop, a.desktop_stride, a.prefix, a.tail, a.mirror, result.selected_mask, r.discover ? 1u : 0u, result.owner); - if (r.discovery_truncated) - x2w_local::logf("x2w-descriptor-registry discovery_truncated limit=%llu", - descriptor_history_heap::discovery_limit); } SetLastError(saved); } diff --git a/src/startup_stubs/descriptor_history/retained_registry.h b/src/startup_stubs/descriptor_history/retained_registry.h index 30684ca239..1b5814de3f 100644 --- a/src/startup_stubs/descriptor_history/retained_registry.h +++ b/src/startup_stubs/descriptor_history/retained_registry.h @@ -24,7 +24,7 @@ struct Registration { U desktop_stride{}, prefix{}; V mirror{}; // CPU-only companion of the canonical visible prefix; no separate logical identity }; -struct Receipt { V generation{}; bool discover{}, discovery_truncated{}; Fault fault{}; }; +struct Receipt { V generation{}; bool discover{}; Fault fault{}; }; struct Observation { V epoch{}, mapping_count{}, mapping_index{}; // captured by actual resolver, NOT guessed later V guest{}, desktop{}; @@ -59,7 +59,7 @@ class Registry { V size_{}, mapped_count_{}; Fault fault_{Fault::none}; bool active() const noexcept {return config_.mode==cfg::Mode::filtered && fault_==Fault::none;} - Receipt reject(Fault f) noexcept {fault_=f;return {0,false,false,f};} + Receipt reject(Fault f) noexcept {fault_=f;return {0,false,f};} public: explicit Registry(cfg::Config c) noexcept:config_(c) { if(c.mode!=cfg::Mode::filtered)return; @@ -97,7 +97,7 @@ class Registry { return false; } Receipt append(Registration r) noexcept { - if(!active())return {0,false,false,fault_}; + if(!active())return {0,false,fault_}; if(!valid_registration(r))return reject(Fault::invalid_registration); if(r.mapping_index && r.mapping_index!=mapped_count_+1) return reject(Fault::publication_order); @@ -109,7 +109,8 @@ class Registry { if(!s.generation&&heap::same_shape(r.shape,heap::shape_of(key))&&++s.seen==key.ordinal) s.generation=size_; } - return {size_,size_<=heap::discovery_limit,size_==heap::discovery_limit+1,Fault::none}; + // Every retained registration is discoverable; capacity is the only limit. + return {size_,true,Fault::none}; } // No retire() on this registry: pinned runtime has no mapping removal. // Reference count observations cannot change generation or mapping ownership. diff --git a/tests/cmake/startup_descriptor_history.cmake b/tests/cmake/startup_descriptor_history.cmake index a42a2a397e..156d4fd7a4 100644 --- a/tests/cmake/startup_descriptor_history.cmake +++ b/tests/cmake/startup_descriptor_history.cmake @@ -5,7 +5,7 @@ target_compile_features(startup_descriptor_history_check PRIVATE cxx_std_17) add_test(NAME startup_descriptor_history_model COMMAND startup_descriptor_history_check) if(EXISTS "${INTAKE_PYTHON}" AND TARGET startup_indirect_draw_indexed) foreach(adapter IN ITEMS warp hardware) - foreach(family IN ITEMS filter exhaustion) + foreach(family IN ITEMS filter exhaustion incomplete) add_test(NAME startup_descriptor_history_${family}_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_descriptor_history_check.py" "$" ${adapter} ${family}) diff --git a/tests/startup_descriptor_history_check.cpp b/tests/startup_descriptor_history_check.cpp index 31e4fd34c2..6d92373b22 100644 --- a/tests/startup_descriptor_history_check.cpp +++ b/tests/startup_descriptor_history_check.cpp @@ -1,10 +1,13 @@ // Source-built checks for the same filtering, attribution and admission code used by the shim. #include "startup_stubs/descriptor_history/history_admission.h" +#include "startup_stubs/descriptor_history/history_omissions.h" #include #include #include #include #include +#include +#include #include namespace admission_checks { @@ -325,16 +328,51 @@ void run() { "view:cpu:0:64:1:0:1;view:cpu:0:64:1:1:1","view:cpu:0:64:1:0:0"}) require(parse(true,text).mode==Mode::invalid,"reject invalid selector"); using namespace descriptor_history_retained; - Registry reg(parse(true,"view:cpu:0:1:1024:0:1")); + require(capacity == 1024, "unchanged retained capacity"); + Registry reg(parse(true,"view:cpu:0:1:257:0:1;view:cpu:0:1:1024:0:1")); const heap::Shape one{HeapType::view,false,0,1}; + unsigned discovered = 0; for (V i=1;i<=capacity;++i) { const auto result=reg.append({one,{0x10000+i*64,32},i,0x100000+i*64,0,32,1,0}); - require(result.generation==i&&result.discover==(i<=heap::discovery_limit)&& - result.discovery_truncated==(i==heap::discovery_limit+1),"bounded discovery"); + require(result.generation==i && result.fault==Fault::none, "successful registration"); + require(result.discover, "full-capacity discovery"); + discovered += result.discover; + require(reg.selected_generation(0)==(i>=257?257:0) && + reg.selected_generation(1)==(i==1024?1024:0), "late selector ordinals"); + } + require(discovered==1024 && reg.epoch()==1024 && reg.mapping_count()==1024, + "exactly one discovery receipt for every retained registration"); + for (V i : {256,257,1023,1024}) { + Registration record{}; + require(reg.registration(i,record) && record.mapping_index==i && + record.guest.base==0x10000+i*64 && record.desktop==0x100000+i*64, "boundary registration identity"); + const Observation observation{capacity,capacity,i,record.guest.base,record.desktop,1,32,32,HeapType::view,0}; + const auto endpoint=reg.attribute(observation); + require(endpoint.status==Attribution::mapped && endpoint.generation==i && endpoint.slot==0, + "boundary attribution"); + const auto plan=reg.plan(endpoint,endpoint); + require(plan.status==filter::Status::filtered && plan.size==(i==257||i==1024?1u:0u), + "late selector plan"); } - require(reg.selected_generation(0)==capacity,"selector beyond discovery"); const auto fault=reg.append({one,{0x50000,32},capacity+1,0x60000,0,32,1,0}); - require(fault.fault==Fault::capacity&®.plan({},{}).status==filter::Status::registry_fault,"fail closed at registry capacity"); + require(fault.fault==Fault::capacity && !fault.generation && !fault.discover && + reg.epoch()==capacity && reg.plan({},{}).status==filter::Status::registry_fault, + "fail closed at registry capacity"); + const auto repeated=reg.append({one,{0x50040,32},capacity+2,0x60040,0,32,1,0}); + require(repeated.fault==Fault::capacity && !repeated.generation && !repeated.discover && + reg.epoch()==capacity, "faulted registry cannot discover additional registrations"); + descriptor_history_budget::Budget budget; + const auto plan=reg.plan({},{}); + const auto batch=budget.take(plan,1); + require(batch.decision==descriptor_history_budget::Decision::rejected && !batch.count() && + !batch.truncate && budget.used()==0, "registry fault does not consume history budget"); + for (auto config : {parse(false,""),parse(true,""),parse(true,"invalid")}) { + Registry inactive(config); + const auto receipt=inactive.append({one,{0x10000,32},1,0x20000,0,32,1,0}); + require(!receipt.generation && !receipt.discover && inactive.epoch()==0, + "inactive registry does not discover heaps"); + } + std::cout<<"PASS full heap discovery retained=1024 discovered=1024 late_selectors=257,1024 fault=1025\n"; Registry overlap(parse(true,"view:cpu:0:1:1:0:1")); require(overlap.append({one,{0x10000,32},1,0x20000,0,32,1,0}).generation==1,"first retained mapping"); require(overlap.append({one,{0x10000,32},2,0x30000,0,32,1,0}).generation==2,"retain overlapping mapping"); @@ -345,8 +383,91 @@ void run() { } } +namespace omission_checks { +using namespace descriptor_history_omissions; +using admission::Operation; +using admission::Failure; +using admission::shadow::Verdict; +using configuration_checks::require; + +void run() { + constexpr std::array expected_names{{ + "registry-fault", "view-attribution", "copy-attribution", + "selected-view-allocation-failed", "registration-changed-before-note", + "selected-shadow-ambiguous", "selected-view-untracked", + "selected-copy-untracked", "selected-shadow-identity" + }}; + require(reason_count == expected_names.size(), "omission reason inventory"); + Counters counters; + for (unsigned i = 0; i < reason_count; ++i) { + const auto reason = static_cast(i); + require(names[i] == expected_names[i], "stable omission reason text"); + require(counters.total(reason) == 0, "independent initial counters"); + unsigned lines = 0; + for (Count n = 1; n <= 10000; ++n) { + const auto actual = counters.record(reason); + const bool expected = n == (Count{1} << lines); + require(actual == (expected ? n : 0), "exact per-reason milestones"); + if (expected) ++lines; + } + require(lines == 14 && counters.total(reason) == 10000, "bounded omission output"); + for (unsigned j = i + 1; j < reason_count; ++j) + require(counters.total(static_cast(j)) == 0, "other reasons untouched"); + } + require(counters.record(Reason::count) == 0, "no omission is not counted"); + for (const auto op : {Operation::view, Operation::copy}) { + const bool view = op == Operation::view; + require(reason_for(op, Failure::none, Verdict::verified) == Reason::count, "successful admission"); + require(reason_for(op, Failure::plan, Verdict::verified) == + (view ? Reason::view_attribution : Reason::copy_attribution), "plan reason"); + require(reason_for(op, Failure::allocation, Verdict::verified) == Reason::view_allocation, "allocation reason"); + require(reason_for(op, Failure::publication, Verdict::verified) == Reason::stale_publication, "publication reason"); + for (const auto failure : {Failure::source, Failure::destination}) { + require(reason_for(op, failure, Verdict::stale) == Reason::stale_publication, "stale shadow"); + for (const auto verdict : {Verdict::shared_boundary, Verdict::off_boundary}) + require(reason_for(op, failure, verdict) == Reason::ambiguous_shadow, "ambiguous shadow"); + for (const auto verdict : {Verdict::opaque, Verdict::tail, Verdict::missing}) + require(reason_for(op, failure, verdict) == + (view ? Reason::untracked_view : Reason::untracked_copy), "untracked endpoint"); + for (const auto verdict : {Verdict::uncertain_mapping, Verdict::wrong_owner, Verdict::wrong_heap, + Verdict::wrong_slot, Verdict::short_span}) + require(reason_for(op, failure, verdict) == Reason::shadow_identity, "other shadow refusal"); + } + } + constexpr auto max_count = (std::numeric_limits::max)(); + require(milestone(Count{1} << 63) && !milestone(max_count) && !milestone(0), "last milestone"); + std::atomic near_limit{max_count - 1}; + require(increment(near_limit) == max_count && increment(near_limit) == 0 && + near_limit.load() == max_count, "counter saturation"); + + // Concurrent callers can publish log lines in a different order, but each + // milestone must be claimed once and no counter updates may be lost. + Counters shared; + std::array, 4> results; + std::array threads; + for (unsigned i = 0; i < threads.size(); ++i) + threads[i] = std::thread([&, i] { + for (unsigned j = 0; j < 2500; ++j) + if (const auto count = shared.record(Reason::registry_fault)) + results[i].push_back(count); + }); + for (auto& thread : threads) thread.join(); + std::vector milestones; + for (const auto& values : results) + milestones.insert(milestones.end(), values.begin(), values.end()); + std::sort(milestones.begin(), milestones.end()); + require(milestones.size() == 14 && shared.total(Reason::registry_fault) == 10000, + "concurrent omission count"); + for (unsigned i = 0; i < milestones.size(); ++i) + require(milestones[i] == (Count{1} << i), "concurrent unique milestone"); + require(shared.total(Reason::copy_attribution) == 0, "concurrent reason independence"); + std::cout << "PASS omission counters reasons=9 occurrences_per_reason=10000 lines_per_reason=14 concurrent=10000\n"; +} +} // namespace omission_checks + int main() { configuration_checks::run(); registry_checks::run(); admission_checks::run(); + omission_checks::run(); } diff --git a/tests/startup_descriptor_history_check.py b/tests/startup_descriptor_history_check.py index 9105fc795c..7c22c7a4cf 100644 --- a/tests/startup_descriptor_history_check.py +++ b/tests/startup_descriptor_history_check.py @@ -115,9 +115,63 @@ def check_exhaustion(o,s,case,slots,mode): if mode=="target":check_history(o,s,case) print(f"descriptor history exhaustion: slots={slots} mode={mode} records={len(hist)} truncated={int(truncated)}",flush=True) +def check_incomplete(o,s,case,mode): + assert case == "positive" + assert one(o,"provenance debug ")["info_queue"] in ("present","absent") + assert not re.search(r"x2w-d3d12-debug .* sev=[01] ",s),s + assert "x2w-descriptor-history truncated" not in s + hist=records(s,"x2w-descriptor-history seq=") + assert [dec(h,"seq") for h in hist]==list(range(1,len(hist)+1)) + omissions=records(s,"x2w-descriptor-history incomplete ") + regs=records(s,"x2w-descriptor-registry generation=") + raw=one(o,"provenance descriptor ") + if mode in ("opaque-copy","off"): + opaque=one(o,"provenance opaque-copy ") + assert dec(opaque,"copies")==5 and opaque["guest_token"]=="unchanged" + assert hx(opaque,"destination")==hx(raw,"guest") + assert raw["token_source"]=="56573258,2" and raw["token_bound"]=="56573258,1" + if mode=="off": + assert not hist and not omissions and not regs + assert "x2w-descriptor-history " not in s and "x2w-descriptor-registry " not in s + else: + assert [(h["reason"],dec(h,"count")) for h in omissions]==[ + ("selected-copy-untracked",1),("selected-copy-untracked",2),("selected-copy-untracked",4)],omissions + assert len(regs)==2 and [dec(h,"selected") for h in regs]==[2,1] + assert hx(opaque,"source") not in {hx(h,k) for h in regs for k in ("guest","desktop","mirror")} + src,dst=hx(raw,"source"),hx(raw,"guest") + assert [(h["op"],hx(h,"guest"),hx(h,"source"),dec(h,"old"),dec(h,"new"),dec(h,"first")) + for h in hist]==[("create",dst,0,0,1,0),("create",src,0,0,2,8), + ("copy",dst,src,1,2,8),("create",src,0,2,3,4)],hist + assert all(dec(h,"slot")==18 and dec(h,"materialized")==1 for h in hist) + assert s.index("x2w-descriptor-history seq=3 ") < s.index("incomplete reason=selected-copy-untracked count=1") + assert s.index("incomplete reason=selected-copy-untracked count=4") < s.index("x2w-descriptor-history seq=4 ") + assert "x2w-descriptor-registry fault=" not in s + else: + assert mode=="discovery" + discovery=one(o,"provenance discovery ") + assert dec(discovery,"successful_heaps")==1029 and dec(discovery,"overflow")==5 and discovery["tokens"]=="verified" + assert [dec(h,"generation") for h in regs]==list(range(1,1025)),len(regs) + assert [dec(h,"mapping") for h in regs]==list(range(1,1025)) + assert all(dec(h,"logical")==dec(h,"prefix")==dec(h,"discovery")==1 for h in regs) + assert len({hx(h,"guest") for h in regs})==len({hx(h,"owner") for h in regs})==1024 + assert [dec(h,"selected") for h in regs]==[0]*1022+[2,1] + assert [dec(h,"visible") for h in regs]==[0]*1022+[1,0] + assert hx(regs[-2],"guest")==hx(raw,"guest") and hx(regs[-1],"guest")==hx(raw,"source") + assert "discovery_truncated" not in s + fault=one(s,"x2w-descriptor-registry fault=") + assert fault["fault"]=="3" and fault["history_incomplete"]=="1",fault + assert [(h["reason"],dec(h,"count")) for h in omissions]==[ + ("registry-fault",1),("registry-fault",2),("registry-fault",4), + ("view-attribution",1),("copy-attribution",1)],omissions + assert len(hist)==5 + assert s.index("x2w-descriptor-history seq=5 ") < s.index("x2w-descriptor-registry fault=") + check_history(o,s,case) + print(f"descriptor history incomplete: mode={mode} records={len(hist)} omissions={len(omissions)} registrations={len(regs)}",flush=True) + + def main(): exe,adapter,family=Path(sys.argv[1]).resolve(),sys.argv[2],sys.argv[3] - assert family in ("filter","exhaustion") + assert family in ("filter","exhaustion","incomplete") if family=="filter": selectors={"both":SOURCE+";"+DESTINATION,"source":SOURCE,"destination":DESTINATION, "empty":"","off":"invalid","invalid":"invalid","unmatched":"view:cpu:0:1:2:0:1"} @@ -126,7 +180,7 @@ def main(): for case,mode in cases: if not check(exe,adapter,case,trace=mode!="off",settings={"X2W_D3D12_DESCRIPTOR_HISTORY_FILTER":selectors[mode]}, history_check=lambda o,s,c:check_filtered(o,s,c,mode)):return 77 - else: + elif family=="exhaustion": cases=[(4093,"legacy"),(4094,"legacy"),(5000,"legacy"),(5000,"target"),(5000,"off"), (4096,"noise"),(5000,"noise"),(4095,"mixed"),(5000,"sparse")] for slots,mode in cases: @@ -137,6 +191,14 @@ def main(): if selector is not None:settings["X2W_D3D12_DESCRIPTOR_HISTORY_FILTER"]=selector if not check(exe,adapter,"positive",trace=mode!="off",settings=settings, history_check=lambda o,s,c:check_exhaustion(o,s,c,slots,mode)):return 77 + else: + cases=("opaque-copy","off","discovery") + for mode in cases: + settings={"X2W_MESH_PROVENANCE_HISTORY_CONTROL":"opaque-copy" if mode=="off" else mode, + "X2W_D3D12_DESCRIPTOR_HISTORY_FILTER": + "view:cpu:0:1:1023:0:1;"+DESTINATION if mode=="discovery" else SOURCE+";"+DESTINATION} + if not check(exe,adapter,"positive",trace=mode!="off",settings=settings, + history_check=lambda o,s,c:check_incomplete(o,s,c,mode)):return 77 print(f"PASS descriptor history {family}: {len(cases)} cases") return 0 diff --git a/tests/startup_mesh_argument_provenance.inl b/tests/startup_mesh_argument_provenance.inl index 75c0c5b88a..11400e0c8c 100644 --- a/tests/startup_mesh_argument_provenance.inl +++ b/tests/startup_mesh_argument_provenance.inl @@ -14,6 +14,15 @@ bool check_mesh_argument_provenance(ID3D12Device* device, ID3D12Device* guest, if (!scenario.empty() && scenario != "positive" && !missing && !stale && !wrong_srv && !wrong_argument) return false; const char* label = scenario.empty() ? "positive" : scenario.c_str(); + char history_setting[32]{}; + const DWORD history_length = GetEnvironmentVariableA("X2W_MESH_PROVENANCE_HISTORY_CONTROL", + history_setting, sizeof(history_setting)); + if (history_length >= sizeof(history_setting)) return false; + const std::string history_control = history_setting; + const bool opaque_copy = history_control == "opaque-copy"; + const bool discovery = history_control == "discovery"; + if ((history_length && !opaque_copy && !discovery) || + ((opaque_copy || discovery) && std::string(label) != "positive")) return false; constexpr UINT64 input_offset = 16; constexpr UINT64 written_offset = 4; const UINT64 consumed_offset = wrong_argument ? 20 : written_offset; @@ -70,6 +79,25 @@ RWByteAddressBuffer data : register(u0); else if (noise_value == "5000") noise_slots = 5000; else if (noise_value != "0") return false; } + if (noise_slots && (opaque_copy || discovery)) return false; + // Keep all prefix and overflow heaps alive so no mapping can be recycled. + std::vector> discovery_heaps; + struct DiscoveryHeapDesc { + D3D12_DESCRIPTOR_HEAP_DESC desc; + UINT64 address, bytes; + }; + const DiscoveryHeapDesc discovery_desc{{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}, 0, 0}; + const auto discovery_heap = [&] { + ComPtr next; + check(guest->CreateDescriptorHeap(&discovery_desc.desc, IID_PPV_ARGS(&next)), + "provenance discovery heap"); + discovery_heaps.push_back(std::move(next)); + }; + if (discovery) { + discovery_heaps.reserve(1027); + for (unsigned i = 0; i < 1022; ++i) discovery_heap(); + } // Keep both heaps alive through the positive fixture so their ranges cannot be reused. ComPtr noise_source, noise_destination; if (noise_slots) { @@ -146,9 +174,36 @@ RWByteAddressBuffer data : register(u0); create_srv(0, input_offset + 16); if (!missing) slot(guest, 24)(guest, 1, bound_cpu, guest_cpu, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - create_srv(0, wrong_srv ? input_offset + 16 : input_offset); // overwrite the source - if (!missing && !stale) slot(guest, 24)(guest, 1, bound_cpu, guest_cpu, - D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + ComPtr opaque_heap; + if (opaque_copy) { + // The destination currently points at the zero-valued adjacent scalar. + // A real native CPU heap is intentionally outside guest history/shadow + // registration. Only its omitted copies can change the bound GPU view. + check(device->CreateDescriptorHeap(&source_desc, IID_PPV_ARGS(&opaque_heap)), + "provenance opaque source heap"); + const auto opaque = opaque_heap->GetCPUDescriptorHandleForHeapStart(); + if (!opaque.ptr || opaque.ptr == guest_cpu || opaque.ptr == bound_cpu || + opaque.ptr == desktop_cpu) return false; + std::uint32_t before[8]{}; + std::memcpy(before, reinterpret_cast(bound_cpu), sizeof(before)); + srv.Buffer.FirstElement = input_offset / 4; + device->CreateShaderResourceView(input.native.Get(), &srv, opaque); + for (unsigned i = 0; i < 5; ++i) + slot(guest, 24)(guest, 1, bound_cpu, opaque.ptr, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + // No guest token is available for the native source. The existing copy + // path does not rewrite the guest token in this case; only the GPU + // oracle establishes that the native descriptor was copied correctly. + if (std::memcmp(before, reinterpret_cast(bound_cpu), sizeof(before)) != 0) + return false; + std::printf("provenance opaque-copy source=%llx destination=%llx copies=5 guest_token=unchanged\n", + static_cast(opaque.ptr), bound_cpu); + create_srv(0, input_offset); // next valid history event, does not touch bound GPU view + } else { + create_srv(0, wrong_srv ? input_offset + 16 : input_offset); // overwrite the source + if (!missing && !stale) slot(guest, 24)(guest, 1, bound_cpu, guest_cpu, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + } std::uint32_t tokens[2][8]{}; std::memcpy(tokens[0], reinterpret_cast(guest_cpu), 32); std::memcpy(tokens[1], reinterpret_cast(bound_cpu), 32); @@ -309,6 +364,17 @@ RWByteAddressBuffer data : register(u0); pixels->Unmap(0, &none); std::printf("provenance result case=%s changed=%u total=%u writer_x=%u consumer_x=%u\n", label, changed, width * height, expected_x, consumed_x); + if (discovery) { + // The successful GPU oracle above uses the last two retained heaps. + // Subsequent actual heap creation continues even after diagnostics fault. + for (unsigned i = 0; i < 5; ++i) discovery_heap(); + create_srv(0, input_offset); + slot(guest, 24)(guest, 1, bound_cpu, guest_cpu, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + check(device->GetDeviceRemovedReason(), "provenance discovery device"); + if (std::memcmp(reinterpret_cast(guest_cpu), + reinterpret_cast(bound_cpu), 32) != 0) return false; + std::printf("provenance discovery successful_heaps=1029 overflow=5 tokens=verified\n"); + } ComPtr messages; const bool has_info_queue = SUCCEEDED(device->QueryInterface(IID_PPV_ARGS(&messages))); std::printf("provenance debug info_queue=%s\n", has_info_queue ? "present" : "absent"); diff --git a/tests/startup_mesh_argument_provenance_check.py b/tests/startup_mesh_argument_provenance_check.py index cebc61d5f7..f54cb01d60 100644 --- a/tests/startup_mesh_argument_provenance_check.py +++ b/tests/startup_mesh_argument_provenance_check.py @@ -75,6 +75,7 @@ def check(executable, adapter, scenario, trace=True, *, settings=None, history_c env = dict(os.environ) env.pop("X2W_D3D12_DESCRIPTOR_HISTORY_FILTER", None) env.pop("X2W_MESH_PROVENANCE_NOISE_SLOTS", None) + env.pop("X2W_MESH_PROVENANCE_HISTORY_CONTROL", None) env["X2W_MESH_PROVENANCE_CASE"] = scenario if trace: env["X2W_D3D12_DESCRIPTOR_HISTORY"] = "1"