Repository navigation
fix(engine): preserve shared prefixes in StateCache - #56
Merged
rkinas merged 2 commits intoNov 2, 2026
Merged
Conversation
Keep every entry sharing a block prefix, choose the longest match, and remove only the evicted entry from the prefix index. Bound tail comparisons to one block and retain block hashes for eviction. Add regression, randomized-oracle and tiny-model integration tests.
Reviewer's GuideThe PR fixes StateCache prefix reuse by retaining every entry in shared block-prefix buckets, selecting the longest matching candidate deterministically, and maintaining those buckets correctly through eviction and replacement. It also caches block hashes and adds targeted, randomized, and model-level regression coverage. Sequence diagram for shared-prefix StateCache lookupsequenceDiagram
participant Caller
participant StateCache
participant PrefixIndex
participant Entries
Caller->>StateCache: longest(tokens)
StateCache->>StateCache: _blocks(tokens)
StateCache->>PrefixIndex: Find deepest matching block bucket
PrefixIndex-->>StateCache: Candidate keys
StateCache->>Entries: Compare candidate token tails
Entries-->>StateCache: Longest matching state
StateCache->>Entries: move_to_end(key)
StateCache-->>Caller: key, kv, matched_length, state_length
Flow diagram for shared-prefix StateCache bucket maintenanceflowchart TD
Put["put(key, kv, tokens)"] --> Blocks[Compute and retain block hashes]
Blocks --> Existing{Prefix bucket exists?}
Existing -->|No| Singleton[Store direct key]
Existing -->|Yes, singleton| Shared[Convert to insertion-ordered key map]
Existing -->|Yes, map| Add[Add key to bucket]
Singleton --> Budget{Over budget?}
Shared --> Budget
Add --> Budget
Budget -->|Yes| Drop["_drop(key)"]
Budget -->|No| Ready[Shared prefixes remain discoverable]
Drop --> Remove[Remove evicted key from each bucket]
Remove --> Collapse{One key remains?}
Collapse -->|Yes| Direct[Collapse bucket to direct key]
Collapse -->|No| Ready
Direct --> Ready
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 2 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="basal/engine.py" line_range="826" />
<code_context>
+ stop, limit = min(len(t), start + self.BLOCK), min(len(t), start + self.BLOCK - 1)
+ best, matched = None, start - 1
+ # shortcut: scan this bucket only; consider a trie if large buckets dominate measured lookup time.
+ for key in keys if isinstance(keys, dict) else (keys,):
+ kv, _, own, _ = self.entries[key]
+ n = min(len(own), stop)
</code_context>
<issue_to_address>
**Cache lookups serialize on large buckets**
When many cached states share the deepest matching block prefix, `longest()` compares every candidate while holding the cache lock, so concurrent `get()` and `put()` calls wait for a bucket-sized scan and cache latency grows linearly; `stats()` exposes no bucket-size or lock-wait data to reveal the contention.
Avoid scanning the full bucket under the shared lock, and expose bucket-size and lock-wait measurements in `stats()`.
</issue_to_address>
### Comment 2
<location path="basal/engine.py" line_range="826-834" />
<code_context>
+ stop, limit = min(len(t), start + self.BLOCK), min(len(t), start + self.BLOCK - 1)
+ best, matched = None, start - 1
+ # shortcut: scan this bucket only; consider a trie if large buckets dominate measured lookup time.
+ for key in keys if isinstance(keys, dict) else (keys,):
+ kv, _, own, _ = self.entries[key]
+ n = min(len(own), stop)
+ if n <= matched or (matched >= start and own[matched] != t[matched]):
+ continue
+ diff = np.nonzero(own[start:n] != t[start:n])[0]
+ m = start + int(diff[0]) if len(diff) else n
+ if m > matched:
+ best, matched = (key, kv, m, len(own)), m
+ if m == limit:
+ break
</code_context>
<issue_to_address>
**Reusable cached prefixes are recomputed**
When a bucket contains a farther raw match whose Gemma sliding-layer KV has discarded positions needed to continue, alongside a shorter usable match, `longest()` selects the farther raw match, then `_extend_states()` gets 0 from `_usable()` and abandons lookup without trying the shorter entry, so the request recomputes a reusable prefix.
Have `longest()` skip candidates whose KV is unusable for the match and continue to the next-best usable candidate.
</issue_to_address>Filter candidates through the backend's KV usability check and fall back to shallower buckets when needed. Avoid checking rejected entries twice. Cover same-bucket and deeper-bucket rejection with the Gemma CPU fixture. Count only accepted prefix matches as hits.
Owner
|
Thank you, Marcin! The shared-prefix StateCache passed our GPU check and is merged into the basal 2.5 release branch with your commits as you wrote them. One addition on top: with |
rkinas
added a commit
that referenced
this pull request
Nov 2, 2026
….5 with #50 (branch pr56-25) Conflict in StateCache.longest: #56's lookup and usable() check (with 2.5's 8-bit unpack) kept, #50's use(key) counts the prefix hit at the return; longest(tokens, usable=None, use=None). A test takes both together; #50's test reads the entry as (kv, size, tokens, blocks). Gated again on this head (G56M on f6, G50c on the Mac) before it goes into release-2.5.
rkinas
added a commit
that referenced
this pull request
Nov 2, 2026
…e longest usable one (#56, Marcin Brzeżański), with #50's hit counting (branch merge56-25) G56M on the merged code (release-2.5 178659d vs merge56-25 9f08617, H100): exact hits bit-identical, no flip at margin >= 0.05, top-1 against the cache off 0.9902 / 0.9892 (basal-2.0-mini) and 0.9961 (omni-1.0-mini); G50c on 9f08617: 1,032 / 1,032, max |dp| 0.
rkinas
added a commit
that referenced
this pull request
Nov 2, 2026
… version CONTRIBUTING.md credits the 2.5 pull requests as the release notes' community line lists them (Paweł Kiszczak #52, #62, #64, #66, #68, #71, #73, #75; Marcin Brzeżański #56; Grzegorz Brzezinka #76, #78) and adds Dariusz Koryto (#53, #58, #59, #60 and #55); the README's list names him too. docs/changes/README.md and the changelog.py help use 2.5.1, the next release, as the example.
This was referenced Nov 19, 2026
Closed
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.
Problem
The state-cache prefix index keeps only one entry per chained block hash. Adding a second state with the same
prefix overwrites the first entry's reference. This causes two failures:
longest()can return a shorter match even though a better one is cached. ForA = P + [10],B = P + [20]and a 256-token
P, inserting A then B makes a lookup forA + [99]reuse 256 tokens instead of 257.the available prefix and recomputes it.
Runtime impact
This affects workloads using
--state-cache-gb, particularly branching agent histories and states sharing commonprefixes. Incorrect prefix selection can cause unnecessary GPU prefill work, while eviction can make still-cached
states undiscoverable. The fix restores correct prefix reuse without changing model outputs. Actual end-to-end
gains depend on workload characteristics.
Change
candidates otherwise. Remove only the evicted entry's reference and collapse singleton buckets again.
next 256 tokens: a further matching full block would have selected a deeper bucket.
Tests
94 related CPU tests passed on a clean snapshot of upstream
mainatb20f0f9with only this patch applied:test_state_cache,test_prefix_cache,test_engine,test_engine16, andtest_gemma4_graph. Coverage includesboth reproductions, ties and replacement, 900 randomized update/query steps checked against a full-scan oracle,
and a tiny-model test comparing cached answers with separate forwards. Pytest used a workspace-local
--basetemp.CPU measurements and limits
Windows 11, Python 3.13.7, NumPy 2.4.6, PyTorch 2.13.0+cpu. Median batch-average microseconds per operation over nine batches with shuffled before/after order; baseline
2437d7f.The 1000-candidate benchmarks are stress tests of large shared-prefix buckets. With approximately 4k-token states, retaining 1000 independent KV-cache entries can require substantial GPU memory, making this configuration less likely under typical cache budgets. Actual feasibility depends on the model architecture and KV-cache layout. Large buckets of shorter states remain possible. These benchmarks use small CPU KV tensors and therefore do not model actual GPU memory requirements.
Large buckets are still scanned linearly under the cache lock. The baseline finds the best prefix for only 1/1000 short-tail queries and returns 4096 rather than 4223 tokens in the adversarial case; the fix finds the best match in both. These are correctness/performance tradeoffs, not equivalent-work speedups. CPU memory increases by 1.49 MiB for 1000 states of 4097 tokens.
The measurements use Python token lists, matching the engine's caller. Query conversion and prefix hashing are included in
longest()timings; full-state keys for exact lookups and writes are precomputed. Writes use small, preallocated CPU KV tensors to isolate indexing overhead. Eviction runs cycle through 64 states in a 32-entry cache. Cold insertion builds 64 entries per call, with time divided by 64. Garbage collection is disabled during timed batches. The benchmark scripts and result files are kept outside this PR; its diff contains onlybasal/engine.pyandtests/test_state_cache.py.No CUDA inference, production workload or contention measurements were run. This fixes prefix reuse; it does not establish an end-to-end throughput improvement or a no-regression guarantee for large buckets.
Summary by Sourcery
Fix state-cache prefix indexing so shared cached prefixes remain reusable and the longest valid match is selected deterministically.
Bug Fixes:
Enhancements:
Tests: