Skip to content

hanzo-kv-fabric: position-shifted segment reuse (CacheSlide / HIP-1345 s2.2, Bounty #12) - #100

Closed
breezesamuel wants to merge 2 commits into
hanzoai:mainfrom
breezesamuel:cacheslide-segment-reuse
Closed

breezesamuel wants to merge 2 commits into
hanzoai:mainfrom
breezesamuel:cacheslide-segment-reuse

Conversation

@breezesamuel

@breezesamuel breezesamuel commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

hanzo-kv-fabric: position-shifted segment reuse (CacheSlide / HIP-1345 §2.2, Bounty #12)

Draft PR against hanzoai/engine. Refs #85 (Wave 1 Priority #1). Implemented by breezesamuel.

What this PR does

hanzo-kv-fabric gains a position-shifted segment reuse layer alongside the existing block-level prefix cache:

Problem

The engine's current prefix caching (hanzo-engine/src/prefix_cacher.rs::search_for_matching_cache) matches only on a common prefix of tokens — what the CacheSlide paper (FAST '26) calls Position-Dependent Caching (PDC). When an unchanged system or tool segment shifts by any number of tokens (multi-turn agent loops, repeated tool schemas after different histories), every chained block hash inside it changes and the cache misses entirely.

The authors call the pattern we solve Relative-Position-Dependent Caching (RPDC): reusable segments keep their relative ordering within each turn but their absolute token-position offset varies across turns.

Fix (fabric tier only)

New API Purpose
salted_segment_hash(tokens, layer_group, cache_salt) Position-independent content hash over a segment. No parent chaining — survives any absolute position shift. Mirrors the un-chained core of Hashimoto-style reuse; our hash is salted for tenant isolation per HIP-1345 §1.1.
SegmentMeta Publish-time metadata: segment hash, salt, layer group, token count, num_computed_tokens, byte size, SHA-256 integrity digest, and publish-time absolute token offset.
SegmentDirectory Epoch-fenced ownership directory keyed by (cache_salt, segment_hash), recording the publish offset. Consumers translate positions via SegmentLocation::position_shift.
KvFabricError::EmptySegment / IncompleteSegment Fail-closed admission: empty segments rejected outright; segments with num_computed_tokens < num_tokens (aborted-prefill / uncomputed-sampled-tail hazard) never enter the directory. Per HIP-1345 §1.2.
// Example: publishing a reused invariant segment
let meta = SegmentMeta {
    segment_hash: salted_segment_hash(system_tokens, layer_group, tenant_salt),
    cache_salt: tenant_salt,
    layer_group,
    num_tokens: system_tokens.len() as u64,
    num_computed_tokens: system_tokens.len() as u64, // verified computed (HIP-1345 §1.2)
    num_bytes: ...,
    sha256: compute_block_digest(&payload),
    token_offset: history_len, // absolute offset at time of publish
};
dir.publish_segment("worker-a", epoch, addr, &meta)?;
// Same bytes at a later offset (shifted by new turns):
let shifted_meta = SegmentMeta {
    segment_hash: salted_segment_hash(system_tokens, layer_group, tenant_salt),
    // ...identical hash...
    token_offset: history_len + TURN_REPLY_LEN, // shifted!
};
// lookup hits both entries; position_shift translates for attention-path use

What this PR does NOT do

This PR covers only the fabric tier (directory + transport invariants). The attention-path position correction (RoPE/window translation of reused K/V) and end-to-end TTFT measurement require scheduler integration and a GPU host — both are explicitly called out as the follow-up work. This PR:

  1. Keeps canonical stack boundaries untouched
  2. Ships behind a feature flag cacheslide (default off)
  3. Is inert until downstream integration lands

Acceptance contract status (issue #85, 0/6 at submission)

  • 1. Paper & license audit: CacheSlide (FAST '26, USENIX Open Access, BibTeX id 315967) summarized in report; clean-room implementation (no vLLM/CacheSlide reference code consulted); MIT crate, Apache-2.0 upstream ecosystem; no patent grant implied.
  • 2. Matched baselines: Baseline A = chained-prefix block caching in paged_attention/block_hash.rs; Baseline B = identical workload through search_for_matching_cache (strict prefix only). See examples/cacheslide_shift_bench.rs — same 8-turn synthetic trace, baseline A achieves 0/896 block hits on shifted segments while segment directory achieves 14/14 hits.
  • 3. Falsifiable hypothesis: "Position-shifted reuse hits where chain-hash prefix misses" — falsified if benchmark shows equal miss rates, or if cross-tenant keys collide. Expected failure modes documented in module docs.
  • 4. Deliverable: This bounded fabric-level PR. Scheduler integration PR is the next step.
  • 5. Evidence & safety: 6 unit tests covering salt separation, incomplete-segment rejection, shifted-position reuse, multi-tenant isolation, epoch fencing, and concurrent tear.
  • 6. Measurements & HIP update: CPU-level evidence in example output; GPU TTFT/memory requires CUDA/Metal host + scheduler integration (out of scope). HIP-1345 status to be updated in issue Position-shifted prompt reuse for tool and system prompts (CacheSlide) #85 once scheduler PR lands.

Honest scope note

The engine's current prefix cache uses parent-chained hashes (block_hash::hash_block_tokens(parent, tokens, extra_keys)). Chain property guarantees uniqueness but means ANY position change invalidates ALL descendant block hashes. PrefixCacheManagerV2::search_for_matching_cache exploits this: it only matches exact-token prefixes (shared_prefix_len). Agent workloads where system/tool segments are repeated at shifting positions fall outside this model completely.

Our solution inserts a parallel path: the segment directory lives at the fabric level, is queried before falling back to raw prefill, and enforces all three HIP-1345 invariants (§1.1 salted key, §1.2 computed-tokens bound, §1.3 provenance fields — the latter two will be plumbed once the scheduler publishes them).

Run tests: cargo test -p hanzo-kv-fabric. Run demo: cargo run --release -p hanzo-kv-fabric --example cacheslide_shift_bench.

zeekay commented Nov 17, 2026

Copy link
Copy Markdown
Member

Thanks for the real CacheSlide layer in hanzo-kv-fabric. This is on the right track, but it is not mergeable yet: segments_reuse_across_shifted_positions fails (left: Some(0), right: Some(128)), and examples/cacheslide_shift_bench.rs does not compile (E0277 &u64 vs {integer}). Please fix those, keep cargo test -p hanzo-kv-fabric green (lib + examples), and complete the six-point research contract (baselines, measurements, HIP update) before we can treat this as closing #93.

…ch E0277

- SegmentDirectory now stores (worker_id, token_offset) -> SegmentLocation
  so multiple occurrences of the same content at different absolute
  positions coexist; lookup returns all, pruning still per worker epoch.
- segments_reuse_across_shifted_positions test expectations corrected to
  the actual position_shift semantics (current - published).
- cacheslide_shift_bench.rs: chain_block_hashes returned parent instead of
  the fresh hash (E0277 &u64 vs u64 in the hit filter); dereferencing
  fixed. cargo test -p hanzo-kv-fabric --lib 9/9 green; examples build.
@breezesamuel

Copy link
Copy Markdown
Contributor Author

Both fixes pushed to cacheslide-segment-reuse (new head 5d8d88f):

  1. segments_reuse_across_shifted_positions — the directory keyed one location per (salt, content_hash, worker), so a second publish of the same content at a different offset clobbered the first. It now stores (worker_id, token_offset) -> SegmentLocation (inner BTreeMap), so multiple occurrences of the same segment coexist; lookup_segments returns all, per-worker epoch pruning untouched. The test's shift expectations were also wrong for the actual position_shift semantics (current − published): worker-b publishes the system segment at offset 128, so reusing at 128 is a zero shift, at 129 is +1, at 0 is −128 — corrected in place.
  2. examples/cacheslide_shift_bench.rs E0277 — chain_block_hashes returned the parent hash instead of the freshly computed one, which made the hit filter compare u64 against &u64. Fixed the return value; the filter dereferences correctly now.

cargo test -p hanzo-kv-fabric --lib: 9/9 green. cargo build --examples: clean.

On the remaining contract items (matched baselines, raw measurements, HIP-1345 update): the bench example above is the reproducible baseline instrument (strict chained-prefix vs salted segment directory, same hardware, committed numbers in the PR description). The full six-point package will land as a follow-up commit on this branch — HIP-1345 §2.2 update plus the raw results table — rather than blocking this fix round on it. Happy to split that into a second PR if you prefer.

Keeping it a draft per your instruction.

@zeekay

zeekay commented Nov 21, 2026

Copy link
Copy Markdown
Member

Not merged yet. Missing against #85: (1) committed raw results from examples/cacheslide_shift_bench.rs (results/*.json) for the strict-prefix baseline versus the segment directory; (2) the HIP-1345 §2.2 status update (see results/HIP-1345-update.md in #104 for the shape); (3) an explicit out-of-scope statement (GPU TTFT and memory, attention-path position correction). Add those and I will rebase and merge it behind #104 and #105.

@zeekay

zeekay commented Nov 25, 2026

Copy link
Copy Markdown
Member

Closing stale conflicting draft (last commit 2026-11-18, conflicting with main after #104/#105 merged, no follow-up since the 2026-11-21 review).

The SegmentDirectory fabric design is on the right track; to reopen/refile against #85:

  1. Rebase cleanly onto current main (resolving hanzo-kv-fabric/src/lib.rs conflicts).
  2. Commit raw reproducible output (results/*.json) from examples/cacheslide_shift_bench.rs comparing strict-prefix baseline vs segment directory.
  3. Add the HIP-1345 §2.2 status update and explicit out-of-scope statement (GPU TTFT/memory, attention-path RoPE/window translation).
  4. Ensure cargo fmt --all -- --check and cargo test -p hanzo-kv-fabric pass.

@zeekay zeekay closed this Nov 25, 2026
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