flint-world architecture essay
Engineering Deep Dive · Infrastructure Systems

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 and reconciler.

30,494
Lines of Rust
0
External Cargo Crates
8
Focused Workspace Crates
169
Live Resources Validated

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 asks a simpler question: what if you treated your entire infrastructure like a program — compiled it into one checked dependency graph, verified it before running, and used that exact same graph for production, dry-run simulations, and your laptop?

01
Describe once
Write hosts, databases, services, alerts, and smart contracts in one typed graph (or import existing YAML).
02
Compile & seal a plan
Check rules, simulate in memory, redact secrets to hashes, and cryptographically sign the exact diff.
03
Converge safely
Lock via S3, re-verify live state, roll out in parallel waves with blue/green cutovers, and keep instant rollback checkpoints.

Where It Started: The “Enforce / Apply” Pattern

Before flint-world, our infrastructure wasn’t chaos — it actually followed a disciplined pattern called enforce / apply (internally, SDS: State Declaration System). Understanding why it worked so well — and where it started cracking — explains every design choice in flint-world.

The idea behind enforce/apply is straightforward:

  • Git is the source of truth. Every host, database, alert, service, and Solana program is described in YAML files under environments/{devnet,mainnet,opsnet}/config.yaml.
  • Enforce is read-only. It inspects reality and compares it against Git. If anything drifted — someone hotfixed a server, a DNS record changed, an image tag fell behind — enforce exits non-zero and tells you what doesn’t match.
  • Apply is the mutator. It runs the tools needed to converge reality back to what Git declares.

That discipline eliminated “cowboy SSHing.” The problem wasn’t the philosophy — it was the machinery underneath. Because different kinds of infrastructure lived in different tools, the stack split into numbered layers orchestrated 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) — plus separate sidecar tools for linting (dlinter), drift checks (denforcer), querying (qsds), and local development (dev.sh).

Interactive Architecture Comparison
Compare the original layered Enforce / Apply stack with the unified flint-world compiler
config.yaml + shared.yaml Untyped YAML + Jinja strings Makefile + Bash Manual layer sequence dlinter + denforcer Separate Python tools qsds + dev.sh Separate API & local dev d0 OpenTofu EC2 / DNS / CF d1 / d2 Ansible + SSH Host & Compose db / df OpenTofu ×2 ClickHouse / Pages d3 OpenTofu Grafana Alerts ds Python + Bash Solana Programs dh Shell Hooks Exit-2 scripts Five Structural Cracks No shared dependency graph across layers · Time gap between enforce and apply · Separate state files Slow sequential SSH loops · Local dev.sh drifts out of sync with production

Those five cracks are concrete, everyday pain:

  1. 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.
  2. The enforce-to-apply time gap. Reviewing an enforce diff at 2:00 PM doesn’t guarantee apply at 2:05 PM sees the same live state.
  3. Bolted-on linting. Because YAML is just untyped strings, catching a bad DSN or a floating :latest tag required maintaining a separate Python linter (dlinter) in parallel.
  4. SSH + Ansible friction. Rolling out containers sequentially over SSH is slow, hard to make truly atomic, and often restarts a whole trading server just to sync static assets like token icons.
  5. Dev/prod drift. Because laptops couldn’t run OpenTofu + Ansible, local dev lived in a separate dev.sh script that constantly drifted out of date.

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 at your existing config.yaml directory via world import so there’s no flag-day rewrite.

The compiler evaluates expressions, resolves module imports, tracks every secret reference, and outputs a content-addressed DAG (a Directed Acyclic Graph where every resource gets a fingerprint hash of its inputs, and dependency arrows only flow forward with no circular loops). You never manually number layers “d0, d1, d2”; simply referencing a resource creates the dependency edge automatically:

specs/devnet-margin.worldtyped references infer the DAG
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"],
    }
}

Because the graph knows every dependency edge, two superpowers fall out for free: parallel topological waves (everything independent runs at the same time) 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).

Interactive DAG Wave & Slice Explorer
Filter by slice or click any resource node to inspect its dependencies and wave
WAVE 0 (parallel) WAVE 1 (parallel) WAVE 2 (parallel) WAVE 3 devnet-tokyo-1 host.machine · AWS flint-margin solana.program · BPF devnet-ch-main db.clickhouse_cloud declare:margin solana.declared_state flint-server-tokyo host.service · blue/green questdb-retention host.service · cron api.flint.trade cloudflare.tunnel_route ch-lag-alert grafana.alert
Full graph: 8 resources across 4 parallel waves. Orphan deletion is active when applying the full world.

From “Enforce / Apply” to Signed Plans & Instant Rollbacks

To close the gap between checking drift and applying changes, flint-world introduces a Plan Artifact (.plan.json). A plan isn’t just text printed to a terminal — it is a cryptographically sealed contract containing three hashes:

  • world_digest — the exact compiled specification from Git.
  • baseline_digest — a hash of the live world at the moment the plan was created.
  • plan_digest — the exact list of waves, actions, field diffs, and policy verdicts.

For production environments, a quorum of approvers (for instance, two distinct engineers) signs the plan_digest with Ed25519 keys (world sign-plan). When world apply runs, it acquires a distributed S3 lease lock with background heartbeat renewal, re-observes reality to prevent TOCTOU (time-of-check to time-of-use) drift, and refuses to move unless every gate passes.

Interactive Apply Safety Pipeline
Test what happens on a healthy deploy vs. real-world failure modes
1
Compile & Check
Build DAG, validate rules, compute world_digest
2
Policy & Quorum
Verify Ed25519 signatures & competition locks
3
S3 Lock + Heartbeat
Conditional If-None-Match: * lease + auto-renew
4
Baseline Guard
Re-observe live state; verify baseline_digest
5
Journal & Converge
Write pre-state checkpoint before each wave

Notice Step 5: before wave 0 mutates anything, apply appends the pre-apply snapshot to an append-only NDJSON journal (local disk or S3 with ETag optimistic concurrency) and writes a new checkpoint after every wave. If a laptop loses power or a CI runner gets SIGKILL’d halfway through, the journal still has the pre-apply snapshot — and world rollback --to <apply-id> reconstructs the exact inverse plan to put everything back.


Solving the Secret Trap: Redacted Plans, Plaintext Runtimes

Every infrastructure system hits the same dilemma with secrets like database passwords and RPC API keys:

  • If you resolve secrets into your plan or state files, you just leaked plaintext credentials to disk, CI logs, and S3.
  • If you strip secrets out completely during diffing, then rotating a password produces “zero drift” and never actually rolls out to your containers.

flint-world solves this 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) when calling a container or hook.

Secret Split Pipeline
Rotate the password below to see how drift triggers immediately while zero plaintext hits disk
Source (.world)
DB_PASSWORD: secret("db.prod_pw")
Decrypted in memory via sops -d stdout pipe
Disk: .plan.json · state.json · journal.ndjson
"DB_PASSWORD": "secret_sha256:9f3a8c12e4b0..."
Zero plaintext on disk. Hash changes instantly on rotation.
RAM Only: Docker Container Env
DB_PASSWORD=ultra-secret-pw-v1
Injected over Tailscale into container; seed zeroed on Drop.

Replacing SSH + Ansible Loops with sds-agent

Ansible deploys by SSHing into each server, uploading Python scripts, templating files, and shelling out to docker compose. It works, but it’s slow, fragile when connections drop, and has no native concept of zero-downtime slot cutovers or live-reloading static files without restarting the server.

In flint-world, each server runs a tiny, static Rust daemon called sds-agent on its private Tailscale address. Instead of SSH, the control plane talks authenticated HTTP directly to the agent, and the agent talks HTTP directly to Docker over /var/run/docker.sock:

  • Zero-trust identity auth: On every request, sds-agent queries Tailscale’s LocalAPI (/localapi/v0/whois) over Unix socket to verify the peer’s tailnet user or tag (e.g., tag:deployer), optionally layered with a constant-time Bearer token.
  • Content-addressed blob store: Configs and static assets are uploaded once to HEAD/POST /v1/blobs/<sha256>. Restart-sensitive configs mount from an immutable directory; hot-reloadable directories (like token icons/) sync in place without restarting the container.
  • Blue/green cutovers with health gates: For zero-downtime services (like flint-server using SO_REUSEPORT), the agent starts the alternate slot, waits for Docker’s healthcheck to pass, and only then drains the old container using its configured stop_grace_secs. If the new container fails health, it is deleted and the old slot never drops traffic.
  • Full host lifecycle: Also handles d1 host configs (nginx, cloudflared, Alloy with reload hooks), a persisted 5-field UTC cron scheduler with non-overlap locks, demuxed Docker container logs (world logs --agent), native Prometheus /metrics, and --print-systemd-unit.
Interactive sds-agent Rollout Simulator
Trigger real deployment scenarios to see how slots, blobs, and health gates behave
SLOT: BLUESERVING
flint-server:v1
cid: a81f02c9 · healthy · port :8080
/v1/blobs/<sha256>
Immutable Configsha256:4a1e..
Live-Reload Mountsha256:9c02..
Steady state: 0 restarts, 0 drift.
SLOT: GREENIDLE
—
No candidate container running

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 frontends depend directly on them. Instead of hiding Solana deploys in ad-hoc Bash scripts, SolanaProvider puts them right inside the DAG:

Native Solana BPF Loader Decoding

Queries live getAccountInfo over JSON-RPC, follows Program → ProgramData, decodes the 45-byte header (deploy slot + upgrade authority), and computes the trailing-zero-stripped ELF SHA-256 directly in Rust.

For Squads multisig upgrades, it scans on-chain buffers via getProgramAccounts with memcmp filters and reuses matching buffers instead of burning SOL on duplicates. It also fetches GitHub Release .so binaries, verifies their SHA-256 against tamper, and runs declare state reconcilers in wave order.

Native Zero-Dep Cloud Providers

No Terraform state files or wrapper CLIs required. world-providers talks directly to every upstream API:

  • AWS S3 & EC2 via pure-Rust AWS Signature Version 4 (verified against AWS’s official test vector)
  • Cloudflare (paginated DNS, Tunnel routes, Pages + custom domains, Worker ES module uploads)
  • Grafana (Provisioning alerts, folders, dashboards, mute timings)
  • ClickHouse Cloud, Kellnr, and legacy dh hooks

One Graph, Three Worlds

Every resource talks through a swappable ResourceProvider interface. That means the exact same compiled graph can target three completely different environments without changing a single line of config:

Target Backend Switcher
See how one .world graph drives production, dry-run simulation, and local worktrees

Why Zero External Cargo Dependencies?

Every crate in flint-world builds solely on 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 log stream demuxing), and the .world language compiler and formatter.

Workspace Crate Dependency Map
8 clean layers · ~9.6s full release build · 53 integration tests including live Docker 27.5.1
BINARY · world world-cli world-importer Legacy SDS YAML bridge world-providers AWS · CF · Grafana · Solana BINARY · sds-agent world-agent world-lang DSL compiler · world fmt world-graph DAG · Policy · Locks · Journal world-http HTTP/1.1 · SigV4 · Docker API world-codec (0 external dependencies) JSON · YAML 1.2 · SHA-256/512 · HMAC · RFC 8032 Ed25519 · Base58

That wasn’t dogmatism — it paid off directly in debugging and security:

  • Ownership of subtle bugs: When our connection-cap test caught Linux sending a TCP RST instead of a clean FIN after a 503 Busy response, or when live Docker testing caught a 15-second stop timeout on service deletion, the entire stack was small, readable Rust we could fix in minutes.
  • Pragmatism where it matters: We didn’t hand-roll TLS 1.3 or KMS encryption. Verified HTTPS delegates cleanly to stdin-piped curl --globoff -K - (keeping auth tokens off process arguments and binary bodies in 0600 zero-wiped temp files), SOPS decryption pipes from sops -d, and on-chain transaction signing calls solana.
  • Instant builds & zero supply-chain bloat: An optimized cargo build --release finishes in under 10 seconds with zero transitive dependencies to audit.
Where It Goes Next

Today flint-world validates all 169 live Flint resources across devnet, mainnet, and opsnet and passes 53 end-to-end tests — including real Docker 27.5.1 blue/green cutovers, blob mounts, and log demuxing. Next up: running in shadow CI alongside the legacy pipeline to verify 100% parity on real PRs, rolling sds-agent onto devnet hosts, and exploring CUE-style algebraic constraint lattices inside world-lang so invariants become un-bypassable at compile time.