Compiling an Infrastructure Stack
How we took a multi-layer “enforce / apply” stack of Makefiles, OpenTofu, Ansible, Python, and Bash — and collapsed it into a single, zero-dependency Rust compiler, planner, and host daemon.
If you run a small website, “deploying” means pushing code to one server. If you run a real-time trading platform, the system isn’t one server — it’s machines in Tokyo and Frankfurt, ClickHouse databases, S3 archives, Cloudflare routes, Grafana alerts, Docker containers, encrypted secrets, and smart contracts live on Solana.
Every piece depends on other pieces. A server container needs the database hostname and the deployed smart-contract address. A firewall rule needs the server’s IP. A Cloudflare route needs the service port. An alert rule needs the metric source.
Usually, teams manage this with half a dozen separate tools glued together by Makefiles and convention. flint-world starts from a simpler premise: treat your entire infrastructure like a program — compile it into one checked dependency graph, prove it before running, and execute that exact same graph against production, an in-memory simulator, or your laptop.
Where It Started: The “Enforce / Apply” Pattern
Before flint-world, our infrastructure wasn’t chaos — it followed a disciplined pattern called enforce / apply (internally, SDS: State Declaration System). Understanding why that pattern worked so well — and where it started cracking — explains every design choice in flint-world.
The philosophy behind enforce/apply is remarkably clean:
- Git is the single source of truth. Every host, database, alert, service, and Solana program is declared in YAML files under
environments/{devnet,mainnet,opsnet}/config.yaml. - Enforce is strictly read-only. It inspects live infrastructure and compares it against Git. If anything drifted — someone hotfixed a server, a DNS record changed, an image tag fell behind — enforce fails loudly and tells you what diverged.
- Apply is the controlled mutator. It converges live reality back to match Git.
That discipline eliminated “cowboy SSHing.” The trouble wasn’t the philosophy — it was the machinery underneath. Because different kinds of resources belonged to different ecosystems, the stack fractured into numbered layers stitched together by a 600-line Makefile: d0 (cloud machines & DNS), d1/d2 (host setup & Docker containers via Ansible), db/df (ClickHouse & frontends), d3 (Grafana alerts), ds (Solana smart contracts), and dh (custom shell hooks) — flanked by separate sidecar tools for linting (dlinter), drift checks (denforcer), querying (qsds), and local development (dev.sh).
Those five structural cracks translate into everyday operational friction:
- No single tool sees the whole system. OpenTofu didn’t know what Ansible was going to deploy, and Ansible didn’t know which Solana program version was live.
- The enforce-to-apply time gap. Reviewing an
enforcediff at 2:00 PM doesn’t guaranteeapplyat 2:05 PM sees the same live reality. - Bolted-on linting. Because YAML is just untyped text, catching a broken DSN or a floating
:latesttag meant maintaining a parallel Python linter (dlinter). - SSH + Ansible friction. Rolling out containers over SSH loops is slow, hard to make atomic, and often restarts an entire trading server just to update static token icons.
- Dev / prod drift. Because laptops couldn’t run OpenTofu + Ansible, local dev lived in a separate
dev.shscript that quietly went stale.
The Big Idea: Compile Infrastructure Into One Typed Graph
In flint-world, you describe your environment in a small, typed language (.world) — or point the tool straight at your existing config.yaml directory via world import so there’s no flag-day migration.
The compiler evaluates expressions, resolves module imports, tracks every secret reference, and emits a content-addressed DAG — a Directed Acyclic Graph where every resource carries a deterministic SHA-256 fingerprint of its inputs, and dependency arrows only flow forward with no circular loops. You never manually number layers “d0, d1, d2”; simply referencing another resource creates the edge automatically:
world "devnet" {
let tokyo = resource host.machine "devnet-tokyo-1" {
provider: "aws",
region: "ap-northeast-1",
instance_type: "c7i.2xlarge",
slices: ["margin", "serving"],
}
let ch = resource db.clickhouse_cloud "devnet-ch-main" {
region: "us-east-1",
allow_hosts: [tokyo],
slices: ["data", "margin"],
}
let prog = resource solana.program "flint-margin" {
pubkey: "CUKvWFbt2mGjbgmvtTPW8yRihH1WY8Ej1WtsjLJrftSa",
release_tag: "v0.0.17",
multisig: { vault: "2e1yLNm..." },
slices: ["onchain", "margin"],
}
resource host.service "flint-server-tokyo" {
host: tokyo,
service: "flint-server",
zero_downtime: true,
env: {
CH_URL: "https://writer:\(secret("db.writer"))@\(ch.outputs.endpoint)",
PROGRAM_ID: prog.outputs.pubkey,
},
slices: ["margin"],
}
}
Once the entire stack lives in one compiled DAG, two superpowers fall out automatically: parallel topological waves (everything independent executes concurrently) and transitive slicing (--slice margin automatically pulls in every upstream host, database, and program that margin depends on, while refusing to touch or delete anything outside the slice).
From “Enforce / Apply” to Signed Plans & Instant Rollbacks
To eliminate the gap between reviewing drift and mutating production, flint-world introduces a Plan Artifact (.plan.json). A plan isn’t human-readable text thrown at a terminal — it is a cryptographically sealed contract binding three hashes:
world_digest— the exact compiled specification from Git.baseline_digest— a hash of live observed reality at the moment the plan was built.plan_digest— the exact waves, actions, field-level diffs, and policy verdicts.
For production environments, a quorum of approvers (for example, two distinct engineers) signs the plan_digest using Ed25519 keys (world sign-plan). When world apply runs, it acquires a distributed S3 lease lock with background heartbeat renewal, re-observes reality to block TOCTOU (time-of-check to time-of-use) drift, and refuses to move unless every gate passes.
world_digestIf-None-Match: * + heartbeatbaseline_digest
Look closely at Gate 05: before Wave 0 mutates a single byte, apply appends the pre-apply snapshot to an append-only NDJSON journal (local disk or S3 guarded by ETag optimistic concurrency) and flushes a fresh checkpoint after every wave. If a laptop loses power or a CI runner gets SIGKILL’d halfway through, the journal still holds the exact pre-apply state — and world rollback --to <apply-id> compiles the inverse plan to restore everything cleanly.
Solving the Secret Trap: Redacted Plans, Plaintext Runtimes
Every infrastructure tool eventually runs straight into the same dilemma with secrets like database passwords and RPC API keys:
- If you write resolved secrets into plans or state files, you just leaked plaintext credentials onto disk, into CI logs, and into S3 buckets.
- If you strip secrets out completely during diffing, then rotating a password shows “zero drift” and never rolls out to your containers.
flint-world breaks the deadlock by running two resolver passes on every resource: a redacted pass for anything that gets diffed, signed, or persisted, and a runtime pass kept strictly in RAM (and volatile-zeroized on Drop) only at the instant a container or hook is invoked.
DB_PASSWORD: secret("db.prod_pw")
"DB_PASSWORD": "secret_sha256:9f3a8c12e4b0..."
DB_PASSWORD=ultra-secret-pw-v1
Replacing SSH + Ansible Loops with sds-agent
Ansible deploys by SSHing into every machine, uploading Python scripts, rendering templates, and shelling out to docker compose. It works, but it’s slow, fragile when connections drop, and has no built-in model for zero-downtime slot cutovers or hot-reloading static assets without bouncing a trading engine.
In flint-world, each server runs a small, static Rust daemon called sds-agent bound to its private Tailscale address. Instead of SSH, the control plane speaks authenticated HTTP directly to the agent, and the agent speaks HTTP straight to Docker over /var/run/docker.sock:
- Zero-trust peer auth: On every request,
sds-agentqueries Tailscale’s LocalAPI (/localapi/v0/whois) over Unix socket to verify the caller’s tailnet user or tag (e.g.tag:deployer), optionally layered with a constant-time Bearer token. - Content-addressed blob store: Configs and static files upload once to
HEAD/POST /v1/blobs/<sha256>. Restart-sensitive configs mount from an immutable directory; hot-reloadable directories (like tokenicons/) sync atomically in place without restarting the container. - Blue/green cutovers with health gates: For zero-downtime services (like
flint-serverusingSO_REUSEPORT), the agent starts the alternate slot, waits for Docker’s healthcheck to turn green, and only then drains the old container using its configuredstop_grace_secs. If the candidate fails health, it is deleted and the live slot never drops a packet. - Complete host lifecycle: Also reconciles
d1host configs (nginx,cloudflared, Alloy with reload hooks), runs a persisted 5-field UTC cron scheduler with non-overlap locks, streams demuxed Docker logs (world logs --agent), exports Prometheus/metrics, and generates its own systemd unit (--print-systemd-unit).
sha256:4a1e..sha256:9c02..0GET /v1/services/flint-server → 200 OK { active_slot: "blue", digest: "4a1e..", drift: false }
Smart Contracts & Cloud APIs as First-Class Nodes
In a crypto trading stack, on-chain programs aren’t separate from cloud infrastructure — your servers, indexers, and web apps depend directly on them. Instead of hiding Solana upgrades in ad-hoc Bash scripts, SolanaProvider places them directly inside the dependency graph alongside AWS, Cloudflare, ClickHouse, and Grafana:
Native BPF Loader Decoding
Queries live getAccountInfo over JSON-RPC, follows Program → ProgramData, decodes the 45-byte header (deploy slot + upgrade authority), and hashes the trailing-zero-stripped ELF binary directly in Rust.
For Squads multisig upgrades, it scans existing on-chain buffers via getProgramAccounts with memcmp filters and reuses matching buffers instead of burning SOL on duplicates. It also downloads GitHub Release .so artifacts, verifies their SHA-256 against tampering, and runs declare state reconcilers in wave order.
Direct Cloud API Providers
No Terraform state files or wrapper CLIs required. world-providers talks straight to upstream REST APIs with bounded timeouts and idempotent 429/5xx retry backoff:
- AWS S3 & EC2 via pure-Rust SigV4 (verified against AWS’s official test vector)
- Cloudflare paginated DNS, Tunnel routes, Pages + custom domains, Worker ES modules
- Grafana Provisioning alerts, folders, dashboards, mute timings
- ClickHouse Cloud, Kellnr, and legacy
dhhooks
One Graph, Three Worlds
Every resource speaks through a swappable ResourceProvider trait. That means the exact same compiled graph can drive three completely different targets without duplicating a single line of configuration:
Why Zero External Cargo Dependencies?
Every crate in flint-world compiles solely against the Rust standard library — zero third-party Cargo crates. We wrote our own JSON and YAML 1.2 parsers (with 128-level nesting guards), SHA-256, SHA-512, HMAC, pure-Rust RFC 8032 Ed25519, Base58, AWS SigV4, HTTP/1.1 client and server, Docker Engine Unix-socket client (including 8-byte multiplexed log demuxing), and the .world language compiler and formatter.
Zero dependencies wasn’t purism — it paid off directly when debugging subtle production edge cases:
- Total ownership of hard bugs: When our connection-cap stress test caught Linux emitting a
TCP RSTinstead of a cleanFINafter a503 Busyresponse, or when live Docker testing revealed a 15-second stop timeout on service deletion, the entire stack was small, readable Rust we could fix in minutes. - Pragmatism where cryptography belongs: We didn’t hand-roll TLS 1.3 or KMS encryption. Verified HTTPS delegates cleanly to stdin-piped
curl --globoff -K -(keeping auth headers off process arguments and binary payloads in0600zero-wiped temp files), SOPS decryption pipes over stdout, and on-chain signing invokessolana. - Instant builds & zero supply-chain bloat: An optimized
cargo build --releasecompletes in under 10 seconds with zero transitive crates to audit.