Skip to content

fix(storage-flags): accept only canonical multi-epoch flag bytes - #977

Merged
QuantumExplorer merged 3 commits into
developfrom
claude/issue-701-fix-4ab134
Sep 27, 2026
Merged

QuantumExplorer merged 3 commits into
developfrom
claude/issue-701-fix-4ab134

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

Issue

Closes #701.

StorageFlags::deserialize_multi_epoch and deserialize_multi_epoch_owned read the non-base epoch records into a BTreeMap with a loop guarded by while offset + 2 < len. Three things went wrong with that:

  1. Trailing bytes were accepted. The loop exits with one or two bytes unread and never checks offset == len. One junk byte after valid flags decoded fine, and so did two: an epoch index with no byte count after it.
  2. Repeated epochs silently overwrote each other. insert keeps the last record, so [(2, 10), (2, 20)] decoded as {2: 20}. Descending records were reordered the same way, so distinct byte strings decoded to the same flags.
  3. A non-base record could sit on the base epoch. MultiEpoch(4, {4: 10}) decoded. In split_storage_removed_bytes the LIFO walk then writes that record's share into the removal map under epoch 4, and the base-epoch residue is inserted under the same key afterwards. Splitting 20 removed bytes reported 13.

The audit addendum (C009) asked for all three; an overlong varint byte count (0x8a 0x00 for 10) was a fourth non-canonical form found along the way.

All were reproduced at runtime before the fix (tests written first):

deserialize_multi_epoch_rejects_trailing_bytes ... FAILED        expected trailing byte error: Some(MultiEpoch(1, {2: 10}))
deserialize_multi_epoch_rejects_duplicate_epochs ... FAILED      expected duplicate epoch error: Some(MultiEpoch(1, {2: 20}))
deserialize_multi_epoch_rejects_descending_epochs ... FAILED     expected epoch order error: Some(MultiEpoch(1, {3: 20, 5: 10}))
deserialize_multi_epoch_rejects_non_base_epoch_at_or_below_base ... FAILED   expected base collision error: Some(MultiEpoch(4, {4: 10}))
deserialize_multi_epoch_rejects_overlong_varint ... FAILED       expected overlong varint error: Some(MultiEpoch(1, {2: 10}))
split_removal_bytes_refuses_base_epoch_collision ... FAILED

Severity stays low. Flags are opaque bytes to GroveDB and Drive only ever writes what serialize emits, so none of these byte strings is reachable from a state transition.

What was done

  • Both decoders now share one private deserialize_epoch_map(data, base_epoch). It accepts only what serialize emits:
    • the loop runs to the end of the buffer, so a partial record is a StorageFlagsWrongSize error (the same error a truncated varint already gave)
    • the byte count must be a minimal varint (bytes_used == required_space())
    • each epoch index must be above the one before it, with the base epoch standing in for "before" on the first record. That one comparison covers duplicates, ordering, and records at or below the base epoch.
  • New StorageFlagsError::NonCanonicalStorageFlags for the last two. Platform does not match on this enum's variants.
  • Single-epoch decoding, the minimum-length checks and the unknown-type check are untouched.

Not version-gated. The map is a BTreeMap, so serialize writes unique ascending records. The only production constructors are the combine functions: combine_with_higher_base_epoch inserts rhs.base_epoch, which the caller has just checked is above ours, and combine_same_base_epoch merges maps under an equal base. By induction every record stays above the base epoch. Platform builds MultiEpoch* directly only in test expectations. So no stored flags decode differently, and there is no historical acceptance to preserve. combined_flags_always_decode pins that invariant.

Record values are deliberately not constrained: combine_with_higher_base_epoch can legitimately store a count at or below MINIMUM_NON_BASE_FLAGS_SIZE.

Tests

Each rejection runs against both the borrowed and the owned form, on bytes built record by record:

  • one and two trailing bytes
  • duplicate epochs, descending epochs
  • a non-base record on the base epoch, and one below it
  • an overlong varint
  • split_removal_bytes refuses colliding flags before any accounting, with the Drive context string attached
  • boundary round trip: byte counts 0, 127, 128, 16 384 and u32::MAX, epoch u16::MAX, re-serialising to the same bytes
  • a chain of combine_added_bytes / combine_removed_bytes whose every intermediate result decodes back to itself

cargo test -p grovedb-epoch-based-storage-flags (50 tests), the just_in_time cost tests in grovedb, cargo clippy --all-targets -D warnings on the crate and cargo fmt --check pass locally.

🤖 Generated with Claude Code

PR Hygiene · 4de4eb5

  • Bots — coderabbitai ✓ · thepastaclaw not yet — /skip-bots proceeds without the ones not yet reported
  • Self-review — post /self-reviewed once the bots are done
  • Within your 5 open PRs
  • Build running
  • Approvals — you own every area touched; none needed

When every box is checked the PR Hygiene check passes and this can merge.

Summary by CodeRabbit

  • Behavior Changes
    • Multi-epoch storage flags must contain complete records with minimally encoded byte counts and strictly ascending epochs above the base epoch. Incomplete records and complete but noncanonical encodings produce distinct errors; existing noncanonical data may no longer decode.
    • Serialization now requires non-base epochs to be above the base epoch.
    • When splitting removals, remaining bytes assigned to the base epoch are combined with any amount already recorded there.

@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: a3112f04-fe11-4748-be49-8149f7ab3b44

📥 Commits

Reviewing files that changed from the base of the PR and between 37f8627 and 4de4eb5.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • docs/crates/auxiliary.md
  • grovedb-epoch-based-storage-flags/src/lib.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

Multi-epoch storage flag decoding now uses shared validation for owned and unowned data. It rejects incomplete records and noncanonical encodings. Removal splitting adds base-epoch residue to any existing removal amount.

Changes

Canonical multi-epoch decoding

Layer / File(s) Summary
Noncanonical encoding error
grovedb-epoch-based-storage-flags/src/error.rs, CHANGELOG.md
Adds StorageFlagsError::NonCanonicalStorageFlags(String), includes it in mutable error-info handling and its test, and documents the error and decoding requirements.
Validated multi-epoch decoding
grovedb-epoch-based-storage-flags/src/lib.rs, docs/crates/auxiliary.md, CHANGELOG.md
Owned and unowned decoding use shared validation. Incomplete records return StorageFlagsWrongSize; nonminimal varints, invalid byte counts, duplicate or descending epochs, and epochs at or below the base epoch return NonCanonicalStorageFlags. Serialization debug-asserts that the epoch map is nonempty and begins above the base epoch. Tests cover malformed inputs, boundary values, and round trips.
Base-epoch removal accumulation
grovedb-epoch-based-storage-flags/src/lib.rs, docs/crates/auxiliary.md
Removal splitting adds remaining bytes to an existing base-epoch removal amount. Tests cover base-epoch collisions and removal entries.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Low

Suggested reviewers: thepastaclaw

Merge Risk: ⚪ Minimal · up to 4de4e

Canonical storage flags appear to decode and round-trip as intended. No issue requiring a fix before merge was established.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 4de4e

Stricter decoding prevents ambiguous flags from affecting storage accounting. Previously accepted flags may now block updates or removals, however, and release builds can still write some flags that the new decoder will reject. Whether such flags exist in stored data is unknown.

Retained concerns

  • Medium · reliability · inferred: Previously readable noncanonical persisted flags, including a base-epoch collision that the public serializer can still emit in release builds, now fail decoding before update or removal accounting. Affected records may need a recovery path; their existence and operational reach are unverified.
Security review details

Security Blast Radius

  • inferred — If a caller can persist noncanonical flags, later update or removal operations using those flags will receive a parse error. Attacker control, affected record counts, and any broader batch failure scope were not established.

Trust Boundaries and Controls

  • observed — Owned and unowned byte inputs reach the same canonical parser. The public in-memory variants can bypass that parser before serialization, while the new serializer ordering check is a debug assertion rather than a release-build control.

Resilience and Maintainability Implications

  • observed — The base-epoch accumulation closes the demonstrated loss of an existing removal share. Near-maximum removal arithmetic has a separate, unchanged addition-overflow hazard; production reachability for that input was not established.

Hardening Proposals

  • proposed — Before rollout, determine whether persisted flags use formerly accepted noncanonical encodings and define a recovery policy that does not silently reinterpret ambiguous epoch or owner accounting. Enforce the matching producer invariant in release builds if callers may construct multi-epoch variants directly.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: restricting storage-flag decoding to canonical multi-epoch encodings.
Linked Issues check ✅ Passed The pull request satisfies the coding requirements in issue #701. The shared deserialize_base_epoch_and_epoch_map path serves borrowed and owned multi-epoch decoding. It rejects incomplete records, …
Out of Scope Changes check ✅ Passed The changes remain within issue #701. The decoder refactor, NonCanonicalStorageFlags error, canonicality tests, removal-splitting fix, documentation, and changelog entry directly support canonical m…
Docstring Coverage ✅ Passed Docstring coverage is 92.59% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 2 files. (2 skipped: 2 …
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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.

@thepastaclaw

thepastaclaw commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

🕓 Queued for automated review — 1st in line, estimated start in ~20 min (commit 4de4eb5)
Estimated review time once started: ~1.3 h (two-phase automated review; median of recent runs).

  • Request priority review — click to move this review to the front of the queue.

@codecov

codecov Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.58333% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 93.13%. Comparing base (dce8252) to head (4de4eb5).
⚠️ Report is 5 commits behind head on develop.

Files with missing lines Patch % Lines
grovedb-epoch-based-storage-flags/src/lib.rs 99.57% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #977      +/-   ##
===========================================
+ Coverage    93.10%   93.13%   +0.02%     
===========================================
  Files          336      336              
  Lines       105421   105603     +182     
===========================================
+ Hits         98153    98354     +201     
+ Misses        7268     7249      -19     
Components Coverage Δ
grovedb-core 91.48% <ø> (ø)
merk 94.03% <ø> (ø)
storage 91.94% <ø> (ø)
commitment-tree 95.62% <ø> (ø)
mmr 95.43% <ø> (ø)
bulk-append-tree 93.72% <ø> (ø)
element 97.18% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Final validation — Phase 1 + Phase 2

Verified the combined reviewer evidence against head ddaf012: the shared decoder correctly rejects malformed and non-canonical records, and no blocking implementation defect was established. The new public error variant does introduce a source-compatibility break that should be explicitly identified in the release notes. All 50 storage-flags tests and the workspace formatting check passed locally; the working tree remains unchanged.

🟡 1 suggestion(s)

Review provenance

Source: reviewer 1: muse-spark-1.3-contributor (agent: phase1-reviewer, role: general); reviewer 2: muse-spark-1.3-contributor (agent: phase1-reviewer, role: architecture-layering); reviewer 3: muse-spark-1.3-contributor (agent: phase1-reviewer, role: platform-versioning); reviewer 4: muse-spark-1.3-contributor (agent: phase1-reviewer, role: rust-quality); reviewer 5: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 6: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 7: gpt-6-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 8: gpt-6-astra (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)

  • Triage: low by gpt-6-astra (effort low) — This is a small, well-contained validation fix in storage-flag decoding with focused tests, and it does not itself alter consensus, funds movement, cryptography, peer-facing deserialization, or storage migrations.
  • Phase 1 reviewers: muse-spark-1.3-contributor — general (completed, effort high); agent phase1-reviewer, muse-spark-1.3-contributor — architecture-layering (completed, effort high); agent phase1-reviewer, muse-spark-1.3-contributor — platform-versioning (completed, effort high); agent phase1-reviewer, muse-spark-1.3-contributor — rust-quality (completed, effort high); agent phase1-reviewer
  • Phase 1 model: muse-spark-1.3-contributor — not quota-gated; passed over gemini-3.8-flash-high (antigravity below 15% reserve: weekly 11% left, 5h 100% left), glm-5.3-flash (zai quota lookup failed)
  • Fresh verifier: gpt-6-astra — final-verifier; agent astra-verifier
  • Phase 2 reviewers: gpt-6-astra — general (completed, effort medium); agent phase2-reviewer, gpt-6-astra — architecture-layering (completed, effort medium); agent phase2-reviewer, gpt-6-astra — platform-versioning (completed, effort medium); agent phase2-reviewer, gpt-6-astra — rust-quality (completed, effort medium); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `grovedb-epoch-based-storage-flags/src/error.rs`:
- [SUGGESTION] grovedb-epoch-based-storage-flags/src/error.rs:11-12: Mark the new exhaustive error variant as a breaking public API change
  StorageFlagsError is exposed through the public error module and is not marked #[non_exhaustive]. Adding NonCanonicalStorageFlags therefore breaks downstream code that exhaustively matches the previous variants, independently of whether Platform currently does so. The Unreleased changelog names the new variant but does not identify this compatibility consequence. Explicitly document the source-breaking change so the eventual release uses an appropriate major-version boundary; if this change must ship in a compatible 6.x release, reuse an existing error variant instead. This concerns the Rust package API, not GroveVersion or serialized error compatibility, and does not require an immediate version bump in this implementation PR.

@github-actions github-actions Bot added bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. waiting-bots Waiting for the review bots to report on this head labels Sep 20, 2026
@github-actions

github-actions Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Your move: thepastaclaw left review threads unresolved; resolve them.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Sep 23, 2026
@QuantumExplorer
QuantumExplorer force-pushed the claude/issue-701-fix-4ab134 branch from ddaf012 to 37f8627 Compare September 27, 2026 08:41
@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. labels Sep 27, 2026
@github-actions github-actions Bot added the bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. label Sep 27, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-review — Final validation — Phase 1 + Phase 2

Independently reviewed the complete diff at 8485265; no actionable in-scope defects remain, and the prior public-API compatibility documentation finding is fixed. The shared decoder enforces canonical records, and the removal-accounting change preserves base-epoch allocations without changing canonical-state accounting. Local storage-flags tests passed in debug (54 tests) and release (52 tests), documentation tests completed successfully, and the worktree remains unchanged.

🔴 0 blocking | 🟡 0 suggestion(s) | 💬 0 nitpick(s)

Review provenance

Source: reviewer 1: glm-5.3-flash (agent: phase1-reviewer, role: general); reviewer 2: glm-5.3-flash (agent: phase1-reviewer, role: architecture-layering); reviewer 3: glm-5.3-flash (agent: phase1-reviewer, role: platform-versioning); reviewer 4: glm-5.3-flash (agent: phase1-reviewer, role: rust-quality); reviewer 5: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 6: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 7: gpt-6-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 8: gpt-6-astra (agent: phase2-reviewer, role: rust-quality); reviewer 9: gpt-6-astra (agent: phase2-reviewer, role: general); reviewer 10: gpt-6-astra (agent: phase2-reviewer, role: architecture-layering); reviewer 11: gpt-6-astra (agent: phase2-reviewer, role: platform-versioning); reviewer 12: gpt-6-astra (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6-astra (agent: astra-verifier, role: final-verifier)

  • Triage: low by gpt-6-astra (effort low) — The diff is a contained decoder hardening that shares parsing logic and adds straightforward canonicality checks with extensive tests, without introducing intricate changes to a critical surface.
  • Phase 1 reviewers: glm-5.3-flash — general (completed, effort high); agent phase1-reviewer, glm-5.3-flash — architecture-layering (completed, effort high); agent phase1-reviewer, glm-5.3-flash — platform-versioning (completed, effort high); agent phase1-reviewer, glm-5.3-flash — rust-quality (completed, effort high); agent phase1-reviewer
  • Phase 1 model: glm-5.3-flash — zai quota: 5h 94% left, weekly 35% left; passed over gemini-3.8-flash-high (antigravity below 15% reserve: weekly 13% left, 5h 100% left)
  • Fresh final gate: an independent Phase-2 review ran after iterative findings were reconciled
  • Fresh verifier: gpt-6-astra — final-verifier; agent astra-verifier
  • Phase 2 reviewers: gpt-6-astra — general (completed, effort medium); agent phase2-reviewer, gpt-6-astra — architecture-layering (completed, effort medium); agent phase2-reviewer, gpt-6-astra — platform-versioning (completed, effort medium); agent phase2-reviewer, gpt-6-astra — rust-quality (completed, effort medium); agent phase2-reviewer, gpt-6-astra — general (completed, effort medium); agent phase2-reviewer, gpt-6-astra — architecture-layering (completed, effort medium); agent phase2-reviewer, gpt-6-astra — platform-versioning (completed, effort medium); agent phase2-reviewer, gpt-6-astra — rust-quality (completed, effort medium); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.

No unresolved findings remain from the prior review on this head.
Out-of-scope follow-up suggestions (1)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • Pre-existing debug-build u32 overflow in the split loop condition above the PR's new overflow comment — Out of scope: the addition at lib.rs:820 can overflow with the supplied near-u32::MAX removal count, but the identical loop condition exists at base commit 50d53bc. This PR neither introduces nor worsens that condition, and its new base-epoch accumulation is bounded by the removal total. No newly reachable production path was demonstrated; this is adjacent hardening rather than a defect required to resolve #701. The proposed replacement also reverses the existing comparison and is not a valid behavior-preserving fix.
    • Follow-up: Consider creating a separate issue or author/maintainer-requested PR for this.

@github-actions

github-actions Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

Bots are done — your move: post /self-reviewed.
Full checklist in the description.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed and removed waiting-bots Waiting for the review bots to report on this head labels Sep 27, 2026
QuantumExplorer and others added 3 commits September 28, 2026 00:47
The multi-epoch decoders stopped with one or two bytes unread, replaced
repeated epochs silently, and accepted a non-base record on the base
epoch, which removal splitting then overwrote with the base residue.
Both forms now share one record decoder that requires complete,
minimally encoded records in strictly ascending order above the base
epoch.

Closes #701

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…h flags

- split_storage_removed_bytes adds the base-epoch residue to a share
  already taken at the base epoch instead of replacing it, so flags built
  in memory are split correctly too
- serialize debug-asserts that non-base epochs are above the base epoch,
  matching what the decoder accepts
- a complete varint byte count beyond u32 is NonCanonicalStorageFlags,
  not a size error
- error strings are built lazily on the decode path
- the public decoders document the canonical-only contract
- the non-empty map rule and base-epoch header parsing live in the
  shared helper instead of the 6/38 byte length guards

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The storage flags section still said the decoder did not reject every
non-canonical multi-epoch encoding and listed the old 6/38-byte length
rule. Describe which malformed bytes are StorageFlagsWrongSize and which
are NonCanonicalStorageFlags, the round-trip guarantee, the serialize
debug-assert on epochs above the base, and the base-epoch residue in
split_storage_removed_bytes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@QuantumExplorer
QuantumExplorer force-pushed the claude/issue-701-fix-4ab134 branch from 8485265 to 4de4eb5 Compare September 27, 2026 18:23
@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. labels Sep 27, 2026
@QuantumExplorer
QuantumExplorer merged commit 0b3f9fc into develop Sep 27, 2026
11 of 12 checks passed
@QuantumExplorer
QuantumExplorer deleted the claude/issue-701-fix-4ab134 branch September 27, 2026 18:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

waiting-bots Waiting for the review bots to report on this head

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[audit][medium] Epoch storage flags accept trailing bytes and duplicate epochs

2 participants