Skip to content

Runtime: buffer_at finds a buffer by binary search, not a scan of every resource - #2823

Merged
ItsNotRexed merged 4 commits into
ItsNotRexed:mainfrom
jsthope:perf/buffer-at-va-map
Nov 23, 2026
Merged

ItsNotRexed merged 4 commits into
ItsNotRexed:mainfrom
jsthope:perf/buffer-at-va-map

Conversation

@jsthope

@jsthope jsthope commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Item: D3D-322 (claimed in #2516)

VulkanContext::buffer_at walked every registered resource, images included, for each vertex-buffer slot, index
buffer and WriteBufferImmediate of every draw (runtime/src/vulkan_backend.h). Its own comment and the "Lookups"
known gap in docs/d3d12_vulkan.md already asked for an ordered map by VA once it showed.

Changes

  • runtime/src/buffer_va_index.h (new): BufferVaIndex, buffers' VA ranges in a std::map keyed by first VA. A
    lookup 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.
  • VulkanContext keeps it in step with resources_ in add_resource (both overloads), add_sparse_buffer and
    remove_resource; a re-registered ID drops its old range first. Indexed buffers are what the scan accepted: no
    image, a VkBuffer, a VA and a non-zero size.
  • docs/d3d12_vulkan.md: the "Lookups" known gap is gone; the WriteBufferImmediate paragraph says how the lookup
    works now.

Behaviour change

Placed buffers may alias, so ranges can overlap. The scan returned whichever matched first in unordered_map order;
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 size cut can differ.

Tests

  • buffer_va_index_test (new, CPU only, in CTest): edges, overlapping and nested ranges, same start, erase and
    re-registration, then 200 random tables checked against a linear scan with the same rule.
  • Full runtime build and ctest on top of ec8ec4c9: 113/113 passed (the skipped tests skip on main too: missing
    data or tools), including d3d12_vulkan_device, which goes through VulkanContext.
  • Lookup time, half the resources images (buffer_va_index_test --bench):
Resources Scan (before) Index
1 000 1.7 µs 43 ns ×41
10 000 44 µs 115 ns ×381
100 000 2.9 ms 165 ns ×17 590

Not measured with replay_cpu_bench as the claim said: its frame on main has 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

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (Not applicable: no translator change.)

AI-assisted

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 kacper-serewis left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@tupacfan04

Copy link
Copy Markdown
Contributor

Code read of df1ae87e (I didn't build it). Looks right. The only places resources_ is written are set_resource_locked (try_emplace, or unindex the old binding then overwrite) and the single erase in remove_resource, which unindexes first, so the VA index can't drift from the map. addressable() is exactly the old scan's filter. In find, the early offset >= longest_ exit is sound because longest_ is an upper bound on every range and only ever grows. It can make a miss walk further after large buffers are freed, but never gives a wrong hit. The one behaviour change is for aliased (overlapping) placed buffers: the old loop returned whichever matching entry unordered_map iteration reached first, and this returns the nearest start below (larger id on a tie). That's deterministic, so it's an improvement.

AI-assisted review (Claude Code).

@padhossein

Copy link
Copy Markdown
Contributor

Independent VA-index churn check (df1ae87e). The fixed cases and all 200 random tables agree with the scan on Linux/C++20. I also measured a case where the documented stale longest_ bound matters: two indexes with the same 20,000 disjoint 256-byte buffers, with a temporary 1 GiB overlapping range added and then removed in one index. After removal, misses one stride past the final buffer were about 64–78 ns each in the fresh index and 418–481 microseconds each in the previously enlarged index (three local runs). Results are correct, but the miss still walks the whole table even after the large buffer is gone. Consider updating the bound when the largest range is removed, or documenting that the miss path can retain this cost after transient large allocations.

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.
@jsthope

jsthope commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

@padhossein thanks, fixed in 111b634c: the bound now follows the live ranges instead of only growing.

  • BufferVaIndex keeps a std::multiset of the indexed sizes, so longest_ is the longest range indexed now (0 when the index is empty). insert and erase stay O(log n) and 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 now checks the bound after erases, including two ranges of the same size and a re-registration with a smaller size. It also compares longest() with the longest live range in all 200 random tables, and times your case: 20 000 buffers of 256 bytes, a 1 GiB range added then removed, then a miss one stride past the last buffer.
Miss past 20 000 buffers Fresh index After a freed 1 GiB range
df1ae87e 51-66 ns 251-595 µs (3 runs)
111b634c 45-97 ns 45-47 ns

The bound checks fail on df1ae87e (4 failures) and pass on 111b634c.

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 111b634c: full runtime build and ctest, 113/113 passed (the skipped tests skip on main too), including buffer_va_index and d3d12_vulkan_device. Windows 11, MSVC 14.50 (Visual Studio 18), NVIDIA GeForce RTX 3060 Ti, driver 32.0.15.9186. Vulkan headers came from -DLEONIDA_VULKAN_HEADERS_FETCH=ON. No game files.

AI-assisted (Claude Code).

@Kam471 Kam471 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@traeb0n

traeb0n commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Code review of 111b634 (read only, no runs): looks right to me.

What I checked:

  • The index can't go stale. Every write to resources_ in vulkan_backend.h now goes through set_resource_locked. Re-registering an ID unindexes its old range first, and remove_resource unindexes before erasing. Nothing else assigns into resources_ or edits a binding's va/size in place (I grepped the branch for both).
  • Locking: find is const and runs under the shared resource_mutex_ that prepare holds. insert/erase only run under the unique lock, as before.
  • addressable() accepts exactly what the old scan did: no image, a VkBuffer, a VA and a size.
  • The longest_ bound is right after erases: the multiset keeps one entry per range, and drop_size removes one copy.
  • Overlaps are now deterministic: the closest start below wins, then the larger ID. The old scan returned whichever buffer unordered_map iterated first.

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. buffer_at gets the requested size, so find could prefer, among the ranges that hold va, one that also holds va + size, and fall back to the closest otherwise. The old code had the same exposure, only in hash order, so this PR doesn't make anything worse.

One note on measuring: replay_cpu_bench has its own buffer_at lambda over a single arena, so its draw rows won't show this change. The gain is in VulkanContext with many live resources, where the old scan visited every image and buffer for each vertex and index view.

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.
@jsthope

jsthope commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

@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:

  • BufferVaIndex::find(va, hit, bytes): among the ranges that hold va, it returns the closest start (larger ID on a tie) that also holds [va, va + bytes). When none does, it returns the closest one that holds va, as before. buffer_at passes the requested size, so a view that starts in S and runs past it now resolves to B and isn't cut.
  • Cost: without overlaps the first range looked at is still the answer. Once a fallback is found, the walk stops as soon as no range can hold all the bytes (bytes > longest_ - offset), so the extra walking only happens when ranges alias and is bounded by the longest live range, the same bound a miss already had.
  • buffer_va_index_test: new fixed cases (a view that fits in S stays in S, one byte past S goes to B, a view no range holds falls back to the closest start, size 0 counts as one byte). In the 200 random tables, three quarters of the lookups now name a view of up to 32 KiB, checked against a scan with the same rule.

Tested on b8273c0: full runtime build and ctest, 113/113 passed (gameinput disabled as on main). buffer_va_index_test --bench: 37 ns at 1 000 resources, 75 ns at 100 000, unchanged from before. The miss after a freed 1 GiB range is still 48 ns. Windows 11, MSVC (Visual Studio 18), Vulkan headers from -DLEONIDA_VULKAN_HEADERS_FETCH=ON, CPU only. No game files.

Agreed on replay_cpu_bench: its own buffer_at over one arena won't show this, which is why the PR measures with the standalone bench.

AI-assisted (Claude Code).

@dcastell1

Copy link
Copy Markdown
Contributor

Tested b8273c0 on RTX 5090, 621.24, Windows 11: pass. Built buffer_va_index_test from this tree and ran ctest -R buffer_va_index → 1/1 passed (0.52 s).

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.

@ItsNotRexed
ItsNotRexed merged commit 6b38929 into ItsNotRexed:main Nov 23, 2026
2 of 4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants