Fix cache-thrash livelock and speed up reads and counts - #28
Merged
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Read-path improvements that keep the original design (reference counting + deterministic buffer pooling, on every platform including Unity):
(1 op = 1000 queries for point lookups, 100 for range/count. All read paths remain zero-allocation.)
PageCache.GetOrLoad— fixes a latent cache-thrash livelockThe old miss protocol (
while (!TryGet(pn)) Load(pn)) is unsound under thrash: a loaded page can be evicted by concurrent loaders before the loading thread looks it up again, so concurrent loaders keep evicting each other's pages and nobody makes progress. A new stress test (8-page cache, concurrent point reads + range scans) spins forever onmain.GetOrLoad/GetOrLoadAsyncnow publish the entry with the caller's reference already taken (RefCount = 2), so the returned page stays valid even if it is evicted immediately after. All ~15 retry loops acrossTreeWalker/RangeIterator/ secondary index queries are gone, which also simplifies the tree-walk code considerably.TreeWalker.TrySearch's miss/resume protocol is replaced by self-sufficientSearch/SearchAsync.Two more hazards fixed along the way:
Optimistic fetch-add refcount
TryRetainIfAliveused a CAS retry loop, which degrades badly under contention (retry storms on the hot page's cache line). It is now a singleInterlocked.Incrementwith a dead-entry bias: a result ≥ 1 means alive; once the count reaches zero,Releasestamps the entry withint.MinValue / 2via a one-shot CAS before disposing, so late optimistic increments can never resurrect a dead entry. This is sound because theEntryobject itself is GC-managed — only the buffer must not be touched after dispose.Same-key parallel reads improve 1.7x; with realistically spread keys the refcount cost is within ~14% of having no refcount at all (a GC-based no-refcount mode was prototyped and measured, then dropped in favor of keeping one simple code path — see commit history).
Per-leaf binary search for range bounds
CountRangecompared every entry against the end key; since leaf entries are sorted, the bound is now located with one binary search per leaf and whole leaves are counted by subtraction (9.5x).GetRange(both directions, sync and async) uses the same bound computation, removing the per-row key comparison.Also
ReadOnlyDatabase.Disposenow releases the pinned root pages (fixes a native-memory leak of one page per tree with the Unity NativeArray loader).PageCacheno longer preallocates dictionary buckets for the full capacity (~MBs at open with the default 2 GB cache size).All 73 tests pass, including the new stress test that deadlocks on
main.🤖 Generated with Claude Code