upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime/test/vk_queue_query_sync_test.cpp
diff options
context:
space:
mode:
authorVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 15:51:40 +0100
committerVonsek <45567075+Vonsek@users.noreply.github.com>2026-11-22 15:51:40 +0100
commitdf91c6624b69ee4e6c6eeca20ed68d331ed0e728 (patch)
tree323c88b9df89bf8abaa2b98d10808474ab675dc2 /runtime/test/vk_queue_query_sync_test.cpp
parentb40d8039a98f57b26bd05860febbabbe59b97873 (diff)
parent6a6704df1592e1dc4a3215ddf1423a78adb52045 (diff)
Merge main into test/valu-int-misc (#1492)
Conflicted files: runtime/test/shaders/check.py, scripts/run_gpu_tests.py AI-assisted.
Diffstat (limited to 'runtime/test/vk_queue_query_sync_test.cpp')
-rw-r--r--runtime/test/vk_queue_query_sync_test.cpp351
1 files changed, 351 insertions, 0 deletions
diff --git a/runtime/test/vk_queue_query_sync_test.cpp b/runtime/test/vk_queue_query_sync_test.cpp
new file mode 100644
index 000000000..a9daf6477
--- /dev/null
+++ b/runtime/test/vk_queue_query_sync_test.cpp
@@ -0,0 +1,351 @@
1// VulkanQueue / VulkanContext query-state synchronization and failed-submit wait preservation regressions
2// (runtime/src/vulkan_backend.h):
3// 1. VulkanContext::remove_query_pool() must serialize with tracker_mutex_ so an in-flight VulkanQueue::execute()
4// that already unlocked resource_mutex_ cannot suffer a use-after-free in QueryReplay::commit().
5// 2. VulkanQueue::execute() must acquire tracker_mutex_ before QueryReplay::plan() so concurrent queues see
6// submission-order query state (no data race on QueryPool::ended / QueryPool::occlusion and no stale zero-fill).
7// 3. A transient vkQueueSubmit failure must preserve pending VulkanQueue::wait() timeline semaphores for the retry.
8// 4. Concurrent multi-queue query End/Resolve + add/remove_query_pool stress with zero Vulkan validation errors.
9// Skips with exit code 77 when no Vulkan 1.3 device is available. No game data.
10#include "vk_test_device.h"
11#include "../src/vulkan_backend.h"
12
13#include <atomic>
14#include <chrono>
15#include <cstdint>
16#include <cstdio>
17#include <cstring>
18#include <functional>
19#include <string_view>
20#include <thread>
21#include <vector>
22
23#define EXPECT(condition) do { \
24 if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \
25} while (0)
26
27namespace {
28
29namespace driver {
30PFN_vkGetDeviceProcAddr real_get_device = nullptr;
31PFN_vkQueueSubmit real_submit = nullptr;
32PFN_vkCmdCopyQueryPoolResults real_copy_queries = nullptr;
33PFN_vkCmdFillBuffer real_fill_buffer = nullptr;
34
35std::atomic<VkResult> fail_next_submit{VK_SUCCESS};
36std::atomic<bool> capture_next_waits{false};
37std::atomic<std::uint32_t> captured_wait_count{0};
38std::atomic<std::uintptr_t> captured_wait_sem{0};
39std::atomic<std::uint64_t> captured_wait_val{0};
40
41std::atomic<bool> count_resolves{false};
42std::atomic<std::uint32_t> copy_query_calls{0};
43std::atomic<std::uint32_t> fill_buffer_calls{0};
44
45// Optional one-shot callback invoked inside vkQueueSubmit right before calling the real driver.
46// Returning non-VK_SUCCESS short-circuits the submit with that status.
47std::function<VkResult()> on_next_submit;
48
49VKAPI_ATTR VkResult VKAPI_CALL queue_submit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits,
50 VkFence fence) {
51 if (on_next_submit) {
52 auto cb = std::move(on_next_submit);
53 on_next_submit = {};
54 const VkResult override_res = cb();
55 if (override_res != VK_SUCCESS) return override_res;
56 }
57 const VkResult armed = fail_next_submit.exchange(VK_SUCCESS);
58 if (armed != VK_SUCCESS) return armed;
59 if (capture_next_waits.exchange(false) && count > 0 && submits) {
60 captured_wait_count.store(submits[0].waitSemaphoreCount);
61 if (submits[0].waitSemaphoreCount > 0 && submits[0].pWaitSemaphores) {
62 captured_wait_sem.store(reinterpret_cast<std::uintptr_t>(submits[0].pWaitSemaphores[0]));
63 const auto* timeline = reinterpret_cast<const VkTimelineSemaphoreSubmitInfo*>(submits[0].pNext);
64 if (timeline && timeline->sType == VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO &&
65 timeline->waitSemaphoreValueCount > 0 && timeline->pWaitSemaphoreValues) {
66 captured_wait_val.store(timeline->pWaitSemaphoreValues[0]);
67 }
68 }
69 }
70 return real_submit(queue, count, submits, fence);
71}
72
73VKAPI_ATTR void VKAPI_CALL cmd_copy_query_pool_results(VkCommandBuffer cb, VkQueryPool pool, std::uint32_t first,
74 std::uint32_t count, VkBuffer dst, VkDeviceSize offset,
75 VkDeviceSize stride, VkQueryResultFlags flags) {
76 if (count_resolves.load(std::memory_order_relaxed)) copy_query_calls.fetch_add(1, std::memory_order_relaxed);
77 real_copy_queries(cb, pool, first, count, dst, offset, stride, flags);
78}
79
80VKAPI_ATTR void VKAPI_CALL cmd_fill_buffer(VkCommandBuffer cb, VkBuffer dst, VkDeviceSize offset, VkDeviceSize size,
81 std::uint32_t data) {
82 if (count_resolves.load(std::memory_order_relaxed)) fill_buffer_calls.fetch_add(1, std::memory_order_relaxed);
83 real_fill_buffer(cb, dst, offset, size, data);
84}
85
86VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL get_device(VkDevice device, const char* name) {
87 const std::string_view n = name;
88 if (n == "vkQueueSubmit") return reinterpret_cast<PFN_vkVoidFunction>(queue_submit);
89 if (n == "vkCmdCopyQueryPoolResults") return reinterpret_cast<PFN_vkVoidFunction>(cmd_copy_query_pool_results);
90 if (n == "vkCmdFillBuffer") return reinterpret_cast<PFN_vkVoidFunction>(cmd_fill_buffer);
91 return real_get_device(device, name);
92}
93
94void install(PFN_vkGetDeviceProcAddr device_proc, VkDevice device) {
95 real_get_device = device_proc;
96 real_submit = reinterpret_cast<PFN_vkQueueSubmit>(device_proc(device, "vkQueueSubmit"));
97 real_copy_queries =
98 reinterpret_cast<PFN_vkCmdCopyQueryPoolResults>(device_proc(device, "vkCmdCopyQueryPoolResults"));
99 real_fill_buffer = reinterpret_cast<PFN_vkCmdFillBuffer>(device_proc(device, "vkCmdFillBuffer"));
100}
101} // namespace driver
102
103} // namespace
104
105int main() {
106 using namespace leonida;
107
108 vktest::Device d;
109 if (!d.create(false)) {
110 std::fprintf(stderr, "vk_queue_query_sync_test: no Vulkan 1.3 device, skipped\n");
111 return 77;
112 }
113 driver::install(d.device_proc, d.device);
114
115 const auto create_query_pool = d.fn<PFN_vkCreateQueryPool>("vkCreateQueryPool");
116 const auto destroy_query_pool = d.fn<PFN_vkDestroyQueryPool>("vkDestroyQueryPool");
117 EXPECT(create_query_pool && destroy_query_pool);
118
119 auto make_occlusion_pool = [&](std::uint32_t count) -> VkQueryPool {
120 VkQueryPoolCreateInfo info{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};
121 info.queryType = VK_QUERY_TYPE_OCCLUSION;
122 info.queryCount = count;
123 VkQueryPool pool = VK_NULL_HANDLE;
124 if (create_query_pool(d.device, &info, nullptr, &pool) != VK_SUCCESS) return VK_NULL_HANDLE;
125 return pool;
126 };
127
128 const VkQueryPool pool_uaf = make_occlusion_pool(2);
129 const VkQueryPool pool_race = make_occlusion_pool(2);
130 const VkQueryPool pool_stress = make_occlusion_pool(32);
131 EXPECT(pool_uaf && pool_race && pool_stress);
132
133 {
134 VulkanContext context(driver::get_device, d.device, true);
135 EXPECT(context.loaded());
136 VulkanQueue queue_a(context, d.queue, d.family);
137 VulkanQueue queue_b(context, d.queue, d.family);
138 EXPECT(queue_a.ok() && queue_b.ok());
139
140 void* src_ptr = nullptr;
141 void* dst_ptr = nullptr;
142 void* res_ptr = nullptr;
143 const VkBuffer src_buf = d.buffer(64, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &src_ptr);
144 const VkBuffer dst_buf = d.buffer(64, VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &dst_ptr);
145 const VkBuffer res_buf = d.buffer(64, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &res_ptr);
146 EXPECT(src_buf && dst_buf && res_buf);
147
148 ResourceBinding src_rb{};
149 src_rb.buffer = src_buf;
150 src_rb.size = 64;
151 ResourceBinding dst_rb{};
152 dst_rb.buffer = dst_buf;
153 dst_rb.size = 64;
154 dst_rb.host_readable = true;
155 ResourceBinding res_rb{};
156 res_rb.buffer = res_buf;
157 res_rb.size = 64;
158 res_rb.host_readable = true;
159 context.add_resource(1, src_rb);
160 context.add_resource(2, dst_rb);
161 context.add_resource(3, res_rb);
162
163 // 1. remove_query_pool() must block on tracker_mutex_ while execute() is between resource_lock.unlock() and
164 // QueryReplay::commit(), preventing a use-after-free on the QueryPool* stored in QueryReplay::pending_.
165 {
166 constexpr QueryHeapId heap_id = 77;
167 QueryPool qp{};
168 qp.pool = pool_uaf;
169 qp.heap_type = d3d12_query_heap::occlusion;
170 qp.count = 2;
171 qp.ended.assign(2, false);
172 context.add_query_pool(heap_id, qp);
173
174 CommandList list;
175 EXPECT(list.begin_query({heap_id, d3d12_query::occlusion, 0}));
176 EXPECT(list.end_query({heap_id, d3d12_query::occlusion, 0}));
177 EXPECT(list.close());
178 const CommandList* ptr = &list;
179
180 std::atomic<bool> removed{false};
181 bool removed_during_submit = false;
182 std::thread remover;
183 driver::on_next_submit = [&]() -> VkResult {
184 remover = std::thread([&] {
185 context.remove_query_pool(heap_id);
186 removed.store(true, std::memory_order_release);
187 });
188 std::this_thread::sleep_for(std::chrono::milliseconds(30));
189 removed_during_submit = removed.load(std::memory_order_acquire);
190 // If remove_query_pool already erased the node, abort the submit so queries.commit() does not
191 // corrupt the heap before the EXPECT below reports the failure cleanly.
192 return removed_during_submit ? VK_ERROR_OUT_OF_HOST_MEMORY : VK_SUCCESS;
193 };
194 const ReplayResult exec_res = queue_a.execute({&ptr, 1});
195 if (remover.joinable()) remover.join();
196 EXPECT(!removed_during_submit);
197 EXPECT(exec_res == ReplayResult::success);
198 EXPECT(removed.load(std::memory_order_acquire));
199 EXPECT(context.query_heap_type(heap_id) == ~0u);
200 EXPECT(queue_a.idle());
201 std::printf("queue/query sync: remove_query_pool serialized with QueryReplay::commit ok\n");
202 }
203
204 // 2. Concurrent queue_b.execute(ResolveQueries) must not run QueryReplay::plan() before queue_a commits
205 // EndQuery; otherwise queue_b sees ended[0] == false and emits vkCmdFillBuffer(0) instead of copying.
206 {
207 constexpr QueryHeapId heap_id = 88;
208 QueryPool qp{};
209 qp.pool = pool_race;
210 qp.heap_type = d3d12_query_heap::occlusion;
211 qp.count = 2;
212 qp.ended.assign(2, false);
213 context.add_query_pool(heap_id, qp);
214
215 CommandList end_list;
216 EXPECT(end_list.begin_query({heap_id, d3d12_query::occlusion, 0}));
217 EXPECT(end_list.end_query({heap_id, d3d12_query::occlusion, 0}));
218 EXPECT(end_list.close());
219 const CommandList* end_ptr = &end_list;
220
221 CommandList resolve_list;
222 EXPECT(resolve_list.resolve_queries({heap_id, d3d12_query::occlusion, 0, 1, 3, 0}));
223 EXPECT(resolve_list.close());
224 const CommandList* resolve_ptr = &resolve_list;
225
226 std::memset(res_ptr, 0xAB, 64);
227 driver::copy_query_calls.store(0);
228 driver::fill_buffer_calls.store(0);
229 driver::count_resolves.store(true);
230
231 std::thread resolver;
232 ReplayResult resolve_res = ReplayResult::unsupported;
233 driver::on_next_submit = [&]() -> VkResult {
234 resolver = std::thread([&] { resolve_res = queue_b.execute({&resolve_ptr, 1}); });
235 // Give queue_b ample time to run prepare() and reach QueryReplay::plan() while queue_a holds
236 // tracker_mutex_ (and has already unlocked resource_mutex_).
237 std::this_thread::sleep_for(std::chrono::milliseconds(40));
238 return VK_SUCCESS;
239 };
240
241 const ReplayResult end_res = queue_a.execute({&end_ptr, 1});
242 if (resolver.joinable()) resolver.join();
243 driver::count_resolves.store(false);
244 EXPECT(end_res == ReplayResult::success);
245 EXPECT(resolve_res == ReplayResult::success);
246 EXPECT(queue_a.idle() && queue_b.idle());
247 EXPECT(driver::copy_query_calls.load() == 1);
248 EXPECT(driver::fill_buffer_calls.load() == 0);
249 std::uint64_t resolved = 0xDEADBEEFULL;
250 std::memcpy(&resolved, res_ptr, sizeof(resolved));
251 EXPECT(resolved == 0); // empty occlusion query resolves 0 via vkCmdCopyQueryPoolResults
252 context.remove_query_pool(heap_id);
253 std::printf("queue/query sync: cross-queue QueryReplay::plan serialized with commit ok\n");
254 }
255
256 // 3. A transient vkQueueSubmit failure must preserve pending VulkanQueue::wait() semaphores for the retry.
257 {
258 VulkanFence fence(context, 0);
259 EXPECT(fence.semaphore() != VK_NULL_HANDLE);
260
261 const std::uint64_t pattern = 0x1122334455667788ULL;
262 std::memcpy(src_ptr, &pattern, sizeof(pattern));
263 std::memset(dst_ptr, 0, sizeof(pattern));
264
265 CommandList copy_list;
266 EXPECT(copy_list.copy_buffer({2, 0, 1, 0, sizeof(pattern)}));
267 EXPECT(copy_list.close());
268 const CommandList* ptr = &copy_list;
269
270 queue_a.wait(fence.semaphore(), 1);
271 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY);
272 EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::unsupported);
273
274 // Retry: the pending wait on (fence, 1) must still be attached to the next vkQueueSubmit.
275 EXPECT(fence.signal(1));
276 driver::captured_wait_count.store(0);
277 driver::captured_wait_sem.store(0);
278 driver::captured_wait_val.store(0);
279 driver::capture_next_waits.store(true);
280 EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::success);
281 EXPECT(queue_a.idle());
282 EXPECT(driver::captured_wait_count.load() == 1);
283 EXPECT(driver::captured_wait_sem.load() == reinterpret_cast<std::uintptr_t>(fence.semaphore()));
284 EXPECT(driver::captured_wait_val.load() == 1);
285
286 std::uint64_t got = 0;
287 std::memcpy(&got, dst_ptr, sizeof(got));
288 EXPECT(got == pattern);
289 std::printf("queue/query sync: pending Wait() preserved across failed vkQueueSubmit ok\n");
290 }
291
292 // 4. Concurrent multi-queue EndQuery + ResolveQueries + temporary query pool add/remove stress.
293 // Each iteration uses a distinct query slot so no slot is reset while another submission resolves it.
294 {
295 constexpr QueryHeapId main_heap = 99;
296 QueryPool qp{};
297 qp.pool = pool_stress;
298 qp.heap_type = d3d12_query_heap::occlusion;
299 qp.count = 32;
300 qp.ended.assign(32, false);
301 context.add_query_pool(main_heap, qp);
302
303 CommandList res_list;
304 EXPECT(res_list.resolve_queries({main_heap, d3d12_query::occlusion, 0, 1, 3, 0}));
305 EXPECT(res_list.close());
306 const CommandList* res_ptr_cmd = &res_list;
307
308 std::atomic<bool> stop{false};
309 std::atomic<bool> worker_err{false};
310 std::thread worker([&] {
311 for (std::uint64_t round = 0; !stop.load(std::memory_order_relaxed); ++round) {
312 if (queue_b.execute({&res_ptr_cmd, 1}) != ReplayResult::success || !queue_b.idle()) {
313 worker_err.store(true);
314 break;
315 }
316 const QueryHeapId temp_id = 1000 + (round % 16);
317 context.add_query_pool(temp_id, qp);
318 context.remove_query_pool(temp_id);
319 }
320 });
321
322 ReplayResult main_err = ReplayResult::success;
323 for (std::uint32_t i = 0; i < 32; ++i) {
324 CommandList end_list;
325 if (!end_list.begin_query({main_heap, d3d12_query::occlusion, i}) ||
326 !end_list.end_query({main_heap, d3d12_query::occlusion, i}) || !end_list.close()) {
327 main_err = ReplayResult::invalid_query;
328 break;
329 }
330 const CommandList* end_ptr = &end_list;
331 main_err = queue_a.execute({&end_ptr, 1});
332 if (main_err != ReplayResult::success) break;
333 }
334 stop.store(true, std::memory_order_relaxed);
335 worker.join();
336 EXPECT(main_err == ReplayResult::success);
337 EXPECT(!worker_err.load());
338 EXPECT(queue_a.idle() && queue_b.idle());
339 context.remove_query_pool(main_heap);
340 std::printf("queue/query sync: concurrent multi-queue query stress ok\n");
341 }
342 }
343
344 destroy_query_pool(d.device, pool_uaf, nullptr);
345 destroy_query_pool(d.device, pool_race, nullptr);
346 destroy_query_pool(d.device, pool_stress, nullptr);
347
348 EXPECT(d.validation_errors() == 0);
349 std::printf("vk_queue_query_sync_test: ok\n");
350 return 0;
351}