Skip to content

fix(engine): preserve shared prefixes in StateCache - #56

Merged
rkinas merged 2 commits into
rkinas:mainfrom
marcinbrzezanski:fix/state-cache-prefix-index
Nov 2, 2026
Merged

rkinas merged 2 commits into
rkinas:mainfrom
marcinbrzezanski:fix/state-cache-prefix-index

Conversation

@marcinbrzezanski

@marcinbrzezanski marcinbrzezanski commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

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. For A = P + [10], B = P + [20]
    and a 256-token P, inserting A then B makes a lookup for A + [99] reuse 256 tokens instead of 257.
  • Evicting B can remove their shared prefix from the index while A is still cached. An extension of A then misses
    the available prefix and recomputes it.

Runtime impact

This affects workloads using --state-cache-gb, particularly branching agent histories and states sharing common
prefixes. 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

  • Retain all entry keys sharing a block prefix, with a direct key for singleton buckets and insertion-ordered
    candidates otherwise. Remove only the evicted entry's reference and collapse singleton buckets again.
  • Search the deepest matching bucket and select the longest token match, with stable ties. Compare at most the
    next 256 tokens: a further matching full block would have selected a deeper bucket.
  • Convert query tokens to NumPy once and retain each entry's block hashes for eviction, avoiding repeat hashing.
  • Add regression tests for shared prefixes, eviction, replacement, deterministic ties, and model outputs.

Tests

94 related CPU tests passed on a clean snapshot of upstream main at b20f0f9 with only this patch applied:
test_state_cache, test_prefix_cache, test_engine, test_engine16, and test_gemma4_graph. Coverage includes
both 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.

Case Before After Change
Exact-key lookup 0.40 µs 0.40 µs ~0%
One candidate, 4097 tokens 255.74 µs 165.17 µs -35.4%
Insert + eviction, shared prefixes 232.31 µs 167.17 µs -28.0%
Cold insertion, shared prefixes 163.35 µs 164.33 µs +0.6%
1000 candidates, short tails* 260.07 µs 388.37 µs +49.3%
1000 candidates, adversarial tails* 299.86 µs 2611.79 µs +771.0%

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 only basal/engine.py and tests/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:

  • Preserve and correctly select among cached states that share block prefixes, preventing shorter prefix matches and keeping surviving entries discoverable after eviction.

Enhancements:

  • Optimize prefix lookups by caching block hashes, converting query tokens once, and supporting usable-prefix filtering during model continuation.

Tests:

  • Add regression and randomized oracle tests covering shared-prefix matching, eviction, replacement, deterministic ties, and cached model-output equivalence.

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.
@sourcery-ai

sourcery-ai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The 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 lookup

sequenceDiagram
    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
Loading

Flow diagram for shared-prefix StateCache bucket maintenance

flowchart 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
Loading

File-Level Changes

Change Details Files
Preserve and evaluate all cached entries that share each block-prefix bucket instead of allowing later inserts to overwrite earlier candidates.
  • Represent singleton buckets directly and promote shared buckets to insertion-ordered key maps.
  • Search the deepest indexed bucket and choose the candidate with the longest token-level match using stable insertion-order ties.
  • Limit candidate comparison to the next block and move the selected entry to the LRU tail.
basal/engine.py
Make prefix indexing and eviction consistent with the expanded entry metadata.
  • Convert query tokens once and cache each entry’s computed block hashes.
  • Remove only the evicted key from every bucket and collapse one-key buckets back to direct references.
  • Update cache-entry tuple handling for indexed and unindexed states.
basal/engine.py
Add regression and randomized validation for shared-prefix lookup, eviction, replacement, and model correctness.
  • Cover best-match selection, shared-prefix eviction, deterministic ties, replacement, and continuation from the correct cached state.
  • Compare indexed lookup against a full-scan oracle across randomized updates, edits, short queries, and LRU churn.
  • Verify cached model answers match separate forwards and that unindexed entries eventually leave the index clean.
tests/test_state_cache.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread basal/engine.py Resolved
Comment thread basal/engine.py Resolved
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.
@rkinas

rkinas commented Oct 28, 2026

Copy link
Copy Markdown
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 --state-cache-bits 8 a cached entry is dequantised before your usable() check, with a test for it. The PR will close when 2.5 is published on main.

@rkinas
rkinas merged commit 7a443c6 into rkinas:main Nov 2, 2026
1 check passed
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.
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.

2 participants