Introducing a new way to review your PRs.

Read the announcement

solana-foundation / surfpool

Surfpool is where developers start their Solana journey.

View on GitHub

21 documents · Updated Nov 23, 2026

docs / account-storage

Account storage backends

Surfpool storage gives each Surfnet runtime one key-value view for accounts, chain records, indexes, and control state. The same view can use process memory for fast isolated runs or SQLite/PostgreSQL for state that survives a restart. The storage layer sits below the SVM and RPC paths described in State and Surfnet execution, while its use during virtual execution is related to Surfnet virtual network.

Storage model

The storage model separates what the runtime stores from where it stores it. A Surfnet opens named stores through one backend, then the SVM uses those stores without depending on a database-specific API.

Storage contract

The Storage<K, V> contract presents a small key-value interface for runtime state. It supports writes, reads, removal, clearing, key and entry scans, counting, value updates, cloning, and explicit shutdown. Keys and values must be serializable so that the same runtime state can move between maps and SQL records. OverlayLike adds an optional way to expose buffered changes for an atomic commit, while shutdown gives persistent stores a place to finish database-specific cleanup.

The contract also defines copy-on-write behavior for shared in-memory stores. A clone can keep reading the same map, then a later write separates the writer's copy so a sandbox does not change the original state.

References: crates/…/mod.rs• L172-239 crates/…/mod.rs• L241-283 crates/…/hash_map.rs• L6-59 crates/…/fifo_map.rs• L6-47

Backend selection

StorageBackend chooses the store family from the database URL. No URL selects independent in-process maps. A PostgreSQL URL selects the PostgreSQL backend. Other URLs select SQLite, including the special :memory: URL. Persistent backends report that their stores can survive a process restart when the same database is used.

The backend owns the connection resources for one Surfnet and creates the named stores used by that Surfnet. This keeps the runtime state contract stable while the persistence choice changes.

References: crates/…/backend.rs• L3-21 crates/…/backend.rs• L46-60 crates/…/backend.rs• L93-109

Runtime state

The SVM keeps hot execution state in LiteSVM and uses named stores for data that must be queried by the runtime or retained beyond the current process. The stores are part of one Surfnet state boundary and are opened together when the SVM starts.

Account state layers

The account view has two local layers. LiteSVM holds the active execution state. When a persistent backend is enabled, the accounts store retains account data outside the active SVM state. Reads use the active SVM first and then the account store when an account is not in the active state. This lets garbage collection reduce memory use without losing the retained account record.

When a runtime account changes, the SVM mirrors the change to the account store and updates its lookup data. A deleted account is removed from the account store and marked offline so a later remote lookup does not silently restore it.

References: crates/…/surfnet_lite_svm.rs• L27-48 crates/…/surfnet_lite_svm.rs• L178-228 crates/…/svm.rs• L1592-1644

Derived account indexes

Derived indexes make account scans practical without decoding every retained account for each request. The runtime groups account addresses by owner and keeps separate groups for token accounts by wallet owner, mint, and delegate. It also keeps parsed token accounts, parsed mints, and token metadata needed for readable RPC amounts.

These indexes are derived state rather than a second source of account truth. An account update first removes old index entries, then adds entries for the new account. A change that bypasses this path can leave scans out of step with account data.

State groupRuntime purpose
Account recordsRetain account data for local reads and recovery.
Owner and token indexesFind accounts by program owner, wallet, mint, or delegate.
Token caches and associated dataSupport token balance and parsed-account queries.
Chain and transaction recordsRetain blocks, transactions, and bundle history.
Runtime control recordsRetain profiles, IDLs, streamed/offline account settings, scheduled overrides, and slot checkpoints.

References: crates/…/svm.rs• L292-340 crates/…/svm.rs• L1613-1701 crates/…/locker.rs• L2570-2670

In-memory stores

In-memory stores are the default for a Surfnet with no database URL. They are useful for short-lived tests and local runs because they avoid database setup, but their contents end when the owning process or Surfnet state is dropped.

Hash-map stores

StorageHashMap adapts the standard Rust hash map to the storage contract. It provides direct in-process access for general named stores and is the default constructor when the memory backend opens a store. Its update operation can change or remove a value in place, which avoids an extra lookup and write for local state changes.

FIFO profile store

StorageFifoMap adapts the runtime FIFO map to the storage contract. The memory backend uses it for executed transaction profiles so a configured profile limit can evict the oldest entries. A database-backed profile store uses the normal persistent key-value behavior instead.

The profile map keeps its eviction capacity when it is cloned. This preserves the same profile limit in a copy-on-write sandbox and prevents the copied store from growing beyond the configured bound.

References: crates/…/backend.rs• L46-92 crates/…/hash_map.rs• L1-61 crates/…/fifo_map.rs• L1-104 crates/…/svm.rs• L908-916

Overlay stores

An OverlayStorage is a temporary in-memory layer over any storage implementation. Reads check the overlay first and fall through to the base store. Writes stay in the overlay. Deletes use tombstones so a deleted base value remains hidden, and clear hides the whole base without changing it.

The overlay can report a delta made of writes, deletes, and a whole-base-clear marker. This gives a caller a safe way to inspect or replay changes without allowing a trial execution to alter the base store.

References: crates/…/overlay.rs• L11-35 crates/…/overlay.rs• L64-100 crates/…/overlay.rs• L144-245 crates/…/overlay.rs• L274-300

Persistent backends

SQLite and PostgreSQL implement the same storage contract for the runtime. Each named store maps to a database table whose rows are separated by surfnet_id, so one database can retain state for more than one Surfnet.

SQLite persistence

SQLite is the default database feature in the core crate. A file path gives a persistent local database. :memory: gives a database-backed run that lasts for the backend lifetime; separate SQLite backends receive separate in-memory databases, while stores opened from one backend share its database.

The SQLite backend owns one connection pool for a Surfnet and shares it across that Surfnet's stores. Pools use a process-wide housekeeping scheduler, which keeps connection cleanup from creating a separate worker group for every backend. File-backed databases use a write-ahead log, so normal shutdown performs a checkpoint before the process exits.

References: crates/…/mod.rs• L25-49 crates/…/sqlite.rs• L23-57 crates/…/sqlite.rs• L62-110 crates/…/sqlite.rs• L112-177

PostgreSQL persistence

PostgreSQL uses one process-wide connection pool for each database URL. All PostgresBackend instances that use the same URL reuse that pool, while each store query includes its Surfnet identifier. This allows several Surfnet instances to share PostgreSQL without mixing their rows and limits connection growth across concurrent runs.

When a named store opens, PostgreSQL creates its table if needed. The table creation runs inside a transaction with a database advisory lock keyed by the table name. This serializes concurrent creation attempts and releases the lock on both success and failure, so one failed or parallel open does not block later store construction.

PostgreSQL support is optional. A build without the PostgreSQL feature rejects a PostgreSQL URL rather than silently falling back to another backend.

References: crates/…/mod.rs• L51-73 crates/…/postgres.rs• L24-59 crates/…/postgres.rs• L61-101 crates/…/postgres.rs• L119-150 crates/…/postgres.rs• L394-515 crates/…/backend.rs• L25-33 crates/…/Cargo.toml• L122-126

Shared key-value shape

Both SQL backends store the serialized key and value as text in a named table. JSON serialization keeps the storage interface generic across account types, transaction records, indexes, and control records. The database key is the pair of surfnet_id and serialized key, so storing the same key again replaces the value for that Surfnet.

The SQL adapters create a store table when the store opens. They support direct lookup, removal, full clear, key scans, entry scans, and counts. The database-specific parts are connection syntax and SQL behavior; the runtime-facing contract remains the same.

References: crates/…/diesel_common.rs• L21-45 crates/…/diesel_common.rs• L47-93 crates/…/sqlite.rs• L195-219 crates/…/postgres.rs• L152-366

Storage flows

Storage participates in both ordinary account reads and isolated transaction execution. The first flow combines active execution state with retained state. The second flow protects the retained state while a transaction or bundle is tested.

Account lookup

The account lookup path checks the local execution state before the retained account store. If the local layers do not contain the account and the Surfnet has a remote context, the locker fetches the account from the upstream RPC and can write the result back into local state. Offline account rules can stop that remote fallback.

The following flow shows the source order for a normal account request.

flowchart TD
    A[Account request] --> B[Active LiteSVM state]
    B -->|found| C[Return local account]
    B -->|missing| D[Persistent account store]
    D -->|found| C
    D -->|missing and remote allowed| E[Remote RPC]
    D -->|missing or offline| F[Account not found]
    E --> G[Update local runtime state]
    G --> C

References: crates/…/surfnet_lite_svm.rs• L178-228 crates/…/locker.rs• L296-355 crates/…/locker.rs• L374-465

Account index maintenance

An account write updates the retained account record and then refreshes the derived owner and token indexes. RPC scans use these indexes to select candidate accounts, then apply the requested account filters and encoding before returning results.

This relationship explains why account data and index data must be treated as one state change. Removing an account also removes its owner, mint, delegate, and parsed-token entries when those entries exist.

References: crates/…/svm.rs• L1613-1701 crates/…/svm.rs• L1754-1787 crates/…/locker.rs• L2570-2670 crates/…/accounts_scan.rs• L463-520

Sandbox commit

Profiling and atomic bundle execution clone the SVM and wrap its storage fields in overlays. The sandbox sees the base values but sends all changes to memory. A failed run is discarded with its overlays. A successful bundle drains each overlay delta into the live stores, then publishes the related runtime effects.

The commit boundary matters for persistence: the live SQLite or PostgreSQL store is not changed by sandbox writes until the bundle has passed its success checks.

References: crates/…/svm.rs• L389-425 crates/…/svm.rs• L492-594 crates/…/svm.rs• L643-740

Change checklist

When these files or sections are changed, remember to consider these:

  • Change the Storage contract or its update and clone semantics and review every map, overlay, SQLite, and PostgreSQL implementation. A new operation must preserve the same read, delete, scan, update, and clone meaning in every backend.
  • Change an account write or delete path and check the account store plus owner, mint, delegate, token-cache, and associated-data state. These records form one derived-state contract.
  • Change a named store or its value type and update every opener and every reader that expects the same serialized key and value shape.
  • Change surfnet_id handling and verify both SQLite and PostgreSQL isolation. Rows from one Surfnet must not become visible to another Surfnet that shares a database.
  • Change overlay cloning or commit behavior and check both the inner account database and the outer SVM stores. A partial commit can make execution state and retained state disagree.
  • Change pool setup or connection cleanup and verify that all SQLite and PostgreSQL pools use the shared housekeeping scheduler. Resource use must remain bounded as the number of Surfnets grows.
  • Change SQLite shutdown or connection setup and verify file-backed WAL recovery. Data must be usable after a normal process restart.
  • Change PostgreSQL store creation or pool sharing and verify concurrent opens for the same table. DDL locking must release after both successful and failed creation.

Important failure modes

TriggerConsequenceGuard
A PostgreSQL or SQLite URL is used in a build without the matching feature.Backend creation fails instead of opening the requested store.Enable the matching core and database features before selecting that URL.
A key or value cannot be serialized or a retained value cannot be decoded.A store operation returns a storage error. An entry scan can omit a row that cannot be decoded.Keep key and value types compatible with their existing store and treat decode errors as data-quality failures.
A write updates account data without refreshing derived indexes.Owner and token scans can return stale or missing accounts.Route account mutations through the SVM account update path.
A shared database is opened with the wrong Surfnet identifier.The runtime reads a separate state partition or can write state under the wrong partition.Use one stable, unique identifier for each Surfnet instance.
A SQLite-backed process exits without storage shutdown.Recent writes can remain in SQLite's WAL or leave WAL support files behind.Call the SVM or locker shutdown path during normal exit.
A connection pool is built without the shared housekeeping scheduler.Each pool can create its own worker group and increase process resource use as Surfnets grow.Keep every SQLite and PostgreSQL pool attached to pool_scheduler().
Concurrent PostgreSQL store opens create the same table without the DDL lock.One opener can fail on a catalog race or a failed create can leave later opens blocked.Keep table creation inside the transaction-scoped advisory lock.
A shared in-memory map is cloned without preserving a bounded FIFO profile capacity.A sandbox copy can retain more profiles than the live profile store allows.Preserve the configured capacity when cloning ProfileFifoMap.
A sandbox is committed before all bundle transactions succeed.Partial overlay state can reach the live runtime.Commit only after the complete bundle succeeds while holding the exclusive SVM writer guard.

Key files

FileWhy to read it
crates/…/mod.rsDefines the storage contract, error model, shared pool scheduler, copy-on-write behavior, and overlay commit interface.
crates/…/backend.rsShows how a database URL selects memory, SQLite, or PostgreSQL and how named stores are opened.
crates/…/hash_map.rsShows the general in-memory map behavior and in-place value updates.
crates/…/fifo_map.rsShows FIFO profile retention and capacity-preserving clones.
crates/…/overlay.rsExplains read-through behavior, tombstones, clear semantics, and buffered change extraction.
crates/…/sqlite.rsShows the SQLite persistence boundary, per-Surfnet pool, in-memory behavior, connection settings, and shutdown checkpoint.
crates/…/postgres.rsShows PostgreSQL pool reuse by database URL, concurrent table creation safety, and Surfnet-partitioned store behavior.
crates/…/diesel_common.rsDefines the shared JSON record shape used by both SQL backends.
crates/…/surfnet_lite_svm.rsConnects active LiteSVM account state with the optional retained account store.
crates/…/svm.rsOpens the runtime's named stores and maintains account indexes and sandbox commits.
crates/…/locker.rsConnects local storage, remote fallback, and account scan behavior.