Principle:AI Shell Team Aish Background Driver Spawn
| Knowledge Sources | |
|---|---|
| Domains | MCP, Concurrency |
| Last Updated | 2026-10-29 00:00 GMT |
Overview
Pattern for starting one background task per enabled server that owns the complete connect-session-reconnect cycle, with epoch-based staleness detection.
Description
Background Driver Spawn is the mechanism that launches one tokio task per enabled server when the manager starts. Each driver owns the complete lifecycle for its server: it attempts to connect, runs the session, and handles reconnection on failure. A driver is identified by a (generation, epoch) pair: the generation is global (incremented on shutdown/reload), and the epoch is per-server (incremented on each new driver spawn).
Before spawning, the driver checks that no driver is already attempting the server, that the server is not already connected and alive, and that the shutdown signal has not fired. If any condition fails, the spawn is skipped. The driver's state writes go through driver_update, which drops writes when the (generation, epoch) pair is stale, preventing a superseded task from resurrecting a torn-down connection.
This pattern solves the problem of managing concurrent server lifecycles without race conditions: each server has exactly one driver at a time, and stale drivers cannot interfere with new ones.
Usage
Use this principle when each server needs a dedicated background task for its lifecycle. The epoch-based staleness check is essential for hot-reload: when a server is reconfigured, a new driver is spawned with a new epoch, and the old driver's writes are silently dropped.
Theoretical Basis
The spawn is a guarded task launch with epoch tracking:
# Abstract algorithm (NOT real implementation)
def spawn_driver(name, handle):
with state_lock:
if shutdown_rx.is_set() or not runnable(name) or state.attempting:
return False
if is_connected(state) and connection.is_alive():
return False # already up
state.attempting = True
state.epoch += 1
epoch = state.epoch
generation = self.generation.load()
handle.spawn(drive_server(name, generation, epoch))
return True
Key design ideas:
- One driver per server: the attempting flag and connection liveness check prevent duplicate drivers
- Epoch staleness: every state write checks (generation, epoch) and drops if stale
- Immediate return: the spawn returns immediately; progress is observed via snapshots