Skip to content

impl(011): increment 4, the embedding cache - #445

Merged
bartekus merged 1 commit into
mainfrom
impl/011-cache
Nov 3, 2026
Merged

bartekus merged 1 commit into
mainfrom
impl/011-cache

Conversation

@bartekus

@bartekus bartekus commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Summary

Spec 011, increment 4: the embedding cache (3.14), landing before increment 3.

  • backends/rustev-backend-embed-linear/src/cache.rs is the backend-internal memo the increment 3 backend will call; nothing constructs it yet.
  • Off unless embedding_cache: {max_entries, max_bytes} is given; process memory only.
  • Key: the ArtifactId, a domain-separated SHA-256 of the principal handle and the SHA-256 of the token ids and attention mask after truncation, so entries never cross principal handles (spec 017).
  • Enabling it is refused cache_not_equivalent unless the platform's repeatability evidence shows bitwise run-to-run repeatability in one process: the synthetic encoder has it (3.19.1); an onnx encoder needs a passing feasibility record, which no platform has yet.
  • Admits only finite embeddings of the manifest's dimension from completed, non-cancelled runs; LRU eviction bounded by entries and bytes.
  • clear() and erase_principal(handle) advance a generation, so a run started under an earlier one is not stored; erasure removes every entry of the handle before returning.
  • cache_stats() reports hits, misses, admitted, evicted, bytes, invalidations.

Spec: a dated increment 4 paragraph appended to 011's implementation record (approved spec text; ratifies on merge).

Verification

  • cargo test -p rustev-backend-embed-linear --locked (17 passed, cache_tests in tests/bundle.rs), clippy -D warnings, cargo fmt --all --check, make gate, scripts/check-authored-content.sh.

@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

AI review (no-findings)

Reviewing the four changed files: a new cache.rs module, a module registration in lib.rs, tests in bundle.rs, and a spec increment in spec.md.

cache.rs — correctness and security review

Eviction loop underflow guard. Before the while loop, the code checks bytes > limits.max_bytes and returns early, so limits.max_bytes - bytes in the loop condition cannot underflow. ✓

Empty-entries panic risk. If self.entries were empty while self.stats.bytes > 0, self.entries.remove(0) would panic. Tracing all mutation paths: admit only increments stats.bytes when it pushes an entry; the eviction loop decrements by exactly entry.bytes() per removed entry; clear zeroes both simultaneously; erase_principal recomputes from scratch. The invariant holds. ✓

LRU hit path. entries.remove(index) returns ownership; entry.embedding.to_vec() makes an independent copy; entries.push(entry) returns the box to the back. stats.bytes is unaffected (length unchanged). ✓

Principal isolation. principal_digest prepends a versioned domain separator with a null terminator before the raw handle bytes. The principal hash and the token hash occupy separate fields in Key; #[derive(PartialEq)] compares all three fields independently. ✓

Token key ambiguity. Length-framing with u64 LE before each array means ([1],[0]) and ([1,0],[]) hash differently. Test cache_key_isolates_principals_tokens_masks_and_array_boundaries confirms this. ✓

Generation-based invalidation. Arc::ptr_eq distinguishes pre- and post-invalidate() tickets because invalidate() replaces self.generation with a fresh Arc::new(()). Outstanding tickets retain the old Arc, whose address is never reused until the last holder drops it. ✓

Non-finite rejection. The all(|v| v.is_finite()) guard rejects NaN and ±∞ before admission. ✓

Duplicate admission. CacheMiss is consumed by value, so Rust's ownership prevents reuse of the same ticket. A second outstanding miss for the same key is blocked by self.entries.iter().any(|entry| entry.key == miss.key). ✓

stats.bytes overflow. bytes is computed with checked arithmetic; the guard bytes > limits.max_bytes ensures stats.bytes + bytes <= max_bytes <= usize::MAX. ✓

Zero hidden-size guard. embedding.is_empty() catches the edge case where self.hidden == 0 and an empty slice would otherwise pass the len != self.hidden check. ✓

spec.md increment

The increment text correctly describes: off-by-default, key composition (ArtifactId + principal SHA-256 + token/mask SHA-256), repeatability gating (cache_not_equivalent), admission constraints, LRU eviction bounded by entries and bytes, generation-scoped invalidation, and stats fields. All match the implementation.

No concrete defects found.

{"head": "96bbe3222a81ab500861cd497ddede35d7bd795f", "verdict": "no-findings", "findings": []}

Subject: a49e40f...96bbe32, diff digest 4b7ae8b5c3bed56a4549a89b1d1910ae5f8c5001637e8ebcd6738abee4e71b9f, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus added this pull request to the merge queue Nov 2, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Nov 2, 2026
@bartekus
bartekus enabled auto-merge November 2, 2026 22:21
An opt-in in-process cache of pooled embeddings keyed by artifact,
principal and token digest, refused unless repeatability is shown (3.14).
@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown

AI review (no-findings)

I reviewed the new cache.rs module, the lib.rs module declaration, the tests in bundle.rs, and the spec update.

cache.rs logic review:

  • LRU hit path (lookup): removes the entry, copies the embedding, pushes the entry to the end (MRU position). stats.bytes is unchanged — correct, the entry is re-inserted.
  • Eviction loop in admit: guards bytes <= limits.max_bytes before the loop, so limits.max_bytes - bytes cannot underflow. If entries becomes empty stats.bytes reaches 0 and the second condition is false; the loop terminates.
  • bytes computed in admit and entry.bytes() in the eviction/stats path use identical formulas (size_of::<Entry>() + artifact string length + size_of_val of the f32 slice); they agree because size_of::<Self>() inside Entry::bytes is the same compile-time constant.
  • erase_principal recomputes stats.bytes from scratch after retain — correct. It does not increment evicted; the test explicitly asserts this is intentional.
  • Generation-based invalidation: Arc::ptr_eq guards stale tickets across both clear and erase_principal — correct. Outstanding tickets keep the old Arc alive so the allocator cannot reuse its address.
  • Key design: principal is domain-separated SHA-256; token key uses length-framing to prevent concatenation ambiguity; artifact is compared field-by-field in Key. The isolation properties described in the spec hold.
  • Repeatability gating: Synthetic variant is cfg(feature = "synthetic")-gated consistently in both the enum and the match; Measured requires artifact, platform, feasibility-record, and bitwise flag to all agree with the manifest.
  • reserve_exact(1) prevents geometric growth from violating max_entries in capacity.

Test review:

The LRU scenario in cache_lru_entry_and_byte_limits is correct: after hit(1) E1 moves to MRU, so E2 is evicted when E3 is stored; final counts (hits=3, misses=4, admitted=3, evicted=1) match the trace.

Spec update:

The text in specs/011-semantic-backend/spec.md accurately describes the implementation: off-by-default, key structure, repeatability gate, admission conditions, eviction policy, and invalidation semantics.

No concrete defects found.

{"head": "21110c29468483c265051c58290d6fe6b45cfab7", "verdict": "no-findings", "findings": []}

Subject: 41b490d...21110c2, diff digest 3c3fdd58225e377a04a8c0fe94edd61f73e0d14b0f9b5c1c9d6a5c9cbaa87836, 1 call(s). An AI comment is not an approval.

@bartekus
bartekus added this pull request to the merge queue Nov 3, 2026
Merged via the queue into main with commit e8d1c0f Nov 3, 2026
30 checks passed
@bartekus
bartekus deleted the impl/011-cache branch November 3, 2026 03:37
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.

1 participant