State and Surfnet execution
Surfnet is the local Solana execution environment. It gives clients one local RPC and WebSocket view that can run transactions, move a simulated chain, and retain account and transaction state. It can run offline or use an upstream Solana RPC source to fill missing state. The runtime and RPC service expose this environment to clients. See Runtime and RPC service. Scenario setup can use the same state boundary. See Scenario execution.
Execution environment
The local environment joins a Solana virtual machine with a chain clock, block production, RPC services, and event delivery. One Surfnet instance owns this state and exposes it through local HTTP and WebSocket endpoints.
Surfnet runtime
The Surfnet runtime is the execution boundary for local transactions and account changes. It keeps active account state in the virtual machine and records chain history and indexes through the state layer. It also publishes transaction, account, slot, and startup events so clients observe one local chain view.
The runtime uses one shared read and write boundary. Read operations can run together. A state change takes exclusive access. Each exclusive write also advances a state revision. Isolated work uses that revision to reject a result when live state changed during execution. Accepted transaction signatures remain distinguishable from unknown signatures until processing finishes.
References: crates/…/svm.rs• L493-619 crates/…/svm.rs• L754-782 crates/…/locker.rs• L185-253
Chain progression
Block production controls when a successful transaction becomes part of the local chain. The environment supports three modes:
- Clock: the chain advances on clock ticks.
- Transaction: a processed transaction advances the chain.
- Manual: a client requests each slot advance.
Clients can change the mode while the runtime is active. The same control path supports pause, resume, slot changes, and time travel. Commitment controls which chain position and recent blockhash a client can use. See Surfnet virtual network for execution modes and network behavior.
Blocks are stored sparsely when they contain transactions. Slot checkpoints preserve chain position when empty blocks are not stored. Periodic cleanup can rebuild the in-memory account view from persistent state while preserving the sysvars and slot history that define the live chain. A clean shutdown writes the latest checkpoint and flushes the storage boundary.
References: crates/…/svm.rs• L122-150 crates/…/svm.rs• L813-827 crates/…/svm.rs• L1273-1407 crates/…/surfnet_lite_svm.rs• L116-152
Startup and readiness
Startup is the gate between an initialized process and a usable local network. The runtime can load a snapshot, fetch required accounts from a datasource, start RPC and plugin services, and then announce readiness. Clients should wait for the ready signal before sending work that depends on startup state.
The startup plan must close before the network becomes ready. A runtime with no external startup work closes an empty plan itself. An external planner must close its declared work. If it does not, the network stays unready instead of exposing partial state. Startup transitions are published to both current-state watchers and event consumers.
References: crates/…/locker.rs• L656-859 crates/…/svm.rs• L4787-4846
State management
Surfnet treats state as named key-value stores behind one storage contract. This separates state use from the choice of memory, file, or server persistence. The virtual machine remains the source of the current in-process account view.
State layers
The state model has two related layers. The virtual machine holds accounts needed for immediate execution. The storage layer holds accounts and durable chain data such as blocks, transactions, indexes, profiles, overrides, and checkpoints.
Account reads use the virtual machine first. They use persistent account storage when the account is missing from the active machine state. This permits memory cleanup without losing the account. A restarted Surfnet can also rebuild its chain position from stored state. When both layers have an account, the active virtual machine view wins.
Each account result records its source. Remote and database results can hydrate missing state. Generated state and live local changes are not replaced by a stale fetch. A local delete also marks the account offline, so remote fallback does not recreate a deliberate absence. An account owner can also make all accounts that it owns offline. Coupled data follows the same rule. A token account stays paired with its mint, and an upgradeable program stays paired with its program-data account. The returned coupled account is refreshed from live state after hydration so a newer local dependency is not hidden by an older fetched value.
Updates use two policies:
- Authoritative: replace the selected local value.
- Hydrate if absent: fill missing state and preserve a live value.
Snapshot loading follows these policies. Explicit snapshot data is a local input. Data fetched for a missing snapshot entry is only a hydration candidate. Strict loading reports invalid or failed entries while allowing earlier valid entries to remain installed. Account indexes update with account writes and deletes so owner, mint, delegate, and token-account queries match direct reads. Managed chain sysvars remain under runtime control and cannot be changed as ordinary accounts. Snapshot restoration may set the restart marker through the startup path so restored programs see the same chain context as the runtime.
See Account storage for backend choices and account records.
References: crates/…/svm.rs• L152-183 crates/…/svm.rs• L2945-3100 crates/…/surfnet_lite_svm.rs• L32-45 crates/…/surfnet_lite_svm.rs• L205-320 crates/…/locker.rs• L307-434 crates/…/locker.rs• L644-889
Persistence boundary
The storage backend is selected when Surfnet starts. Without a database URL, the instance uses in-process stores. A SQLite URL gives local persistence. A PostgreSQL URL gives shared server-backed persistence. All named stores opened by one Surfnet use the same backend. The Surfnet identifier keeps one instance's records separate from another instance in the same database. See Database backends for backend behavior.
Persistent state survives a process restart when the same database and Surfnet identifier are used. Startup restores chain position from the latest slot checkpoint when present. It falls back to the newest stored block when needed. An orderly shutdown is part of this boundary because file-backed SQLite state may need a final checkpoint before exit.
References: crates/…/svm.rs• L1181-1387 crates/…/svm.rs• L801-815 crates/…/locker.rs• L185-195
Isolated state views
An isolated state view lets the runtime inspect or execute work without changing live state. It reads through to the base stores but keeps writes and deletes in memory. A failed profile or bundle can therefore be discarded without changing the active network.
Profiling uses isolated storage and separate event and subscription channels. Read-only analysis cannot notify live clients. Atomic bundle execution uses the same isolation and buffers its events. A successful bundle applies state only after all transactions succeed. It then replays the captured events while holding exclusive access. Each sandbox records the live state revision at creation. If any exclusive write changes live state before commit, the bundle is rejected as stale.
The bundle flow moves from a live snapshot to isolated execution and then to either discard or guarded commit.
flowchart LR
A[Live Surfnet state] --> B[Create isolated sandbox]
B --> C[Run bundle and buffer state and events]
C --> D{All transactions succeed?}
D -->|no| E[Discard sandbox]
D -->|yes| F{Live state revision unchanged?}
F -->|no| E
F -->|yes| G[Commit state and replay events]
References: crates/…/svm.rs• L682-721 crates/…/svm.rs• L817-1176 crates/…/surfnet_lite_svm.rs• L72-82
Scheduled state changes
Scenarios schedule account overrides for future slots. The scheduler converts each scenario-relative slot into an absolute slot and stores the plan for later materialization as the local chain reaches that slot.
The public scheduling boundary uses the next slot when no base slot is given. It rejects a base slot that the chain already produced because that plan cannot be applied. It also validates every relative-slot sum before storing any override, so an invalid scenario does not leave a partial schedule. Keep-alive bindings can refresh scenario-touched accounts on later slots, but those bindings are held only in memory and do not resume after restart. See Scenario execution for the scenario workflow.
References: crates/…/locker.rs• L3021-3041 crates/…/svm.rs• L5184-5235 crates/…/svm.rs• L3379-3389
Virtual network connections
Surfnet can act as an offline local network or as a local view connected to an upstream Solana network. The local runtime remains the place where clients execute transactions. The upstream datasource supplies account and chain context only when the selected mode allows it.
Local and remote account flow
An account lookup first checks the local virtual machine and persistent local state. If the account is missing and remote access is enabled, Surfnet asks the datasource for it. The result can then hydrate local state for later reads and transactions.
The lookup checks local state again after the asynchronous fetch. A concurrent local write therefore wins over an older remote or database result. Offline accounts and accounts owned by an offline owner stay absent from remote hydration. The final result also refreshes a coupled program-data or mint account from the live local view. This keeps the returned account pair consistent with execution state.
Transaction lookups follow the same local-first rule. A locally accepted transaction that is still pending is not treated as missing. Address history combines local results with remote results only when the local page does not fill the requested limit. Remote pagination stops at the Surfnet start slot because local signatures are newer than the upstream chain.
For a token query, an upstream response that says a mint is unknown means that the mint may exist only in the local fork. Surfnet treats that narrow response as an empty remote result and keeps local accounts. Other invalid-parameter responses and provider failures remain errors.
Remote account calls have one total deadline, rather than a separate wait for each retry or batch. Large account requests split into provider-sized batches that run in parallel and return in the caller's original order. Errors expose a safe datasource endpoint without credentials. Unsupported remote RPC methods return an explicit unsupported result instead of being mistaken for successful empty data.
The account path moves from a local read to an optional remote fetch and then to a guarded local hydration step.
flowchart LR
A[Account request] --> B[Local VM and stores]
B -->|found| C[Return local view]
B -->|missing| D{Remote access allowed?}
D -->|no| E[Return missing]
D -->|yes| F[Fetch datasource]
F --> G[Recheck local state]
G --> H[Hydrate only if absent]
H --> C
The datasource is an input to local state, not a second execution environment. Each call has a total deadline. Reported errors identify the endpoint without exposing URL credentials. Remote account batches preserve caller order and can run in parallel within the upstream request limit.
References: crates/…/locker.rs• L288-434 crates/…/locker.rs• L493-577 crates/…/locker.rs• L1609-1666 crates/…/locker.rs• L1690-1799 crates/…/remote.rs• L56-175 crates/…/remote.rs• L409-571 crates/…/remote.rs• L620-683 crates/…/remote.rs• L801-815
Network startup choices
The local SDK starts an offline Surfnet by default. A caller can provide a remote RPC URL to enable account fallback. It can also select block production, slot timing, and startup funding. The CLI and embedded MCP path use the same local runtime while choosing their own startup and endpoint handling.
These choices affect the source of initial state and the way time moves. They do not change the core contract. Clients connect to the local RPC and observe one Surfnet-owned chain state. See Surfnet virtual network for the available execution modes.
References: crates/…/surfnet.rs• L27-67 crates/…/surfnet.rs• L71-141 crates/…/surfnet.rs• L167-241
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the local-first account lookup order aligned with remote hydration and snapshot loading. A change in one path can make RPC reads and transaction execution see different account state.
- Keep account source and update policy aligned. Database and remote data may hydrate missing state. Generated or live state must not be replaced by a stale fetch.
- Keep coupled program-data and mint accounts consistent with their primary accounts during reads, hydration, and snapshot loading.
- Keep local deletions aligned with offline-account rules and index removal. A deleted account must not return from the datasource or remain in owner, mint, or delegate queries.
- Keep managed sysvar protection aligned with every account write path. Ordinary account updates must not desync the runtime's clock, blockhash, epoch, restart marker, or slot history.
- Keep the
surfnet_idboundary aligned across every persistent store. A store that omits it can expose one Surfnet instance's state to another. - Keep startup readiness behind the completion of declared hydration work. Clients may submit transactions as soon as the ready signal is visible.
- Keep overlay commit behavior aligned with state-revision checks and event replay. A stale or failed bundle must not publish events or partial state.
- Keep scenario base-slot validation and relative-slot overflow checks before persistence. A schedule must target a future produced slot and must not be partially stored.
- Keep keep-alive bindings aligned with scenario slot materialization. A restart must not imply that an in-memory binding will resume.
- Keep datasource deadlines, batching order, and error sanitization on every remote request path. A new path must not wait without bound or return credentials from its URL.
- Keep the unknown-mint response rule narrow. Only a mint-filtered token query for a mint absent upstream is empty remote data. Other invalid-parameter and provider errors remain errors.
- Keep pending transaction signatures aligned with transaction lookup. An accepted signature must remain visible while processing is still in progress.
- Keep remote account batch limits and input order aligned. A new batching path must not exceed the provider request limit or map results to the wrong pubkeys.
- Keep checkpoint recovery aligned with sparse block storage, restart and landing records, and reset behavior. A stale checkpoint can restore the wrong chain tip when empty blocks are not stored.
- Keep storage shutdown in the process-exit path. SQLite state can remain in the WAL if the backend does not receive its final flush.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A remote account is needed while Surfnet is offline or the account is marked offline | The account remains absent and dependent startup or transaction work can fail | Use an available datasource or preload the account in a snapshot. Honor offline-account rules. |
| A local write occurs during a remote account fetch | An old fetched value can replace newer local state | Recheck the account under the writer boundary and hydrate only when absent. |
| An account owner is marked offline after a batch fetch starts | Accounts owned by that owner can enter local state even though the new rule should block them | Apply offline-owner filtering under the final writer boundary. |
| A coupled mint or program-data account is installed without the matching primary account | Execution can see inconsistent dependency state | Apply the coupled result as one source-aware update and refresh dependencies from live state. |
| A managed sysvar is written as a normal account | Runtime time, blockhash, restart, or slot-history state can diverge from the visible account state | Reject writes to runtime-managed sysvars. |
| An upstream datasource does not know a mint that exists only in the local fork | A token query can hide local token accounts behind a remote error | Treat the unknown-mint response as empty remote data only for mint filters. |
| A scenario uses a base slot that Surfnet already produced | Its overrides have no future slot at which to apply | Default to the next slot or reject a base slot at or before the current slot. |
| A scenario's base and relative slots overflow or validation happens after writes | Scheduling fails with a partial override plan | Check every absolute slot before storing any override. |
| A keep-alive binding is expected after restart | Scenario-touched accounts are not refreshed by that binding | Treat keep-alive bindings as process-local state and rebuild them when needed. |
| An external startup planner does not close its plan | Surfnet never reaches public ready state | Close the plan before clients submit transactions. |
| A bundle commits after live state changed | Sandbox writes or events can describe a different live state | Compare the sandbox state revision and commit only under exclusive access. |
| A bundle fails after execution begins | Buffered state and events are discarded. The live Surfnet stays unchanged | Execute through the isolated bundle view and commit only after every transaction succeeds. |
| A datasource does not answer before its deadline | The remote lookup returns an error instead of waiting without bound | Preserve the total datasource deadline on every remote request path. |
| A datasource error includes its raw URL | Credentials or private URL parts can reach a client | Report only the sanitized endpoint and error class. |
| A pending local transaction is treated as unknown | A remote lookup can return an older or unrelated result | Keep pending signatures distinct from missing local records. |
| A remote account batch exceeds the provider request limit or loses its input order | Some accounts fail to load or results map to the wrong pubkeys | Split batches at the provider limit and restore the caller's order before hydration. |
| SQLite is terminated without storage shutdown | Recent writes can remain in the WAL instead of the main database file | Use the Surfnet shutdown path before process exit. |
Key files
| File | Why to read it |
|---|---|
| crates/…/svm.rs | Defines the Surfnet state boundary, lifecycle, persistence set, recovery point, account update policy, scheduled state changes, startup state, and isolated execution behavior. |
| crates/…/locker.rs | Shows how concurrent readers and writers access Surfnet, how local, persistent, and remote account reads combine, and how future scenario slots are validated. |
| crates/…/surfnet_lite_svm.rs | Explains the relationship between the execution machine and persistent account state, including cleanup and managed sysvars. |
| crates/…/remote.rs | Defines the datasource boundary for remote account and chain reads, including batching, deadlines, local-only mint handling, safe errors, and unsupported methods. |
| crates/…/surfnet.rs | Shows the public local SDK entry point and the main choices available to an embedded caller. |
| docs/account-storage.md | Describes the storage backends and account-specific persistence model. |
| docs/database-backends.md | Describes the persistence backend choices that support Surfnet state. |
| docs/surfnet-virtual-network.md | Describes the client-facing virtual network and execution modes. |