Tutorial 3: Guardrails, rollback, and audited runs
In this tutorial you will experience three safety mechanisms built into Netherframe's hybrid runtime:
- Automatic rollback (
recovery_strategy="ROLLBACK") when a step fails partway through an apply, powered by a@hybrid_runtimePython function. - App-wide checks (
app.check) that gate a run before state is touched (prerequisites) and after planning (plan). - Finalizers (
phase="finalize") that write verifiable audit evidence under the state lock and can be resumed withnf state verify.
Everything runs locally with hashicorp/random—no cloud account required.
Before you start: Complete Tutorial 1 and Tutorial 2 in the same environment.
Step 1: Write the guarded, self-cleaning app
Create release.py in your tutorial directory:
# coding: nf_autoid
import hashlib
import json
from pathlib import Path
from typing import Literal
from nf.core import (
App,
AppCheckContext,
Bind,
BindContext,
Evidence,
Finalized,
Output,
Stack,
Teardown,
)
from nf.core.runtime.runtime import hybrid_runtime
from nf.providers.hashicorp.random import Pet, RandomProvider
HERE = Path(__file__).parent
AUDIT_DIR = HERE / ".nf.out" / "audit"
@hybrid_runtime
def release_label(slot: str, manifest_name: str) -> str:
"""Run during apply once `slot` exists, reading the local manifest file."""
data = json.loads((HERE / manifest_name).read_text())
return f"{slot}-v{data['version']}"
def require_ticket_in_prod(ctx: AppCheckContext) -> str | None:
"""Prerequisite check: runs before state is read or created."""
if ctx.inputs["env"] == "prod" and not ctx.inputs["ticket"]:
return "prod runs require a change ticket (pass ++ticket=CHG-123)"
return None
def no_replacements_in_prod(ctx: AppCheckContext) -> str | None:
"""Plan check: inspects every planned change."""
if ctx.inputs["env"] != "prod":
return None
risky = [c.address for c in ctx.changes_of(actions=("replace", "delete"))]
if risky:
return f"prod forbids destructive changes in routine runs: {', '.join(risky)}"
return None
def write_audit_record(ctx: AppCheckContext) -> Finalized:
"""Finalizer: runs under the state lock after every apply or destroy."""
run = ctx.run
record = {
"run_id": run.run_id,
"attempt": run.attempt,
"operation": run.operation,
"changes": {item.address: item.status for item in run.resources},
"owned": sorted(ctx.state),
}
body = json.dumps(record, indent=2, sort_keys=True).encode()
AUDIT_DIR.mkdir(parents=True, exist_ok=True)
path = AUDIT_DIR / f"{run.run_id}-{run.attempt}.json"
path.write_bytes(body)
problems = tuple(f"{item.address} {item.status}" for item in run.of("failed", "unknown"))
evidence = Evidence("audit", path.resolve().as_uri(), hashlib.sha256(body).hexdigest())
return Finalized(problems=problems, evidence=(evidence,))
def release(
env: Literal["dev", "prod"] = "dev",
manifest: str = "release.json",
ticket: Teardown[str] = "",
) -> App:
with App(nf_id="release", recovery_strategy="ROLLBACK") as app, Stack(nf_id=f"stage-{env}"), BindContext:
random: Bind = RandomProvider()
slot: Bind = Pet(nf_provider=random, length=2)
label: Bind = Pet(
nf_provider=random,
length=1,
prefix=release_label(slot.output.id, manifest),
)
released: Bind = Output(value=label.output.id)
app.check(require_ticket_in_prod, phase="prerequisites")
app.check(no_replacements_in_prod, phase="plan")
app.check(write_audit_record, phase="finalize")
app.enable_hybrid_execution_local(path=f".nf.out/release-{env}.tfstate")
return app
Register release in pyproject.toml:
[tool.nf]
apps = ["release:release"]
Step 2: Test the prerequisite check
Try planning for prod without a change ticket:
nf plan --app release ++env=prod
Netherframe stops immediately before touching state or starting any provider:
prod runs require a change ticket (pass ++ticket=CHG-123)
Step 3: Trigger automatic rollback on failure
Notice we have not created release.json yet. Run an apply in dev:
nf apply --app release
Approve with yes. Watch what happens:
stage-dev.random_pet.slotis created first.stage-dev.random_pet.labelrunsrelease_label(...)during apply and fails withFileNotFoundErrorbecauserelease.jsondoes not exist.- Because
recovery_strategy="ROLLBACK"is set, Netherframe automatically deletesstage-dev.random_pet.slotand reportsRolled back 1 resources created by this apply. - The finalizer still runs and records the failed run in
.nf.out/audit/.
Confirm that state was left completely clean (a fresh plan still proposes creating both
slot and label):
nf plan --app release
No half-created slot remains in state.
Step 4: Fix the manifest and apply cleanly
Create release.json:
{"version": "1.0.0"}
Run nf apply again:
nf apply --app release
Approve with yes. Both slot and label succeed, released outputs the combined name
(for example, brisk-heron-v1.0.0-falcon), and the finalizer writes a new SHA-256 hashed
audit record under .nf.out/audit/.
Step 5: Inspect run records and re-verify
List the recorded runs for this app:
nf state runs --app release
You will see both the failed (rolled-back) run and the finalized successful run, along with attempt counts and evidence references.
If a run were ever killed mid-flight (kill -9 or a lost CI runner), its record would stay
in running status and nf state verify --app release would re-run your finalizers under
the state lock, marking any unrecorded resource changes explicitly as unknown.
Step 6: Clean up
nf destroy --app release
Approve with yes. Notice that the finalizer runs after nf destroy as well, recording
the teardown in .nf.out/audit/.
What you just learned
- How
@hybrid_runtimeexecutes ordinary Python with resolved values during apply. - How
recovery_strategy="ROLLBACK"cleans up newly created resources after partial failure. - How
app.checkenforces policy atprerequisites,plan,apply, andfinalize. - How run records and
nf state runs/nf state verifyguarantee verifiable outcomes.
Next steps
- Try the runnable repo examples:
examples/rollback_on_failure,examples/guardrails, andexamples/audited_runs(which includes akill -9rehearsal). - Understand the safety model: Read How Netherframe works and Hybrid execution semantics.
- Go deeper on checks and recovery: See App checks and finalizers and Rollback and recovery.