Repository navigation
Runtime: buffer_at finds a buffer by binary search, not a scan of every resource - #2823
Conversation
Buffers' VA ranges kept in a std::map by first VA: a lookup is a binary search, walking down from the nearest start only while a range can still reach the VA (bounded by the longest range), so aliasing placed buffers that overlap still resolve, to the range that starts closest below the VA (the larger ID on a tie). buffer_va_index_test checks edges, overlapping and nested ranges, re-registration and erase, then 200 random tables against a linear scan with the same rule, and prints the lookup time against the scan over every resource that buffer_at does today (--bench for 50k and 100k resources).
…ry resource VulkanContext::buffer_at walked every registered resource, images included, for each vertex-buffer slot, index buffer and WriteBufferImmediate of every draw. It now asks a BufferVaIndex of the addressable buffers (no image, a VkBuffer, a VA and bytes: what the scan accepted), kept in step with resources_ by add_resource, add_sparse_buffer and remove_resource; a re-registered ID drops its old range first. Where placed buffers alias, the scan returned whichever matched first in unordered_map order; the index returns the range that starts closest below the VA. docs/d3d12_vulkan.md drops the "Lookups" known gap.
kacper-serewis
left a comment
There was a problem hiding this comment.
Independently tested df1ae87 on Windows with clang++ and synthetic Vulkan handles. A standalone harness called the actual VulkanContext replay buffer_at callback after each of 12 registration, replacement and removal operations. All 3,456 probes agreed with a separate linear reference on hit/miss and, for hits, VkBuffer, offset and clipped size. Cases included sparse registration, same-start and nested aliases, fallback after removal, same-ID relocation, buffer-to-image replacement, VA reuse, empty ranges, and addresses through UINT64_MAX. CPU only, no game files or GPU submission. No timing measurements. AI-assisted review.
|
Code read of AI-assisted review (Claude Code). |
|
Independent VA-index churn check ( AI-assisted (Codex). |
The bound that stops a lookup's walk only grew: once a large buffer was freed, every later miss still walked back as far as that buffer had reached. With 20 000 buffers of 256 bytes, a 1 GiB range added then removed left a miss past the last buffer at 250-600 us instead of ~50 ns (found by @padhossein in review of ItsNotRexed#2823). A multiset of the indexed sizes keeps the bound at the longest range indexed now; insert and erase stay O(log n), find is unchanged. Inserting the same (va, id) again replaces its size instead of leaving the old one in the bound. buffer_va_index_test checks the bound after erases (same sizes and a smaller re-registration included), against the longest live range in all 200 random tables, and times the review's miss-after-free case.
|
@padhossein thanks, fixed in
The bound checks fail on One limit remains, and the header comment now says so: while a large range is still live, a miss walks every start within that range below the VA. For example, a buffer that covers a whole heap with placed buffers inside it. That walk is never longer than the old scan over every resource, images included. Only an interval tree would remove it, and that can be a follow-up if a real frame shows it. Tested on AI-assisted (Claude Code). |
Kam471
left a comment
There was a problem hiding this comment.
Reviewed at head df1ae87e; the branch merges cleanly with current main and the diff is limited to the buffer index, its test, docs and CMake. Inspection found a correct ordered index: (va, id) ordering, upper_bound({va, max_id}) then walk back, nearest start wins, larger ID wins on ties, and offset >= longest_ is a safe early exit. The test covers null/zero skip, first/last byte, one-past-end, gaps, highest VA, nested and same-start aliases, erase/refill, plus 200x2000 randomized comparisons against a linear scan. No game data or host paths. Approve.
Not built here (no configured build dir in the worktree), so this is inspection-only. Non-blocking: longest_ is only recomputed when the index empties, so removing the longest range makes later misses walk every entry; that edge is untested.
|
Code review of 111b634 (read only, no runs): looks right to me. What I checked:
One suggestion, not blocking, about that overlap rule. With placed buffers aliasing in one heap, say a big buffer B at heap offset 0 and a small S inside it, a vertex view that starts in S but runs past S's end will resolve to S, because S starts closer. The view is then cut at S's end, and the rest reads as out of bounds (zeros), even though B holds all of it. One note on measuring: AI-assisted (Claude Code). |
With placed buffers aliasing in one heap, a large buffer B and a small S inside it, a vertex or index view that starts in S and runs past its end resolved to S, the closest start below the VA, and buffer_at cut it at S's end: the rest read as out of bounds, though B holds all of it. Found by traeb0n in the review of ItsNotRexed#2823. BufferVaIndex::find takes the bytes the lookup needs and returns, among the ranges that hold the VA, the closest start (larger ID on a tie) that also holds all of them; when none does, the closest that holds the VA, as before. Without overlaps the first range it looks at is still the answer. With a fallback found, the walk stops once no range can hold all the bytes, bounded by the longest live range. buffer_at passes the requested size. buffer_va_index_test checks views that fit in the small buffer, run past it into the large one, run past every range and have size 0, and three quarters of the random-table lookups now name a view of up to 32 KiB, checked against a scan with the same rule.
|
@traeb0n thanks for the review, and good catch on the aliasing case. I'd add one thing to "this PR doesn't make anything worse": the old scan picked B or S in hash order, so that view was sometimes right, while the nearest-start rule picks S every time. Deterministic, but that case is now wrong every time, so it was worth fixing here rather than in a follow-up. Done in b8273c0, as you suggested:
Tested on b8273c0: full runtime build and Agreed on AI-assisted (Claude Code). |
# Conflicts: # docs/d3d12_vulkan.md
|
Tested b8273c0 on RTX 5090, 621.24, Windows 11: pass. Built Swapping the linear scan for a binary search over the VA ranges is the kind of change that needs exactly this: a test that pins the found/not-found edges, since a wrong comparator only shows up as a missing buffer at runtime. |
|
Independent Windows check of the merged change (BUILD-821, claim): the real Tree: How. A standalone program (below, not for the repository) builds a
At the end, with everything removed, the index holds 0 ranges and its longest-range bound is 0. The check can fail. With one deliberate fault at a time in the tree, the same program exits 1:
With the files restored it is 0 again. Also run: Not covered: concurrency (the callback runs under AI-assisted (Claude Code). The program (va_check_821.cpp)// BUILD-821: an independent check of VulkanContext's replay buffer_at callback (#2823) on Windows, with synthetic
// Vulkan handles and no driver. Not part of the repository: built from a scratch worktree for the check only.
// It registers, replaces and removes resources through the public VulkanContext members and compares every lookup
// of the real callback with a linear reference written from the documented rule (buffer_va_index.h, lines 8-11).
#define _ALLOW_KEYWORD_MACROS 1
#define private public // the callback lives in the private replay_ member; nothing else is touched
#include "../src/vulkan_backend.h"
#undef private
#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <map>
#include <random>
#include <vector>
using namespace leonida;
namespace {
template<class T>
T handle(std::uintptr_t n) { return reinterpret_cast<T>(n); }
VkResult VKAPI_CALL nothing() { return VK_SUCCESS; }
PFN_vkVoidFunction VKAPI_CALL get(VkDevice, const char*) { return reinterpret_cast<PFN_vkVoidFunction>(nothing); }
// The reference: what is registered now, by ID, and a scan of all of it.
struct Reference {
std::map<ResourceId, ResourceBinding> live;
static bool addressable(const ResourceBinding& b) { return !b.image && b.buffer && b.va && b.size; }
// Among the buffers that hold va: the one that starts closest below va (larger ID on a tie) and holds all of
// [va, va + bytes); when none holds all of it, the closest one that holds va.
bool find(std::uint64_t va, std::uint64_t bytes, VkBuffer& buffer, VkDeviceSize& offset, std::uint64_t& size) const {
const std::uint64_t want = bytes ? bytes : 1;
const ResourceBinding* whole = nullptr;
const ResourceBinding* part = nullptr;
ResourceId whole_id = 0, part_id = 0;
for (const auto& [id, b] : live) {
if (!addressable(b) || va < b.va || va - b.va >= b.size) continue;
const bool all = want <= b.size - (va - b.va);
const ResourceBinding*& best = all ? whole : part;
ResourceId& best_id = all ? whole_id : part_id;
if (!best || b.va > best->va || (b.va == best->va && id > best_id)) {
best = &b;
best_id = id;
}
}
const ResourceBinding* b = whole ? whole : part;
if (!b) return false;
buffer = b->buffer;
offset = b->buffer_offset + (va - b->va);
size = bytes < b->size - (va - b->va) ? bytes : b->size - (va - b->va);
return true;
}
};
struct Check {
VulkanContext context{get, handle<VkDevice>(1), true};
Reference ref;
std::uint64_t probes = 0, hits = 0, mismatches = 0;
void add(ResourceId id, const ResourceBinding& b) {
context.add_resource(id, b);
ref.live[id] = b;
}
void add_with_layout(ResourceId id, const ResourceBinding& b) {
context.add_resource(id, b, VK_IMAGE_LAYOUT_UNDEFINED);
ref.live[id] = b;
}
void add_sparse(ResourceId id, const ResourceBinding& b) {
context.add_sparse_buffer(id, b, nullptr);
ref.live[id] = b;
}
void remove(ResourceId id) {
context.remove_resource(id);
ref.live.erase(id);
}
bool probe(std::uint64_t va, std::uint64_t bytes, const char* where) {
std::uint64_t got_size = bytes, want_size = 0;
VkBuffer got_buffer = handle<VkBuffer>(0xdead), want_buffer = VK_NULL_HANDLE;
VkDeviceSize got_offset = 0xdead, want_offset = 0;
const bool got = context.replay_.buffer_at(va, got_size, got_buffer, got_offset);
const bool want = ref.find(va, bytes, want_buffer, want_offset, want_size);
++probes;
if (want) ++hits;
const bool same = got == want && (!want || (got_buffer == want_buffer && got_offset == want_offset &&
got_size == want_size));
if (!same) {
if (mismatches++ < 12)
std::printf("MISMATCH %s: va %016" PRIx64 " bytes %" PRIx64 ": callback %d %p +%" PRIx64 " size %" PRIx64
", reference %d %p +%" PRIx64 " size %" PRIx64 "\n",
where, va, bytes, int(got), static_cast<void*>(got_buffer), std::uint64_t(got_offset),
got_size, int(want), static_cast<void*>(want_buffer), std::uint64_t(want_offset), want_size);
}
return same;
}
// Every edge of every live range, one byte either side, with byte counts that fit, clip and overflow.
void probe_all(const char* where) {
std::vector<std::uint64_t> vas = {0, 1, ~0ull, ~0ull - 1};
for (const auto& [id, b] : ref.live) {
if (!b.va) continue;
const std::uint64_t end = b.va + b.size; // may wrap: the probes below are still valid addresses
for (std::uint64_t v : {b.va - 1, b.va, b.va + 1, b.va + b.size / 2, end - 1, end, end + 1}) vas.push_back(v);
}
for (std::uint64_t va : vas)
for (std::uint64_t bytes : {0ull, 1ull, 2ull, 4ull, 0x100ull, 0x1000ull, 0x10000ull, 1ull << 32, ~0ull})
probe(va, bytes, where);
}
};
ResourceBinding buffer(std::uintptr_t vk_buffer, std::uint64_t va, std::uint64_t size, std::uint64_t at = 0) {
ResourceBinding b;
b.buffer = handle<VkBuffer>(vk_buffer);
b.va = va;
b.size = size;
b.buffer_offset = at;
return b;
}
ResourceBinding image(std::uintptr_t vk_image, std::uint64_t va = 0, std::uint64_t size = 0) {
ResourceBinding b;
b.image = handle<VkImage>(vk_image);
b.format = VK_FORMAT_R8G8B8A8_UNORM;
b.buffer = va ? handle<VkBuffer>(0x777) : VK_NULL_HANDLE; // an image that also names a buffer is still no buffer
b.va = va;
b.size = size;
return b;
}
void lifetime(Check& c) {
const std::uint64_t base = 0x0000'0001'0000'0000ull;
c.probe_all("empty context");
c.add(1, buffer(0x10, base, 0x1000));
c.probe_all("one buffer");
c.remove(1);
c.probe_all("removed again");
c.add(2, buffer(0x20, base, 0x800, 0x40)); // another ID and buffer at the freed VA, shorter
c.probe_all("VA reused by another ID");
c.add(2, buffer(0x21, base + 0x4000, 0x1000)); // the same ID moves: its old range must be gone
c.probe_all("ID re-registered at another VA");
c.add(2, buffer(0x22, base + 0x4000, 0x200)); // same ID and VA, smaller
c.probe_all("ID re-registered smaller");
c.add(2, buffer(0x22, base + 0x4000, 0x4000)); // and larger
c.probe_all("ID re-registered larger");
c.add_with_layout(2, image(0x30, base + 0x4000, 0x4000)); // the ID becomes an image: not addressable any more
c.probe_all("ID became an image");
c.add(2, buffer(0x23, base + 0x4000, 0x100)); // and a buffer again
c.probe_all("ID became a buffer again");
c.add(3, buffer(0, base + 0x8000, 0x1000)); // no VkBuffer
c.add(4, buffer(0x40, 0, 0x1000)); // no VA
c.add(5, buffer(0x50, base + 0x9000, 0)); // no bytes
c.probe_all("bindings that are not addressable");
c.add(3, buffer(0x31, base + 0x8000, 0x1000)); // each of them becomes addressable
c.add(4, buffer(0x40, base + 0xa000, 0x1000));
c.add(5, buffer(0x50, base + 0x9000, 0x1000));
c.probe_all("they became addressable");
c.add_sparse(6, buffer(0x60, base + 0x10000, 0x100000));
c.probe_all("sparse buffer");
c.remove(6);
c.remove(6); // twice, and an ID that never existed
c.remove(99);
c.probe_all("sparse buffer removed");
for (ResourceId id : {ResourceId(2), ResourceId(3), ResourceId(4), ResourceId(5)}) c.remove(id);
c.probe_all("all removed");
}
void clipping(Check& c) {
const std::uint64_t base = 0x0000'0002'0000'0000ull;
c.add(10, buffer(0x100, base, 0x10000, 0x1000)); // a heap-sized buffer
c.add(11, buffer(0x100, base + 0x100, 0x100, 0x1100)); // small placed buffers that alias it
c.add(12, buffer(0x100, base + 0x180, 0x40, 0x1180)); // nested in 11
c.add(13, buffer(0x101, base + 0x100, 0x100, 0)); // same start and size as 11, another VkBuffer, larger ID
c.add(14, buffer(0x102, base + 0xff00, 0x200)); // runs past the end of 10
c.probe_all("aliasing buffers");
for (std::uint64_t bytes = 0; bytes <= 0x240; bytes += 0x10) // a view that grows out of 12, then 11/13, then 10
for (std::uint64_t va : {base + 0x180, base + 0x1bf, base + 0x1ff, base + 0xffff, base + 0x100ff})
c.probe(va, bytes, "growing view");
c.remove(10); // the big one goes: views are cut at the small ones
c.probe_all("aliasing buffers without the large one");
c.add(15, buffer(0x103, base, 1ull << 40)); // a very long range, then gone: later misses stay misses
c.probe_all("very long range added");
c.remove(15);
c.probe_all("very long range removed");
for (ResourceId id : {ResourceId(11), ResourceId(12), ResourceId(13), ResourceId(14)}) c.remove(id);
}
void high_va(Check& c) {
c.add(20, buffer(0x200, 1, 1)); // the lowest address a buffer can have
c.add(21, buffer(0x201, 0x0000'7fff'ffff'f000ull, 0x2000)); // across the 47-bit boundary
c.add(22, buffer(0x202, 0x0000'ffff'ffff'f000ull, 0x2000)); // across the 48-bit boundary
c.add(23, buffer(0x203, 0x0000'0000'ffff'f000ull, 0x2000)); // across 4 GiB
c.add(24, buffer(0x204, 0x7fff'ffff'ffff'f000ull, 0x2000)); // across the sign bit
c.add(25, buffer(0x205, 0xffff'ffff'ffff'f000ull, 0x1000)); // ends exactly at 2^64
c.add(26, buffer(0x206, 0xffff'ffff'ffff'ff00ull, 0xff)); // ends at 2^64 - 1, nested in 25
c.add(27, buffer(0x207, 0xffff'ffff'ffff'ffffull, 1)); // the last byte
c.add(28, buffer(0x208, 0xffff'ffff'ffff'e000ull, 0x4000)); // its end wraps past 2^64
c.probe_all("high addresses");
c.remove(28);
c.remove(25);
c.probe_all("high addresses, two removed");
for (ResourceId id = 20; id <= 27; ++id) c.remove(id);
c.probe_all("high addresses removed");
}
void churn(Check& c, unsigned seed, unsigned operations) {
std::mt19937_64 rng(seed);
const std::uint64_t bases[] = {0x1000, 0x0000'0003'0000'0000ull, 0x0000'ffff'fff0'0000ull, 0xffff'ffff'fff0'0000ull};
const std::uint64_t sizes[] = {1, 0x10, 0x100, 0x1000, 0x10000, 0xfffff, 0x100000};
for (unsigned op = 0; op < operations; ++op) {
const ResourceId id = 1000 + rng() % 24;
const unsigned what = rng() % 10;
if (what < 2) {
c.remove(id);
} else {
const std::uint64_t va = bases[rng() % 4] + (rng() % 0x40) * 0x4000 + (rng() % 3 ? 0 : rng() % 0x4000);
const std::uint64_t size = sizes[rng() % 7];
if (what == 2) c.add_with_layout(id, image(0x900 + id, va, size));
else if (what == 3) c.add(id, buffer(rng() % 2 ? 0x800 + id : 0, rng() % 2 ? va : 0, rng() % 2 ? size : 0));
else if (what == 4) c.add_sparse(id, buffer(0x800 + id, va, size, rng() % 0x1000));
else c.add(id, buffer(0x800 + rng() % 4, va, size, rng() % 0x100000));
}
c.probe_all("random churn");
for (int i = 0; i < 16; ++i) {
const std::uint64_t va = bases[rng() % 4] + rng() % 0x110000;
c.probe(va, rng() % 3 ? rng() % 0x20000 : rng(), "random churn, random address");
}
}
for (ResourceId id = 1000; id < 1024; ++id) c.remove(id);
c.probe_all("random churn, all removed");
}
} // namespace
int main() {
Check c;
struct Part { const char* name; std::uint64_t probes, hits, mismatches; };
std::vector<Part> parts;
std::uint64_t p = 0, h = 0, m = 0;
const auto done = [&](const char* name) {
parts.push_back({name, c.probes - p, c.hits - h, c.mismatches - m});
p = c.probes, h = c.hits, m = c.mismatches;
};
lifetime(c);
done("lifetime reuse");
clipping(c);
done("clipping and aliasing");
high_va(c);
done("high-VA boundaries");
for (unsigned seed = 1; seed <= 20; ++seed) churn(c, seed, 400);
done("random churn (20 seeds x 400 operations)");
for (const Part& part : parts)
std::printf("%-42s %9llu probes, %8llu hits, %llu mismatches\n", part.name,
static_cast<unsigned long long>(part.probes), static_cast<unsigned long long>(part.hits),
static_cast<unsigned long long>(part.mismatches));
std::printf("index after everything was removed: %zu ranges, longest %llu\n", c.context.buffer_vas_.size(),
static_cast<unsigned long long>(c.context.buffer_vas_.longest()));
const bool ok = !c.mismatches && !c.context.buffer_vas_.size() && !c.context.buffer_vas_.longest();
std::printf("%s: %llu probes, %llu mismatches\n", ok ? "OK" : "FAILED", static_cast<unsigned long long>(c.probes),
static_cast<unsigned long long>(c.mismatches));
return ok ? 0 : 1;
}
|
Item: D3D-322 (claimed in #2516)
VulkanContext::buffer_atwalked every registered resource, images included, for each vertex-buffer slot, indexbuffer and
WriteBufferImmediateof every draw (runtime/src/vulkan_backend.h). Its own comment and the "Lookups"known gap in
docs/d3d12_vulkan.mdalready asked for an ordered map by VA once it showed.Changes
runtime/src/buffer_va_index.h(new):BufferVaIndex, buffers' VA ranges in astd::mapkeyed by first VA. Alookup is a binary search that walks down from the nearest start only while a range can still reach the VA (bounded
by the longest range). Standard library only, no Vulkan.
VulkanContextkeeps it in step withresources_inadd_resource(both overloads),add_sparse_bufferandremove_resource; a re-registered ID drops its old range first. Indexed buffers are what the scan accepted: noimage, a
VkBuffer, a VA and a non-zero size.docs/d3d12_vulkan.md: the "Lookups" known gap is gone; theWriteBufferImmediateparagraph says how the lookupworks now.
Behaviour change
Placed buffers may alias, so ranges can overlap. The scan returned whichever matched first in
unordered_maporder;the index returns the range that starts closest below the VA (the larger ID on a tie), every time. Buffer and offset
are the same when the aliasing buffers share the arena; only the
sizecut can differ.Tests
buffer_va_index_test(new, CPU only, in CTest): edges, overlapping and nested ranges, same start, erase andre-registration, then 200 random tables checked against a linear scan with the same rule.
cteston top ofec8ec4c9: 113/113 passed (the skipped tests skip onmaintoo: missingdata or tools), including
d3d12_vulkan_device, which goes throughVulkanContext.buffer_va_index_test --bench):Not measured with
replay_cpu_benchas the claim said: its frame onmainhas no draws yet (#2123 adds them).Windows 11, MSVC (Visual Studio 18), NVIDIA GeForce RTX 3060 Ti, driver 32.0.15.9186. No game files.
Checklist
docs/design.md, with how it was confirmed. (Not applicable: no translator change.)AI-assisted