Skip to content

feat: add optimized accountsdb crate - #14

Open
bmuddha wants to merge 6 commits into
nucleusfrom
accountsdb
Open

feat: add optimized accountsdb crate#14
bmuddha wants to merge 6 commits into
nucleusfrom
accountsdb

Conversation

@bmuddha

@bmuddha bmuddha commented Apr 23, 2026

Copy link
Copy Markdown
Collaborator

What changed

Added the accountsdb crate with persisted and volatile stores, routing logic, snapshot support, and mmap/LMDB-backed storage.

Why

The engine needs one account database that routes mutable and immutable accounts to the correct backend and removes stale copies when an account changes mode.

Closes #6.

Impact

  • Introduces AccountsDB, loaders, iterators, snapshots, backups, and error handling.
  • Adds persisted storage, volatile storage, and the on-disk index layout.
  • Keeps persisted offsets measured in StorageUnit and converts to bytes only at mmap/file boundaries.

Reviewer notes

Snapshot creation requires exclusive write access. The persisted layout and storage-unit arithmetic are the sharp edges to review closely.

Follow-up

ledger and keeper consume this API upstack.

@coderabbitai

coderabbitai Bot commented Apr 23, 2026

Copy link
Copy Markdown

Review Change Stack

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: af96fbe9-d0ee-4a1b-adaf-ee09e8e62aed

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Warning

.coderabbit.yaml has a parsing error

The CodeRabbit configuration file in this repository has a parsing error and default settings were used instead. Please fix the error(s) in the configuration file. You can initialize chat with CodeRabbit to get help with the configuration file.

💥 Parsing errors (1)
Validation error: Invalid input: expected boolean, received string at "reviews.auto_review.enabled"
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Walkthrough

Adds the accountsdb workspace crate for routing Solana accounts between persisted and volatile stores. It implements mapped storage, LMDB indexes, snapshots, backups, compaction, metrics, recovery, and integration tests.

Changes

AccountsDB foundation

Layer / File(s) Summary
Workspace and crate contract
Cargo.toml, accountsdb/Cargo.toml, accountsdb/src/lib.rs, README.md, accountsdb/README.md
The workspace now includes accountsdb and its storage dependencies. The crate defines public database APIs, errors, account aliases, and storage documentation.
Persisted storage engine
accountsdb/src/store/kv.rs, accountsdb/src/store/mmap.rs, accountsdb/src/store/index.rs, accountsdb/src/store/mod.rs
The persisted backend adds byte codecs, memory-mapped account storage, LMDB indexes, freelist allocation, transactional updates, checksums, validation, and program iteration.
Backend routing and account access
accountsdb/src/lib.rs, accountsdb/src/volatile.rs, accountsdb/src/metrics.rs, accountsdb/src/tests.rs
AccountsDB routes accounts between persisted and volatile stores. Loaders and iterators read both stores. Volatile state supports restoration, owner remapping, reset, and metrics.
Snapshots, backups, and compaction
accountsdb/src/snapshot.rs, accountsdb/src/store/defrag.rs, accountsdb/src/tests.rs
Snapshots, volatile dumps, backups, defragmentation, corruption checks, freelist reuse, checksum stability, and large-account storage growth are implemented and tested.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant AccountClient
  participant AccountsDB
  participant PersistedStore
  participant VolatileStore
  AccountClient->>AccountsDB: upsert account
  AccountsDB->>PersistedStore: store authoritative account
  AccountsDB->>VolatileStore: store non-authoritative account
  AccountClient->>AccountsDB: load account
  AccountsDB->>PersistedStore: check persisted storage
  AccountsDB->>VolatileStore: check volatile storage
  AccountsDB-->>AccountClient: return account entry
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning Deleting solana/account/src/cow/tests.rs is unrelated to the accountsdb objectives and lacks a stated migration rationale. Restore the deleted cow tests or explain why their removal is required for the accountsdb implementation.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: adding an optimized accountsdb crate.
Description check ✅ Passed The description explains the accountsdb crate, its storage backends, routing logic, snapshots, and purpose.
Linked Issues check ✅ Passed The changes implement the accountsdb crate with persisted and volatile backends, routing logic, and storage layout required by issue #6.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch accountsdb

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.

@bmuddha
bmuddha force-pushed the accountsdb branch 2 times, most recently from c9feec4 to bb19e9a Compare April 28, 2026 13:23
@bmuddha
bmuddha changed the base branch from solana-account to graphite-base/14 May 12, 2026 14:26
@bmuddha
bmuddha changed the base branch from graphite-base/14 to nucleus May 12, 2026 14:26
@bmuddha
bmuddha force-pushed the accountsdb branch 2 times, most recently from 013aa2e to cd1401e Compare May 14, 2026 14:46
@bmuddha

bmuddha commented Aug 6, 2026

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai 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.

Actionable comments posted: 7

🧹 Nitpick comments (2)
accountsdb/src/snapshot.rs (1)

85-96: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

dump overwrites volatile.db in place and can leave an undeserializable file.

Line 91 opens the target with truncate(true), so the previous payload is destroyed before the new one is written. If the process stops between the truncate and sync_data, the active tree holds a partial volatile.db.

VolatileStore::new calls bincode::deserialize_from on that file and propagates the error, so the next open fails and the operator must remove the file by hand before the database starts.

Write to a temporary file in the same directory, then rename it over the target. rename is atomic within one filesystem, so the reader observes either the old payload or the new one.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@accountsdb/src/snapshot.rs` around lines 85 - 96, Update Snapshot::dump to
serialize the volatile accounts into a temporary file in the destination
directory instead of truncating the target VOLATILE_DB_FILE in place. Flush and
sync the temporary file, then atomically rename it over the target path,
preserving the existing error propagation and ensuring cleanup or safe handling
if writing fails.
accountsdb/src/metrics.rs (1)

175-175: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Derive load counters from StoreKind instead of duplicating ordering.

load uses store as usize while Metrics::new builds loads with an explicit Persisted, Volatile, Absent ordering. A future StoreKind reorder or variant change can mismatch the counter and cause an index panic without a compile error. Generate the counters from the enum at one location.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@accountsdb/src/metrics.rs` at line 175, Update the loads counter
initialization in Metrics::new and the related load indexing to derive their
ordering and count from StoreKind rather than hard-coded [IntCounter; 3] and
explicit Persisted/Volatile/Absent ordering. Centralize the StoreKind-to-index
mapping or iterate the enum variants so adding or reordering variants cannot
mismatch counters or panic.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@accountsdb/src/snapshot.rs`:
- Around line 55-63: Update the safety documentation for snapshot to include
self.persisted.defragment() as the first step, before flushing the persisted
backend, cloning the active tree, and rewriting the volatile store. Keep the
exclusive-write-access requirement and remaining ordering description accurate.
- Around line 99-111: Update AccountsDB::backup so it returns the destination
path `to` for both BackupOp::Save and BackupOp::Restore, rather than always
returning `backup`. Document the Restore contract on backup: callers must stop
using or drop the current AccountsDB instance before restoring because the
active backend may be removed while open. Preserve the existing Save behavior
and rename flow.

In `@accountsdb/src/store/defrag.rs`:
- Around line 82-91: Update the doc comment for defragment to explicitly state
that it is not crash-safe: reindex commits relocated offsets before the
corresponding bytes are moved, so a process crash in that window can leave the
persisted tree inconsistent and require rebuilding from a backup. Mention that
this also applies when snapshot defragmentation runs on the active tree, and
document whether rebuild-from-backup is the intended recovery.

In `@accountsdb/src/store/mmap.rs`:
- Around line 236-240: Correct the rustdoc for the Mmap::meta method to state
that it returns a shared or immutable reference to the metadata header, matching
its &DatabaseMeta return type.

In `@accountsdb/src/store/mod.rs`:
- Around line 280-290: Update the Iterator implementation’s next method so LMDB
errors from self.iter.inner.next() are logged before terminating iteration,
rather than being silently converted to None by the ?.ok()? chain. Preserve
normal end-of-iteration behavior for an actual exhausted iterator, and use the
existing logging mechanism and error context available in the module.

In `@accountsdb/src/volatile.rs`:
- Around line 73-87: Update the owner cleanup in the account upsert flow to
compare the new owner key with prev.owner() before calling
programs.remove_if_sync. Only remove pubkey from the previous owner’s set when
the owners differ, preserving the insertion for legal no-op reassignments to the
same owner.

In `@README.md`:
- Around line 201-203: Update the README account-routing description to use
AccountMode::authoritative() rather than mutable() as the criterion for
selecting the live backend. Clarify that Transient accounts may be
runtime-immutable while remaining authoritative and persisted, and ensure the
statement about moving accounts and removing stale copies matches this
authoritative classification.

---

Nitpick comments:
In `@accountsdb/src/metrics.rs`:
- Line 175: Update the loads counter initialization in Metrics::new and the
related load indexing to derive their ordering and count from StoreKind rather
than hard-coded [IntCounter; 3] and explicit Persisted/Volatile/Absent ordering.
Centralize the StoreKind-to-index mapping or iterate the enum variants so adding
or reordering variants cannot mismatch counters or panic.

In `@accountsdb/src/snapshot.rs`:
- Around line 85-96: Update Snapshot::dump to serialize the volatile accounts
into a temporary file in the destination directory instead of truncating the
target VOLATILE_DB_FILE in place. Flush and sync the temporary file, then
atomically rename it over the target path, preserving the existing error
propagation and ensuring cleanup or safe handling if writing fails.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 5c791543-d3af-4279-ab95-72316709061a

📥 Commits

Reviewing files that changed from the base of the PR and between ef85122 and 4af7215.

📒 Files selected for processing (15)
  • Cargo.toml
  • README.md
  • accountsdb/Cargo.toml
  • accountsdb/README.md
  • accountsdb/src/lib.rs
  • accountsdb/src/metrics.rs
  • accountsdb/src/snapshot.rs
  • accountsdb/src/store/defrag.rs
  • accountsdb/src/store/index.rs
  • accountsdb/src/store/kv.rs
  • accountsdb/src/store/mmap.rs
  • accountsdb/src/store/mod.rs
  • accountsdb/src/tests.rs
  • accountsdb/src/volatile.rs
  • solana/account/src/cow/tests.rs
💤 Files with no reviewable changes (1)
  • solana/account/src/cow/tests.rs

Comment thread accountsdb/src/snapshot.rs
Comment thread accountsdb/src/snapshot.rs
Comment thread accountsdb/src/store/defrag.rs Outdated
Comment thread accountsdb/src/store/mmap.rs Outdated
Comment thread accountsdb/src/store/mod.rs
Comment thread accountsdb/src/volatile.rs
Comment thread README.md Outdated
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.

Implement accountsdb for engine account storage

1 participant