Skip to content

App Checks

A resource's runtime checks belong to the resource, and run only while the code declares it. An app check belongs to the app, and sees the whole run: the site's prerequisites before anything touches state, every change a plan makes, deletes of resources the code no longer declares among them, and, under the apply lock, the changes about to be made against the state read under that lock.

# coding: nf_autoid

import socket

from nf.core import App, AppCheckContext, Bind, BindContext, Provider, Resource, Stack


def cluster_reachable(ctx: AppCheckContext) -> str | None:
    """Before anything touches state: the site's cluster answers."""
    host = f"k8s.{ctx.inputs['env']}.example.com"
    try:
        socket.create_connection((host, 443), timeout=3).close()
    except OSError as exc:
        return f"the site's cluster ({host}) is unreachable: {exc}"
    return None


def keep_data(ctx: AppCheckContext) -> str | None:
    """Under the apply lock: no release holding data is deleted or replaced."""
    doomed = [change.address for change in ctx.changes_of(type="helm_release", actions=("delete", "replace")) if (change.before or {}).get("name") in {"postgres", "kafka"}]
    return f"would delete data-bearing releases: {', '.join(doomed)}" if doomed else None


def site(env: str = "dev") -> App:
    with App(nf_id="site") as app, Stack() as releases, BindContext:
        helm: Bind = Provider(nf_type="helm", kubernetes=[{"config_path": "~/.kube/config", "config_context": env}])
        for chart in ("postgres", "kafka", "web"):
            Resource(nf_type="helm_release", nf_id=chart, nf_provider=helm, name=chart, chart=chart, repository="oci://registry.example.com/charts")
    app.check(cluster_reachable, phase="prerequisites")
    app.check(keep_data, phase="apply")
    return app

app.check(function, phase=..., description=...) declares a check, as here; @app.check(phase=...) decorates one where the app is at hand. Inside an app factory, declare the checks on the app it builds. Define them at module level: a check is named by its module and name (app.cluster_reachable), in output and in saved plans.

Phases

Phase Runs Sees
prerequisites Before a plan, apply or destroy reads or creates state, the state backend's storage included (bootstrap_backend) The app and its inputs
plan Once a plan is made, the plan an apply makes included Every change, and the state planned against
apply (the default) Under the apply lock (and a destroy's), after a saved plan's staleness checks, before approval and before any provider changes anything The changes about to be made, and the state as read under the lock
finalize Once an apply or destroy has run, still under its lock: after it succeeded, failed part way or was stopped, and after one with nothing to change How the run went (run), and the state it left

A failing prerequisites or plan check stops the plan; a failing apply check stops the apply or destroy before it asks for approval; a failing finalize check fails the run, whose changes are made. Every failure is reported.

Writing A Check

A check gets an AppCheckContext:

  • phase, and operation: plan, apply or destroy
  • app, and inputs: the values the app was built with (++env=prod), by name
  • changes: each change as an AppChange: its address, stack, type, name, action (create, update, replace, delete, import), before (the object's attributes as stored; None for a create), after (the configuration planned; None for a delete) and reasons. changes_of(type=..., actions=(...)) selects some
  • state: each managed resource's attributes in state, by address
  • saved_plan: whether an apply runs a saved plan (nf apply --plan-file)

It passes when it returns None or True. It fails when it returns False (its description says why, else its name), a string saying why, a failed RuntimeCheckResult, or raises.

Finalizers

A finalize check verifies what a run leaves: an inventory of what it owns, an audit of what a destroy kept. It runs whatever the outcome, so a failed child deletion that stops a resource's own destroy still gets its verification; a run declined at approval, or refused before it changed anything, has nothing to finalize.

import hashlib
import json
from pathlib import Path

from nf.core import App, AppCheckContext, Evidence, Finalized

#: Kept outside nf: in production a bucket or a database the run's credentials can write
AUDIT = Path(".nf.out/audit")


def audit(ctx: AppCheckContext) -> Finalized:
    run = ctx.run
    problems = tuple(f"{item.address} {item.status}: {item.error}" for item in run.of("failed"))
    record = {"run": run.run_id, "attempt": run.attempt, "operation": run.operation, "kept": dict(run.retained), "owned": sorted(ctx.state)}
    body = json.dumps(record, sort_keys=True).encode()
    path = AUDIT / f"{run.run_id}-{run.attempt}.json"
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(body)
    return Finalized(problems=problems, evidence=(Evidence("audit", path.resolve().as_uri(), hashlib.sha256(body).hexdigest()),))


app = App(nf_id="site")
app.check(audit, phase="finalize")

examples/audited_runs runs one, and shows nf state verify after a kill -9.

ctx.run is a RunOutcome:

  • run_id, operation (apply or destroy), attempt (1 for the run; each nf state verify is the next) and resumed (an nf state verify of a run stopped hard)
  • success (None when a run stopped hard never said) and stopped (request_stop, the first Ctrl-C)
  • resources: each change's ResourceOutcome: address, action, status (completed, failed, skipped, or unknown for one a run stopped hard never recorded) and error; run.of("failed", "skipped") selects some
  • prior: what each changed resource was before the run, by address: its id and the provider's identity
  • retained: what a destroy kept (Keeping resources), with why
  • evidence: the references earlier attempts kept

ctx.state is the state the run left, read under its lock. Besides the values any check returns, a finalizer may return an Evidence reference (or several), or a Finalized with problems (all reported) and evidence. Evidence is a reference only (kind, uri, sha256, schema_version): nf keeps it in the run record, never the evidence, and shows its kind and digest, not its uri. A finalizer must be idempotent: nf state verify runs it again.

Run records

A run of an app with finalizers writes a run record beside its state before its first change (<state>.runs/<run id>.json, on local and S3 state), and completes it once its finalizers ran. From the start it holds what a later verification needs that state may no longer have: the changes planned, the prior id and provider identity of each resource they change (nothing else of them) and what the run keeps, with why. So the finalizers of a run stopped hard see the same prior and retained, even for resources deleted since or no longer declared:

  • running: changes started and the finalizers have not finished. A run stopped hard (killed, a second Ctrl-C, a lost machine) leaves it so.
  • finalized: they passed. failed: they ran and reported failures.
  • abandoned: given up on, with nf state abandon RUN_ID.

running and failed records are never pruned; of the others, the newest 20 are kept. nf state runs lists the unresolved ones (--all: every one). nf state verify [RUN_ID] takes the state lock and runs the finalizers again as the record's next attempt, against state as it is, for the newest unresolved run or RUN_ID. It refuses when another run wrote state since: each run that writes state stamps it with its id (metadata.last_run), and verifying one run against another's state would certify the wrong thing. Check it, then nf state abandon the run.

On a state backend that keeps no run records (GCS, Azure, Consul, HCP Terraform, graph state for now) finalizers run all the same, and the run warns that one stopped hard cannot be verified later.

nf apply --json and nf destroy --json give the run's run_id and its finalization: its status, attempt, problems, the evidence kept (kind and digest) and where its record is.

Saved Plans

nf plan --out records the names of the app's checks with the plan. nf apply --plan-file runs the apply checks again, under the lock, against state as it is then, and refuses a plan made with a check the app no longer declares: a check cannot be dropped between review and apply.