Skip to content

fix: add bounds checking to BatchKVCache::filter() and optimizer state observability - #18

Merged
Brooooooklyn merged 1 commit into
mainfrom
fix/bounds-checking-and-optimizer-observability
Feb 15, 2026
Merged

Brooooooklyn merged 1 commit into
mainfrom
fix/bounds-checking-and-optimizer-observability

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Feb 15, 2026 •

Copy link
Copy Markdown
Contributor

BatchKVCache::filter() previously had no bounds validation on batch indices, which could panic (or cause UB in release mode) with negative or out-of-range values. Added upfront validation returning descriptive errors instead of panicking, plus 5 new test cases covering edge cases.

Added state_count() to all 4 optimizers (Adam, AdamW, SGD, RMSprop) for monitoring tracked parameter count and memory usage. Added 7 new tests verifying reset() properly clears all state.

+12 new Rust tests, 726 total passing.


Note

Low Risk
Changes are additive and defensive (new checks + observability) with test coverage, and should only affect previously-invalid inputs or provide new inspection APIs.

Overview
Prevents invalid batch indices from causing panics/UB by adding upfront bounds checks in BatchKVCache::filter(), returning a descriptive InvalidArg error; adds new tests covering out-of-range, negative, empty, duplicate, and empty-cache filtering.

Adds state_count() to Adam, AdamW, SGD, and RMSprop to report how many parameters have optimizer state allocated (useful for memory monitoring), and extends optimizer tests to verify state tracking and that reset() fully clears state (and step where applicable), including for batch updates.

Written by Cursor Bugbot for commit 57626f4. This will update automatically on new commits. Configure here.

Summary by CodeRabbit

  • New Features

    • Added state count inspection methods to optimizer implementations, enabling users to monitor the number of parameters with tracked state
    • Implemented runtime validation in batch key-value cache filtering to prevent invalid batch indices and provide descriptive error feedback
  • Tests

    • Added comprehensive test coverage for optimizer state lifecycle management, batch update consistency, and edge-case handling in cache filtering operations

…e observability

BatchKVCache::filter() previously had no bounds validation on batch
indices, which could panic (or cause UB in release mode) with negative
or out-of-range values. Added upfront validation returning descriptive
errors instead of panicking, plus 5 new test cases covering edge cases.

Added state_count() to all 4 optimizers (Adam, AdamW, SGD, RMSprop)
for monitoring tracked parameter count and memory usage. Added 7 new
tests verifying reset() properly clears all state.

+12 new Rust tests, 726 total passing.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@coderabbitai

coderabbitai Bot commented Feb 15, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR adds state tracking observability methods (state_count) across four optimizer implementations (Adam, AdamW, RMSprop, SGD), introduces comprehensive unit tests for optimizer state lifecycle and batch updates, and adds input validation with tests to the BatchKVCache filter method.

Changes

Cohort / File(s) Summary
Optimizer state_count methods
crates/mlx-core/src/optimizers/adam.rs, crates/mlx-core/src/optimizers/adamw.rs, crates/mlx-core/src/optimizers/rmsprop.rs, crates/mlx-core/src/optimizers/sgd.rs
Added public state_count(&self) -> usize method to each optimizer that returns the number of tracked parameters by returning the length of the internal state HashMap. Note: adam.rs contains two identical declarations (duplicate).
Optimizer tests
crates/mlx-core/src/optimizers/optimizers_test.rs
Added comprehensive unit tests covering state lifecycle (creation, reset, counting), batch-update consistency, step counters, and state-key/moments access across all optimizers.
Batch KV Cache validation
crates/mlx-core/src/transformer/batch_kv_cache.rs
Added runtime validation in BatchKVCache::filter to ensure batch indices are within valid range (0 to batch_size), returning InvalidArg error for out-of-bounds or negative indices. Includes tests for boundary conditions: out-of-bounds, negative indices, empty indices, duplicates, and empty cache scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Poem

🐰 With state counts now bright and clear,
Validators guard the cache's cheer,
Tests dance where optimizers dwell,
Observability serves all well! ✨

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and clearly summarizes the two main changes: bounds checking for BatchKVCache::filter() and state_count() observability methods for optimizers.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Merge Conflict Detection ✅ Passed ✅ No merge conflicts detected when merging into main

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/bounds-checking-and-optimizer-observability

No actionable comments were generated in the recent review. 🎉


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Brooooooklyn
Brooooooklyn merged commit a1a0094 into main Feb 15, 2026
6 checks passed
@Brooooooklyn
Brooooooklyn deleted the fix/bounds-checking-and-optimizer-observability branch February 15, 2026 12:53
Brooooooklyn added a commit that referenced this pull request Apr 11, 2026
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…eflight after restore, document display-only sizing

Fix-delta review of the review-#17 fixes surfaced two recovery-ordering
defects (one a regression from the #17 preflight hoist) plus one display-only
residual. All verified via control-flow analysis.

- Finding 3 (download.ts, regression): the #17 hoist put the ownership
  preflight above sweepStaging, so a preflight-refused job (unowned/foreign
  finalDir) threw before the only dead-private-staging-tree reap ran, leaking
  crashed multi-GB staging indefinitely. Split sweepStaging into
  reapDeadStagingTrees() (process-wide, pid-gated dead-`<slug>@<sha>.<pid>`
  reap, run BEFORE the preflight so a refused job still frees its tree) and
  recoverBackup(slug, finalDir) (slug-scoped backup restore/reap, run AFTER the
  preflight so a foreign finalDir link is already refused and never followed).

- Finding 1 (download.ts): the backup restore branch renamed any backup back
  onto an absent finalDir; a foreign-symlink backup (from a prior overwrite
  crash) would be restored after the only ownership check and then followed by
  skip-detection. Restore now requires the backup itself be an owned real
  directory (no-follow lstat + our marker), and the no-follow ownership
  preflight is re-run after recovery, before skip-detection.

- Finding 2 (models.ts + docs, document-and-accept): walkDirStats traverses
  lexical paths, so a concurrent ancestor/TOCTOU symlink swap during the walk
  can redirect sizing. Its output is display-only (the Models table + the
  delete-confirmation "(X GB)" hint) and never drives a destructive decision
  (deletion uses the path-safe name, not the size), so the worst case is a
  wrong size number under adversarial mutation of the user's own store. A
  robust fix needs descriptor-relative traversal node:fs does not expose;
  documented as an accepted residual in code and docs/dashboard.md.

Gate: typecheck 0; dashboard 202/202 (×2); lint 0. Dashboard-only — native and
api.ts unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…eflight after restore, document display-only sizing

Fix-delta review of the review-#17 fixes surfaced two recovery-ordering
defects (one a regression from the #17 preflight hoist) plus one display-only
residual. All verified via control-flow analysis.

- Finding 3 (download.ts, regression): the #17 hoist put the ownership
  preflight above sweepStaging, so a preflight-refused job (unowned/foreign
  finalDir) threw before the only dead-private-staging-tree reap ran, leaking
  crashed multi-GB staging indefinitely. Split sweepStaging into
  reapDeadStagingTrees() (process-wide, pid-gated dead-`<slug>@<sha>.<pid>`
  reap, run BEFORE the preflight so a refused job still frees its tree) and
  recoverBackup(slug, finalDir) (slug-scoped backup restore/reap, run AFTER the
  preflight so a foreign finalDir link is already refused and never followed).

- Finding 1 (download.ts): the backup restore branch renamed any backup back
  onto an absent finalDir; a foreign-symlink backup (from a prior overwrite
  crash) would be restored after the only ownership check and then followed by
  skip-detection. Restore now requires the backup itself be an owned real
  directory (no-follow lstat + our marker), and the no-follow ownership
  preflight is re-run after recovery, before skip-detection.

- Finding 2 (models.ts + docs, document-and-accept): walkDirStats traverses
  lexical paths, so a concurrent ancestor/TOCTOU symlink swap during the walk
  can redirect sizing. Its output is display-only (the Models table + the
  delete-confirmation "(X GB)" hint) and never drives a destructive decision
  (deletion uses the path-safe name, not the size), so the worst case is a
  wrong size number under adversarial mutation of the user's own store. A
  robust fix needs descriptor-relative traversal node:fs does not expose;
  documented as an accepted residual in code and docs/dashboard.md.

Gate: typecheck 0; dashboard 202/202 (×2); lint 0. Dashboard-only — native and
api.ts unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
Brooooooklyn added a commit that referenced this pull request Jul 28, 2026
…eflight after restore, document display-only sizing

Fix-delta review of the review-#17 fixes surfaced two recovery-ordering
defects (one a regression from the #17 preflight hoist) plus one display-only
residual. All verified via control-flow analysis.

- Finding 3 (download.ts, regression): the #17 hoist put the ownership
  preflight above sweepStaging, so a preflight-refused job (unowned/foreign
  finalDir) threw before the only dead-private-staging-tree reap ran, leaking
  crashed multi-GB staging indefinitely. Split sweepStaging into
  reapDeadStagingTrees() (process-wide, pid-gated dead-`<slug>@<sha>.<pid>`
  reap, run BEFORE the preflight so a refused job still frees its tree) and
  recoverBackup(slug, finalDir) (slug-scoped backup restore/reap, run AFTER the
  preflight so a foreign finalDir link is already refused and never followed).

- Finding 1 (download.ts): the backup restore branch renamed any backup back
  onto an absent finalDir; a foreign-symlink backup (from a prior overwrite
  crash) would be restored after the only ownership check and then followed by
  skip-detection. Restore now requires the backup itself be an owned real
  directory (no-follow lstat + our marker), and the no-follow ownership
  preflight is re-run after recovery, before skip-detection.

- Finding 2 (models.ts + docs, document-and-accept): walkDirStats traverses
  lexical paths, so a concurrent ancestor/TOCTOU symlink swap during the walk
  can redirect sizing. Its output is display-only (the Models table + the
  delete-confirmation "(X GB)" hint) and never drives a destructive decision
  (deletion uses the path-safe name, not the size), so the worst case is a
  wrong size number under adversarial mutation of the user's own store. A
  robust fix needs descriptor-relative traversal node:fs does not expose;
  documented as an accepted residual in code and docs/dashboard.md.

Gate: typecheck 0; dashboard 202/202 (×2); lint 0. Dashboard-only — native and
api.ts unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm
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