Runtime execution loops
The runtime execution loops keep a local Surfnet alive from startup through shutdown. They prepare the state service, expose HTTP and WebSocket RPC, move clock and transaction commands into SVM state, and publish events that let clients observe progress. This page is a child of Runtime and RPC service; see RPC surface and subscriptions for the endpoint families themselves.
Runtime lifecycle
The main lifecycle is coordinated by crates/…/mod.rs. The runloop first makes the SVM usable and starts the supporting services. It then announces core startup and enters the long-lived block production loop, which remains the owner of ordered runtime changes until termination.
The startup sequence has these broad stages:
- Select the first configured simnet and choose local-only or remote-assisted account behavior.
- Initialize the SVM state, apply configured airdrops, and load any snapshots.
- Start the HTTP RPC, WebSocket RPC, and Geyser plugin services.
- Start the clock loop and restore events for stored transactions.
- Seal an empty startup plan when the runloop is the planner, or leave plan sealing to an external planner.
- Publish
CoreStarted, notify Geyser plugins that startup ended, and enter block production.
CoreStarted means that the RPC servers are bound and stored transactions have been replayed. It does not always mean that the public startup phase is Ready: an external planner can still hydrate cloned accounts and run startup runbooks after core startup. The readiness state is exposed through the Surfnet info RPC and a startup status watch channel.
This diagram shows how configuration becomes a live service and then moves into steady-state execution.
flowchart TD
A[Configured Surfnet] --> B[Initialize SVM and optional remote client]
B --> C[Load snapshots and apply airdrops]
C --> D[Start RPC and Geyser services]
D --> E[Start clock]
E --> F{Startup planner}
F -->|Runloop| G[Seal empty plan]
F -->|External| H[Wait for planner commands]
G --> I[CoreStarted and end-of-startup event]
H --> I
I --> J[Block production loop]
J --> K[Terminate and close services]
References: crates/…/mod.rs• L190-388 crates/…/types.rs• L434-456 crates/…/types.rs• L824-842
Startup readiness
Startup readiness is a gate over declared work. A planner seals the task list before work starts. The runtime marks each declared task as running and then as succeeded or failed, so Ready means that the sealed plan is complete. The two runtime tasks are remote account hydration and startup runbook execution.
The default Runloop planner seals an empty plan just before CoreStarted. The CLI uses the External mode when it must inspect the project, then seals and dispatches the work through the same command channel. This split lets the embedded SDK start without project planning while keeping CLI startup work visible to readiness clients.
Accepted startup transitions update both the current status watch and the ordered event stream. A failed planning step or failed task reaches a terminal Failed phase. In headless CLI mode, a watchdog turns that phase into an abort followed by graceful termination; an interactive session can keep the failure visible to the user.
References: crates/…/startup.rs• L74-112 crates/…/types.rs• L742-781 crates/…/mod.rs• L364-373 crates/…/startup.rs• L334-426 crates/…/startup.rs• L84-135
Live command loop
The block production loop is the runtime's central coordinator after startup. It waits on clock ticks and SimnetCommand messages, applies each accepted operation to the SVM through the locker, and confirms a block when the selected production mode requires one.
The loop changes its behavior through BlockProductionMode:
| Mode | Block production trigger |
|---|---|
| Clock | An enabled clock tick |
| Manual | A slot-forward command |
| Transaction | A processed transaction or completed airdrop |
The loop also owns time control. Clock commands pause, resume, toggle, or change the slot interval. Time-travel commands first confirm the current block, then update the clock and epoch state. A pause-with-confirmation command waits until slot progress stops before returning epoch information to its caller.
The loop can also enforce an idle expiry. On a clock tick, it checks whether the service has received a recent state update. If the expiry window has passed, it sends the same termination command used by explicit shutdown paths.
The clock uses one queued tick at most. If the live loop falls behind, missed ticks are coalesced and counted instead of replayed as a burst. This keeps visible slot progress close to real time and reports clock lag without turning delayed work into a catch-up surge.
This diagram shows how clock signals and client requests meet at one ordered state-change boundary.
flowchart LR
C[Clock tick] --> L[Live command loop]
R[RPC request] --> Q[SimnetCommand channel]
Q --> L
L --> S[SVM locker]
S --> P[Confirm current block when due]
P --> E[Runtime and transaction events]
E --> W[RPC readers, subscriptions, and plugins]
References: crates/…/mod.rs• L391-727 crates/…/types.rs• L742-800
Transaction processing
RPC transaction submission does not execute the transaction inside the RPC handler. The handler sends ProcessTransaction to the live command loop and waits for a transaction status result. The runloop normalizes the queued transaction into a versioned form, then applies verification and preflight policy, processes it against the SVM, and may trigger block confirmation in transaction-driven mode.
Before it queues a transaction, the RPC path marks its signature as pending. This lets status reads distinguish a transaction waiting in the runloop from a signature that the runtime has never seen. The runloop clears that marker after processing, including when processing fails.
Transaction-driven production also keeps finalization moving after a block. When pending transactions still need finalization, the loop schedules one follow-up turn through its command selection path. This lets new commands join the next block instead of waiting for a separate finalization window.
This channel ordering also protects startup state. A transaction queued before remote account hydration completes can see the earlier state, so clients should wait for public Ready before sending work that depends on startup clones or runbooks.
References: crates/…/full.rs• L1727-1763 crates/…/full.rs• L1813-1839 crates/…/mod.rs• L555-574 crates/…/mod.rs• L718-723 crates/…/svm.rs• L749-777 crates/…/types.rs• L749-754
Atomic bundle processing
Jito-style bundle processing gives a group of transactions one all-or-nothing execution boundary. The runloop accepts a ProcessBundle command, executes the transactions in order against an isolated SVM view, and commits the result only when the live state has not changed during execution. A failed bundle leaves live state and client events unchanged; a successful bundle replays its state changes and events through the same confirmation path as ordinary transactions.
If another runtime operation changes state while a bundle runs, the runtime discards that sandbox and retries from a fresh view a limited number of times. Remote accounts needed by the bundle are fetched before the sandbox starts, so execution itself uses one stable local view.
References: crates/…/mod.rs• L575-586 crates/…/jito.rs• L851-914 crates/…/jito.rs• L916-998 crates/…/svm.rs• L952-1025
Remote account hydration
Remote account hydration brings selected accounts from the configured datasource into the local SVM. The planner declares the hydration task before dispatch, then the live command loop fetches the batch, installs it as one state update, and completes the startup task.
An account that does not exist at the datasource is not itself a startup failure. The runtime reports it as a warning and can still reach Ready, while a fetch or URL error fails the hydration task and prevents readiness.
References: crates/…/startup.rs• L306-320 crates/…/mod.rs• L645-694 crates/…/startup.rs• L92-112
Runbook execution
Startup runbooks execute outside the live command loop so that their work can proceed while the runtime continues to receive commands. The planner starts the runbook task before dispatching the work, and the worker sends one completion command after all runbook futures finish or after a panic is converted into an error.
During normal CLI operation, runbook start and completion events also update per-runbook status. The locker disables instruction profiling while runbooks are active and restores it only after all active runbooks complete when the initial setting enabled it.
References: crates/…/startup.rs• L358-426 crates/…/mod.rs• L638-644 crates/…/locker.rs• L3987-4009
State and datasource boundary
The live service uses a local SVM as its working state and can use a configured remote RPC datasource to fill gaps. SurfnetSvmLocker is the shared boundary: it gives RPC readers a consistent view and serializes state changes before they become visible to other runtime work.
Account state resolution
Account reads follow a local-first path. The runtime uses live SVM state when available, restores database-backed state when needed, and fetches missing accounts from the remote datasource when remote access is enabled. The final write-lock check makes a newer local change win over an older fetch, while offline accounts and offline owners stay local-only. Coupled accounts, such as a token account and its mint, are resolved together so the returned view matches the state that becomes live.
Remote calls have an outer deadline and run on a datasource runtime that is separate from request workers. A slow provider therefore returns an error instead of holding the runloop forever, and a blocked RPC request does not prevent the runloop from making progress on its own datasource read. Provider errors expose a safe endpoint identity without forwarding URL credentials.
References: crates/…/locker.rs• L178-285 crates/…/locker.rs• L308-435 crates/…/locker.rs• L456-614 crates/…/remote.rs• L56-65 crates/…/remote.rs• L187-245 crates/…/remote.rs• L318-437 crates/…/surfnet_lite_svm.rs• L208-268
RPC runtime bridge
The RPC servers share a SurfnetMiddleware that carries the SVM locker, command sender, optional remote client, RPC settings, cheatcode settings, and plugin command sender. For each request, the middleware builds a RunloopContext, which gives an endpoint a read path into current state and a command path into the live loop.
This creates two clear relationships. Read-oriented RPC methods use the locker to inspect a consistent SVM view. Mutating or time-sensitive methods send a SimnetCommand so the live loop remains the owner of ordered state changes. WebSocket requests receive the same runtime context plus a subscription session. The middleware also applies Surfnet cheatcode access rules before dispatch, including for individual calls inside a batch, so gated methods cannot bypass the same runtime boundary.
References: crates/…/mod.rs• L47-70 crates/…/mod.rs• L73-109 crates/…/mod.rs• L143-229 crates/…/mod.rs• L247-345
RPC server lifecycle
The runloop checks both configured addresses before it starts the servers. It then creates the HTTP and WebSocket handlers from the shared middleware and keeps close handles for both services. Each server reports its bind result through the startup handshake, so a bind failure becomes an aborted runtime event instead of a hidden channel failure. If WebSocket startup fails after HTTP startup succeeds, the runloop closes HTTP before it returns the error.
The WebSocket service owns the async runtime used by its request and subscription work for the life of the server. This keeps startup and shutdown errors on the server lifecycle path and prevents a failed bind from masking the real cause. During shutdown, active WebSocket sessions receive close requests and a short grace period before the server closes. Shutdown then follows the reverse direction: a termination command closes the state service and invokes both RPC close handles on a separate thread. The HTTP and WebSocket handlers publish shutdown events after their server waits finish.
References: crates/…/mod.rs• L1082-1198 crates/…/mod.rs• L1200-1255 crates/…/mod.rs• L1257-1383 crates/…/mod.rs• L594-603
RPC-driven operations
RPC methods use the bridge according to the kind of work they request. Airdrops change state directly through the locker and notify the command loop so transaction-driven production can confirm the resulting block. Transaction submission sends a command and waits for the loop's status response. Administrative exit sends Terminate, which makes the same lifecycle path available to an RPC client.
The RPC surface therefore does not form a second execution engine. It is the client-facing edge of the runloop: it reads shared state, submits ordered commands, and receives status or event results. See RPC surface and subscriptions for the method families that use this bridge.
References: crates/…/full.rs• L1704-1724 crates/…/full.rs• L1727-1779 crates/…/admin.rs• L193-210
Event and plugin loops
The Geyser loop consumes runtime events and forwards account, transaction, slot, block, and entry updates to loaded Geyser plugins. It loads configured plugins during startup and can also handle load, unload, reload, and list commands from the RPC side.
The loop keeps plugin work separate from the SVM command loop. A plugin error is reported through runtime events, while the plugin handler can continue to process later events. A closed event or command channel ends the plugin handler and records the reason for observability.
References: crates/…/mod.rs• L87-167 crates/…/mod.rs• L832-1080 crates/…/mod.rs• L266-294
Clock loop
The clock loop runs on its own thread and emits Tick events at the configured slot interval while enabled. It consumes pause, resume, toggle, and interval-update commands, then reports clock changes through the Surfnet event channel.
The clock keeps a deadline-based cadence instead of sleeping for a full interval after each tick. Its bounded event channel holds at most one pending tick. When the consumer or host falls behind, the clock skips missed deadlines and increments the coalesced-slot count only when clock-driven block production is active. It warns once for each stretch of lag.
The clock does not produce blocks by itself. It supplies timing signals to the live command loop, which decides whether the current production mode turns a tick into a confirmed block.
References: crates/…/mod.rs• L729-829 crates/…/mod.rs• L421-451
Shutdown and ownership
The command channel is the main control boundary for runtime lifetime. RPC exit, CLI shutdown paths, and idle expiry can all reach the same Terminate handling, which checkpoints storage before closing RPC services and ending the live loop.
The Rust SDK starts the core runloop on a named background thread, waits for the startup event, and returns only after the local RPC and WebSocket addresses are available. Its returned Surfnet value retains the command sender and state handle so the caller can use the service and later stop it through the same lifecycle boundary.
References: crates/…/mod.rs• L594-603 crates/…/surfnet.rs• L140-240
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the meaning of
CoreStartedseparate from publicReady; changing either event can break SDK startup waits and CLI readiness planning. - Keep every new startup task wired through the full seal, start, work, and complete path; an omitted completion leaves clients waiting for readiness.
- Preserve command ordering when adding RPC mutations or startup work; state visibility depends on the order of messages on
SimnetCommand. - Keep RPC close handles aligned with every server started by
start_rpc_servers_runloop; otherwise termination can leave a listener alive after the SVM stops. - Keep HTTP rollback aligned with WebSocket startup; a later server failure must not leave an earlier listener serving on its port.
- Keep clock-triggered and command-triggered block production paths consistent when changing
BlockProductionModeor adding a new event source. - Preserve the one-tick clock queue and coalesced-slot accounting; replaying missed ticks can create a burst of visible slots.
- Keep transaction-mode follow-up scheduling aligned with pending-finalization state; dropping the queued turn can leave transactions unconfirmed.
- Keep the pending-signature marker paired with the command send and completion path; stale markers can make an already-finished transaction look queued.
- Keep bundle sandbox commits behind the live-state revision check; committing a stale sandbox can overwrite a newer RPC or cheatcode mutation.
- Keep datasource deadlines and the separate datasource runtime in place; moving provider work onto a blocked RPC worker can deadlock a request against the runloop.
- Keep plugin lifecycle commands on the plugin channel and runtime state commands on the simnet command channel; crossing them can stall or misroute control work.
- Keep idle expiry on the same termination path as explicit shutdown; changing the update timestamp or tick check can leave inactive services running.
- Keep WebSocket session closure ahead of server closure; reversing that order can drop close frames and leave clients without a clean shutdown signal.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| RPC or WebSocket port is already in use | Startup fails before the service can accept requests | Address availability is checked before server creation, and bind errors are returned through the startup handshake and published as an abort |
| WebSocket binding fails after HTTP has started | HTTP can keep its listener unless the partial startup is rolled back | The server coordinator closes the HTTP handle before it returns the WebSocket startup error |
| Startup plan is not sealed | Public readiness cannot reach Ready | The runloop seals an empty plan in default mode; the external planner must complete the seal round trip |
| Remote account fetch fails | The hydration task becomes failed and readiness cannot complete | The command loop completes RemoteAccounts with an error and publishes the failure |
| Startup runbook panics or returns errors | The runbook task fails and a headless session is terminated | The worker catches panics and always sends task completion; the watchdog handles terminal failure |
| The live command loop stops receiving commands | RPC mutations cannot complete and startup seals can time out | Callers treat a closed or timed-out command response as an unavailable runtime |
| A datasource request hangs or returns a provider error | Account hydration or an RPC read can appear stuck or expose an unsafe upstream error | Datasource calls use an outer deadline, a separate runtime, and sanitized endpoint errors |
| Live state changes while a bundle sandbox runs | A successful bundle cannot be applied without risking a lost concurrent update | The runtime rejects stale sandbox commits and retries from a fresh snapshot before giving up |
| A termination path drops RPC close handles | RPC listeners can outlive the state service | Termination takes the close callback and runs both server closes before the loop exits |
| No state update arrives before the idle expiry window | The runtime terminates even though its process is still running | The clock checks the last update time and sends Terminate through the normal shutdown path |
| WebSocket sessions are closed only after the server stops | Clients can miss normal close frames during shutdown | The WebSocket close handle closes tracked sessions, waits briefly, and then closes the server |
| The live loop falls behind the clock | Replayed ticks can produce a burst of slots or hide the amount of lag | The clock keeps one pending tick, skips missed deadlines, and counts coalesced slots in clock mode |
Key files
| File | Why to read it |
|---|---|
| crates/…/mod.rs | Primary lifecycle coordinator for startup, clock, RPC, Geyser, block production, and shutdown |
| crates/…/mod.rs | Defines the context and middleware bridge between RPC handlers and runtime state or commands |
| crates/…/types.rs | Defines the command and event contracts shared by runtime loops and clients |
| crates/…/startup.rs | Defines the public startup phases and task transitions that control readiness |
| crates/…/jito.rs | Shows isolated bundle execution, stale-state retry, and atomic commit behavior |
| crates/…/remote.rs | Shows the bounded and isolated path to the optional remote datasource |
| crates/…/locker.rs | Provides the guarded state boundary used by the runloops and RPC handlers |
| crates/…/startup.rs | Shows how the external planner seals and dispatches project startup work |
| crates/…/surfnet.rs | Shows how an embedded caller starts the runloop and waits for service startup |