super fast nix deploys
stoker SPEC.md
24 kB 371 lines
Markdown
at main

stoker: Technical Specification #

stoker is a Tailscale-native, warm-store deployment orchestrator for heterogeneous NixOS and nix-darwin fleets. It replaces ephemeral CI builds and ad-hoc SSH pushes with persistent, warm-store hosts authenticated directly by Tailscale identity, exact derivation diffing, and crash-safe automatic rollback.


1. Problem & Goals #

Standard Nix CI deploys run on ephemeral cloud VMs with empty /nix/store directories. On a 3-line NixOS module edit, an ephemeral runner spends 95%+ of its wall-clock time re-downloading flake inputs, pulling gigabytes of already-cached store paths just to assemble etc.drv and system-units.drv, and shipping a few kilobytes of diff back to hosts that already had 99.9% of the closure on disk.

Existing tools each solve one slice of this:

  • deploy-rs has magic rollback and nix-darwin support, but is stateless SSH push, struggles across architectures, and lacks .drv diffing.
  • comin keeps stores warm via pull-based GitOps, but forces weak hosts to build locally, has no central builder routing, and has no failure-triggered rollback.
  • colmena does parallel push, but has no magic rollback and no nix-darwin support.
  • None use Tailscale identity as the auth and transport layer.

Design Goals #

  1. 15 to 25 second deploys for normal config changes on warm hosts; <5 seconds to skip unchanged hosts.
  2. Zero public webhooks, zero SSH keys, zero bearer tokens. All control-plane traffic stays on the tailnet and authenticates via Tailscale WhoIs.
  3. Exact change detection. Decide which hosts need deploying by evaluating .drv / output paths and comparing against what is actually running, never by path regexes.
  4. First-class NixOS and nix-darwin. Both platforms get detached activation, closure diffs, and working automatic rollback.
  5. Smart build routing. Build where the store is already warm; offload heavy compiles from weak hosts to fast builders of matching architecture.
  6. Bulletproof rollback. A broken network config, broken Tailscale config, or self-upgrade of stoker itself must never strand a host.

Non-Goals #

  • Initial machine provisioning (use nixos-anywhere / disko).
  • Secret management (keep agenix / sops-nix).
  • Replacing binary caches (stoker complements attic or cachix, it does not serve NARs itself).

2. Architecture Overview #

stoker ships as a single static Go binary (x86_64-linux, aarch64-linux, aarch64-darwin) with three subcommands:

  • stoker coordinator: Runs on one always-on host (e.g., prattle). Maintains a warm git checkout and warm Nix eval-cache, evaluates the flake, diffs each target's derivation against live state, routes builds, triggers activations, and streams logs to callers.
  • stoker agent: Runs as a root daemon on every managed host (including the coordinator host itself). Exposes a tiny Tailscale-only HTTP API for status, local builds, detached activation, and rollback confirmation.
  • stoker (CLI): Invoked from a developer laptop or a thin GitHub Action. Connects to the coordinator over Tailscale, triggers a deploy, streams structured progress/logs, and exits with a clean status code.
  [GitHub Action (tag:deploy)]  or  [Developer Laptop (atalanta)]
                      |
                      | HTTPS/HTTP over Tailscale (WhoIs auth)
                      v
         +-------------------------+
         |   stoker coordinator    |  (on prattle: warm git + warm eval-cache)
         +-------------------------+
           |          |          |
     Tailscale    Tailscale   Tailscale  (WhoIs auth: coordinator node only)
           v          v          v
     +---------+ +---------+ +---------+
     | prattle | |  beef   | |terebithia|
     | (agent) | | (agent) | | (agent)  |
     | x86_64  | | darwin  | | aarch64  |
     | builder | | builder | |  light   |
     +---------+ +---------+ +---------+
           \          |          /
            \         v         /
             +-----------------+
             |  attic (cache)  |  (http://prattle:8091/dots)
             +-----------------+

3. Transport & Authentication #

Stoker does not expose anything to the public internet, does not require GitHub webhooks, and does not manage SSH keys or sudoers rules.

Tailscale LocalClient.WhoIs #

Both the coordinator and every agent bind exclusively to the host's Tailscale IPv4/IPv6 address (discovered via tailscale.LocalClient.Status at startup, with retry until tailscaled is ready).

On every incoming HTTP request, the server calls LocalClient.WhoIs(ctx, req.RemoteAddr):

  1. If WhoIs fails or returns no peer, reject with 403 Forbidden.
  2. Extract the peer's tags (Node.Tags) and user login (UserProfile.LoginName).
  3. Enforce role-based policy from config:
    • Coordinator endpoints (/deploy, /rollback): allowlisted Tailscale tags (e.g. tag:deploy) and/or specific user logins (e.g. kierank@...).
    • Coordinator read-only endpoints (/status, /diff): broader tailnet allowlist (e.g. monitoring/status page or any authorized user).
    • Agent endpoints (/build, /activate, /confirm, /rollback): strictly restricted to the coordinator's Tailscale node/tag (e.g. tag:stoker-coordinator or explicit coordinator node ID).
    • Agent read-only endpoint (/status): coordinator + authorized users.

Why LocalClient.WhoIs over embedded tsnet?

  • Reuses each host's existing tailscaled daemon, routes, and MagicDNS.
  • Zero extra Tailscale auth keys to rotate or store in agenix.
  • Zero extra nodes cluttering the tailnet admin console.
  • (An optional --tsnet mode can be added later if a host ever runs without system tailscaled, since both expose the exact same WhoIs interface.)

Security Boundary #

  • Agents never accept arbitrary shell commands. /activate only accepts a validated /nix/store/<hash>-<name> path that exists in the local store (or can be substituted from configured trusted substituters / signed cache).
  • The coordinator only deploys commits from its configured git repository and allowed branches (default: main, or explicit SHA reachable from the configured remote).

4. Configuration #

Coordinator Config (/etc/stoker/coordinator.toml) #

listen_port = 7420
repo_url = "https://github.com/taciturnaxolotl/dots.git"
default_branch = "main"
workdir = "/var/lib/stoker/repo"
state_dir = "/var/lib/stoker"
cache_push_cmd = ["attic", "push", "dots"] # optional, best-effort after build

[auth]
allowed_tags = ["tag:deploy"]
allowed_users = ["kieran@dunkirk.sh"]

# Optional: read nodes from a file in the repo (like lib/deploy-targets.json)
# or declare them explicitly below.
[nodes.prattle]
address = "prattle:7421"
system = "x86_64-linux"
platform = "nixos"
flake_attr = "nixosConfigurations.prattle"
role = "builder"

[nodes.beef]
address = "beef:7421"
system = "aarch64-darwin"
platform = "darwin"
flake_attr = "darwinConfigurations.beef"
role = "builder"
extra_systems = ["aarch64-linux"] # via darwin.linux-builder VM

[nodes.terebithia]
address = "terebithia:7421"
system = "aarch64-linux"
platform = "nixos"
flake_attr = "nixosConfigurations.terebithia"
role = "light"
builder_fallback = "beef"         # offload heavy compiles here
light_drv_budget = 25             # build locally if <= N trivial drvs unbuilt

Agent Config (/etc/stoker/agent.toml) #

listen_port = 7421
platform = "nixos" # or "darwin"
state_dir = "/run/stoker" # /var/run/stoker on darwin
confirm_timeout = "60s"
activation_timeout = "240s"

[auth]
allowed_nodes = ["prattle"]       # Tailscale MagicDNS hostname or NodeID
allowed_tags = ["tag:stoker-coordinator"]

5. Exact .drv Diffing & Change Detection #

Regex-based path filtering (modules/ -> deploy everything) produces constant false positives. Stoker replaces it with Nix's own dependency graph:

  1. Coordinator runs git fetch origin in its persistent worktree (workdir) and checks out the target commit into a detached worktree (or evaluates git+file:///var/lib/stoker/repo?rev=<sha>).
  2. Because the coordinator's /nix/store and ~/.cache/nix/eval-cache-v* are persistent, flake inputs are already on disk unless flake.lock changed.
  3. For each requested node (in parallel, bounded concurrency), coordinator evaluates:
    • toplevel output path: nix eval --raw .#<attr>.config.system.build.toplevel.outPath
    • toplevel derivation path: nix eval --raw .#<attr>.config.system.build.toplevel.drvPath
  4. Coordinator queries GET /status on each target agent in parallel to get:
    • current_system: readlink -f /run/current-system
    • last_drv: last successfully activated .drv path (recorded by agent)
  5. Skip rule: If target.outPath == agent.current_system (and --force is not set), mark the node unchanged and skip it completely. Total time for an unchanged node: ~3 to 5 seconds of warm eval, 0 seconds of build/copy/activate.

6. Warm-Store Build Routing #

Once the coordinator knows which nodes actually changed, it decides where each node builds.

Case A: role = "builder" (e.g., prattle, beef) #

The target host itself has CPU, RAM, and a warm /nix/store.

  1. Coordinator sends POST /build to the host's agent with {repo_url, rev, flake_attr} (or copies the .drv closure via nix copy --derivation if the agent doesn't keep a git mirror; keeping a tiny shallow git checkout on builders avoids even copying .drv closures).
  2. The builder runs nix build --no-link --print-out-paths against its warm store.
  3. If cache_push_cmd is configured, the builder pushes newly created outputs to attic in the background (non-blocking or best-effort, never fails a deploy).

Case B: role = "light" (e.g., terebithia) #

Small VPSes have warm stores for runtime closures, so building 8 tiny config derivations (etc.drv, system-units.drv, activate.drv) locally takes ~3 seconds and requires zero network transfer. Compiling a Rust or Go package locally would thrash the VPS.

Stoker uses a two-path heuristic:

  1. Coordinator inspects the unbuilt derivations for the node (nix build --dry-run --json or checking which .drv outputs are missing from both the target and attic).
  2. Fast path (config-only change): If the number of unbuilt derivations is within light_drv_budget and none are flagged as heavy (or all match cheap builders like etc, unit-*, activate, nixos-system-*, dry-activate, boot.json, system-path, manifest), instruct terebithia's agent to build locally directly against its warm store.
  3. Offload path (package compile needed): Route the build to builder_fallback (e.g., beef, which has aarch64-linux via darwin.linux-builder with native Apple Silicon virtualization and a warm store). The builder compiles the package, pushes the output to attic, and terebithia substitutes only the new store paths from attic before activating.

If builder_fallback is offline, stoker either falls back to building on the target (configurable) or fails cleanly with a clear reason.


7. Bulletproof Activation & Rollback Protocol #

This is the core reliability contract. Every failure mode must leave the host reachable on Tailscale and running a known-good generation.

7.1 Single-Flight Locking #

Each agent holds an exclusive file lock (/run/stoker/deploy.lock). If a deploy is already in progress, a new /activate request immediately returns 409 Conflict with the active deploy ID. The coordinator also serializes per-node deploys and cancels/queues overlapping runs cleanly.

7.2 Detached Execution (Surviving Self-Upgrades) #

If a deploy upgrades stoker-agent itself, switch-to-configuration will restart the stoker-agent service. If the switch ran as a child process of stoker-agent, systemd/launchd would kill the switch mid-flight.

Therefore, /activate never runs activation in-process:

  • NixOS: Spawns a transient detached unit via systemd-run --unit=stoker-activate-<id> --collect --no-block ....
  • nix-darwin: Spawns a detached job via launchctl (or a detached helper binary outside the agent's launchd job).

7.3 State Machine & Dead-Man's Switch #

Before switching, the agent writes /run/stoker/pending.json (atomically via write + rename):

{
  "deploy_id": "01J...",
  "previous_path": "/nix/store/...-nixos-system-...",
  "target_path": "/nix/store/...-nixos-system-...",
  "previous_generation": 42,
  "started_at": "2026-11-28T19:00:00Z",
  "confirm_deadline": "2026-11-28T19:01:00Z",
  "status": "activating"
}

Then the detached activator executes:

  1. Arm independent watchdog: Starts a separate detached watchdog unit (stoker-watchdog-<id>) that sleeps until confirm_deadline (default: 60s after activation finishes). The watchdog is a tiny subcommand (stoker watchdog --state /run/stoker/pending.json).
  2. Realize & register profile:
    • Ensure target_path is present in /nix/store (substituting from attic / cache.nixos.org if built on a remote builder).
    • Set the system profile: nix-env -p /nix/var/nix/profiles/system --set <target_path>.
  3. Activate:
    • NixOS: <target_path>/bin/switch-to-configuration switch
    • nix-darwin: <target_path>/activate (note: modern nix-darwin runs activate-user + activate as root, or uses darwin-rebuild's exact activation sequence).
    • If activation exits non-zero, immediately run the rollback procedure (Section 7.4) and mark pending.json as rolled_back.
  4. Await confirmation:
    • Activator updates pending.json to "status": "awaiting_confirm" with confirm_deadline = now + confirm_timeout.
    • Coordinator polls GET /activation/<id> over Tailscale until it sees awaiting_confirm.
    • Coordinator runs optional post-activation health probes (e.g. Tailscale reachable is already proven by the HTTP call itself; optional custom checks like systemctl is-system-running --wait or HTTP checks).
    • Coordinator sends POST /confirm/<id> over Tailscale.
  5. Confirm & disarm:
    • Agent verifies deploy_id matches pending.json, writes "status": "confirmed", removes pending.json, and stops the watchdog unit.
    • Because state lives in /run/stoker/pending.json, even if stoker-agent was restarted by the switch, the new agent instance reads pending.json and handles POST /confirm/<id> seamlessly.
  6. Watchdog expiry (dead-man's switch):
    • If confirm_deadline passes and pending.json still exists without "status": "confirmed", the watchdog triggers rollback automatically.
    • This catches broken firewall rules, broken tailscaled, broken DNS, crashed stoker-agent, or a crashed coordinator.

7.4 Platform-Specific Rollback #

NixOS Rollback:

  1. nix-env -p /nix/var/nix/profiles/system --set <previous_path>
  2. <previous_path>/bin/switch-to-configuration switch
  3. Record failure reason in /var/lib/stoker/last-result.json.

nix-darwin Rollback (explicitly avoiding deploy-rs's bug): In deploy-rs, darwin rollback fails when trying to invoke nix-darwin's generation switcher through nix-env --rollback / broken environment variables. Stoker instead rolls back deterministically using the exact saved store path:

  1. nix-env -p /nix/var/nix/profiles/system --set <previous_path>
  2. Execute <previous_path>/activate directly with a clean root environment (PATH containing /nix/var/nix/profiles/default/bin:/usr/bin:/bin:/usr/sbin:/sbin).
  3. Verify /run/current-system resolves to <previous_path> and tailscaled is up.

8. HTTP/RPC Wire Protocol #

Plain JSON over HTTP/1.1 (Tailscale WireGuard already provides encryption and mutual authentication; no TLS cert management needed inside the tailnet). Streaming endpoints use NDJSON (application/x-ndjson) so both CLI and GitHub Actions can render live logs cleanly.

Coordinator Endpoints #

Method Path Description
GET /health Liveness check (200 OK).
GET /status Fleet-wide summary: per-node current rev, system path, last deploy time, health, active lock.
POST /diff Body: {"rev": "HEAD", "nodes": []}. Evaluates and returns per-node changed bool + closure diff without deploying.
POST /deploy Body: {"rev": "sha-or-ref", "nodes": [], "dry_run": false, "force": false}. Streams NDJSON events until all targeted nodes finish.
POST /rollback Body: {"nodes": ["beef"]}. Manually rolls back specified nodes to their previous generation.

Agent Endpoints #

Method Path Description
GET /status Returns {hostname, system, platform, current_system, last_drv, pending, uptime}.
POST /build Body: {"rev": "...", "flake_attr": "...", "repo_url": "..."}. Streams build log NDJSON, ends with {out_path, drv_path, built_drvs}.
POST /activate Body: {"deploy_id": "...", "target_path": "...", "drv_path": "..."}. Starts detached activation, returns immediately with 202 Accepted.
GET /activation/{id} Returns current state (activating, awaiting_confirm, confirmed, rolled_back, failed) + log tail.
POST /confirm/{id} Disarms watchdog and finalizes the deployment.
POST /rollback Immediately rolls back to previous generation.

NDJSON Event Schema (Coordinator -> CLI / CI) #

{"ts":"...","node":"prattle","phase":"eval","msg":"drv changed: /nix/store/..."}
{"ts":"...","node":"beef","phase":"eval","status":"skipped","msg":"unchanged"}
{"ts":"...","node":"terebithia","phase":"eval","status":"offline","error":"agent terebithia GET .../status: dial tcp ...: i/o timeout"}

An offline node is one whose agent could not be reached at all. It is a warning, not a failure: the rest of the fleet deploys, the deploy still finishes ok, and the node is caught up by the next deploy because drv diffing compares against what it actually runs.

{"ts":"...","node":"prattle","phase":"build","msg":"building 12 derivations locally"}
{"ts":"...","node":"prattle","phase":"diff","added":0,"removed":0,"updated":1,"summary":"crushling: 0.1.0 -> 0.1.1"}
{"ts":"...","node":"prattle","phase":"activate","msg":"switching generation"}
{"ts":"...","node":"prattle","phase":"confirm","status":"ok","duration_ms":14200}

9. Closure Diffing & Observability #

Before (or right after) switching, the agent computes a closure diff between previous_path and target_path using store-path runtime references (nix path-info -r or direct SQLite read of /nix/var/nix/db/db.sqlite / invoking dix if present).

  • Shows added, removed, and version-bumped packages right in the CLI and GitHub Actions log.
  • Stored in /var/lib/stoker/history.jsonl (ring buffer of last 50 deploys) so stoker history works from anywhere on the tailnet.
  • Coordinator /status JSON is directly consumable by status pages (e.g. infra.dunkirk.sh).

10. CLI & CI Integration #

CLI UX #

stoker status                    # table of all nodes: rev, drift, last deploy, health
stoker diff                      # evaluate HEAD and show which nodes would deploy + why
stoker deploy                    # deploy main to all changed nodes
stoker deploy --node prattle     # deploy only prattle
stoker deploy --rev <sha>        # deploy a specific commit
stoker rollback prattle          # roll back prattle to previous generation

GitHub Actions Integration (10-second trigger) #

The existing .github/workflows/deploy.yaml shrinks to two tiny jobs:

  1. deploy: ubuntu-latest -> tailscale/github-action (tag:deploy) -> run stoker deploy --rev ${{ github.sha }} (a single prebuilt static binary, ~5 MB, zero Nix install on the runner!). Streams the full fleet logs straight into the GitHub Actions UI and exits non-zero if any node fails.
  2. docs: stays gated on needs: deploy, unchanged.

This keeps GitHub commit status checks, concurrency locks, and the docs gate intact while cutting runner setup from ~60s + 5.6 GiB downloads down to ~5s.


11. NixOS & nix-darwin Packaging #

The stoker flake exports:

  • packages.<system>.stoker — single Go binary (buildGoModule, CGO disabled on Linux).
  • nixosModules.coordinator — systemd service (stoker-coordinator), user stoker, persistent /var/lib/stoker, Nix eval access, firewall rule allowing listen_port on tailscale0 only.
  • nixosModules.agent — systemd service (stoker-agent), runs as root (required for switch-to-configuration), firewall rule on tailscale0 only.
  • darwinModules.agent — launchd.daemons.stoker-agent, compatible with both nix.enable = true and Determinate Nix (nix.enable = false, reading /nix/var/nix/profiles/default/bin).

12. Failure Modes Matrix #

Failure What happens Recovery
New config breaks tailscaled or firewall Coordinator cannot reach /confirm over Tailscale. Watchdog expires after 60s and reverts to previous_path. Tailscale comes back.
Deploy upgrades stoker-agent itself Detached systemd-run / launchctl finishes switch while agent restarts. New agent reads /run/stoker/pending.json. Coordinator's /confirm hits the new agent and disarms watchdog. If new agent crashes on boot, watchdog reverts.
Coordinator crashes mid-deploy Agent never receives /confirm. Watchdog reverts cleanly after 60s.
Activation script fails mid-switch Detached activator catches non-zero exit. Immediate rollback without waiting 60s; error returned to coordinator.
Two pushes trigger deploys simultaneously Coordinator queues or rejects; agent file lock rejects concurrent /activate with 409. Second deploy runs cleanly after first completes (or evaluates latest SHA).
attic binary cache is down Build still succeeds using cache.nixos.org + local warm store; cache push is best-effort. Warning logged; deploy succeeds.
builder_fallback (beef) is asleep/offline Coordinator detects unreachable builder before starting activation. Either falls back to local build on target (if allowed) or fails fast before touching the target's running generation.
Host reboots while pending.json exists /run/stoker is tmpfs (cleared on reboot); system boots into whichever profile was last set. On NixOS, boot loader entries are only updated after /confirm (optional enhancement: switch-to-configuration test before confirm, boot after confirm, so even a hard power-cut during activation boots the old generation!).

Subtle NixOS win from the last row: Running switch-to-configuration test before /confirm and switch-to-configuration boot after /confirm means even a kernel panic or sudden power loss during the 60s confirmation window automatically reboots into the previous known-good generation.


13. Implementation Roadmap #

Phase 1: MVP (Working 20-second deploys) #

  • Go module setup + flake.nix with packages, nixosModules, darwinModules.
  • Tailscale LocalClient.WhoIs middleware + config loader.
  • agent: /status, /build, detached /activate, /confirm, watchdog rollback (NixOS + nix-darwin).
  • coordinator: warm git worktree, .drv / outPath diffing, parallel per-node deploy with NDJSON streaming.
  • cli: stoker deploy, stoker status, stoker diff.
  • Wire up prattle, terebithia, beef and swap .github/workflows/deploy.yaml to the thin trigger.

Phase 2: Smart Builder Routing & Hardening #

  • light vs builder heuristic (inspect unbuilt .drv count, offload heavy compiles for terebithia to beef's linux-builder + attic).
  • NixOS two-stage test -> /confirm -> boot so even power-loss mid-deploy rolls back on reboot.
  • Integration tests in NixOS VM (nixosTest) explicitly testing: broken firewall rollback, self-upgrade survival, and concurrent deploy locking.

Phase 3: Polish & Observability #

  • Built-in closure diffing (package added/removed/updated summary in CLI & CI logs).
  • Deploy history ring buffer (stoker history, stoker rollback).
  • Optional infra.dunkirk.sh integration via /status.