Files
mandy/runtime/test/vk_presenter_sync_test.cpp
AlxcBTW f8007dda67 Queue holds: review fixes (Present ordering, pins, timeline monotonicity, fence lifetime, teardown, docs)
- Present is queued behind held work (QueueHolds::after_held) and submitted in order by the releasing thread.
- Held batches keep the pipeline states and root signatures of their lists; fences a queue waits on or signals are
  kept until the submission has completed on the GPU (a D3D12 queue holds them).
- A held Signal released below an unheld one on the same fence leaves the Vulkan signal out (claimed under the submit lock).
- A queue destroyed with held Signals completes the CPU waits on their fences and reports it.
- A failed held batch is reported (take_held_failure, last_execute_result), its waits stay for the next submission,
  and the Signal behind it still signals.
- d3d12_queue_handover_test: pairs, two-thread signalling stress, held Signal of a released fence, shared fence,
  teardown with a CPU waiter; --two-queues and --shared-queue modes on a caller-owned device.
- Tests for each fix in vk_presenter_sync_test, vk_queue_query_sync_test and d3d12_m4_compute_test; docs section 4.4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 21:02:33 +01:00

397 lines
19 KiB
C++

// VulkanPresenter synchronization regressions (runtime/src/vulkan_present.h):
// 1. A failed vkQueueSubmit rolls back LayoutTracker changes (an UNDEFINED back buffer stays UNDEFINED until a
// present actually submits its zero-fill).
// 2. With enable_capture(), every frame's vkCmdCopyImageToBuffer into the shared capture buffer is preceded by a
// TRANSFER_WRITE -> TRANSFER_WRITE barrier to prevent WRITE_AFTER_WRITE hazards across the two in-flight frames.
// A failed capture fence wait also leaves the caller's outputs untouched.
// 3. Concurrent present() + VulkanQueue::execute() + add_resource()/remove_resource() follows VulkanContext's
// resource_mutex_ -> tracker_mutex_ -> submit_mutex_ lock hierarchy without data races or deadlocks.
// Skips with exit code 77 when no Vulkan 1.3 device with Win32 presentation is available. No game data.
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#define VK_USE_PLATFORM_WIN32_KHR
#include <windows.h>
#include "vk_test_device.h"
#include "../src/vulkan_present.h"
#include <atomic>
#include <chrono>
#include <cmath>
#include <condition_variable>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <mutex>
#include <string_view>
#include <thread>
#include <vector>
#define EXPECT(condition) do { \
if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
} while (0)
namespace {
LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM w, LPARAM l) {
return DefWindowProcW(window, message, w, l);
}
void pump() {
MSG message;
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&message);
DispatchMessageW(&message);
}
}
namespace driver {
PFN_vkGetInstanceProcAddr real_get_instance = nullptr;
PFN_vkGetDeviceProcAddr real_get_device = nullptr;
PFN_vkQueueSubmit real_submit = nullptr;
PFN_vkQueuePresentKHR real_present = nullptr;
PFN_vkWaitForFences real_wait = nullptr;
PFN_vkCmdPipelineBarrier real_barrier = nullptr;
PFN_vkCmdCopyImageToBuffer real_copy_i2b = nullptr;
std::atomic<VkResult> fail_next_submit{VK_SUCCESS};
std::atomic<VkResult> fail_next_wait{VK_SUCCESS};
std::function<void()> on_next_present;
std::atomic<bool> observe_capture{false};
std::atomic<bool> saw_capture_waw{false};
std::atomic<std::uint32_t> capture_copies{0};
std::atomic<std::uint32_t> capture_waw_barriers{0};
VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits,
VkFence fence) {
const VkResult armed = fail_next_submit.exchange(VK_SUCCESS);
if (armed != VK_SUCCESS) return armed;
return real_submit(queue, count, submits, fence);
}
VKAPI_ATTR VkResult VKAPI_CALL queue_present(VkQueue queue, const VkPresentInfoKHR* info) {
if (on_next_present) {
auto cb = std::move(on_next_present);
on_next_present = {};
cb();
}
return real_present(queue, info);
}
VKAPI_ATTR VkResult VKAPI_CALL wait_for_fences(VkDevice device, std::uint32_t count, const VkFence* fences,
VkBool32 wait_all, std::uint64_t timeout) {
const VkResult armed = fail_next_wait.exchange(VK_SUCCESS);
if (armed != VK_SUCCESS) return armed;
return real_wait(device, count, fences, wait_all, timeout);
}
VKAPI_ATTR void VKAPI_CALL cmd_pipeline_barrier(VkCommandBuffer cb, VkPipelineStageFlags src_stage,
VkPipelineStageFlags dst_stage, VkDependencyFlags flags,
std::uint32_t mem_count, const VkMemoryBarrier* mem,
std::uint32_t buf_count, const VkBufferMemoryBarrier* buf,
std::uint32_t img_count, const VkImageMemoryBarrier* img) {
if (observe_capture.load(std::memory_order_relaxed) && (src_stage & VK_PIPELINE_STAGE_TRANSFER_BIT) &&
(dst_stage & VK_PIPELINE_STAGE_TRANSFER_BIT)) {
for (std::uint32_t i = 0; i < buf_count; ++i) {
if ((buf[i].srcAccessMask & VK_ACCESS_TRANSFER_WRITE_BIT) &&
(buf[i].dstAccessMask & VK_ACCESS_TRANSFER_WRITE_BIT))
saw_capture_waw.store(true, std::memory_order_relaxed);
}
for (std::uint32_t i = 0; i < mem_count; ++i) {
if ((mem[i].srcAccessMask & VK_ACCESS_TRANSFER_WRITE_BIT) &&
(mem[i].dstAccessMask & VK_ACCESS_TRANSFER_WRITE_BIT))
saw_capture_waw.store(true, std::memory_order_relaxed);
}
}
real_barrier(cb, src_stage, dst_stage, flags, mem_count, mem, buf_count, buf, img_count, img);
}
VKAPI_ATTR void VKAPI_CALL cmd_copy_image_to_buffer(VkCommandBuffer cb, VkImage src, VkImageLayout layout,
VkBuffer dst, std::uint32_t count,
const VkBufferImageCopy* regions) {
if (observe_capture.load(std::memory_order_relaxed)) {
capture_copies.fetch_add(1, std::memory_order_relaxed);
if (saw_capture_waw.exchange(false, std::memory_order_relaxed))
capture_waw_barriers.fetch_add(1, std::memory_order_relaxed);
}
real_copy_i2b(cb, src, layout, dst, count, regions);
}
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) {
const std::string_view n = name;
if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
if (n == "vkQueuePresentKHR") return reinterpret_cast<PFN_vkVoidFunction>(queue_present);
if (n == "vkWaitForFences") return reinterpret_cast<PFN_vkVoidFunction>(wait_for_fences);
if (n == "vkCmdPipelineBarrier") return reinterpret_cast<PFN_vkVoidFunction>(cmd_pipeline_barrier);
if (n == "vkCmdCopyImageToBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_image_to_buffer);
return real_get_device(device, name);
}
VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_instance(VkInstance instance, const char* name) {
if (std::string_view(name) == "vkGetDeviceProcAddr") return reinterpret_cast<PFN_vkVoidFunction>(get_device);
return real_get_instance(instance, name);
}
void install(PFN_vkGetInstanceProcAddr instance_proc, VkInstance instance, VkDevice device) {
real_get_instance = instance_proc;
real_get_device = reinterpret_cast<PFN_vkGetDeviceProcAddr>(instance_proc(instance, "vkGetDeviceProcAddr"));
real_submit = reinterpret_cast<PFN_vkQueueSubmit>(real_get_device(device, "vkQueueSubmit"));
real_present = reinterpret_cast<PFN_vkQueuePresentKHR>(real_get_device(device, "vkQueuePresentKHR"));
real_wait = reinterpret_cast<PFN_vkWaitForFences>(real_get_device(device, "vkWaitForFences"));
real_barrier = reinterpret_cast<PFN_vkCmdPipelineBarrier>(real_get_device(device, "vkCmdPipelineBarrier"));
real_copy_i2b = reinterpret_cast<PFN_vkCmdCopyImageToBuffer>(real_get_device(device, "vkCmdCopyImageToBuffer"));
}
} // namespace driver
} // namespace
int main() {
using namespace leonida;
vktest::Device d;
if (!d.create(true)) {
std::fprintf(stderr, "vk_presenter_sync_test: no Vulkan device with presentation, skipped\n");
return 77;
}
WNDCLASSW wc{};
wc.lpfnWndProc = window_proc;
wc.hInstance = GetModuleHandleW(nullptr);
wc.lpszClassName = L"LeonidaPresenterSyncTest";
wc.hCursor = LoadCursorW(nullptr, reinterpret_cast<LPCWSTR>(IDC_ARROW));
EXPECT(RegisterClassW(&wc));
constexpr std::uint32_t width = 128, height = 96;
RECT fr{0, 0, LONG(width), LONG(height)};
AdjustWindowRect(&fr, WS_OVERLAPPEDWINDOW, FALSE);
HWND window = CreateWindowExW(0, wc.lpszClassName, L"Leonida presenter sync test", WS_OVERLAPPEDWINDOW, 80, 80,
fr.right - fr.left, fr.bottom - fr.top, nullptr, nullptr, wc.hInstance, nullptr);
EXPECT(window);
ShowWindow(window, SW_SHOWNORMAL);
UpdateWindow(window);
pump();
driver::install(d.instance_proc, d.instance, d.device);
{
VulkanContext context(driver::get_device, d.device, true);
EXPECT(context.loaded());
VulkanQueue queue(context, d.queue, d.family);
VulkanQueue worker_queue(context, d.queue, d.family);
EXPECT(queue.ok() && worker_queue.ok());
const VkImage back_img = d.image(VK_FORMAT_R8G8B8A8_UNORM, width, height, 1,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
const VkImage side_img = d.image(VK_FORMAT_R8G8B8A8_UNORM, 32, 32, 1,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
EXPECT(back_img != VK_NULL_HANDLE && side_img != VK_NULL_HANDLE);
ResourceBinding back_rb{};
back_rb.image = back_img;
back_rb.format = VK_FORMAT_R8G8B8A8_UNORM;
back_rb.aspects = VK_IMAGE_ASPECT_COLOR_BIT;
back_rb.width = width;
back_rb.height = height;
back_rb.mip_levels = 1;
back_rb.array_layers = 1;
back_rb.depth = 1;
back_rb.samples = 1;
back_rb.color_attachment = true;
context.add_resource(1, back_rb, VK_IMAGE_LAYOUT_UNDEFINED);
ResourceBinding side_rb = back_rb;
side_rb.image = side_img;
side_rb.width = 32;
side_rb.height = 32;
const auto create_surface = reinterpret_cast<PFN_vkCreateWin32SurfaceKHR>(
d.instance_proc(d.instance, "vkCreateWin32SurfaceKHR"));
EXPECT(create_surface);
VkWin32SurfaceCreateInfoKHR surface_info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR};
surface_info.hinstance = GetModuleHandleW(nullptr);
surface_info.hwnd = window;
VkSurfaceKHR surface = VK_NULL_HANDLE;
EXPECT(create_surface(d.instance, &surface_info, nullptr, &surface) == VK_SUCCESS);
VulkanPresenter presenter(context, driver::get_instance, d.instance, d.physical, d.queue, d.family, surface);
EXPECT(presenter.ok());
EXPECT(presenter.enable_capture());
// 1. Failed vkQueueSubmit must NOT commit the UNDEFINED -> GENERAL transition in LayoutTracker (O(1) rollback
// even with many live tracked textures), and tracker_mutex_ must be released before vkQueuePresentKHR.
for (ResourceId extra = 1000; extra < 1512; ++extra)
context.add_resource(extra, side_rb, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED);
driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY);
EXPECT(presenter.present(1, true) == VK_ERROR_OUT_OF_HOST_MEMORY);
EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_UNDEFINED);
EXPECT(context.layout(1000, 0) == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
// Next present succeeds, runs the deferred zero-fill, commits GENERAL, and unlocks tracker_mutex_ before
// vkQueuePresentKHR so other threads' emit() / layout() calls are not blocked by presentation.
std::mutex sync_mutex;
std::condition_variable sync_cv;
bool reader_started = false;
bool read_done = false;
VkImageLayout seen_during_present = VK_IMAGE_LAYOUT_UNDEFINED;
bool unblocked_during_present = false;
std::thread reader;
driver::on_next_present = [&] {
reader = std::thread([&] {
{
std::lock_guard lk(sync_mutex);
reader_started = true;
}
sync_cv.notify_all();
const VkImageLayout layout = context.layout(1, 0);
{
std::lock_guard lk(sync_mutex);
seen_during_present = layout;
read_done = true;
}
sync_cv.notify_all();
});
std::unique_lock lk(sync_mutex);
const bool started = sync_cv.wait_for(lk, std::chrono::seconds(2), [&] { return reader_started; });
unblocked_during_present =
started && sync_cv.wait_for(lk, std::chrono::milliseconds(500), [&] { return read_done; });
};
const VkResult present_rc = presenter.present(1, true);
if (reader.joinable()) reader.join();
EXPECT(present_rc == VK_SUCCESS);
EXPECT(unblocked_during_present);
EXPECT(seen_during_present == VK_IMAGE_LAYOUT_GENERAL);
EXPECT(context.layout(1, 0) == VK_IMAGE_LAYOUT_GENERAL);
for (ResourceId extra = 1000; extra < 1512; ++extra) context.remove_resource(extra);
std::vector<std::uint8_t> pixels{0x7f};
VkExtent2D ext{1, 2};
VkFormat fmt = VK_FORMAT_R8_UNORM;
driver::fail_next_wait = VK_ERROR_DEVICE_LOST;
EXPECT(!presenter.read_back(pixels, &ext, &fmt));
EXPECT(pixels.size() == 1 && pixels[0] == 0x7f);
EXPECT(ext.width == 1 && ext.height == 2 && fmt == VK_FORMAT_R8_UNORM);
EXPECT(presenter.read_back(pixels, &ext, &fmt));
EXPECT(pixels.size() == std::size_t(ext.width) * ext.height * 4);
const std::size_t mid = (std::size_t(ext.height / 2) * ext.width + ext.width / 2) * 4;
EXPECT(pixels[mid + 0] == 0 && pixels[mid + 1] == 0 && pixels[mid + 2] == 0);
std::printf("presenter sync: failed-submit LayoutTracker rollback ok\n");
// 2. Capture-buffer WAW barrier before vkCmdCopyImageToBuffer on both present() and present_blank().
{
CommandList clear_list;
EXPECT(clear_list.transition({1, 0, d3d12_state::common, d3d12_state::render_target}));
EXPECT(clear_list.clear_render_target({1, 0, 0, 1}, {0.2f, 0.6f, 0.9f, 1.0f}));
EXPECT(clear_list.transition({1, 0, d3d12_state::render_target, d3d12_state::common}));
EXPECT(clear_list.close());
const CommandList* ptr = &clear_list;
EXPECT(queue.execute({&ptr, 1}) == ReplayResult::success);
}
driver::saw_capture_waw.store(false);
driver::capture_copies.store(0);
driver::capture_waw_barriers.store(0);
driver::observe_capture.store(true);
EXPECT(presenter.present(1, true) == VK_SUCCESS);
EXPECT(presenter.present(1, true) == VK_SUCCESS);
EXPECT(presenter.present_blank(true) == VK_SUCCESS);
EXPECT(presenter.present(1, true) == VK_SUCCESS);
driver::observe_capture.store(false);
EXPECT(driver::capture_copies.load() == 4);
EXPECT(driver::capture_waw_barriers.load() == 4);
EXPECT(presenter.read_back(pixels, &ext, &fmt));
EXPECT(pixels.size() == std::size_t(ext.width) * ext.height * 4);
const std::size_t mid2 = (std::size_t(ext.height / 2) * ext.width + ext.width / 2) * 4;
const bool bgra = (fmt == VK_FORMAT_B8G8R8A8_UNORM || fmt == VK_FORMAT_B8G8R8A8_SRGB);
const int r = bgra ? pixels[mid2 + 2] : pixels[mid2 + 0];
const int g = pixels[mid2 + 1];
const int b = bgra ? pixels[mid2 + 0] : pixels[mid2 + 2];
EXPECT(std::abs(r - 51) <= 2 && std::abs(g - 153) <= 2 && std::abs(b - 230) <= 2);
std::printf("presenter sync: capture-buffer WAW barriers (4/4) and read_back (%d,%d,%d) ok\n", r, g, b);
// 2b. A Present behind held work shows what that work draws (queue_holds.h). The render waits for a gate with
// no submitted Signal, so the queue holds it; the Present is queued behind it instead of blitting the back
// buffer as it was. Two presents queue up and keep their order; the blank one in the middle reads nothing.
{
VulkanFence gate(context, 0);
EXPECT(gate.semaphore() != VK_NULL_HANDLE);
CommandList red;
EXPECT(red.transition({1, 0, d3d12_state::common, d3d12_state::render_target}));
EXPECT(red.clear_render_target({1, 0, 0, 1}, {0.9f, 0.1f, 0.2f, 1.0f}));
EXPECT(red.transition({1, 0, d3d12_state::render_target, d3d12_state::common}));
EXPECT(red.close());
const CommandList* ptr = &red;
queue.wait(gate.semaphore(), 1);
EXPECT(queue.execute({&ptr, 1}) == ReplayResult::success); // held
const auto center = [&](int& cr, int& cg, int& cb) {
std::vector<std::uint8_t> shot;
VkExtent2D e{};
VkFormat f{};
if (!presenter.read_back(shot, &e, &f)) return false;
const std::size_t at = (std::size_t(e.height / 2) * e.width + e.width / 2) * 4;
const bool bgr = (f == VK_FORMAT_B8G8R8A8_UNORM || f == VK_FORMAT_B8G8R8A8_SRGB);
cr = bgr ? shot[at + 2] : shot[at + 0];
cg = shot[at + 1];
cb = bgr ? shot[at + 0] : shot[at + 2];
return true;
};
int cr = 0, cg = 0, cb = 0;
EXPECT(presenter.present(1, true) == VK_SUCCESS); // queued: returns at once
EXPECT(center(cr, cg, cb) && std::abs(cr - 51) <= 2 && std::abs(cg - 153) <= 2 && std::abs(cb - 230) <= 2);
EXPECT(gate.signal(1)); // releases the render, then the presents, on this thread
EXPECT(queue.idle());
EXPECT(center(cr, cg, cb) && std::abs(cr - 230) <= 2 && std::abs(cg - 26) <= 2 && std::abs(cb - 51) <= 2);
std::printf("presenter sync: Present queued behind held work shows the rendered content (%d,%d,%d)\n", cr, cg, cb);
}
// 3. Concurrent present() + VulkanQueue::execute() + add/remove_resource() hammering LayoutTracker.
std::atomic<bool> stop{false};
std::atomic<bool> worker_failed{false};
std::thread worker([&] {
std::uint64_t round = 0;
while (!stop.load(std::memory_order_relaxed)) {
const ResourceId base = 100 + (round % 8) * 32;
for (ResourceId i = 0; i < 32; ++i)
context.add_resource(base + i, side_rb, VK_IMAGE_LAYOUT_UNDEFINED);
CommandList list;
if (!list.clear_render_target({base, 0, 0, 1}, {0.1f, 0.2f, 0.3f, 1.0f}) || !list.close()) {
worker_failed.store(true);
break;
}
const CommandList* ptr = &list;
if (worker_queue.execute({&ptr, 1}) != ReplayResult::success) {
worker_failed.store(true);
break;
}
(void)context.layout(base, 0);
for (ResourceId i = 0; i < 32; ++i) context.remove_resource(base + i);
++round;
}
});
VkResult present_err = VK_SUCCESS;
for (int i = 0; i < 40; ++i) {
pump();
present_err = presenter.present(1, false);
if (present_err != VK_SUCCESS) break;
}
stop.store(true, std::memory_order_relaxed);
worker.join();
EXPECT(present_err == VK_SUCCESS);
EXPECT(!worker_failed.load());
EXPECT(queue.idle() && worker_queue.idle());
std::printf("presenter sync: concurrent present + queue.execute + tracker mutations ok\n");
}
DestroyWindow(window);
UnregisterClassW(wc.lpszClassName, wc.hInstance);
EXPECT(d.validation_errors() == 0);
std::printf("vk_presenter_sync_test: ok\n");
return 0;
}