startup: direct indexed draws ignore index-buffer writes made before submission #2706

Closed
opened 2026-11-26 03:13:57 +00:00 by chasegrindy · 2 comments
chasegrindy commented 2026-11-26 03:13:57 +00:00 (Migrated from github.com)
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by chasegrindy on 2026-11-26T03:13:57Z.


Commit or build

546d881be2e14097fd086c52d711a3173d605471 (main, x64 Release). Only the test fixture was patched; the runtime is unchanged.

Reproduction

The fixture registers a 256-byte aliased buffer via slot 133, binds three R16 indices via slot 47, then records a direct indexed draw via slot 13. The vertex shader maps 0,1,2 to a full-coverage triangle and 3,4,5 to a triangle wholly beyond x > w. The late cases rewrite those same six bytes after recording the draw but before ExecuteCommandLists. Nothing is submitted while the CPU writes. A fence precedes the full 8×4 RGBA8 readback.

Save the three source files below in the checkout root. Adjust $sdkBin to the x64 binary directory of your installed SDK if needed. The runner uses WARP and explicitly selects the RX 7900 XTX for its hardware run.

git checkout --detach 546d881be2e14097fd086c52d711a3173d605471
git apply fixture.diff
$sdkBin = "${env:ProgramFiles(x86)}/Windows Kits/10/bin/10.0.26100.0/x64"
$py = (Get-Command python).Source
cmake -S . -B out/index-probe -G "Visual Studio 17 2022" -A x64 -DX2W_TRACY=OFF -DX2W_WITH_OPUS=OFF "-DDXC_EXECUTABLE=$sdkBin/dxc.exe" "-DINTAKE_PYTHON=$py"
cmake --build out/index-probe --config Release --target startup_stream_consumer --parallel 3
python -B reproduce.py --source . --exe out/index-probe/Release/startup_stream_consumer.exe --fxc "$sdkBin/fxc.exe" --out out/index-probe-results

Expected behavior

For this sequence, the draw should read the final contents of the live index buffer. With the final indices 0,1,2, all 32 pixels should be red. With 3,4,5, all 32 should retain the blue clear. Microsoft documents the pre-submit write ordering for CPU-accessible resources in ID3D12Resource::Map.

Observed behavior

The draw uses the indices present when it was recorded. The slot-133 log confirms an alias and the direct indexed draw still logs drawn. Three fresh-process runs per case and adapter: all 12 unchanged-input controls match; all 12 late-write draws mismatch 32/32 pixels. No skips. The reproducer exits 1 for these pixel mismatches.

warp-late-visible-1: 32/32 mismatches, expected ff0000ff, observed {'0000ffff': 32}
warp-late-clipped-1: 32/32 mismatches, expected 0000ffff, observed {'ff0000ff': 32}
hardware-late-visible-1: 32/32 mismatches, expected ff0000ff, observed {'0000ffff': 32}
hardware-late-clipped-1: 32/32 mismatches, expected 0000ffff, observed {'ff0000ff': 32}

The direct indexed branch takes a frame_copy during recording and binds the upload-ring slice instead of the live index resource. This can leave a target unchanged despite a recorded draw. Refs #870 for that symptom only: the public capture does not establish that its 2560×1440 producer used this index-write sequence.

Environment

Windows 11 26300.9974, VS 2022 17.14 / MSVC 19.44.35229.0, Windows SDK 10.0.26100.0. RX 7900 XTX driver 32.0.32015.7029 and Microsoft Basic Render Driver 10.0.26100.9818. D3D12 debug layer enabled on both.

Checklist

  • Reproduced on source-built synthetic input.
  • No game files, dumps, distribution links or credentials included.

AI-assisted (Hermes Agent / OpenAI Codex). Measurements are from local GPU readbacks.

fixture.diff
diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp
index 3f2405a97ad4d3860d54c854f3f57969087d3f3e..7e27a2671c8f04e3b29831bed383f2beafde564c 100644
--- a/tests/startup_stream_draw.cpp
+++ b/tests/startup_stream_draw.cpp
@@ -307,7 +307,39 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char*
     auto* queue = frame.queue;
     auto* fence = frame.fence;
     if (export_word) invoke(list, 40, 0, 1, arg(&export_word), 0);
-    if (GetEnvironmentVariableW(L"X2W_TEST_LOGICAL_VIEW", nullptr, 0)) {
+    char index_probe[32]{};
+    GetEnvironmentVariableA("X2W_TEST_INDEX_PROBE", index_probe, sizeof(index_probe));
+    void* index_resource = nullptr;
+    void* index_memory = nullptr;
+    if (index_probe[0]) {
+        bool initial_visible = false, final_visible = false;
+        if (!std::strcmp(index_probe, "visible")) initial_visible = final_visible = true;
+        else if (!std::strcmp(index_probe, "late-visible")) final_visible = true;
+        else if (!std::strcmp(index_probe, "late-clipped")) initial_visible = true;
+        else if (std::strcmp(index_probe, "clipped")) return 70;
+        D3D12_FEATURE_DATA_EXISTING_HEAPS capability{};
+        if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &capability, sizeof(capability))) || !capability.Supported)
+            return 77;
+        index_memory = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
+        if (!index_memory) return 71;
+        const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1,
+            DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE};
+        if (FAILED(static_cast<HRESULT>(invoke(guest, 133, arg(index_memory), arg(&desc),
+                D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&index_resource)))) ||
+            !index_resource || invoke(index_resource, 11) != arg(index_memory)) return 72;
+        auto* const words = static_cast<std::uint16_t*>(index_memory);
+        const auto write = [&](bool visible) {
+            for (std::uint16_t i = 0; i < 3; ++i) words[i] = static_cast<std::uint16_t>(i + (visible ? 0 : 3));
+        };
+        write(initial_visible);
+        const D3D12_INDEX_BUFFER_VIEW index_view{arg(words), 6, DXGI_FORMAT_R16_UINT};
+        const D3D12_RECT full{0, 0, static_cast<LONG>(width), static_cast<LONG>(height)};
+        invoke(list, 22, 1, arg(&full));
+        invoke(list, 47, arg(&index_view));
+        invoke(list, 13, 3, 1, 0, 0, 0);
+        write(final_visible);
+        std::printf("indexed probe %s: final indices %u %u %u before submission\n", index_probe, UINT{words[0]}, UINT{words[1]}, UINT{words[2]});
+    } else if (GetEnvironmentVariableW(L"X2W_TEST_LOGICAL_VIEW", nullptr, 0)) {
         if (int result = draw_logical_tables(desktop.Get(), guest, list)) return result;
     } else if (GetEnvironmentVariableW(L"X2W_TEST_PLACED_VERTEX", nullptr, 0)) {
         extern int draw_placed_vertices(ID3D12Device*, void*, void*);
@@ -495,6 +527,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char*
         last = 2;
     }
     if (const int rc = submit(last)) return rc;
+    if (index_resource) invoke(index_resource, 2); // The backing heap can outlive the resource.
     if (GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0)) {
         extern int report_pixel_uavs(const char*);
         if (const int rc = report_pixel_uavs(pixels)) return rc;
index_probe_vs.hlsl
float4 main(uint vertex : SV_VertexID) : SV_Position {
    uint corner = vertex % 3;
    float2 xy = float2(corner == 1 ? 3.0 : -1.0, corner == 2 ? -3.0 : 1.0);
    return float4(xy.x + (vertex >= 3 ? 8.0 : 0.0), xy.y, 0.5, 1.0);
}
reproduce.py
"""Synthetic direct indexed draw regression. Exit 1 only for a pixel-oracle failure."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys

MODES = {
    'visible': (0, 0), 'clipped': (3, 3),
    'late-visible': (3, 0), 'late-clipped': (0, 3),
}
RGBA = {0: bytes.fromhex('ff0000ff'), 3: bytes.fromhex('0000ffff')}
ADAPTERS = {'warp': 'Microsoft Basic Render Driver', 'hardware': 'AMD Radeon RX 7900 XTX'}


def main():
    p = argparse.ArgumentParser(description=__doc__)
    for arg in ('source', 'exe', 'fxc', 'out'):
        p.add_argument('--' + arg, required=True, type=Path)
    p.add_argument('--repeats', type=int, default=3)
    a = p.parse_args()
    if a.repeats < 1:
        p.error('at least one repeat is required')
    a.source, a.exe, a.fxc, a.out = [v.resolve() for v in (a.source, a.exe, a.fxc, a.out)]
    sys.path.insert(0, str(a.source / 'tests'))
    from startup_stream_draw_check import vertex, pixel

    a.out.mkdir(parents=True, exist_ok=False)
    cache, tmp = a.out / 'cache', a.out / 'tmp'
    cache.mkdir()
    tmp.mkdir()
    env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('X2W_', 'XBOX2WINDOWS_'))}
    env.update(TEMP=str(tmp), TMP=str(tmp), X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1',
               X2W_D3D12_RENDER='1', X2W_D3D12_DEBUG='1', X2W_SHADER_CACHE=str(cache),
               X2W_FXC=str(a.fxc), XBOX2WINDOWS_ADAPTER=ADAPTERS['hardware'])
    vs, ps, root = (a.out / name for name in ('vs', 'ps', 'root'))
    vs.write_bytes(vertex())
    ps.write_bytes(pixel(False))
    args = [a.exe, vs, ps, root]

    def run(cmd, name, more=None):
        proc = subprocess.run(cmd, cwd=a.source, env=env | (more or {}), capture_output=True, timeout=30)
        (a.out / (name + '.log')).write_bytes(proc.stdout + b'\n--- stderr ---\n' + proc.stderr)
        out, err = (x.decode(errors='replace') for x in (proc.stdout, proc.stderr))
        if proc.returncode not in (0, 77):
            raise RuntimeError(f'{name} exit {proc.returncode}; inspect captured log')
        if re.search(r'(?i)device (?:hung|removed|reset)|0x887a000[567]|x2w-d3d12-debug [^\n]*sev=[01]\b', err):
            raise RuntimeError(f'{name} driver or validation failure; inspect captured log')
        return proc.returncode, out, err

    if run(args, 'publish')[0] or run([sys.executable, '-B', a.source / 'tools/startup/gfx2hlsl.py',
                                      '--pending', cache], 'translate')[0]:
        raise RuntimeError('Could not prepare source-built shader request')
    manifest, = cache.glob('*.txt')
    shader = Path(__file__).with_name('index_probe_vs.hlsl')
    if run([a.fxc, '/nologo', '/T', 'vs_5_0', '/E', 'main', '/Fo', manifest.with_suffix('.vs.cso'),
            shader], 'compile-vs')[0]:
        raise RuntimeError('Could not build probe HLSL')
    manifest_json = a.out / 'results.json'
    artifacts = [a.exe, a.exe.with_name('d3d12_xs.dll'), a.fxc, shader, manifest,
                 manifest.with_suffix('.vs.cso'), manifest.with_suffix('.ps.cso')]
    results = {'sha256': {str(f): hashlib.sha256(f.read_bytes()).hexdigest() for f in artifacts}, 'runs': []}
    for i in range(1, a.repeats + 1):
        for adapter, label in ADAPTERS.items():
            for mode, (recorded, submitted) in MODES.items():
                key = f'{adapter}-{mode}-{i}'
                output = a.out / (key + '.rgba')
                cmd = list(map(str, [*args, adapter, output]))
                rc, out, err = run(cmd, key, {'X2W_TEST_INDEX_PROBE': mode})
                if rc == 77:
                    raise RuntimeError(f'{key}: adapter or existing heap not available (skip, not a PASS)')
                device, = re.findall(r'^adapter=(.*)$', out, flags=re.MULTILINE)
                device = device.strip()
                if not device.startswith(label + ' driver='):
                    raise RuntimeError(f'{key}: unexpected adapter: {device}')
                recorded_data = ' '.join(x.to_bytes(2, 'little').hex(' ') for x in range(recorded, recorded + 3))
                final_msg = f'indexed probe {mode}: final indices {submitted} {submitted+1} {submitted+2} before submission'
                if ('debug layer: 0x00000000 enabled' not in err or final_msg not in out or
                    not re.search(r'slot133[^\n]*-> 0x00000000 aliased gpuva=', err) or
                    not re.search(r'indexed\(3, 1, start 0, base 0\)[^\n]*-> drawn;[^\n]*fmt 57 \['
                                  + re.escape(recorded_data), err)):
                    raise RuntimeError(f'{key}: required path or index provenance not confirmed')
                data = output.read_bytes()
                if len(data) != 8 * 4 * 4:
                    raise RuntimeError(f'{key}: bad image length {len(data)}')
                pixels = [data[x:x+4] for x in range(0, len(data), 4)]
                mismatches = sum(c != RGBA[submitted] for c in pixels)
                counts = {c.hex(): pixels.count(c) for c in sorted(set(pixels))}
                outcome = {'key': key, 'adapter': device, 'command': cmd, 'mode': mode, 'iteration': i,
                           'expected_rgba': RGBA[submitted].hex(), 'observed_rgba_counts': counts,
                           'mismatches': mismatches, 'index_at_record': recorded, 'index_at_submit': submitted}
                results['runs'].append(outcome)
                manifest_json.write_text(json.dumps(results, indent=2), encoding='utf8')
                print(f'{key}: {mismatches}/32 mismatches, expected {RGBA[submitted].hex()}, observed {counts}', flush=True)
    return int(any(r['mismatches'] for r in results['runs']))


if __name__ == '__main__':
    try:
        sys.exit(main())
    except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as error:
        print(f'Setup or execution error: {error}', file=sys.stderr)
        sys.exit(2)
<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6618696380 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/2714). Originally posted by [chasegrindy](https://github.com/chasegrindy) on 2026-11-26T03:13:57Z. --- ## Commit or build `546d881be2e14097fd086c52d711a3173d605471` (`main`, x64 Release). Only the test fixture was patched; the runtime is unchanged. ## Reproduction The fixture registers a 256-byte aliased buffer via slot 133, binds three R16 indices via slot 47, then records a direct indexed draw via slot 13. The vertex shader maps `0,1,2` to a full-coverage triangle and `3,4,5` to a triangle wholly beyond `x > w`. The late cases rewrite those same six bytes after recording the draw but before `ExecuteCommandLists`. Nothing is submitted while the CPU writes. A fence precedes the full 8×4 RGBA8 readback. Save the three source files below in the checkout root. Adjust `$sdkBin` to the x64 binary directory of your installed SDK if needed. The runner uses WARP and explicitly selects the RX 7900 XTX for its hardware run. ```powershell git checkout --detach 546d881be2e14097fd086c52d711a3173d605471 git apply fixture.diff $sdkBin = "${env:ProgramFiles(x86)}/Windows Kits/10/bin/10.0.26100.0/x64" $py = (Get-Command python).Source cmake -S . -B out/index-probe -G "Visual Studio 17 2022" -A x64 -DX2W_TRACY=OFF -DX2W_WITH_OPUS=OFF "-DDXC_EXECUTABLE=$sdkBin/dxc.exe" "-DINTAKE_PYTHON=$py" cmake --build out/index-probe --config Release --target startup_stream_consumer --parallel 3 python -B reproduce.py --source . --exe out/index-probe/Release/startup_stream_consumer.exe --fxc "$sdkBin/fxc.exe" --out out/index-probe-results ``` ## Expected behavior For this sequence, the draw should read the final contents of the live index buffer. With the final indices `0,1,2`, all 32 pixels should be red. With `3,4,5`, all 32 should retain the blue clear. Microsoft documents the pre-submit write ordering for CPU-accessible resources in [`ID3D12Resource::Map`](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12resource-map#advanced-usage-models). ## Observed behavior The draw uses the indices present when it was recorded. The slot-133 log confirms an alias and the direct indexed draw still logs `drawn`. Three fresh-process runs per case and adapter: all 12 unchanged-input controls match; all 12 late-write draws mismatch **32/32 pixels**. No skips. The reproducer exits 1 for these pixel mismatches. ```text warp-late-visible-1: 32/32 mismatches, expected ff0000ff, observed {'0000ffff': 32} warp-late-clipped-1: 32/32 mismatches, expected 0000ffff, observed {'ff0000ff': 32} hardware-late-visible-1: 32/32 mismatches, expected ff0000ff, observed {'0000ffff': 32} hardware-late-clipped-1: 32/32 mismatches, expected 0000ffff, observed {'ff0000ff': 32} ``` The [direct indexed branch](https://github.com/R0Y00/Xbox2Windows/blob/546d881be2e14097fd086c52d711a3173d605471/src/startup_stubs/d3d12_draw.inl#L2554-L2567) takes a `frame_copy` during recording and binds the upload-ring slice instead of the live index resource. This can leave a target unchanged despite a recorded draw. Refs #870 for that symptom only: the public capture does not establish that its 2560×1440 producer used this index-write sequence. ## Environment Windows 11 26300.9974, VS 2022 17.14 / MSVC 19.44.35229.0, Windows SDK 10.0.26100.0. RX 7900 XTX driver `32.0.32015.7029` and Microsoft Basic Render Driver `10.0.26100.9818`. D3D12 debug layer enabled on both. ## Checklist - [x] Reproduced on source-built synthetic input. - [x] No game files, dumps, distribution links or credentials included. AI-assisted (Hermes Agent / OpenAI Codex). Measurements are from local GPU readbacks. <details> <summary>fixture.diff</summary> ```diff diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 3f2405a97ad4d3860d54c854f3f57969087d3f3e..7e27a2671c8f04e3b29831bed383f2beafde564c 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -307,7 +307,39 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* auto* queue = frame.queue; auto* fence = frame.fence; if (export_word) invoke(list, 40, 0, 1, arg(&export_word), 0); - if (GetEnvironmentVariableW(L"X2W_TEST_LOGICAL_VIEW", nullptr, 0)) { + char index_probe[32]{}; + GetEnvironmentVariableA("X2W_TEST_INDEX_PROBE", index_probe, sizeof(index_probe)); + void* index_resource = nullptr; + void* index_memory = nullptr; + if (index_probe[0]) { + bool initial_visible = false, final_visible = false; + if (!std::strcmp(index_probe, "visible")) initial_visible = final_visible = true; + else if (!std::strcmp(index_probe, "late-visible")) final_visible = true; + else if (!std::strcmp(index_probe, "late-clipped")) initial_visible = true; + else if (std::strcmp(index_probe, "clipped")) return 70; + D3D12_FEATURE_DATA_EXISTING_HEAPS capability{}; + if (FAILED(desktop->CheckFeatureSupport(D3D12_FEATURE_EXISTING_HEAPS, &capability, sizeof(capability))) || !capability.Supported) + return 77; + index_memory = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + if (!index_memory) return 71; + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, 256, 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_NONE}; + if (FAILED(static_cast<HRESULT>(invoke(guest, 133, arg(index_memory), arg(&desc), + D3D12_RESOURCE_STATE_COMMON, 0, arg(&__uuidof(ID3D12Resource)), arg(&index_resource)))) || + !index_resource || invoke(index_resource, 11) != arg(index_memory)) return 72; + auto* const words = static_cast<std::uint16_t*>(index_memory); + const auto write = [&](bool visible) { + for (std::uint16_t i = 0; i < 3; ++i) words[i] = static_cast<std::uint16_t>(i + (visible ? 0 : 3)); + }; + write(initial_visible); + const D3D12_INDEX_BUFFER_VIEW index_view{arg(words), 6, DXGI_FORMAT_R16_UINT}; + const D3D12_RECT full{0, 0, static_cast<LONG>(width), static_cast<LONG>(height)}; + invoke(list, 22, 1, arg(&full)); + invoke(list, 47, arg(&index_view)); + invoke(list, 13, 3, 1, 0, 0, 0); + write(final_visible); + std::printf("indexed probe %s: final indices %u %u %u before submission\n", index_probe, UINT{words[0]}, UINT{words[1]}, UINT{words[2]}); + } else if (GetEnvironmentVariableW(L"X2W_TEST_LOGICAL_VIEW", nullptr, 0)) { if (int result = draw_logical_tables(desktop.Get(), guest, list)) return result; } else if (GetEnvironmentVariableW(L"X2W_TEST_PLACED_VERTEX", nullptr, 0)) { extern int draw_placed_vertices(ID3D12Device*, void*, void*); @@ -495,6 +527,7 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* last = 2; } if (const int rc = submit(last)) return rc; + if (index_resource) invoke(index_resource, 2); // The backing heap can outlive the resource. if (GetEnvironmentVariableW(L"X2W_TEST_PIXEL_UAV", nullptr, 0)) { extern int report_pixel_uavs(const char*); if (const int rc = report_pixel_uavs(pixels)) return rc; ``` </details> <details> <summary>index_probe_vs.hlsl</summary> ```hlsl float4 main(uint vertex : SV_VertexID) : SV_Position { uint corner = vertex % 3; float2 xy = float2(corner == 1 ? 3.0 : -1.0, corner == 2 ? -3.0 : 1.0); return float4(xy.x + (vertex >= 3 ? 8.0 : 0.0), xy.y, 0.5, 1.0); } ``` </details> <details> <summary>reproduce.py</summary> ```python """Synthetic direct indexed draw regression. Exit 1 only for a pixel-oracle failure.""" import argparse import hashlib import json import os from pathlib import Path import re import subprocess import sys MODES = { 'visible': (0, 0), 'clipped': (3, 3), 'late-visible': (3, 0), 'late-clipped': (0, 3), } RGBA = {0: bytes.fromhex('ff0000ff'), 3: bytes.fromhex('0000ffff')} ADAPTERS = {'warp': 'Microsoft Basic Render Driver', 'hardware': 'AMD Radeon RX 7900 XTX'} def main(): p = argparse.ArgumentParser(description=__doc__) for arg in ('source', 'exe', 'fxc', 'out'): p.add_argument('--' + arg, required=True, type=Path) p.add_argument('--repeats', type=int, default=3) a = p.parse_args() if a.repeats < 1: p.error('at least one repeat is required') a.source, a.exe, a.fxc, a.out = [v.resolve() for v in (a.source, a.exe, a.fxc, a.out)] sys.path.insert(0, str(a.source / 'tests')) from startup_stream_draw_check import vertex, pixel a.out.mkdir(parents=True, exist_ok=False) cache, tmp = a.out / 'cache', a.out / 'tmp' cache.mkdir() tmp.mkdir() env = {k: v for k, v in os.environ.items() if not k.upper().startswith(('X2W_', 'XBOX2WINDOWS_'))} env.update(TEMP=str(tmp), TMP=str(tmp), X2W_D3D12_PERMISSIVE='1', X2W_D3D12_LIST_NOOP='1', X2W_D3D12_RENDER='1', X2W_D3D12_DEBUG='1', X2W_SHADER_CACHE=str(cache), X2W_FXC=str(a.fxc), XBOX2WINDOWS_ADAPTER=ADAPTERS['hardware']) vs, ps, root = (a.out / name for name in ('vs', 'ps', 'root')) vs.write_bytes(vertex()) ps.write_bytes(pixel(False)) args = [a.exe, vs, ps, root] def run(cmd, name, more=None): proc = subprocess.run(cmd, cwd=a.source, env=env | (more or {}), capture_output=True, timeout=30) (a.out / (name + '.log')).write_bytes(proc.stdout + b'\n--- stderr ---\n' + proc.stderr) out, err = (x.decode(errors='replace') for x in (proc.stdout, proc.stderr)) if proc.returncode not in (0, 77): raise RuntimeError(f'{name} exit {proc.returncode}; inspect captured log') if re.search(r'(?i)device (?:hung|removed|reset)|0x887a000[567]|x2w-d3d12-debug [^\n]*sev=[01]\b', err): raise RuntimeError(f'{name} driver or validation failure; inspect captured log') return proc.returncode, out, err if run(args, 'publish')[0] or run([sys.executable, '-B', a.source / 'tools/startup/gfx2hlsl.py', '--pending', cache], 'translate')[0]: raise RuntimeError('Could not prepare source-built shader request') manifest, = cache.glob('*.txt') shader = Path(__file__).with_name('index_probe_vs.hlsl') if run([a.fxc, '/nologo', '/T', 'vs_5_0', '/E', 'main', '/Fo', manifest.with_suffix('.vs.cso'), shader], 'compile-vs')[0]: raise RuntimeError('Could not build probe HLSL') manifest_json = a.out / 'results.json' artifacts = [a.exe, a.exe.with_name('d3d12_xs.dll'), a.fxc, shader, manifest, manifest.with_suffix('.vs.cso'), manifest.with_suffix('.ps.cso')] results = {'sha256': {str(f): hashlib.sha256(f.read_bytes()).hexdigest() for f in artifacts}, 'runs': []} for i in range(1, a.repeats + 1): for adapter, label in ADAPTERS.items(): for mode, (recorded, submitted) in MODES.items(): key = f'{adapter}-{mode}-{i}' output = a.out / (key + '.rgba') cmd = list(map(str, [*args, adapter, output])) rc, out, err = run(cmd, key, {'X2W_TEST_INDEX_PROBE': mode}) if rc == 77: raise RuntimeError(f'{key}: adapter or existing heap not available (skip, not a PASS)') device, = re.findall(r'^adapter=(.*)$', out, flags=re.MULTILINE) device = device.strip() if not device.startswith(label + ' driver='): raise RuntimeError(f'{key}: unexpected adapter: {device}') recorded_data = ' '.join(x.to_bytes(2, 'little').hex(' ') for x in range(recorded, recorded + 3)) final_msg = f'indexed probe {mode}: final indices {submitted} {submitted+1} {submitted+2} before submission' if ('debug layer: 0x00000000 enabled' not in err or final_msg not in out or not re.search(r'slot133[^\n]*-> 0x00000000 aliased gpuva=', err) or not re.search(r'indexed\(3, 1, start 0, base 0\)[^\n]*-> drawn;[^\n]*fmt 57 \[' + re.escape(recorded_data), err)): raise RuntimeError(f'{key}: required path or index provenance not confirmed') data = output.read_bytes() if len(data) != 8 * 4 * 4: raise RuntimeError(f'{key}: bad image length {len(data)}') pixels = [data[x:x+4] for x in range(0, len(data), 4)] mismatches = sum(c != RGBA[submitted] for c in pixels) counts = {c.hex(): pixels.count(c) for c in sorted(set(pixels))} outcome = {'key': key, 'adapter': device, 'command': cmd, 'mode': mode, 'iteration': i, 'expected_rgba': RGBA[submitted].hex(), 'observed_rgba_counts': counts, 'mismatches': mismatches, 'index_at_record': recorded, 'index_at_submit': submitted} results['runs'].append(outcome) manifest_json.write_text(json.dumps(results, indent=2), encoding='utf8') print(f'{key}: {mismatches}/32 mismatches, expected {RGBA[submitted].hex()}, observed {counts}', flush=True) return int(any(r['mismatches'] for r in results['runs'])) if __name__ == '__main__': try: sys.exit(main()) except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as error: print(f'Setup or execution error: {error}', file=sys.stderr) sys.exit(2) ``` </details>
triggered02 commented 2026-11-26 04:04:39 +00:00 (Migrated from github.com)
Author
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by triggered02 on 2026-11-26T03:38:33Z.


This reproduces as a real semantics defect, not a fixture artifact: the direct indexed route snapshots the guest index bytes at recording time, while D3D12 reads the index buffer at execution. list_draw_indexed (src/startup_stubs/d3d12_draw.inl:2732) goes through draw_translated(...), and the translated index view resolves the guest BufferLocation into a desktop range when the draw is recorded � the indirect route shows the same resolution shape in d3d12_xs_device.cpp around the list_upload_range(self, view.BufferLocation, view.SizeInBytes) branch, where a guest-owned index range becomes a recording-time upload. A CPU write to those six bytes between DrawIndexedInstanced and ExecuteCommandLists is legal, and the upload is already stale by then.

The fix shape is to keep the guest address and range in the recording and resolve the index bytes at ExecuteCommandLists (or re-upload the range immediately before the recorded draw is executed), for both the direct and indirect translated routes. That is a recording/execute split in the translated draw path, not a one-line change, so I am not claiming a fix here.

What would make this landable: your fixture as a source-built CTest in ests/ (the ixture.diff + runner you pasted are the right shape) with the late-write case and the current early-read case as a negative control, so the failure is pinned before the path is changed. If you can attach the fixture diff as a file (not game data � it is synthetic), I will take it from there.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7181897136 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/2714#issuecomment-7181897136). Originally posted by [triggered02](https://github.com/triggered02) on 2026-11-26T03:38:33Z. --- This reproduces as a real semantics defect, not a fixture artifact: the direct indexed route snapshots the guest index bytes **at recording time**, while D3D12 reads the index buffer at execution. list_draw_indexed (src/startup_stubs/d3d12_draw.inl:2732) goes through draw_translated(...), and the translated index view resolves the guest BufferLocation into a desktop range when the draw is recorded � the indirect route shows the same resolution shape in d3d12_xs_device.cpp around the list_upload_range(self, view.BufferLocation, view.SizeInBytes) branch, where a guest-owned index range becomes a recording-time upload. A CPU write to those six bytes between DrawIndexedInstanced and ExecuteCommandLists is legal, and the upload is already stale by then. The fix shape is to keep the guest address and range in the recording and resolve the index bytes at ExecuteCommandLists (or re-upload the range immediately before the recorded draw is executed), for both the direct and indirect translated routes. That is a recording/execute split in the translated draw path, not a one-line change, so I am not claiming a fix here. What would make this landable: your fixture as a source-built CTest in ests/ (the ixture.diff + runner you pasted are the right shape) with the late-write case and the current early-read case as a negative control, so the failure is pinned before the path is changed. If you can attach the fixture diff as a file (not game data � it is synthetic), I will take it from there.
R0Y00 commented 2026-11-26 04:04:42 +00:00 (Migrated from github.com)
Author
Contributor

Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-26T03:51:30Z.


I independently reproduced both late-write failures on WARP and RTX 4060 Laptop. PR #2724 integrates the source-built fixture and a narrow fix: retain an existing live placed alias when the drawn index interval is proven and the shader does not need sliced vertex streams. All five cases now match 32/32 pixels per backend. The snapshot-dependent path remains open under this issue. The actual executable's relevant index writer still needs tracing.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7182084149 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/issues/2714#issuecomment-7182084149). Originally posted by [R0Y00](https://github.com/R0Y00) on 2026-11-26T03:51:30Z. --- I independently reproduced both late-write failures on WARP and RTX 4060 Laptop. PR #2724 integrates the source-built fixture and a narrow fix: retain an existing live placed alias when the drawn index interval is proven and the shader does not need sliced vertex streams. All five cases now match 32/32 pixels per backend. The snapshot-dependent path remains open under this issue. The actual executable's relevant index writer still needs tracing.
Sign in to join this conversation.
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
R0Y00/Xbox2Windows#2706
No description provided.