Files
spinifex/docs/DESIGN.md
Josh Siviour ea1ca38c52 fix: boot LB and SQS worker microvms with PCIe NICs (#1385)
* test: direct-boot LB and SQS worker NICs must be virtio-net-pci on microvm pcie=on

* fix: boot LB and SQS worker microvms on PCIe with virtio-net-pci NICs

virtio-mmio devices share level-triggered IRQ lines and a NIC's RX path
stalled on them. The direct-boot machine gets pcie=on, so NICs are
virtio-net-pci with MSI-X, and the virtio_mmio.device= kernel args go.
IsMMIO is now the transport check (false with pcie=on) and IsMicrovm the
machine check. Data volumes keep their serial and ID on virtio-blk-pci.
The LB guest console loglevel is raised to 7.

* refactor: trim microvmMachineType comment

* docs: describe direct-boot microVM NICs and data volumes on PCIe
2026-11-01 20:51:40 +10:00

46 KiB
Raw Permalink Blame History

Spinifex Architecture

Spinifex is an AWS-compatible infrastructure platform for bare-metal, edge, and on-premise deployments. It provides EC2-compatible VM orchestration backed by QEMU/KVM, with storage provided by companion projects Viperblock (EBS) and Predastore (S3).

High-Level Architecture

Spinifex high-level architecture — AWS SDK, gateway, NATS broker, per-node daemons, QEMU/KVM VMs

Request Flow

1. AWS SDK Request

Users interact with Spinifex using standard AWS SDKs or the AWS CLI by using the spinifex profile.

AWS_PROFILE=spinifex aws ec2 run-instances \
    --image-id ami-debian13 \
    --instance-type t3.micro \
    --key-name my-keypair

The AWS SDK formats this as an HTTPS POST with:

  • AWS SigV4 authentication headers
  • EC2 Query Protocol body (Action=RunInstances&ImageId=ami-debian13&...)

2. AWS Gateway

The gateway (spinifex/runtime/roles/awsgw/awsgw.go) is the entry point:

// Connect to NATS (retries while the local broker comes up)
natsConn, err := natsmsg.ConnectNATSWithRetry(...)

// Load IAM (master key + JetStream KV), then compose the gateway: composeGateway
// sets every production hook and wires the service registry from each domain's
// awsapi registration.
gw, err := composeGateway(gatewayInputs{
    NATS:        natsConn,
    IAM:         iamService,
    Credentials: credentials,
    Admission:   admission,
    // ...
}, ecrControlPlane, acmControlPlane, ec2ControlPlane /* ... */)

// Serve over TLS
server.ListenAndServeTLS("", "")

Request routing (spinifex/ingress/aws/pipeline/gateway.go):

  1. Public routes: /oidc/eks/... and /v2 (the ECR registry) are mounted ahead of SigV4 by runtime/roles/awsgw
  2. Authentication: SigV4 middleware validates AWS credentials and resolves the account ID
  3. Throttling: Per-account+action token bucket rejects bursts post-auth
  4. Service Detection: Extracts service name from the Authorization header
  5. Action Dispatch: Every service is a registration (ingress/aws/dispatch) built by its domain's awsapi.NewRegistration and wired by runtime/roles/awsgw. The pipeline dispatches by registered service name and holds no per-service code. The private /admin/<Method> surface dispatches to the registration awsgw names as Admin.Service.

3. EC2 Handler

The EC2 registration (spinifex/domains/ec2/awsapi, NewRegistration) parses the Action parameter and looks the handler up in its action table. The account ID resolved by SigV4 auth is threaded into every handler so requests are scoped per IAM principal. Each action's handler is built from the owning EC2 resource package (domains/ec2/instance, volume, vpc and so on), with PassRole, quota and client-token idempotency wrapped on at the action table rather than inside the resource.

4. NATS Messaging

The gateway communicates with daemons via NATS request/response. Most calls go through natsmsg.NATSRequest, which marshals the input, attaches the account ID as a NATS header, and unmarshals the typed response:

func (s *NATSInstanceService) RunInstances(ctx context.Context, input *ec2.RunInstancesInput, accountID string) (*ec2.Reservation, error) {
    topic := fmt.Sprintf("ec2.RunInstances.%s", aws.StringValue(input.InstanceType))
    return natsmsg.NATSRequest[ec2.Reservation](ctx, s.natsConn, topic, input, 5*time.Minute, accountID)
}

The gateway's RunInstances places instances itself (domains/ec2/awsapi/instance/placement.go): it gathers capacity from every node on spinifex.node.status, spreads the launch across eligible nodes, and sends each node its share on the node-targeted subject ec2.RunInstances.{type}.{nodeId}, rolling back on partial failure.

Cross-Process Contract Ownership

NATS subjects and JSON payloads that cross a process boundary are contracts, not incidental implementation details. A domain owns its named and versioned contract under contracts/<domain>/vN; consumers own only their narrow in-process capability interfaces, and runtime composition wires the two.

The first realised example is the EC2 instance-command contract. ec2.cmd.<instance-id> is deliberately a targeted request/reply route: only the node that owns the QEMU process may execute a live-instance command. Its JSON shape and ec2.cmd.* subject form are compatibility-tested. The wildcard matches one final instance-ID token; it is not a broad descendant subscription.

Changing that subject shape or a JSON field is a contract change, not a refactor. It needs a versioned successor or an explicit compatibility plan.

5. Daemon Processing

Daemons (spinifex/runtime/daemon/daemon.go) subscribe to NATS topics and handle requests. A table-driven subscribeAll() registers the static EC2/ELBv2 surface at startup:

// Queue group → load-balanced (one daemon handles each request)
{"ec2.CreateKeyPair", handleNATSRequest(d.node, d.keyService.CreateKeyPair), "spinifex-workers"},

// No queue group → fan-out (every daemon responds)
{"ec2.DescribeInstanceTypes", handleNATSRequest(d.node, d.instanceService.DescribeInstanceTypes), ""},

ec2.RunInstances is dynamic: ResourceManager subscribes to ec2.RunInstances.{type} only while the node has capacity for that type, and unsubscribes when full. The node-targeted subject ec2.RunInstances.{type}.{nodeId} stays subscribed even at full capacity — the launch-time allocate() enforces limits there. Per-instance commands flow over ec2.cmd.{instanceID}, subscribed only by the owning node.

Queue Groups: topics with the spinifex-workers queue group are load-balanced — only one daemon handles each request. Topics without a queue group fan out to all daemons.

6. VM Launch

When a daemon handles RunInstances:

  1. Resource Check: Validates CPU/memory availability via ResourceManager
  2. Volume Generation: Creates boot and EFI volumes via Viperblock
  3. Volume Mount: Sends a mount request to the colocated Viperblock worker on ebs.{node}.mount, receives NBD URI
  4. QEMU Launch: Builds and executes QEMU command with NBD-backed disks
  5. QMP Monitoring: Establishes QEMU Machine Protocol connection for VM management
  6. Command subscription: Subscribes to ec2.cmd.{instanceID} for subsequent commands on this VM
// Volume mounting via NATS (runtime/daemon/vm_adapters.go)
reply, err := ebsRequestWithTrace(ctx, a.nc, instance.AccountID, viperblocklegacyv1.MountSubject(a.node), ebsMountRequest, 30*time.Second)

// QEMU launch with NBD-backed drives in args (runtime/compute/vm/vm.go)
cmd := exec.Command(qemuArchitecture, args...) // qemu-system-x86_64 or qemu-system-aarch64

Key Components

Daemon Structure

type Daemon struct {
    node          string                  // Node identifier
    clusterConfig *config.ClusterConfig   // Cluster-wide configuration
    config        *config.Config          // Node-specific configuration
    natsConn      *nats.Conn              // NATS connection
    resourceMgr   *ResourceManager        // CPU/Memory tracking + dynamic RunInstances subscriptions
    vmMgr         *vm.Manager             // Local VMs
    // ... + one service struct per EC2/ELBv2 resource
    //       (instance, key, image, volume, snapshot, tags, vpc, subnet,
    //        igw, eigw, natgw, routetable, eip, placementgroup, elbv2, ...)
}

Resource Manager

Tracks available and allocated CPU/memory to prevent overcommit, and drives the dynamic ec2.RunInstances.{type} subscriptions:

One instance vCPU is one CPU the kernel has online: a thread with SMT on, a core with SMT off or on ARM, as AWS counts a vCPU. The OS and Spinifex's own services keep 1 CPU on a host with up to 8, 2 up to 16, 4 up to 63 and 8 from 64, and every other CPU is schedulable one-to-one with no overcommit. ADR-0015 fixes this rule.

type ResourceManager struct {
    mu            sync.RWMutex
    hostVCPU      int                                // online CPUs (ADR-0015:S1)
    hostMemGB     float64                            // raw /proc/meminfo MemTotal
    reservedVCPU  int                                // ADR-0015:S2 tier: 1, 2, 4 or 8
    reservedMem   float64                            // held back for spinifex services
    allocatedVCPU int
    allocatedMem  float64
    instanceTypes map[string]*ec2.InstanceTypeInfo   // t3.micro, t3.small, etc.
    // ... + capacity-reservation accounting, GPU manager, nbdkit memory
    //       overhead tracking, and the dynamic-subscription state
}

Multi-Node Aggregation

For operations that need data from all nodes (like DescribeInstances), the gateway uses the scatter-gather helper natsmsg.Gather (spinifex/foundation/messaging/nats/nats.go), called from spinifex/domains/ec2/awsapi/instance/DescribeInstances.go:

// Publish to every node (no queue group = all daemons respond) and collect
// the replies. The account ID travels as a NATS header so each daemon scopes
// its response.
frames, sum, err := natsmsg.Gather(ctx, natsConn, "ec2.DescribeInstances", jsonData, gatherOpts)

Given the configured node IDs, Gather checks each reply's X-Node-ID header against them, and DescribeInstancesChecked fails closed rather than returning a partial listing when a node is missing, duplicated or unidentified.

Storage Integration

Viperblock (EBS)

Block storage volumes are managed via NATS messages to Viperblock:

// Volume mount request
type EBSRequest struct {
    Name      string  // Volume name (vol-xxxxx)
    VolType   string  // gp2, io1, etc.
    Boot      bool    // Boot volume flag
    EFI       bool    // EFI boot volume
    NBDURI    string  // NBD URI returned from mount
    // ... + DeviceName, DeleteOnTermination, hotplug port and host block-device fields
}

Viperblock responds with an NBD URI that QEMU uses to access the block device.

Direct-boot microVM data volumes

A direct-boot microVM keeps the launcher's saved vm.Config as a clean base, and startQEMU adds data volumes only to a launch-only copy of it (runtime/compute/vm/lifecycle.go). At each start the daemon takes one snapshot of the instance's already-mounted data requests, probes each NBD or host block export from that snapshot, and builds the command from the same snapshot, so the launched endpoint is the one that was checked and is never written back into the saved base. The microVM boots with pcie=on, so its NICs are virtio-net-pci devices with MSI-X interrupts instead of virtio-net-device MMIO devices. Each data volume becomes a virtio-blk-pci device on the default PCIe bus with the same id, node name, I/O thread, serial and werror=stop,rerror=stop policy as the q35 device, and takes no PCIe hot-plug port. A microVM started without pcie=on keeps the virtio-*-device MMIO transports.

Boot and EFI requests are rejected on this path, and a direct-boot instance with no data requests launches its base unchanged. Disk-boot (q35) instances keep the existing PCI hot-plug path.

Hot-attaching a volume to a running direct-boot microVM is not supported, because the microVM has no PCIe hot-plug root port to plug into. AttachVolume refuses it before mounting the volume or changing any instance or volume state, and the EC2 API returns UnsupportedOperation.

This covers only requests that are already mounted when the instance starts; nothing yet supplies data volumes to a system instance, and the path is verified with fake-QEMU unit tests, not with a real EBS volume in a guest.

Volume leases

Before opening an engine on a volume, the Viperblock worker takes a lease: one entry per volume in the VIPERBLOCK_VOLUME_LEASES JetStream KV bucket, which expires 45 seconds after its last write (providers/ebs/viperblock/volume_lease.go). A renewal becomes eligible once the last confirmed write is 10 seconds old, and the holder checks for that periodically, so the rewrite lands some time after that point. Each rewrite is conditioned on the revision the holder last wrote, and a refused write that finds the entry gone or naming another owner or generation fences the export as a takeover. It may keep writing for 40 seconds after the last write the store acknowledged, measured from when that write was sent, because the server starts the entry's expiry when it applies the write and never earlier. A slow acknowledgement therefore shortens the remaining validity rather than extending it, and an acquisition acknowledged after its validity has already run out is refused as retryable.

For a holder that cannot renew, a timer is armed for the validity deadline, leaving a nominal 5 seconds before the entry can expire; when it fires, the export's nbdkit is fenced with SIGKILL (volume_fence.go). The fence runs on its own goroutine, so Go scheduling, that goroutine and process termination all delay the kill, and enough delay can use up the whole margin; a kill held in uninterruptible sleep, which the fence waits up to 30 seconds for, is the extreme case. Once a lease is lost or has lapsed it stays lost: a renewal that succeeds afterwards is ignored, and another open on the same node cannot share it while the fence runs.

These rules bound only the holder's own clock. The storage backend does not reject a stale writer, so a paused or partitioned host that resumes after its validity can still write; generation enforcement at the write boundary is required by Q-24 in the umbrella repository's docs/specs/viperblock/rfc3-1_overview.md and is not implemented. An export that survives a daemon restart writes without a renewed lease until recovery adopts it, and a survivor that recovery cannot adopt while a guest still uses it is left running without a lease or a fence.

Unsealed writes and start elsewhere (interim)

A volume is unsealed while its node holds writes the backend has not confirmed; the node records this in a dirty marker naming itself as owner (providers/ebs/viperblock/volume_dirty.go). Opening such a volume on another node loses those writes, so two guards stop it while the previous owner may still hold them. This is an interim guard until the instance lifecycle work defines ownership, and it is not a fence.

When ec2.start is forwarded to the node that last ran a stopped instance and that node refuses for capacity, the forwarding node normally starts the instance locally. If the refusing node still holds unsealed writes for any of the instance's volumes, it sets the X-Unsealed-Writes NATS reply header and the forwarder relays InsufficientInstanceCapacity instead of starting elsewhere. The check asks the owner's viperblockd over the per-node unsealed verb with a 5 second bound, and a check that fails or times out counts as holding, so the refusal is kept.

Independently, a node that finds another node's dirty marker on a volume refuses to open it when that node's daemon heartbeat (heartbeat.<node> in the cluster-state bucket) is under 60 seconds old. It also refuses when the heartbeat cannot be read or no heartbeat source is wired, and the refusal maps to the held-elsewhere error that recovery retries. A previous owner that has stopped heartbeating is opened over with a warning, as before. The heartbeat age is compared across node clocks, so the 60 second window is also the clock-skew allowance.

EKS control-plane recovery treats both refusals, capacity and held-elsewhere, as retryable: it keeps retrying the stopped member and does not count them against its restart attempts.

Predastore (S3)

Object storage used for:

  • AMI image storage
  • SSH public key storage (/bucket/ec2/{key-name}.pub)
  • Volume metadata and configuration

Spinifex runs Predastore in-process: spx service predastore start loads /etc/spinifex/predastore/predastore.toml, selects the [[host]] naming this machine, and serves it until the process is signalled. The topology is written by spx admin init / join from the servers that form the cluster.

One [[host]] is one process. The nodes pinned to it under [[host.node]] carry the roles:

Role Port Responsibility
gate TCP 8443 The S3 API. Holds no cluster state; dials the meta and blob nodes to serve a request.
blob UDP 6660 Erasure-coded object shards, encrypted at rest under this host's master key.
meta UDP 7660 Raft replica of global state — buckets and the object index.

Ports are unique within a host but repeat across the cluster, so a multi-node cluster puts one node of each role on every machine and every machine uses the same three ports. Nodes sharing a host talk over an in-process pipe and bind no socket; nodes on other hosts are reached over QUIC, authenticated by the cluster CA.

A single-node install is the same arrangement with one host: seven nodes — a gate, three blob and three meta — colocated in one process, needing seven distinct ports (8443, 6660–6662, 7660–7662) to stay unique within the host even though only the gate opens a listener. It has no code path of its own.

The daemon reports the topology on spinifex.storage.config (the contracts/operator/v1 Predastore-topology contract) by parsing the config file. It does not connect to Predastore to do so, and no Predastore node exposes a status endpoint. This is an operator status interface, not a generic storage-provider contract.

SQS message store (internal)

domains/sqs/message defines the store-neutral interface the SQS domain reaches its message store through (ADR-0011:S6), with a JetStream adapter in domains/sqs/message/jetstream and a shared conformance suite in domains/sqs/message/conformance. It is an internal primitive: nothing outside the SQS domain uses it, no daemon or service is wired to it, and it does not itself deliver an SQS API. The dedicated JetStream server ADR-0011 describes is not deployed by this code, and Spinifex ships no host service, unit, user or firewall rule for it; the guest that could run it is described under SQS store system instance (not wired).

The interface covers durable and idempotent append, body and metadata reads, conditional state writes and deletes, per-namespace counts, namespace enumeration, an ordered change feed, a bounded paginated scan, namespace deletion and a sweep of tombstoned bodies. A namespace carries an immutable message-shard and state-shard allocation chosen when the queue is created, so a later change in shard counts never moves an existing queue.

The adapter provisions a fixed set of shared message streams (SQS_M_<shard>, one subject per queue) and shared state buckets (sqs_state_<shard>), keeps historical ones, and applies a 14-day-plus-one-hour retention backstop to both. It supports one node (R1) and three nodes (R3) only and refuses any other declared cluster size before provisioning.

Reads that must observe a completed write or delete go to the stream leader: GetState, the state-key pass behind Count and Namespaces, and the body pass behind Namespaces and Scan. This avoids the follower-served direct gets and follower-placed consumers that returned purged data in local three-node fault-injection tests; it is not a general linearizability guarantee. Each leader read is one request per record, and the body pass transfers each full body internally even though Scan returns metadata only, which is a material cost for a large backlog. A state-key pass is bounded but is not a snapshot when a key is overwritten during it.

The feed reads through an in-memory, headers-only ordered consumer. If that consumer delivers nothing for about two seconds while the stream holds a change after the feed's cursor, the feed replaces it from the cursor, so a stored change does not wait on a stalled consumer; the cause of those stalls is not established. Close is terminal, waits for consumer opens and deletes in progress and retries failed deletes, but cleanup is best effort for a create whose outcome is unknown: a consumer that lands after its last delete is removed by the server's one-minute inactive threshold.

Coverage is unit and conformance tests on in-process R1 and R3 servers; there is no end-to-end or multi-host validation of this code, and earlier multi-host evidence predates the final feed.

SQS store system instance (not wired)

Spinifex can build, install, launch, restart and give storage to a dedicated SQS store microVM, but nothing calls any of it. No SQS API, domain service, admin command or daemon start-up path creates a store, so none of this is in production use.

The guest image is built by make build-sqs-store-microvm-image, separate from the load balancer image, and bundles the nats-server version pinned in go.mod plus the ext4 tools. Release tarballs carry it as microvm-sqs-store/, and setup.sh installs it to /usr/share/spinifex/microvm/sqs-store/. A release without a complete image removes any previously installed one, so a launch is then refused rather than booting a stale image.

At boot the guest reads three firmware config values: the data disk's serial, an IPv4 address on one of its interfaces, and one NATS user NKey public key. It mounts exactly one matching disk at /data after e2fsck -p, refuses a missing, duplicate, unformatted or unrepairable disk, and never formats. JetStream keeps its data on /data with sync_interval: always (ADR-0011:S3), max_payload: 2MiB admits a full 1 MiB SQS message with its headers (ADR-0011:S4), and the server listens only on that address and accepts only that key. On shutdown the store is stopped before /data is unmounted; a store that survives SIGKILL leaves every mount in place.

A launch uses the versioned subject system.LaunchSQSStore.v1, which a daemon without this code does not serve, so it fails with no responder instead of booting another guest. The legacy system.LaunchInstance path refuses the store kind on both send and receive. Every input check runs before capacity is reserved, and the data volume must be an available system-account volume. It is mounted through the normal EBS path and detached, never deleted, on terminate, which is the protection standard EBS gives today and nothing stronger. CPU mitigations stay enabled for the store, unlike the load balancer. A successful launch means the VM is running, not that NATS is ready.

The instance record keeps the store's non-secret guest settings so a restart on the node that launched it rewrites the firmware config files. A relaunch on any other node is refused, and cross-node recovery never claims a store. Both checks exist only in daemons with this code: an older daemon can still claim and relaunch a store elsewhere, and an explicit start served by another node claims the instance before its relaunch is refused.

domains/sqs/storevolume prepares a fresh data volume, because the guest never formats. It checks for mkfs.ext4 and qemu-img before allocating, creates the volume in creating, writes an empty ext4 image to it over NBD on the local node, unpublishes it, and only then makes it available. While a volume is creating, attach, delete, modify, force-detach and snapshot are refused. A volume is deleted only after a confirmed unpublish; any publish error, an unconfirmed unpublish or a failed release keeps it and reports its ID, with its state reported as unknown after a failed release.

Evidence is local only: unit tests, real QEMU boots against disposable scratch disks, and one run of the preparer against the qemunbdd provider whose volume kept acknowledged writes across a reboot. Viperblock, volume encryption, the EC2 volume record path, multiple nodes and host reachability of the guest address are not tested. Credential issuance and rotation, store placement and NATS readiness checks do not exist, and there is no failover: a lost node leaves its store unavailable.

SQS worker guest (operator-launched)

The shared SQS worker guest holds the SQS store's client credential, so that no platform component does (ADR-0011:S2). Only an operator activates it, with the super-admin EnsureSQSWorker action described below; nothing starts it at daemon startup, and no worker service runs after boot.

make build-sqs-worker-microvm-image builds it with the store image's script and network /init under SQS_MICROVM_PROFILE=worker; it carries the static sqs-worker binary and the ext4 tools, no nats-server, and an empty /data mountpoint. Releases build it beside the store image and ship it as microvm-sqs-worker, which setup.sh installs to /usr/share/spinifex/microvm/sqs-worker with the store image's rules: a release without it removes an earlier one, and an incomplete one is refused. At boot sqs-worker boot reads three firmware config values under opt/spinifex/sqs-worker/: the worker disk's serial, its Region and the gateway URL; none is a first-store decision, because a static value survives a guest reset. A missing, empty or malformed value refuses before any disk is touched.

It selects exactly one disk with that serial, runs e2fsck -p, mounts it at /data and then confirms from /proc/self/mountinfo that this disk, as a whole ext4 filesystem, is what is mounted there; an empty mountpoint, a foreign mount or a failed check or mount refuses, and the guest never formats. Only then does it ask the gateway for the current decision with ClaimFirstStore, signed by internal/sqsworkergw with credentials from the instance metadata service only (gwsign.NewInstanceRole, no environment, profile or static-key fallback), over TLS 1.3 that trusts only the cluster CA from opt/spinifex/ca-cert and never follows a redirect. Under that decision workerkey.Acquire creates the key on /data/sqs-worker-key, owner-only and synced, records only its public key and then uses it, or loads the recorded key; a missing or different key once one is recorded refuses and is never replaced. The VM can start before its launch binds the instance, so its first calls are legitimately AccessDenied; that denial creates nothing and is asked again, as are a lost reply and a ServiceUnavailable or Throttling refusal, all within one bound (60 attempts 5 seconds apart), after which a worker that was never bound, or was replaced, refuses the boot. A signature or other refusal, or an answer that is neither "create" nor one valid public key, refuses the boot at once.

domains/sqs/firststore is the SQS domain's first-store decision: one record per Region in the spinifex-sqs-first-store KV bucket moves from claimed to key-recorded to launch-intent under compare-and-swap, bound to the worker's instance ID, claim ID and generation. A claim authorizes key creation only while no public key is recorded; once one is, every claim returns only that key, and a store launch intent needs it recorded first. An older generation, a different identity at the same generation or an unreadable record authorizes nothing, and the record holds no private key material. Reads are stream message gets answered by the stream leader, never direct gets a lagging replica can answer, and every authorizing answer is also confirmed by a compare-and-swap at the revision it read, so a stale or unavailable read authorizes nothing. The authenticated caller that will carry this decision must derive the worker's instance ID and generation from authoritative instance state; a generation supplied in a request cannot itself authorize a takeover.

domains/sqs/workerident is that authoritative instance state: one record per Region in the spinifex-sqs-worker-identity KV bucket holds a monotonic generation, claim ID, pinned node and encrypted data volume, and moves from launching to bound to stopped, or from launching to failed, under compare-and-swap. A launch intent is refused while the previous attempt is launching or bound, including one whose outcome is unknown, so only one caller ever holds an intent to start a VM on the pinned volume. A replacement takes the next generation only after FailLaunch or RecordStopped records that nothing holds the volume, and each request names the generation it supersedes, so a replayed request cannot take a generation it never observed; there is no automatic takeover. The launch path then raises the first-store fence to the successor's generation with firststore.Fence before BeginLaunch, which refuses a replacement until a leader read shows that fence; the fence only rises, and firststore refuses every call from a generation below it. Only the current claim ID is recorded, so claim IDs are minted fresh per attempt and a VM launch must be idempotent on generation and claim together. Binding writes the instance's index entry first and then binds the record to that instance. The index is only a lookup: Authorize accepts an instance only while the Region's record is bound to exactly that instance, generation and claim, confirmed by a compare-and-swap at the leader-read revision, so an old, orphaned, rewritten or unbound entry authorizes nothing. A same-instance reboot keeps its instance ID and identity; a replacement takes a new generation, and the first cut refuses another node or data volume and an unencrypted volume, although the encryption flag is the caller's claim and the launch wiring must verify it from the volume's metadata. Both buckets are opened through OpenDurableKV, which refuses an existing bucket whose effective stream configuration could expire, evict, lose, lag or refuse records: non-limits retention, an age, per-message or delete-marker TTL, memory storage, asynchronous flush, a size, count or message-size cap, a discard policy other than discard-new, unacknowledged writes, a sealed stream, a mirror or sources, or fewer replicas than the cluster needs. workerkey.Acquire drives that decision: it syncs a new key to disk, records its public key and only then returns it, so a crash before recording reuses the key already on disk.

domains/sqs/awsapi/worker carries the decision to the worker as ClaimFirstStore and RecordWorkerPublicKey, served under the internal spinifex-sqs signing service, which no AWS SDK signs for; the public AmazonSQS action inventory is untouched. The gateway admits only an assumed-role session of sqsWorkerRole in the system account, then the role's policy, and only then resolves the session name, the instance ID STS set, through workerident.Authorize; the request carries no identity, and any parameter beyond the action's own is refused. The first-store identity is the current record's instance, claim and generation, and a worker bound to another Region is refused. A request that passed Authorize just before a confirmed stop and replacement still carries the old generation; the fence was raised before the successor began, so firststore refuses it whether or not the successor has claimed yet. The adapter never logs a caller-chosen parameter name, because one could carry a secret. RecordWorkerPublicKey accepts only a valid public user key, so a seed is refused without being recorded, logged or echoed. The gateway binds both buckets per request and never creates them, so it provisions nothing and answers ServiceUnavailable until a worker launch has created them; the worker launch below ensures the role. The private key stays on the worker disk; the guest logs and publishes only the public key to /run/sqs-worker/public-key.

domains/sqs/workerlaunch realizes the worker on the node it runs on, its only node: a bound record is returned as is; otherwise it takes the intent, then on the first launch marks the intent's one volume create, prepares the volume and records its ID, reads the volume's own record and refuses it unless encrypted, ensures the role, finds or creates the network for the claim and reads the recorded store key, and marks the intent dispatched before launching. A dispatched launch is never sent again: a lost reply or error leaves the intent launching and dispatched, and every later call returns ErrOutcomeUnknown until the outcome is reconciled, since the launch path is not idempotent. A failure before dispatch leaves an undispatched intent that the next call resumes with the same claim; a confirmed stop or failure is replaced only after firststore.Fence excludes the old generation, reusing the pinned volume. The launch passes no store decision or key: the guest asks the gateway at boot. The intent exists before any volume, so concurrent first launches allocate nothing for the losers. A Prepare proven to have sent no create withdraws the mark and returns ServiceUnavailable, or UnsupportedOperation when the cluster storage key is not configured, and a retry may prepare the volume; a create that may have applied is never sent again, and every later call returns IncorrectState until it is reconciled. A volume the call knows of but cannot use is reported with its ID in a VolumeError and left in place, never deleted. An intent that has sent no create may be re-typed; one that has keeps its type until replaced. The worker role is created with EC2-only trust, and an existing role is checked for that trust before any policy is granted; the instance profile must carry exactly the worker role, and one holding any other role is refused unchanged. The daemon's LaunchSQSWorkerInstance boots the sqs-worker image through the same direct-boot path as the store, with the data volume attached at boot and kept on terminate, a required instance profile, and a required mgmt NIC; it re-reads the volume's own record and refuses one that is not available and encrypted, before anything is allocated. Its firmware config adds the gateway URL on this node's mgmt bridge and the cluster CA from the daemon's own trust store; the caller cannot supply either, and no value written is secret. A relaunch rebuilds that config from the VM record on the node that launched it and is refused anywhere else, and membership takeover already skips SQS-managed instances. sqsWorkerRole is ensured in the system account granting exactly spinifex-sqs:ClaimFirstStore and spinifex-sqs:RecordWorkerPublicKey, from the domains/sqs/workerrole contract the gateway gate also reads; an existing role whose trust admits more than the EC2 service is refused.

Evidence is local only: unit tests with a fake firmware config, sysfs and mount table, tests running the boot through the real client against the real spinifex-sqs registration and records, and QEMU boots of the built image against disposable scratch disks and a host-side test gateway and metadata service, showing the first boot creates the key, reboots reuse it, a key lost after recording is never replaced, and the seed reaches no log or request. The worker's network is a private SQS system VPC per Region, built by systemvpc.EnsurePrivate from the [sqs] supernet (default 10.240.0.0/14): one VPC and one /24 subnet, with no internet gateway, NAT gateway, EIP, route table or daemon-to-store node port. Each launch claim gets one ENI in that subnet, in the VPC default security group, found again by its claim on a retry; two ENIs for one claim are refused. The launch intent is marked before the one create is sent, so a create whose ENI is not yet visible is never sent again: the launch fails closed with IncorrectState until the ENI appears or the outcome is reconciled. Worker-to-store TCP and the guest's route to the metadata service are not yet proven by any traffic test. The super-admin EnsureSQSWorker action on the internal spinifex operator service takes a NodeId, which must be a node of this cluster and a single subject token, and an InstanceType, and sends a request to sqs.worker.Ensure.v1.<node> with no queue group, so only that node answers and the worker stays pinned. That node's daemon re-checks the node the request names and the instance type, and refuses as ServiceUnavailable before allocating a volume or network or recording an intent unless the worker image's kernel and initramfs are non-empty files, its mgmt bridge exists and the cluster CA is readable; a call after the image is installed then launches. It then runs its one composed launcher for its own Region, one launch at a time, in the daemon's own context with a 30-minute bound, so a caller's timeout does not cancel it. A reply lost to that timeout is reported as ServiceUnavailable; calling again reports the bound worker, or IncorrectState for a dispatched launch whose outcome is unknown, which is never resent; a Region pinned to another node is refused as InvalidParameterValue. The reply names the bound VM's node, Region, instance ID and generation; bound is not ready, and it says nothing about the guest's boot, its key or the store. Stop/detach evidence for RecordStopped is not wired, the guest's metadata route and gateway TLS on a real ENI and worker-to-store TCP are unproven, and Viperblock's at-rest key is held by the platform.

The worker identity record holds the instance type of its generation; a request for another type is refused as IncorrectState, before dispatch and after binding, the reply names the recorded type, and only a replacement after a confirmed stop may change it. Operators call both actions with spx admin sqs ensure-worker --node --instance-type and spx admin sqs ensure-store --node --instance-type --volume-size-gib, signed for the spinifex service with the standard AWS credential chain like the other spx admin gateway commands. Each command refuses missing inputs before sending anything and reports only the bound VM; a bound VM is not a ready worker or store. The super-admin EnsureSQSStore action takes a NodeId, an InstanceType and a VolumeSizeGiB and sends a request to sqs.store.Ensure.v1.<node> with no queue group; only the node the Region's worker is bound to can launch the store. That node refuses an instance type whose memory does not exceed 512 MiB, the store's GOMEMLIMIT under ADR-0011:S11; this is a floor, not a validated size, and no type is defaulted. It refuses before recording or allocating anything unless the store image and the cluster storage key are present, the worker is bound on this node, and that worker's identity has recorded its public key in the first-store decision, which it then advances to a launch intent. The store's own launch record in spinifex-sqs-store-launch holds only that public key, the claim, the node and the operator's instance type and size, and marks each step before its uncertain create: the volume, the ENI in the worker's private subnet, and the launch. A later request for a different instance type or size is refused as IncorrectState, before dispatch and after binding, and the reply names the type the store was launched with. A volume preparation that failed before sending any create, such as a missing mkfs.ext4 or a scratch or format failure, withdraws its mark and returns ServiceUnavailable, so a retry may try again once the host is fixed. Any other marked step whose result is not visible is reported as IncorrectState and never resent; a volume that is not encrypted by its own record is refused as UnsupportedOperation with its ID kept, and the daemon re-checks the volume's encryption and the guest's size at launch. The daemon never receives the worker's seed; the store's NATS server accepts only that public key, and the reply's bound VM and address are not readiness, which only the worker can check.

After boot, the worker's long-running sqs-worker ready step mounts and verifies its disk again and calls the internal spinifex-sqs DescribeStore action, which admits only the current worker and returns the bound store's address and recorded public key, or pending. It loads its key only if it matches that public key, then connects to the store's NATS on port 4222 with it and asks JetStream for account info, each pass bounded to 30 seconds. The step runs until shutdown with no overall deadline, so a store the operator launches at any time is picked up: it asks again every 5 seconds while the store is pending, not answering or the reply was lost, and re-checks a ready store every 30 seconds. A pass writes only the address and public key to /run/sqs-worker/store-ready; any failed pass removes that file, and so does the step's own exit. A start that finds shutdown in progress or no worker key logs once and waits in place rather than exiting, so init does not respawn it in a loop; shutdown stops it like a running watcher. Init respawns the step, at most once every 5 seconds, and every start removes a marker left by a watcher that was killed or crashed before the new watcher runs. A ready store that fails is noticed up to one re-check interval plus one bounded call later, so the marker can be up to about a minute stale. Shutdown blocks further respawns, removes the marker, and stops the watcher by its recorded PID and start time, escalating to SIGKILL after a budget; it unmounts the worker disk only once the watcher is confirmed gone, and a survivor leaves every mount in place. A mismatched key, a store that refuses the key, a key missing from the disk or an unclassified gateway refusal is asked again only every 5 minutes, so it never spins and still recovers if the operator fixes it; a missing key is never replaced. The NKey authenticates the worker to the store, but nothing authenticates the store to the worker: there is no TLS, so a pass means only that something at that address accepted the key. This is store readiness for the worker alone; there is no SQS API, and no production sizing or support is claimed.

Configuration

Cluster configuration (spinifex/bootstrap/config/config.go):

type ClusterConfig struct {
    Epoch     uint64            // Incremented on config changes
    Node      string            // This node's identifier
    Version   string            // Spinifex version
    Network   NetworkConfig     // Cluster-wide external network settings (IP pools, IPsec)
    Bootstrap BootstrapConfig   // Default VPC IDs written by admin init
    AWS       AWSConfig         // Cluster-wide AWS-parity settings (region, endpoint suffix)
    Nodes     map[string]Config // Configuration for all nodes
}

type Config struct {
    Node, Host, AdvertiseIP  string
    Region, AZ               string
    BaseDir, DataDir, WalDir string
    Services   []string         // Which services this node runs locally
    Daemon     DaemonConfig
    NATS       NATSConfig       // Broker address, JetStream, ACL token, CA cert
    AWSGW      AWSGWConfig      // Gateway host, TLS certs, throttle config
    Predastore PredastoreConfig // S3 endpoint + service credentials
    Viperblock ViperblockConfig
    VPCD       VPCDConfig       // OVN/OVS endpoints
    // ... + EBS, Northstar, RDS, ACM, Bedrock, OchreVector
}

Configs are generated by spx admin init (leader) or spx admin join (followers).

File Structure

The layout follows Mulga ADR-0001 (Spinifex package boundary and layout). architecture/layering enforces its dependency rules in make preflight.

spinifex/
├── cmd/                     # Thin executable mains: spx, installer, in-guest agents, dev tools
├── contracts/               # Versioned cross-process wire contracts (contracts/<domain>/vN)
├── spinifex/
│   ├── foundation/          # Shared primitives: AWS errors/ARNs/filters/tags, KV state, messaging, telemetry, PKI
│   ├── providers/           # Backend adapters: EBS (Viperblock), object store, cloud (OCI, Exoscale)
│   ├── domains/             # Service domains (ec2, acm, ecr, dns, network, ochre, rds, tagging, ...)
│   │   └── <domain>/awsapi/ # A domain's AWS action adapters
│   ├── ingress/             # AWS protocol ingress: query/REST parsing, dispatch registry, rate limiting
│   ├── runtime/
│   │   ├── roles/           # Long-running service roles (awsgw, spinifex, vpcd, nats, predastore, ...)
│   │   ├── daemon/          # Per-node daemon and its NATS subscription table
│   │   └── compute/         # VM lifecycle, QMP, NBD, GPU
│   ├── bootstrap/           # Cluster and node configuration structures, preflight checks
│   ├── operator/            # spx CLI commands, admin use cases, account lifecycle, installer, upgrade
│   ├── agents/              # In-guest agent libraries (ecs, eks, elbv2, rds)
│   └── gateway/             # Legacy root: HTTP route assembly, SigV4 auth, legacy per-service dispatch
├── internal/                # In-guest SigV4 clients, AWS Smithy models and test kits
├── architecture/            # Executable architecture rules (package layering)
├── build/                   # systemd units, node helper scripts, microVM build
├── scripts/                 # Install, dev-environment, image-build scripts
└── tests/
    ├── integration/         # Gateway router against embedded NATS JetStream
    └── e2e/                 # Live-cluster suites (see docs/testing/e2e-coverage.md)

The one remaining legacy root, gateway, predates ADR-0001 and is frozen: it may shrink but not gain packages. PACKAGE_BOUNDARY_MIGRATION.md records what remains in it and what blocks its move.

Development

Running the Stack

sudo spx admin init --node node1 --nodes 1
sudo systemctl start spinifex.target

spx admin init generates the cluster CA, IAM credentials, TLS certs, and AWS CLI spinifex profile, then writes config to /etc/spinifex/ and data to /var/lib/spinifex/. spinifex.target brings up all services (NATS, Predastore, Viperblock, vpcd, the daemon, awsgw, the UI) under systemd. Use spx admin join for additional nodes.

Testing with AWS CLI

export AWS_PROFILE=spinifex

# Run instance
aws ec2 run-instances --image-id ami-debian13 --instance-type t3.micro

# List instances (queries all nodes)
aws ec2 describe-instances

# Terminate instance
aws ec2 terminate-instances --instance-ids i-xxxxx

For cluster-state inspection that bypasses the AWS API surface, use the spx CLI directly: spx get nodes, spx get vms, spx top nodes.