Skip to content

Hybrid Execution Semantics

This document explains the exact runtime guarantees, ordering rules, durability invariants, and explicit fail-closed boundaries of Netherframe's default hybrid execution engine.

Hybrid execution is faster than Terraform Core partly because it eliminates external process orchestration and HCL evaluation overhead. Making its semantic contract explicit ensures speed never comes from quietly omitting safety checks.


Design principle: Strict and fail-closed by default

Hybrid execution follows a strict-by-default contract:

  • Core plan/apply safety checks are always on; there is no matrix of flags to opt into basic correctness.
  • When a Terraform-only feature is not implemented safely in hybrid mode (such as provisioner blocks, create_before_destroy, count/for_each, or Fn.* calls), Netherframe fails closed with an explicit diagnostic rather than silently ignoring or approximating it.
  • Unattended execution (--auto-approve) refuses high-risk implicit changes—externally deleted objects, undeclared stack deletions, or unapproved imports—unless you explicitly opt in or apply a saved, reviewed plan.

1. Whole-app graph and dependency ordering

An app has one dependency graph spanning every stack it declares:

  • Dependency edges come from attribute references (vpc.output.id), explicit depends_on, replace_triggered_by, and references inside provider configurations.
  • Stacks are organizational scopes, not execution barriers. Independent stacks plan and apply concurrently up to max_concurrent_reads (default 40) and max_concurrent_resources (default 10). Cross-stack references without resource-level cycles (a.first → b.second → a.third) plan and apply cleanly.
  • Failure isolation: A failed resource skips only constructs that depend on it (in any stack); independent branches continue or stop cleanly according to your recovery strategy.
  • Construct addressing: Every construct has a unique address (<stack>.<type>.<name>, <stack>.data.<type>.<name>, <stack>.ephemeral.<type>.<name>, <stack>.output.<name>). A data source and managed resource may share a type and name, just as in Terraform.
  • Circular dependencies: Cycles fail planning with CircularDependencyError unless phased resolution (enable_circular_dep_resolution) is enabled, which breaks the cycle explicitly with a warning so creation can converge across passes.

2. Planning, refresh, and unknown values

Planning never writes state

plan, plan_stack, and create_stack_plan leave stored state untouched byte for byte. Refreshes read and upgrade in-memory copies of stored entries.

Refresh and external deletion

Before diffing desired configuration, plan refreshes stored resources via provider ReadResource (upgrading older state schemas and resource identities first):

  • If a provider returns no object, the object was deleted outside Netherframe. By default (deleted_objects="review"), the plan schedules recreation, flags it in deleted_outside_resources, and blocks --auto-approve until reviewed (recreate allows unattended recreation; error fails the plan).
  • Refresh failures are preserved in summary.refresh_diagnostics and block unattended apply when a resource's live state is unknown.

Dependency-ordered planning and unknown propagation

Each construct is planned only after its prerequisites are planned:

  • A reference to a resource with a planned change reads its planned values (known values verbatim, computed unknowns as UNKNOWN); references to unchanged resources read their refreshed state.
  • Values not yet known are sent to the provider as UNKNOWN (distinct from null) via go-cty MessagePack encoding, and displayed as (known after apply). Any string or expression combining an UNKNOWN operand becomes UNKNOWN as a whole.
  • For updates, proposed new state follows Terraform's rule: written configuration merged with prior-state values for unset computed attributes. No-op provider plans are dropped so an immediate re-plan after apply is empty.
  • Some providers contact remote registries during PlanResourceChange (for example, Helm fetching a chart to validate a helm_release). Treat plan-time external lookups as a plan requirement.

Data sources, ephemeral resources, write-only arguments, and outputs

  • Data sources (ReadDataSource): Read during planning when their configuration is known and no depends_on resource has a planned change; otherwise deferred to apply time. Stored in state with mode: "data".
  • Ephemeral resources (OpenEphemeralResource): Opened at their place in the walk, renewed if requested, and closed when the run finishes. Deferred to apply when inputs are unknown. Ephemeral values may flow only to write-only arguments or other ephemeral resources—never to plans, outputs, or state.
  • Write-only arguments: Sent in configuration only, stripped from planned/stored state (null), and never trigger diffs; bump the companion version argument to rotate values.
  • Outputs: Evaluated as graph nodes, stored under <stack>.output.<name> (with sensitivity metadata), and shown under "Changes to Outputs". A plan changing outputs alone still counts as a change requiring approval.

3. Immutable saved plans and final-plan consistency

Saved plan integrity

A plan saved with nf plan --out FILE is a frozen execution contract, not a hint:

  • Records every node's planned change, unknown_values masks, deferred changes, provider binary/config fingerprints, declared app-check names, app inputs (secrets as salted digests), state serial/lineage/state_fingerprint, and a SHA-256 content_digest (with optional HMAC signing).
  • nf apply --plan-file refuses plans whose digest fails verification, whose state serial or fingerprint has moved, whose provider versions/configurations changed, whose inputs differ, or whose app no longer declares an app check recorded when the plan was made.
  • Applying a saved plan without the app source is only permitted when every planned configuration is fully known; plans containing UNKNOWN values require the app to re-plan at apply time.

Final-plan consistency check

When a change containing unknown values is re-planned at apply time, Netherframe checks that the provider kept every value known in the initial plan and kept the same action (an in-place update that suddenly requires replacement is refused):

  • Mismatches fail the resource with an inconsistent-final-plan error naming the changed attributes.
  • Even on providers using the legacy Terraform Plugin SDK type system, known-value drift fails closed by default (set allow_legacy_plan_drift=True to downgrade legacy-SDK known-value drift to a warning).

4. Replacement, deletion, and retention semantics

Replacement ordering

When a provider requires replacement (or replace_triggered_by forces one), the new object is planned fresh with no prior state so computed attributes become UNKNOWN and downstream dependents plan accordingly.

During apply, old objects are destroyed in reverse dependency order and new objects are created in dependency order:

  • If both a parent and its dependent are replaced, the dependent's old object is destroyed first, then the parent's old object, then the parent's new object is created, then the dependent's new object.
  • Removed resources that depend on a replaced resource are deleted before the replaced resource's old object is destroyed.
  • A failed delete of a dependent leaves the parent untouched.
  • Admitted graph-state plans (--concurrent-applies or --graph-plan-scope affected) apply each replacement as a single fenced operation.

Undeclared stacks and destroy

  • A whole-app plan deletes resources, data sources, and outputs belonging to stacks the app no longer declares (for example, a renamed or removed stack). These appear separately as undeclared_stacks and are refused under --auto-approve unless applying a reviewed saved plan.
  • nf destroy rebuilds the app with the deployment inputs recorded by the last apply (refusing conflicting overrides) and walks the dependency graph in reverse.
  • prevent_destroy blocks deletion and replacement at plan time and stops nf destroy before approval (honoring both code rules and rules recorded in state for removed resources).

Retained teardown (LifecycleRules(retain=...))

  • Marking a resource with LifecycleRules(retain="reason") keeps both the live object and its state entry across nf destroy (and prevents deletion if removed from code).
  • Everything a retained resource depends on—and everything depending on it unless marked retain=False—must also be retained, or the destroy is refused before approval.
  • After deleting non-retained resources, nf destroy reads each kept object back from its provider and runs its @retained_check validators; missing, unreadable, or failing kept objects fail the destroy.

5. Deferred provider configuration and rounds

When a provider's configuration depends on a resource or data source whose value is not yet known (or is changing in the current plan):

  1. The provider is started for schemas only; its resources and their dependents are listed under deferred_changes (provider_config_unknown / deferred_prereq), and import IDs waiting on runtime values are deferred as import_id_unknown.
  2. During nf apply, once prerequisites finish, Netherframe configures the provider and plans/applies the deferred changes in rounds.
  3. Approval defaults to deferred_approval="each_round" (every deferred round is shown and approved separately; options: each_round, once, auto, always).
  4. A saved plan or --auto-approve apply executes deferred rounds only when apply_deferred (--apply-deferred) is enabled; otherwise the apply succeeds partially with ExecutionResult.complete == False and exits with incomplete_exit_code (default 4).

See Deferred Provider Configuration.


6. Adoption of existing objects

Adoption is always a reviewed import plan action—never an out-of-band state edit:

  • Requested via import_from(id), LifecycleRules(adopt=True | "required"), or an adoption manifest (--adopt-from, with optional --terraform-state).
  • Planning performs read-only ImportResourceState + ReadResource lookups and diffs against desired configuration (import if matching, update/replace marked importing if differing).
  • Missing objects plan a create unless adopt_missing="error" or adopt="required".
  • Duplicate adoption of an object already in state under another address is refused unless allow_duplicate_adoption=True.
  • --auto-approve refuses plans containing imports unless approve_imports=True (--approve-imports).

7. State durability, private data, and tainting

  • Document backends protect state with locking, lineage/serial conditional writes, periodic persistence every state_persist_interval seconds (default 20), pre-apply checkpoints, and <outdir>/errored.tfstate fallback.
  • PostgreSQL graph state commits each resource, output, and observation row immediately under renewable leases and fenced operations (reserved → dispatched → returned → committed/aborted), quarantining uncertain addresses for nf state recover.
  • Provider private data and identities are stored with every entry and round-tripped on subsequent reads, plans, applies, imports, and moves.
  • Partial provider failures & tainting: An object returned by a provider is recorded in state immediately—before post_apply runtime checks run. If a provider returns state alongside a create error, the entry is recorded and marked status: "tainted" so the next plan replaces it. Operators can also manage taint explicitly with nf state taint and nf state untaint.

8. Feature status matrix

Feature Hybrid status Behavior / Notes
State locking & conditional writes Supported Active across plan, apply, destroy, import, state edits
Plan refresh & drift detection Supported Read-only refresh; deleted_objects defaults to review
Dependency-ordered planning & unknowns Supported Whole-app graph; UNKNOWN kept distinct from null
Immutable saved plans Supported SHA-256 content_digest, serial/lineage, provider & input checks
Final-plan consistency Supported Fails closed on drift, including legacy SDK unless opted in
Deferred provider configuration Supported Multi-round convergence; deferred_approval="each_round", incomplete_exit_code=4
Data sources & ephemeral resources Supported Dependency-ordered; ephemeral values never written to plan/state
Write-only arguments Supported Sent in config only; omitted from plans and state
Private data & resource identity Supported Persisted and round-tripped across v5 and v6 providers
prevent_destroy, ignore_changes, replace_triggered_by Supported Enforced during planning and destroy
retain & Teardown[T] Supported Managed retention with dependency closure and post-destroy checks
App checks & finalizers Supported prerequisites, plan, apply, finalize + nf state verify
Adoption (import_from, adopt, manifests) Supported Planned import action; requires review or --approve-imports
Tainted resources Supported Automatic on partial create error; nf state taint / untaint
create_before_destroy Rejected (fail closed) Fails planning rather than approximating CBD
count / for_each Rejected (fail closed) Use Python loops to instantiate one construct per instance
provisioner / connection Rejected (fail closed) Use user data / cloud-init / baked images, or nf synth
Fn.* Terraform functions Rejected (fail closed) Use Python or @hybrid_runtime functions
Move / Import constructs Rejected (fail closed) Use nf state mv and import_from() / --adopt-from
Non-importable runtime checks Rejected (fail closed) Define checks as module-level functions for saved-plan serialization
Terraform precondition / postcondition / check blocks Rejected / Unsupported Use @runtime_check, @retained_check, and app.check