Skip to content

How Netherframe Works: Architecture and Internals

This page explains how Netherframe turns Python code into planned, verified, and durable infrastructure changes. It covers every layer of the system—from construct instantiation and runtime values down to gRPC provider calls, state engines, and crash recovery.

For a quick hands-on walkthrough first, see Tutorial 1: Run your first hybrid app. For exact runtime guarantees and fail-closed rules, see Hybrid Execution Semantics.


End-to-end pipeline

In Netherframe's default hybrid execution mode, the Python process you run is the orchestration engine:

flowchart LR
    A["Python App & Inputs"] --> B["Construct Tree & Dependency Graph"]
    B --> C["App Checks (prerequisites)"]
    C --> D["State Engine & Lock/Lease"]
    D --> E["Dependency-Ordered Planner"]
    E --> F["Provider Pool (tfplugin5/6 gRPC)"]
    F --> G["Cloud & Service APIs"]
    E --> H["Saved Plan / Approval"]
    H --> I["App Checks (plan / apply)"]
    I --> J["Parallel Orchestrator"]
    J --> F
    J --> D
    J --> K["Finalizers & Recovery"]

When you use legacy compatibility (nf synth), the pipeline stops after building the construct tree and emits Terraform JSON (or HCL) under .nf.out/ for an external Terraform or OpenTofu process to execute.


1. Python authoring and the construct tree

Every Netherframe app is a tree of Python objects rooted at an App:

  • App owns execution settings, recovery strategy, app-wide checks (app.check), and one or more Stack children.
  • Stack groups Provider configurations, Resource declarations, DataSource reads, EphemeralResource opens, and Output values.
  • Every construct gets a stable state address of the form <stack>.<resource_type>.<resource_id> (for example, network.aws_vpc.main).

Explicit auto-ID injection (nf_autoid)

Writing nf_id="vpc" on every construct is repetitive, yet implicit frame inspection is fragile. Netherframe solves this with an opt-in Python source codec (# coding: nf_autoid from netherframe.codec.autoid, registered via a lightweight .pth file at interpreter startup):

  • Only files carrying # coding: nf_autoid are transformed via libcst.
  • Only explicit binding markers are rewritten:
  • name: Bind = Construct(...) or name: Bind[T] = Construct(...) injects nf_id="name".
  • with Construct() as name, BindContext: injects nf_id="name".
  • Plain assignments (vpc = Vpc(...)) are never rewritten, so helper variables cannot silently alter state addresses.

Typed provider bindings and the nf.* alias

nf generate providers inspects a provider's schema over gRPC and generates a standard Python package (netherframe.providers.<namespace>.<type>) with typed constructors, keyword-only nested block dataclasses, and typed output accessors.

At runtime, nf.* is a permanent alias for netherframe.* (import nf.core returns the exact same module object as import netherframe.core), backed by a runtime import hook and generated shim modules so static type checkers and IDEs understand both spellings.


2. Typed app inputs and configuration layers

Netherframe deliberately reads no NF_* environment variables. Every value that shapes an infrastructure run is explicit and reproducible:

  • Settings (parallelism, recovery strategy, backend target, timeouts, provider mirrors) follow a strict 5-layer precedence order:
  • CLI flag (nf --max-concurrent-resources 20 apply) or Project(settings=...)
  • [tool.nf.config] in pyproject.toml
  • Direct App(...) or backend constructor argument (conflicting [tool.nf.config] and code settings fail fast with ConfigurationError)
  • Machine-local user defaults in ~/.config/nf/config.toml (strictly limited to TUI, logging, and provider cache/mirror settings—never engine or backend choices)
  • Built-in default
  • App inputs are the type-annotated parameters of an app factory function (def shop(env: Literal["dev", "prod"] = "dev", ...) -> App). Given as ++env=prod or ++@prod.toml, they are resolved before the construct tree is built. Deployment inputs are recorded in state on apply so nf destroy always rebuilds against what was actually applied; Teardown[T] inputs are verified to change only lifecycle policy (retain, prevent_destroy) and nothing about the deployed resource shape.

3. Runtime values, tokens, and the dependency graph

When your Python app executes, cloud resources do not exist yet. Referencing vpc.output.id returns a RuntimeValue—a typed placeholder carrying its source construct, attribute path, and schema type.

  • Strings and JSON: Formatting a RuntimeValue in an f-string (f"subnet-{vpc.output.id}") or serializing it with json_nf_dumps embeds a token that preserves the dependency edge.
  • Expressions: Arithmetic, indexing, slicing, and boolean/comparison helpers (.eq(), .ne(), runtime_len(), runtime_contains()) build expression ASTs evaluated consistently in hybrid execution and Terraform synthesis. Truthiness (if vpc.output.id:) raises TypeError immediately so unknown values never silently branch in Python.
  • Whole-app graph: Netherframe builds one dependency graph across every stack in the app. Edges come from attribute references, explicit depends_on, replace_triggered_by, and provider configuration references. Stacks organize names and ownership without acting as artificial execution barriers: independent stacks plan and apply in parallel under the shared concurrency limits (max_concurrent_reads / max_concurrent_resources).
  • Circular dependencies: When resources form a reference cycle and phased resolution is enabled, Netherframe partitions the cycle into ordered phases so creation can converge.

4. Dependency-ordered planning and saved plans

During nf plan, Netherframe walks the whole-app graph in topological order:

  1. Refresh: Existing managed objects in state are refreshed through provider ReadResource calls (upgrading older state schemas and identities first). Planning never mutates stored state.
  2. Validate and plan: Each construct is validated (ValidateResourceConfig) and planned (PlanResourceChange) once its prerequisites have been planned. References to a resource with a planned change see its planned values (known values as-is, computed unknowns as UNKNOWN), matching Terraform's graph walk.
  3. Deferred provider configurations: If a provider's own configuration depends on a value not known yet (such as an EKS cluster endpoint being created in the same run), the provider is started for schemas only and its constructs are recorded as deferred changes. During nf apply, once prerequisites finish, Netherframe configures that provider and plans/applies the deferred round.
  4. Immutable saved plans: nf plan --out FILE writes a self-contained JSON plan artifact containing every planned change, unknown-value masks, deferred records, provider binary/configuration fingerprints, declared app-check names, app inputs (secrets as salted digests), state serial/lineage/fingerprint, and a SHA-256 content_digest (with optional HMAC signing). Applying a saved plan refuses stale state, mismatched inputs, changed provider fingerprints, or removed app checks.

5. Provider protocol (tfplugin5 / tfplugin6)

Netherframe communicates directly with standard Terraform provider binaries over local gRPC:

sequenceDiagram
    participant NF as Netherframe Engine
    participant P as Provider Binary (subprocess)
    NF->>P: Launch with go-plugin handshake env
    P-->>NF: stdout: 1|6|unix|/tmp/...|grpc
    NF->>P: GetProviderSchema / GetResourceIdentitySchemas
    NF->>P: ConfigureProvider
    NF->>P: ReadResource (refresh)
    NF->>P: ValidateResourceConfig & PlanResourceChange
    NF->>P: ApplyResourceChange
    NF->>P: StopProvider
  • Protocol negotiation: Both protocol v5 and v6 are supported automatically based on the handshake response.
  • Type-faithful serialization: Payloads are encoded as DynamicValue using go-cty MessagePack rules (CtyMsgpackDecoder), preserving unknown markers (UNKNOWN) distinctly from null, arbitrary-precision numbers, sets, maps, and nested blocks.
  • Private state and identities: Opaque provider private bytes and ResourceIdentity objects are persisted alongside each state entry and round-tripped on every read, plan, apply, and move.
  • Verified installation: Providers are fetched from registries or mirrors (network mirrors like Artifactory/Nexus or filesystem mirrors) with OpenPGP SHA256SUMS signature and h1:/zh: checksum verification.

6. State engines: Document state vs. PostgreSQL Graph State

Netherframe supports two state architectures behind its state-engine protocols:

Document state backends (local, S3, GCS, Azure, Consul, PostgreSQL doc, HCP Terraform)

State is stored as a versioned document with a lineage and monotonic serial:

  • Mutual exclusion: A run acquires the backend lock (flock locally on POSIX; remote locks in cloud backends) before reading or writing.
  • Compare-and-swap writes: Every write carries the precondition that stored state still matches the serial the run read (conditional put, ETag/generation match, CAS). A run whose lock lapsed can never overwrite a newer run's state.
  • Periodic durability: During apply, completed resource results are flushed every state_persist_interval seconds (default 20 s) and at run completion; if final storage fails, uncommitted state is preserved in <outdir>/errored.tfstate.

PostgreSQL Graph State (PostgreSQLGraphBackend)

For large shared apps or teams applying concurrently, state is stored as normalized rows in PostgreSQL (nf_entries, nf_outputs, nf_operations, nf_leases, nf_versions, nf_edges, nf_baselines):

  • Row-level commits: Every resource change commits immediately on completion with its own revision, incarnation, and full version history.
  • Fenced operations: Every mutating provider RPC is recorded durably as a state machine (reserved → dispatched → returned → committed/aborted). If a process crashes or loses its renewable lease, its provider processes are terminated and any uncertain address is quarantined until resolved with nf state recover.
  • Concurrent applies & affected planning: With --concurrent-applies and a retained branch baseline, runs whose changes are provably disjoint acquire fine-grained resource grants instead of an app-wide lock. With --graph-plan-scope affected, qualified workloads plan only the dependency closure of what changed.

7. Safety, verification, and recovery layers

Netherframe treats failure, teardown, and auditability as first-class engine phases:

Mechanism When it runs What it guarantees
App checks (prerequisites, plan, apply) Before state access, after plan, and under the apply lock before approval Enforces org/environment invariants across the whole run, including deleted undeclared stacks
Finalizers (phase="finalize") Under the lock after every apply or destroy (success, partial failure, or stop) Records RunOutcome and hashed Evidence references; a run killed by kill -9 stays unresolved until nf state verify runs under the lock
Recovery strategy (CHECKPOINT, ROLLBACK, NONE) After a failed or stopped apply/destroy CHECKPOINT retains a pre-run state snapshot; ROLLBACK deletes resources created by the failed apply and restores affected outputs
Retained teardown (LifecycleRules(retain=...)) During nf destroy (and removal plans) Keeps retained objects and their dependency closure in state, verifies they still exist via provider reads, and runs @retained_check validators
Final-plan consistency At apply time when re-planning unknown values Ensures known planned values and actions did not drift between plan and apply (failing closed even on legacy SDK providers unless allow_legacy_plan_drift=True)

8. SDK, CLI, and TUI layering

Every nf command is implemented first in netherframe.sdk (nf.sdk.Project and nf.sdk.AsyncProject), which binds project roots, settings, and inputs per call using contextvars (never calling os.chdir()).

  • The CLI (netherframe.cli) parses arguments, invokes nf.sdk, renders structured tree diffs and live progress, and emits terminal status sequences (OSC 7501 / OSC 9;4) where supported.
  • The TUI (nf tui) is built on Textual using an Elm-style immutable Model + pure update(model, message, env) loop, supporting live run following, dependency graph visualization (:graph), read-only guards, and deterministic JSONL session recording and replay (nf tui --record / nf tui replay).

Where to go next