Graph State Backend
A hybrid app can keep its state in PostgreSQL as rows instead of one document: one row per
resource, output and data source result, each committed as soon as its change completes, with a
history of every version. Every mutating provider call (ApplyResourceChange) and state import or
move is a durable operation whose stage is recorded before and after the call, so a run that crashes
or loses its lease leaves nothing unrecorded: recovery finishes or aborts each operation.
The backend provides the graph state backend RFC's
rows, operations and recovery, symbolic intent, pinned baselines, three-way conflict detection and
authoritative input revisions. Independent branch changes can be combined; preserved consumers
whose inputs change are marked for reconciliation atomically with those changes. By default,
applies use an app-wide lease. concurrent_applies=True selects resource grants for plans with
complete coverage and supported object identities. Every new grant checks run grants, retained
operation footprints and older conflicting waiters through one fair atomic queue. App and stack
applies plan unleased, acquire their complete grant and validate before approval. The protocol follows the TLA+ model in
specs/graph-state/ (Graph State Backend Model).
Reverse dependencies and their generations are maintained transactionally. The backend can validate
a plan's observed rows, input proofs and reverse predicates under its actual granted leases;
resource-level mutation footprints and claim-based recovery preserve those preconditions across
run loss.
The combined execution model also covers a replacement's delete and create as one operation, alongside an updating sibling or a dependent and a provider alias waiting on the same canonical object identity. TLC traces replay against memory and PostgreSQL, checking the gap, retained identity protection, late responses, recovery, tombstones and the new incarnation. A further combined model covers initial/deferred approval, immutable round coverage and time or complete grant loss during SQL waits, including rollback of buffered writes. Its traces use actual bounded approval and real PostgreSQL lock waits; real AWS workloads also verify deferred timeout after a buffered first-round commit. These are finite scenario checks with admission and recovery claims as atomic assumptions. The provider/read audit records the implemented RPC and cache dispositions and their explicit observation contracts.
The graph backend is hybrid-only: Terraform cannot read this state, and it is not a backend construct synthesis can write. Document backends (local, S3, GCS, Azure, Consul, the PostgreSQL document backend, HCP Terraform) are unchanged.
Setup
from nf.backends.postgresql import PostgreSQLGraphBackend
from nf.core import App
app = App(nf_id="app")
# ... stacks and resources ...
backend = PostgreSQLGraphBackend(
state_id="app", # one app's state; several apps can share a database
host="db.internal", # nf --postgresql-host or [tool.nf.config] postgresql_host overrides it
database="netherframe", # postgresql_database
username="nf_apply", # postgresql_username
ssl_mode="verify-full",
ssl_ca="/etc/ssl/rds-ca.pem",
)
app.enable_hybrid_execution(state_backend=backend)
The password is never an argument or a flag, and never logged. It comes from a file
(nf --postgresql-password-file, postgresql_password_file in [tool.nf.config], or
password_file=: a mounted secret, or process substitution <(...)) or a callable
(password_source=, such as a secrets manager client). Nothing is read from the environment.
Keep it out of code and out of chat.
End active runs before calling backend.close(). Closing permanently stops that instance from
accepting work; use a new backend instance for later operations. A heartbeat cannot reopen its
connections after closure. Closing does not clear durable unresolved operations or their retained
footprints; those still use the normal recovery protocol.
The backend creates its schema (nf_graph by default, tables prefixed nf_) and applies its
migrations on first use, serialized across processes. The release schema starts at version 1
in nf_schema_migrations. The upgrade retains development migration history in
nf_development_schema_migrations and preserves the data and lineage. End active runs and
update all writers before opening an existing database with the release version.
Construction resolves configuration but opens no connections, starts no event-loop thread and
does not read the password. First use creates one pool and runs initialization; concurrent first
uses of the same instance share that work. Schema, table-prefix and reader-role names are plain,
unquoted SQL identifiers, normalized to lowercase so state identities, migration locks and role
checks agree with PostgreSQL. NF_ therefore selects the same tables and views as nf_.
TLS modes follow PostgreSQL negotiation semantics: prefer (the default) tries TLS before
falling back, allow tries plaintext first, and disable uses plaintext. require requires TLS;
verify-ca also validates the certificate and verify-full validates the hostname. Use
verify-full with the appropriate CA for authenticated TLS. Unknown mode names fail during
construction. Lease TTL and renewal interval must be finite and positive, with renewal below
TTL; recovery quiescence must be finite and non-negative (zero disables that bound).
| Table | Holds |
|---|---|
nf_apps |
Per app: lineage, schema version, ownership epoch, commit counter (the frontier), metadata |
nf_entries |
One row per resource address: state, revision (never reused, kept by tombstones), incarnation (new when the object is created, replaced, adopted or moved in), object_identity (unique within the app), intent_fp, consumed inputs, applied_fp, status (ready, tainted, uncertain, stale_inputs, unconverged), sensitive paths |
nf_outputs |
One row per output, with revision, intent, inputs, evaluated fingerprint, status and tombstone |
nf_observations |
Data source results: a cache, never versioned or compared |
nf_versions |
Every committed version of every row, with its commit sequence, run and operation |
nf_convergence_evidence |
Immutable upgrade certificates for retained resource versions; removed with their versions |
nf_commits |
Every commit: sequence, run, epoch, and the lease expiry its fence checked |
nf_runs |
Every run: operation, actor, host, epoch, status, expires_at, immutable branch origin, pending/granted lease state and the granted set |
nf_run_mutations |
Durable evidence that a run has dispatched a call or committed state; its grant must then remain until the run ends |
nf_leases |
Granted keys and modes: app-wide X by default, resource grants with concurrent applies |
nf_grant_checks |
Exact-grant validation results; database triggers invalidate them when lease keys, owners or modes change |
nf_lease_queue |
Immutable all-at-once requests, in ticket order; waiting requests hold nothing |
nf_operations |
Every operation: stage, expectations, request, returned result, outcome |
nf_baselines |
Retained origins: pin ID, state ID, lineage, sequence and an intent history digest |
nf_checkpoints |
Pre-apply write targets, pinned revisions and digests, origin run and history/operation frontiers |
nf_checkpoint_restores |
Atomic restore receipts: run, checkpoint, force policy and resulting sequence |
nf_edges |
Authoritative reverse dependencies, including ordering edges and broad read scopes |
nf_edge_generations |
Monotonic counters for changed reverse predicates, retained after edges disappear |
Construction and validation costs
Rows become durable through fenced commits. Consumed inputs construct reverse edges; missing input knowledge conservatively creates an app-wide predicate, while an explicitly empty input set records no reads. Ordering dependencies also contribute edges. Broad predicates cover future members without expanding the graph into today's members. Their generations survive edge removal, so removing and restoring a dependency still invalidates an earlier plan.
Concrete plan inputs use point lookups for both revision and uncertainty checks. With no unresolved operations, validating N concrete inputs no longer scans N rows for each input. Broad scopes still examine their members, and unresolved operations still protect absent rows and retained footprints. Commits with unchanged dependencies reuse the local edge index when its generations are unchanged. A generation-only delta still invalidates old evidence.
The backend validates a grant's entire key-to-mode mapping when it is installed, then checks its validation result at each mutation's initial and final fence. Lease edits and truncation invalidate that result in the same transaction; setting it back to true through SQL recomputes the exact mapping. Installation and invalidation serialize on the validation row, independently of the run row, so a lease loss during an operation's SQL wait remains visible at the final fence. Missing validation rows fail closed. Upgrades check existing grants before certifying them. Ownership, expiry, admission and unresolved-operation checks still run; the validation result does not cache liveness. Per-mutation footprint reads fetch only required keys and their ancestors, including an app-wide covering lease. These changes avoid rescanning and transferring the entire grant for each row commit. Admitted-plan membership checks and the serialized commit counter retain separate costs.
The backend stores the admitted write set, auxiliary targets and possible actions in generated
columns on nf_runs. Permission checks read these smaller projections instead of repeatedly
unpacking the complete admission proof. PostgreSQL derives the columns from admitted_plan,
refuses independent edits and clears or replaces them when admission changes. The original proof,
closed-write/action checks and initial/final ownership fences remain authoritative. Membership
checks still grow with the write set, and the commit counter still orders publications.
The upgrade backfills existing runs and rewrites nf_runs while holding a table lock; its duration
and extra storage depend on retained admission history. Large installations should account for
that one-time migration cost when scheduling the upgrade.
The repeatable Python measurements in tests/performance/graph_python.py isolate these two
costs at 100, 1,000 and 10,000 rows. On the recorded host, the 10,000-row concrete-input check
fell from 1.84 seconds to about 63 milliseconds; applying 1,000 unchanged edge deltas fell from
367 milliseconds to under 1 millisecond. These isolate Python wall time, not total apply time.
SQL, grant installation, broad scopes, history validation, changed-edge copies and provider
calls retain their own costs. See tests/performance/README.md for captures and database workloads.
Branch baselines
A baseline records the deployed state your code was based on. For example, your branch started at sequence 100; another branch added a database at 101. The baseline distinguishes "my branch has never declared that database" from "my branch deliberately deleted it."
From a checkout whose configuration matches the deployed state, pin the origin before branching:
# Existing states first need a reviewed apply to record their symbolic intent.
nf apply --app demo
nf state --app demo baseline pin
# Commit nf.baseline with the code, then create the branch.
nf plan --app demo
For a graph backend, planning automatically reads nf.baseline from the current directory.
The JSON reference contains the backend type, state ID, lineage, commit sequence and pin ID;
using it with another state fails. Pinning a frontier does not verify that your checkout matches
it: do not pin the latest frontier from an old branch and treat it as that branch's origin.
nf state --app demo baseline show
nf state --app demo baseline pin --at 100 --file release.baseline
nf plan --app demo --baseline release.baseline
nf plan --app demo --baseline 100 # pins this sequence for the plan
nf plan --app demo --baseline RUN_ID # pins this run's last committed frontier
nf state --app demo baseline unpin PIN_ID
Keep separate files for separate apps and select them with --baseline. File replacement leaves
earlier pins intact because other branches or saved plans may still need them; release those pins
explicitly once unused. Pins protect each entry's origin against retention. Retention keeps a
boundary version of each entry so frontiers within the retained window can still be pinned.
Older frontiers need an existing pin; incomplete origins are rejected, never read as absence.
Python callers can set App(baseline=...) and App(prefer_mine=(...)); CLI flags override them.
Planning scope
Full planning is the default. To request affected planning from a retained branch baseline,
use this App constructor in the graph backend setup.
from nf.core import App
app = App(nf_id="app", baseline="nf.baseline", graph_plan_scope="affected")
nf plan --app demo --graph-plan-scope affected --out reviewed.plan.json
nf apply --app demo --plan-file reviewed.plan.json
nf apply --app demo --graph-plan-scope affected
nf deploy --app demo --graph-plan-scope affected
These commands read the app's nf.baseline as described above. The setting also accepts
[tool.nf.config].graph_plan_scope = "affected" or App(graph_plan_scope="affected").
Precedence is flag > project > App value > full. Invalid values fail.
An affected request requires graph state and a valid retained baseline, even for an empty plan.
The setting controls planning scope; concurrent_applies independently controls grant policy.
Affected planning refreshes and evaluates a selected dependency closure. Its review names the
inspected resources and explicitly reports that unrelated infrastructure was not inspected for
external drift. Use --graph-plan-scope full when planning an app-wide refresh. An omitted payload
does not mean a resource was deleted: removals require the complete desired manifest and retained
branch/current intent evidence. Selected reads and writes still pass ordinary immutable admission
before approval and provider mutation.
Review also reports retained consumers and downstream outputs that will need reconciliation after their inputs change. An apply that preserves newer consumer configuration can succeed while remaining incomplete; applying an older branch does not reconcile those newer consumers.
The current affected runtime qualification covers AWS provider 6.74.0 SSM parameters with the
restricted static-configuration profile in the
RFC.
Recognized built-in expressions can participate, including string concatenation, arithmetic,
supported collection indexes and methods such as upper. Their inputs and declared types remain
part of the planning evidence. Arbitrary Python callbacks and custom expression classes require
full planning; declaring an empty read set does not make a callback eligible for omission.
Missing optional backend planning APIs, other runtime configurations, adoption, auxiliary state
cleanup and unsupported or deferred work
fall back to full planning with a recorded reason. Stack-targeted planning currently falls back to
full planning of the requested stacks. Invalid proofs, intent conflicts and unexpected provider
errors stop the attempt; they are not eligibility fallbacks. A full fallback's scope label does
not replace its refresh diagnostics or certify that every read succeeded.
Saved affected plans retain their selected originals, complete manifest and reviewed nodes.
nf show --plan-file reviewed.plan.json reads that evidence without state access. The planning
scope setting applies to newly created plans: passing --graph-plan-scope full while applying
an existing affected plan does not change the file's scope. Changed boundary evidence or a missing
baseline rejects the saved plan and requires replanning. After admission, out-of-set reads or
writes fail; execution never expands the approved scope automatically.
Complete graph reads cross-check the persisted reverse index against stored dependencies and consumed inputs, including newer consumers absent from the current app. Missing or inconsistent edges and invalid reverse generations stop both planning modes; full planning cannot bypass this integrity check. Saved provider startup retains the original reviewed values and validates their admitted proofs and grant. An unrelated publication may proceed without invalidating those proofs; changed selected evidence still rejects the saved plan.
Full Python app construction and complete summary/topology evidence still cost O(N+E). Selected payload boundaries are tested; broader runtime qualification, shadow comparisons and end-to-end performance gates remain open. This feature does not establish a speed or safety comparison with Stategraph.
Concurrent applies
After pinning the branch origin, enable resource grants for independent runs with
concurrent_applies=True on the App in the graph backend setup.
from nf.core import App
app = App(nf_id="app", baseline="nf.baseline", concurrent_applies=True)
Or enable them for a CLI invocation:
nf apply --app demo --baseline nf.baseline --concurrent-applies
nf deploy --app demo --concurrent-applies # reads nf.baseline automatically
The setting defaults to false. It is also available as concurrent_applies = true in
[tool.nf.config] or App(concurrent_applies=True). Precedence is CLI flag, project
configuration, App argument, then default. --no-concurrent-applies selects the ordinary
app-wide grant for that invocation. The setting controls overlap between runs;
max_concurrent_resources controls parallel resources within a run.
The opt-in requires graph state and a retained baseline, including for empty plans. A missing, wrong-state or pruned origin stops planning. Keep the branch's original pin when newer commits arrive; selecting the latest frontier does not make an old checkout current. Saved plans retain their own baseline and captured coverage and are validated before approval.
Complete coverage with canonical object identity contracts allows disjoint resource grants to overlap. Unsupported identities select app-wide X. An incomplete proof, invalid contract or lost lease stops the attempt. The complete grant is fixed before approval and cannot grow during deferred rounds. See the plan-admission details below for queueing, retries and recovery holds.
Uncertain operations and unresolved upstream drift defer their consumers with reason
upstream_unresolved, including provider settings, runtime scopes and data source observations.
Independent changes can proceed; the apply reports the deferred addresses and remains incomplete.
Resolve the operation with nf state recover, or review the upstream's current configuration,
then replan. A provider read alone cannot establish that an uncertain mutation has stopped.
Drift correction defaults on. nf --no-drift-correction, drift_correction = false in [tool.nf.config] or
App(drift_correction=False) accepts
refreshed values when both symbolic and evaluated configuration match the last applied
configuration. The refresh commits before its consumers execute. Explicit configuration edits,
taint and replacement triggers still take precedence. This option requires graph state with
recorded fingerprints. A stale branch cannot reconstruct newer configuration to repair its drift:
that address and its consumers wait for a plan using the current configuration.
Replacement triggers are retained as consumed revisions. If a preserved consumer waits while its
trigger changes, its next reconciliation still replaces it. The backend records the last revision
written by an operation separately from metadata revisions so an intent-only edit does not cause
a replacement.
Intent describes configuration before evaluation: symbolic references, runtime functions and their arguments, lifecycle settings and the provider configuration name. Changing an upstream value does not change a dependent's intent. Successful no-ops record changed intent; failures keep the last committed intent. No-op intent and refreshed state commit in dependency order, before consumers record their inputs. Even an apply with no provider changes walks these graph nodes. Unexpected configuration changes after a no-op was planned require a new plan. Saved plans retain the refreshed entries and reviewed configurations; older graph no-op plans without that evidence must be recreated. Resource and output tombstones retain their last intent. Legacy rows and document restores have unknown intent until a reviewed apply records it; they cannot serve as a baseline while unknown.
Independent no-op resource writes now share bounded publication transactions during an apply. The coordinator belongs to one plan and admission, accepts up to 128 pending writes under a conservative 1-MiB serialized budget, and collects a cohort for at most 20 ms before publishing (database/backpressure waits are additional). A single oversized row uses the ordinary writer. Read/write overlaps are separated. Waiting releases execution capacity, but a node completes only after its durable receipt; consumers cannot read a merely queued result.
During ordinary whole-app applies, eligible fresh creates with qualified known object identities can share one durable authorization transaction. Request preparation and final provider planning happen first; current inputs, ownership and object exclusion are checked before operations are recorded directly as dispatched. No provider mutation starts before its authorization is acknowledged. The authorization queue retains execution slots and collects for at most 2 ms when peers exist; database waits are additional. Cancelling a queued preparation sends nothing. An ambiguous authorization reply stops the callers and leaves any committed operations available for recovery. Resource-grant applies, unsupported identities/actions and oversized requests keep separate reservation and dispatch. Provider responses are submitted for durable retention immediately after they return.
An experimental completion path for qualified fresh creates can store responses and publish resources in the same transaction. It is disabled by default in PostgreSQL: the matched 10,000-resource qualification reduced requests and transactions but increased elapsed time and publication count. Ordinary applies retain the separate durable-return path. The qualification harness explicitly enables the candidate for further testing. When enabled, the completion coordinator drains available responses without a collection timer while state-row preparation runs independently. PostgreSQL records all raw outcomes first, then attempts any already prepared writes inside a savepoint. Publication rejection rolls back those writes and commits the raw responses as returned; it does not discard the provider's result. The node completes only after a successful publication receipt.
To avoid fragmenting publications, the coordinator combines new prepared rows with compatible, already-durable creates waiting in the publication queue. It attempts the shared publication when those rows cover the current occupied execution window. This is a scheduling policy, not an ownership proof or a guaranteed batch size. If publication cannot proceed, borrowed rows return to their original queue and deadline; no raw response waits for more resources to arrive.
The coordinator accepts at most 128 responses under a 1-MiB raw-response budget and keeps the configured resource execution slots. A slow preparation uses later ordinary publication. While a completion publication is running, new responses drain independently through return-only transactions. A busy app frontier also falls back to return-only storage without waiting for its publication lock. An oversized response or full queue uses immediate individual storage. Cancellation drains accepted response receipts; ownership loss or an ambiguous database reply retains complete raw outcomes in the recovery journal, without automatically repeating the database operation or provider call.
Successful creates with canonical object identity and authoritative input evidence use a separate queue with the same bounds. Creates retain their execution slots while waiting, so unresolved provider outcomes remain inside the configured parallelism limit; the publication worker needs no slot. If completion did not already publish the row, its raw response is durable before entering this publication queue. A publication commits independent new resource rows, full history and their operation transitions together. The node and its dependents wait for that transaction. Updates, replacements, deletes, imports, partial errors, explicit save groups, unsupported identities and output writes retain their existing publication path.
Cancellation removes a write that has not started; once publication starts, cancellation drains its outcome before the plan releases ownership. A conflict, ownership loss or ambiguous reply fails the cohort and stops its publication queue. A cancelled or unattempted create keeps its durable returned operation for recovery. Attempted writes use the existing recovery journal; ambiguous commits are not automatically retried. A row that becomes stale during publication requires a fresh plan instead of a successful node acknowledgement.
PostgreSQL also groups the stale-consumer marks caused by a publication. Resource/output status changes and complete history remain in the producer's transaction, including transitive invalidation; a failure rolls back the complete publication. Statements process at most 128 consumers with a 64-KiB budget for target descriptors. That budget does not limit the history payload or split the transaction. Legacy rows needing representation or identity-column repair retain the ordinary writer. Large publication batches expand admitted permissions once per check; smaller checks keep the existing lookup. Both paths retain the same ownership fences and exact kind/target/action checks. Consumer discovery groups concrete reverse-edge lookups separately from scope/enumeration observers, then applies the existing input-change check; it also checks newly written rows with inputs. Known-empty row reads and a duplicate operation read at dispatch are skipped. Within the same app-row-locked transaction, footprint and object checks share the unresolved-operation snapshot; entry checks remain fresh for every write. Dispatch uses the locked run's admission status to skip plan permission queries when there is no admitted plan.
Planning compares origin, this branch and current intent before evaluating this branch's resource and output configuration. A change only in current state is preserved, including a newer deletion; a change only in this branch proceeds. Equal targets are satisfied. Changes on both sides conflict with the addresses and fingerprints shown. After reviewing a conflict, resolve an address explicitly:
nf plan --app demo --prefer-mine stack.aws_instance.web
The option is repeatable and requires a baseline. It resolves conflicts only; a preserved newer entry is still preserved. Saved plans retain their baseline and preservation decisions and validate the pin again when applied; replan to change these decisions.
Independent changes proceed when preserved entries have known inputs. When an input changes, its
consumers and transitive consumers are marked stale_inputs in the same transaction, retaining
their newer intent and values. The plan and apply report those entries; the apply is successful but
incomplete until a run with their current configuration reconciles them. A provider result that
commits after one of its inputs changed is also marked stale. Reservations and dispatches validate
consumed revisions again, including quarantined creates whose addresses still appear absent.
Legacy entries whose consumed inputs are unknown need an apply of their current configuration before combining branch changes. A preserved row with unresolved drift or status still stops planning; static references to preserved deletions are rejected before apply.
Without a file or override, the CLI announces a two-way graph plan: this configuration is
compared with current state. Known reversions to historical intent are refused with their run IDs;
to revert deliberately, review the current state and pass its frontier with --baseline. A pinned
origin is required for complete stale-branch protection. Document backends ignore the default file
and reject an explicit baseline override.
Canonical object ownership
Graph state refuses two addresses managing the same cloud object, including declarations using different provider aliases. A canonical ownership key combines the provider source, an established namespace (such as AWS account, partition and region), resource type and object key. Identical names in distinct accounts or regions have distinct keys. Credential hashes and aliases cannot establish these namespaces.
Provider extensions register typed ProviderIdentityContract objects through the
nf.graph_identities entry-point group. Applications may explicitly register a contract with
nf.core.providers.graph_identity.register_graph_identity. A contract resolves a concrete
ObjectScope and a portable ObjectLocator; any read-only provider facts it needs are shared
within one configured client and ownership period. A saved plan applied in a new run establishes
those facts again before a mutating call. A changed account or region fails before dispatch.
Contracts can declare a closed resource_types set. Resource grants additionally require an
IdentityQualification for each type: its key contract, bounded provider-version constraint,
required namespace facts, evidence reference and experimental status. A qualification supplies
the type declaration when resource_types is omitted. Legacy resolvers still interpret stored
locators; a type declaration alone does not authorize concurrent mutation. Experimental profiles,
missing qualifications and unknown or out-of-range provider versions select app X.
Eligibility uses the source/version selected for the process actually launched, preserved from
the loader's versioned cache into that process's connection. A requested range such as ~> 6.0
does not prove the running version. An explicit custom binary has no established release merely
because its filename contains one. Cache selection assumes a trusted installation/cache; it is
not a cryptographic attestation of arbitrary executable contents. Credentials and executable
paths are not included in qualification evidence.
Plans persist the qualification profile, its fingerprint and the running release. A new apply rechecks the profile and actual sender before dispatch; changing either requires replanning. For a deferred provider, the initial grant covers its declared source/type and binds the profile without configuring the provider. Its eventual configured client must establish an eligible running version and actual namespace before dispatch. If it cannot, the run stops; completed earlier rounds retain their normal partial-progress/recovery semantics. It never broadens an already acquired resource grant to app X mid-run.
Core supplies an allocated UUID contract for GeneratedValue. The optional netherframe.ext.aws
package covers the following types at AWS provider 6.74.0. Its configured provider's
aws_caller_identity establishes account and partition; configured/resource region and object
name complete the key. Stored and returned ARN scope facts must agree with that namespace.
| Resource type | Key and eligibility |
|---|---|
aws_ssm_parameter |
Parameter name, normalizing its optional root slash; chosen name must be known before create |
aws_cloudwatch_log_group |
Exact log group name, preserving a leading slash; explicit and provider-generated names |
aws_secretsmanager_secret |
Exact secret name, preserving a leading slash; replicas or a true/unknown force_overwrite_replica_secret require app X |
The built-in generated-value qualification is Netherframe core 0.13.0. Other releases require
their own qualification evidence. Existing rows without qualification metadata retain their
locators and may need an app-X apply to backfill eligibility. Qualification covers the tested
provider release and these mutation domains; subordinate log/secret resources remain serial.
Conditional exclusions are declared in the qualification profile's serial_attributes. Both
old and new configurations contribute to exclusion: removing replicas cannot narrow protection
before that change finishes. Imports of conditionally qualified types use app X until readback
establishes their configuration. An excluded instance retains its locator for duplicate detection
and recovery. Its operation also retains app X, including across a crash, and excludes conflicting
sibling calls in the same run.
Log group and secret create APIs refuse an existing name, permitting their generated-name creates to use fresh-allocation reservations. Losing that response still needs a unique recovery selector: a named log group can be located by name, whereas generated names and secret ARNs may need operator-supplied identity evidence. An allocation contract does not make recovery automatic. Other resource types retain serial compatibility, but need an explicit ownership contract before resource-level concurrency can be enabled for them. Provider import identity schemas alone cannot prove how a create chooses its object key.
Contracts explicitly distinguish chosen keys, which must be known before creating an object,
from allocated keys, for which the service or provider attests a fresh allocation. Unknown
allocated keys conservatively reserve their identity scope. Creates also reserve an adoption scope
that conflicts with imports, preventing adoption from taking an object whose create is still
unresolved. Independent fresh allocations can run within one app grant. Reservations are checked
atomically even within one run, and unresolved operations retain these exclusions after the owner
ends. Canonical duplicates cannot be permitted with allow_duplicate_adoption.
Locators are recorded in entry metadata and operation requests, including declarative key fields and returned scope assertions. Recovery can ingest a returned result using this evidence without loading the original app or provider extension. Saved plans retain the same evidence; older readers must upgrade rather than omit ownership validation.
Rows with unknown ownership block canonical mutations of other objects of the same provider/type. A reviewed no-op apply of their current configuration establishes ownership without changing cloud objects. This bootstrap preserves existing attributes, provider identity, private state and intent; it cannot waive a canonical collision. Resolve legacy uncertain operations first.
Migration 10 requires participating writers before reserving/dispatching operations or writing
resource state. Upgrade all writers sharing the database. A call already in flight may still
record its returned result for recovery; an older writer cannot overwrite canonical ownership.
Ordinary hybrid apply and state commands continue to use the app-wide X grant. The admitted-plan protocol below permits guarded resource-level mutations through
concurrent_applies=True or --concurrent-applies, with a retained baseline.
Consumed inputs and observations
Graph runs always record authoritative consumed revisions, even with provenance_report=False.
The optional report explains those reads. Resource and output inputs survive saved plans, recovery
and history. Empty inputs mean no state was consumed; unknown inputs remain distinct. A provider's
settings and a data source's provenance flow to the resources that consume them; cached values
retain their original provenance.
A stored data-source result alone cannot establish which managed values it observed. Declare its
data source in the app so planning can read it again and capture those inputs. Using an old cached
result without that evidence fails before a managed mutation. A known empty proof (observes=[]
with no configuration or provider reads) remains distinct from missing evidence.
Saved-plan format 17 retains each data-source result's read proof, bound to its address and value fingerprint. Broad scopes retain their original member snapshots. Applying the plan can reuse that result, including without its live resource constructs, after validating its captured inputs; it does not substitute current revisions for the original proof. Missing or mismatched evidence requires a fresh plan. Earlier graph plans must also be recreated when they contain no data-source nodes: a cached value may already have been evaluated into a managed configuration.
Ephemeral results carry the managed revisions read by their configuration and their own provider settings into each write-only consumer, including through another ephemeral result. The temporary result and private bytes stay in the session; only its input proofs reach plans, operation footprints, state and history. A pending provider's declared reads are included in the initial grant even when its ephemeral result cannot be opened until a deferred round. Apply captures the fresh result's actual reads again, so a consumer retains those input leases through recovery.
Hybrid execution also checks ephemeral access during evaluation, including references returned
by runtime bodies, expressions and templates. Data sources, provider settings, outputs and
ordinary managed arguments refuse these values before a consuming RPC or stored result. This
check remains active without provenance reports and covers references that are not open yet.
Managed arguments require a schema identifying them as write-only. Runtime computations that
consume ephemeral values are recomputed in each evaluation environment, even with a cache key,
so apply uses its reopened session. Within one environment, memoized expressions retain the
ephemeral marker. Opaque runtime dependencies still need explicit ordering, such as depends_on.
A refresh can change a provider's stored representation without requiring a cloud update, such as an optional map changing from null to empty. When that advances a consumed value proof, a data-source read waits for the refreshed no-op to commit and is repeated during apply. Its consumers are then planned with the fresh result. A stable subsequent plan needs no reconciliation.
Runtime functions may declare reads=[] when they consume only their arguments, or name resource
addresses, constructs and app / stack:<id> scopes for additional reads. Without a declaration,
opaque functions conservatively read the app. These value scopes track changes to stored values;
metadata-only writes do not cause endless scope invalidation. Checks use their reads= declaration
the same way. A runtime result cached before authoritative recording is evaluated once under graph
recording to establish its proof. reads=[] describes additional body reads; it cannot prove that
evaluated arguments consumed no managed state. Once qualified, a computation with no managed reads
keeps its cache across later phases and runs. A cached computation with managed reads is reevaluated for a different graph
state or run, and between provisional configuration building, dependency-ordered planning and
execution phases. Equal revision numbers in two states do not make their values interchangeable.
Computations with no managed reads retain their cache behavior. Independent nested graph operations
record into their own authoritative context; planning inside its own apply shares that apply's
context. Expression memo hits also replay their captured reads: evaluating an operand in one field
cannot hide it from another field's runtime capture.
Broad declarations can also make sibling resources depend on one another's values
and membership. During creation or updates, publishing one sibling may invalidate a
scope consumed by another. Apply then refuses stale dispatch or reports
stale_inputs after recording completed effects; a successful provider call does
not by itself make the whole apply complete. Create a fresh plan to reevaluate the
remaining work. Under stable values, later metadata reconciliation can finish
without repeating completed cloud mutations. Arbitrary runtime bodies are not
guaranteed to converge. Use reads=[] only when the body has no additional reads
beyond its arguments; it is not an override for stale scope evidence.
Value scopes use each row's monotonic value_revision; enumeration scopes use its
membership_revision. Deleting and recreating an identical object changes both proofs, including
when the final membership is unchanged. Resource/output metadata alone changes neither counter;
numeric storage equality is preserved while booleans remain distinct from numbers. Migration 8
seeds these counters conservatively from existing row revisions. An existing scoped proof may need
one reconciliation under the current configuration after upgrading.
Here upstream is a managed SSM parameter, lookup and identity are data sources, and
temporary is an ephemeral resource:
# coding: nf_autoid
from nf.core import App, Bind, BindContext, Stack
from nf.core.runtime.hybrid_runtime import hybrid_runtime
from nf.providers.hashicorp.aws import (
AwsProvider,
CallerIdentityDataSource,
SsmParameter,
SsmParameterDataSource,
SsmParameterEphemeralResource,
)
def normalize(value: str) -> str:
return value.upper()
# Reads nothing but its arguments: no state, no other object
normalized = hybrid_runtime(normalize, reads=[])
with App(nf_id="settings") as app, Stack() as settings, BindContext:
aws: Bind = AwsProvider(region="eu-west-1")
upstream: Bind = SsmParameter(name="/settings/mode", type_="String", value="fast")
shouted: Bind = SsmParameter(name="/settings/mode-upper", type_="String", value=normalized(upstream.output.value))
# A lookup whose literal filter observes a managed object:
lookup: Bind = SsmParameterDataSource(name="/settings/mode", observes=[upstream])
# A data source known to observe no managed objects:
identity: Bind = CallerIdentityDataSource(observes=[])
# A temporary cloud read with a literal selector:
temporary: Bind = SsmParameterEphemeralResource(arn="arn:aws:ssm:eu-west-1:123456789012:parameter/settings/mode", observes=[upstream])
Generated data sources and ephemeral resources accept observes= directly; existing generated
classes support the attribute too. Observed objects contribute inherited input proofs and reverse
dependency edges. Ephemeral opens wait for independent writes in their declared scopes, including
refresh no-ops, so their proof names the values actually observed during apply.
Omitting the declaration conservatively observes the app. observes is framework metadata and
is not sent to the provider or synthesized as a Terraform argument. An empty declaration removes
only opaque managed-state observations: configuration and provider references still contribute
their actual reads. dependencies is a read-only
SQL view of committed consumed keys and scopes, plus explicit ordering dependencies. Unknown legacy
inputs contribute an app scope until a reviewed apply establishes narrower evidence. Edge counters
advance when that predicate's set of dependents changes; removing and restoring the same edge
cannot make an old reverse-dependency proof valid again.
An adoption not yet checked by a provider plan is unconverged. A plan that owns its intent asks
the provider to plan it even if its attributes appear unchanged; a provider no-op can then record
convergence without another mutating RPC.
How a run works
- Registration and lease. Standalone app and stack plans register renewable ownership
without taking a lease. They read rows and proofs from one captured frontier and leave kept
errored state files untouched. Another writer can commit while providers plan; validation
detects stale row/input evidence before mutation. Two-way history lookups are bounded to
that same frontier. Ordinary app/stack
applyalso plans unleased, then queues for app X and validates fresh state before approval.destroyand ordinary state commands take app X: a run row with the next epoch and an expiry. A heartbeat thread, independent of the walk, renews it everylease_renew_interval. A run whose lease expired cannot renew it. Its ordinary grants expire, while unresolved operations retain their full footprints and block incompatible new grants, including whole-app X. Recovery registers renewable ownership without requesting a new run grant; it uses each operation's retained footprint after a fenced takeover. - Operations. The general path reserves each resource operation in a transaction
that first validates the target row (pre-call validation: revision, incarnation, status,
provider, private-data digest as the run read them; a mismatch fails the node before anything
is sent). It marks the operation dispatched immediately before the provider call, writes
the call's result as soon as it returns (returned), then commits the row, its version
and the next commit sequence in one transaction. The node completes only after its commit is
durable; eligible independent creates can share final publication, either in their
response transaction or after a separate durable return receipt. Commits run in worker threads, off the walk's event loop. A replacement is one
operation through
delete_dispatched,delete_committedandcreate_dispatched. Eligible fresh creates under ordinary whole-app ownership combine reservation and dispatch into one bounded cohort transaction immediately before provider calls. Until that transaction is acknowledged, their prepared operations are local only. Recovery templates omit write-only and ephemeral values, including nested write-only fields; the live configuration still goes to the provider. Ordinary identity fields remain available to locate an object after a lost response. - Fencing. Every reserve, dispatch, combined authorization, completion, return and commit locks the run's ownership row
FOR SHAREand checks its epoch andexpires_at > clock_timestamp()(the database's clock); renewal locks itFOR UPDATE. Liveness and the complete grant are read after the ownership lock is acquired, so waiting for that lock cannot preserve an expired or released capability. Every successful owned transaction checks the database clock and actual grant again after its row writes and receipts. This also covers recovery claims, checkpoint creation/restore, migration stages, plan admission and queue changes. A wait on an operation, app or checkpoint row cannot leave an expired proof usable: the whole transaction rolls back, including its responses, claims, versions, frontier and receipts. Recovery can use a pending registration with its retained operation footprint; a granted registration must still hold its complete set. The final observation is the publication decision point, with ownership locks held through SQL commit. Commit history records that observation's timestamp. Takeover locks the operation and checks the existing owners' registration rows under shared locks. A run that paused past its lease cannot dispatch, record or commit anything after another run took over. - Loss of the lease is terminal. The run sends nothing more, records nothing more, kills its
provider processes (
kill_providers_on_lease_loss) and records that it did, and never rolls back. - Commit order. Each commit takes its sequence from the app's counter row inside the commit
transaction, so sequence order is commit order, and the frontier (last committed sequence)
only ever covers committed work.
batched_saves(interval=math.inf)groups (moves and stored outputs) commit as one transaction. Explicit imports commit each successful read before reserving the next one; a later failure leaves those successes in state.
Plan coverage
Saved graph plans include graph_state.coverage: the initial row revisions, consumed inputs,
reverse-edge generations, closed write set and normalized leases for all possible rounds.
Format 15 also retains possible operation actions and explicit cache/metadata expectations.
Satisfied targets retain shared value coverage; entries preserved by the baseline merge are
covered when consumed. Metadata-only reconciliations close transitively through consumers.
No-op refreshes, output writes, removed observations and externally deleted objects without a
remaining construct are included.
Deferred updates reserve possible replacement coverage. Static references, provider settings, runtime/check scopes and data-source observations cover later reads. A pending provider's unknown account or region uses its source/type prefix; an unknown chosen name uses its concrete identity scope. Actual creates still require a known chosen identity before dispatch. Configured types without canonical contracts explicitly retain serial coverage. Pending contracts must be established before concurrent mutation can be permitted.
Planning records the same loaded rows and proofs that evaluation reads. This prevents a newer database snapshot from silently blessing earlier cached values. Planned input revisions validate their initial state; apply materializes the committed prerequisite revision later.
This coverage is retained and tested against actual operation footprints. Ordinary applies acquire app X after planning and use their global saved-state check. Already-admitted plans validate their exact pinned basis under the complete grant, so unrelated commits need not invalidate them. Automatic resource preparation, bounded approval and deferred coverage are implemented internally. The remaining coverage audit and combined model/reference evidence still gate public concurrency. Older saved plans with captured state evidence can still run through the serial path; they do not supply the complete admission protocol.
Plan admission
The backend can admit one immutable, pinned plan under its complete grant. Registration, a grant or validation alone does not authorize resource-level mutations. Admission checks the retained baseline, rows, inputs, reverse predicates, auxiliary fingerprints and unresolved-operation holds in the same transaction. An active admitted plan protects its baseline against unpinning.
Every reserve and commit must fit the admitted write set; every dispatch must use an allowed action. A reviewed update cannot silently become a delete. Deferred updates explicitly cover possible replacements, and deferred adoptions cover their possible import/update/replace actions and unknown object keys. All admitted resource mutations require canonical contracts and authoritative inputs, even with a broader app grant. Legacy ownership needs a reviewed serial bootstrap first. Traditional unsupported-provider serial runs remain on the existing app-grant path.
The grant is checked in full before mutating: losing an unrelated lease key fences the entire run. Sibling operations in an admitted run also retain their consumed values and object coverage until durable completion. A conflicting sibling receives a typed transient lock refusal. The parallel executor suspends a refused reservation or clean state-only write, yields its execution slot to independent work and resumes the same prepared request after its producers finish. It retains the run's complete grant. A producer's known abort can release the wait; an unresolved/kept outcome requires recovery. A dispatched provider call is never repeated by this mechanism, and a refused post-call commit keeps its response/state evidence for recovery. Attested fresh service allocations may coexist within the same run; their value, edge and adoption holds remain intact. An update/replacement of an object newly adopted into state retains exclusive adoption coverage.
GraphStateEngine.register() opens renewable planning ownership without reconciling errored-state
writes. acquire_plan() queues and admits a plan, cancelling its ticket on timeout and releasing
the whole grant on stale admission. discard_plan() reloads a fresh snapshot before replanning;
it is refused after the first dispatch or commit. acquire_app() obtains app X from a registered
run, then reloads state and reconciles plain kept records before the caller validates its plan.
Ordinary app and stack applies use this lifecycle automatically. They plan while holding no grant,
queue with lease_timeout, reload under their grant and validate before asking for approval. A stale
automatic plan is rebuilt under a fresh registration, with at most 3 attempts total. Each
attempt ends its previous run, releases its grant and discards provider/configuration caches.
The branch origin resolved by the first plan remains fixed across retries. Ownership loss is
terminal; it does not trigger another attempt. A newly discovered intent conflict stops the run.
Late heartbeat results are fenced by their original registration and cannot invalidate a new
preparation attempt after the old run ends.
Supplied plans are never regenerated. Stale errors report the planned/current frontiers and the changed keys or proofs when their coverage provides that evidence. Graph plans without captured state evidence, including no-change summaries without an immutable artifact, require replanning. Provider namespace facts read while unleased are discarded after granting; the actual sender checks fresh facts against its planned/stored object locator before a mutating call.
The concurrent_applies resource-grant preparation policy uses that same apply pipeline. It requires a
pinned baseline and complete coverage matching the artifact's lineage/frontier, queues the
whole capability and admits it before approval. Coverage marked for serial execution selects the
ordinary app-X path. Only stale preconditions trigger bounded rebuilding; invalid contracts,
missing proof, queue timeout and ownership loss stop the attempt. A supplied plan is rejected
with the changed keys rather than rebuilt. Unrelated commits can survive per-key admission.
After admission the engine reloads fresh state for execution and its recovery basis; it leaves
plain errored-state reconciliation to the serial path.
Graph preparation failures can also carry a structured graph_conflicts report on
ExecutionResult and its to_dict() output. Direct planning/admission exceptions expose the
same report in exception.context["graph_conflicts"]. Its categories identify the next action:
| Category | Meaning | Next action |
|---|---|---|
contention |
A granted lease or an older incompatible queued request blocks this run | Wait for that run; preserve queue order |
stale_evidence |
A reviewed row, consumed revision, reverse predicate or full-state frontier changed | Replan before approval; a saved plan is never rebuilt automatically |
changed_intent |
Both the branch and deployed configuration changed since their baseline | Reconcile the configuration explicitly |
unresolved_operation |
An operation still retains its footprint, including after its original run ended | Recover it with the required termination/identity evidence, then review a fresh plan |
Queue details include the requested namespace/mode, incompatible mode, blocking run or operation,
and the plan reason that introduced the demand. Older queued requests are distinguished from
holders. A recovery claim is reported under its current recoverer. Identity/allocation and
auxiliary/extension keys are masked with (sensitive); provider payloads and private state are
omitted. Row and predicate failures report expected versus observed revisions without copying
resource values. Up to 100 conflicting lease keys are returned, with an omitted-key count.
The engine reports advisory blockers when it first waits and when the wait times out. Tooling can
call backend.explain_lease_request(ownership, basis=...) for an existing live queued request.
This reads one consistent view and takes no grant: it does not expire a holder, change a ticket,
or mutate state. Its advisory flag is true, and an empty report does not authorize execution.
The ordinary atomic grant and proof checks still decide admission. Diagnostic-reader failure
leaves the original refusal in place. Proof-check and intent-conflict reports instead describe
the failed check itself and have advisory=false.
PostgreSQL validates concrete plan proofs by reading their expected resource/output rows, consumed revisions, auxiliary values and covering reverse-generation counters. Destructive proofs also read all covering consumers, including broad observers and output consumers outside the closed write set. Every unresolved operation remains visible, including creates with no committed row. Opaque value or membership scopes use the full state view. Both paths use the same validation rules under the app-row lock and the final ownership fence; the selective view stays private to validation. Admission still checks the complete retained baseline intent digest. Normal full-plan execution reloads a full snapshot. Qualified affected-plan execution instead keeps exactly its admitted rows and a selected rollback copy; complete-state and out-of-set reads are refused during execution. The public scope setting and saved-plan loader use that same path. See the RFC's scoped-planning initiative for qualification evidence and the remaining release gates.
Run the backend scale fixture with
uv run python tests/performance/graph_postgresql.py --compare-full-snapshot.
It seeds 100, 1,000 and 10,000 rows through normal graph commits in an isolated PostgreSQL
container and records raw samples, decoded-row counts and source hashes. The repository's
tests/performance/README.md describes its phases and limits. Concrete proof reads stay bounded
by their declared rows; full snapshots, opaque scopes and retained-baseline verification retain
their state-dependent costs. uv run python tests/performance/graph_workloads.py separately
measures high-fanout invalidation/reconciliation and simultaneous disjoint writers, with simulated
provider responses. Complete-grant validation remains proportional to the fixed grant's size.
The final capture reconciles all 10,000 consumers with 210 successful renewals and zero failures,
but takes 113.9 minutes on its recorded host. Each operation repeatedly checks the entire grant;
large fixed grants therefore have substantial costs. See the
delivery verification
for timings, settings and correctness checks.
Graph coverage now carries versioned identity-contract evidence. Resource preparation requires version 2 and rechecks configured qualifications and deferred profile fingerprints before queueing; older saved resource plans require replanning. The ordinary serial path can still read older coverage without claiming that the old artifact captured provider-version qualification. Each admitted deferred round validates its complete planned writes, actions, reads and scopes against the original grant before approval or mutation. A new target, action or broader scope stops the round without changing the grant. Completed rounds remain reported in the result and the configured failure recovery strategy applies.
Reconciliation may itself commit old plain records. If this makes the plan stale, preparation ends that run and replans under a new registration. A run that mutated never releases its grant to request another set. Its next attempt's checkpoint/rollback basis includes the reconciled records.
Each graph approval expires after 300 seconds by default, independently of heartbeat renewal.
Set nf --graph-approval-timeout, graph_approval_timeout in [tool.nf.config], or
PostgreSQLGraphBackend(approval_timeout=...) to a finite positive number of seconds. The complete grant stays
held while asking. An initial timeout ends the run without applying the plan; a timeout between
deferred rounds ends it incomplete, retaining completed changes even with ROLLBACK. The result
lists what remains deferred. Replan to continue; the same mutated run never reacquires a grant.
PostgreSQL gives renewal a turn ahead of newly arriving owned SQL transactions. Resource work shares a per-run advisory turnstile; renewal takes an exclusive turn after active transactions finish. This prevents a continuous stream of short shared row locks from starving the heartbeat. Sibling state transactions can still overlap, and provider calls run outside the turnstile. The existing epoch, status, clock and exact-grant fences remain authoritative; loss is still terminal. Renewal compares the complete expected and actual grants before and after updating expiry. Each comparison expands the maps once, so a newly grown grant can renew without fresh planner statistics.
Graph approval callbacks run in a daemon thread with the caller's context variables. They receive
an ApprovalRequest.deadline on the monotonic clock, remaining_seconds and cancelled; callbacks
that wait on a service should honor those signals. A late answer cannot authorize execution.
Python cannot forcibly stop arbitrary callback code. The built-in console and CLI prompts use
selectable stdin on POSIX and stop reading when cancelled; other input adapters need their own
deadline-aware callback. Ownership loss while waiting is terminal, even before the deadline.
Hybrid app and stack applies can execute a plan admitted through those protocol primitives. They require the same baseline and basis, with the same captured lineage/frontier; another plan or missing evidence fails before provider mutation. Tests exercise real overlapping AWS provider calls and independent outputs, and saved patches applied after unrelated commits. These tests exercise automatic resource-grant acquisition through the public setting.
Format 16 distinguishes untouched three-way no-ops from satisfied patch targets. Untouched
resources and outputs are omitted from target coverage and execution after closing the patch's
writes and reads. Consumers still lease the values they use, and satisfied targets remain shared.
Drift, metadata, status and input-revision repairs still join the write set. A provider's first
refresh may change a returned representation; recording an unqualified difference
requires its own exclusive state write before that row can become untouched.
For AWS 6.74.0 SSM parameters, the optional AWS extension preserves a stored
tags=null when refresh returns an explicitly empty tag map. Nonempty tags,
tags_all, private data and identities remain as read. The rule is specific to
that source, resource and release; raw protocol responses and durable Apply results
are unchanged. New qualified chains need no first-refresh repair for this
null/empty difference. Changing the representation policy invalidates prior
planning evidence; existing states may need a one-time context publication.
Admitted cleanup preserves outputs, observations and metadata added outside its initial write set, including entries committed after the saved plan was created. Later rounds retain the initial untouched decisions. PostgreSQL revalidation locks the ownership row, then holds the app counter row shared for the short proof read, avoiding a false serialization failure when a heartbeat renewed ownership while validation waited.
Migration 13 records admission with the run, exposes its baseline and basis in the read-only
runs view and fences obsolete admission writers. All writers sharing the database must upgrade.
Original in-flight calls may still return after an online upgrade.
Alias transitions verify the namespace reached by the actual sending client. Equivalent aliases can update their stored reference without a cloud mutation; a different namespace requires an explicit migration. Recovery also checks the configured namespace before a refresh/import probe.
Operation-held footprints
An operation's immutable request includes a normalized lease_footprint: its target addresses,
consumed resource/output values, declared value or membership scopes, reverse predicates and
changed outgoing edges, plus canonical identity/adoption scopes. Replacements retain edge writes
across both halves even when their final dependencies are identical. Missing consumed-input
evidence conservatively reads the app's entire value scope.
These footprints have no expiry. Ending a run, expiring its grant or taking recovery ownership does not discard them. Reservations, dispatches, explicit state writes and plan-basis validation check for conflicts with unresolved operations as well as checking the run's actual grant. Thus a successor cannot update an input while an old call still relies on it. Disjoint work can proceed when its provenance proves independence. Shared read keys remain protected until every operation holding them has resolved.
The read-only operation_leases view exposes each unresolved operation's keys and modes:
nf state --app demo query 'SELECT op_id, key, mode FROM operation_leases ORDER BY op_id, key'
Recovery can ingest settled results from the same original run together. Taking over an in-flight sibling does not waive its footprint or establish termination. A blocked result remains quarantined while recovery continues with independent results; losing recovery ownership stops the run.
Recovery claims include the operation ID, its epoch and its attempt. The operation epoch advances independently of the recoverer's registration epoch, so a run registered earlier can recover an expired newer attempt safely. A live original owner or live competing recoverer prevents takeover. Every recovery write must present the current claim and fit the original footprint; it cannot acquire new leases, dispatch another mutation or overwrite the original response. Independent recoverers can resolve different operations concurrently.
Updates reserve membership coverage too, because recovery may find the object gone. An older update with insufficient membership coverage retains a tainted managed row for reviewed recreation, preserving its original footprint. Recovery does not expand that coverage to remove the row.
Partial error results remain recoverable when state persistence fails, including a replacement's create after its delete committed. A response that could not be stored keeps its quarantine and its errored file. Recovery preserves reserved sensitivity paths and any additional paths known by the current schema. Older requests without sensitivity evidence mask all attributes in read-only views. Unavailable or malformed sensitivity information also masks all attributes.
A recovery read establishes what is tracked, rather than whether an unacknowledged apply finished
its configuration. An object found by that read remains unconverged; the next plan reconciles
its configuration even with drift_correction=False. An update returned with provider errors also
remains unconverged, including when its partial response was stored immediately. An incomplete
create stays tainted. A verified successful kept response can be committed as ready.
Migration 11 makes operation requests and their digests immutable and refuses earlier writers before dispatch or resource writes. It preserves legacy requests unchanged, treating missing footprints as whole-app X until recovery resolves them. Already-dispatched calls may still record their results. All writers sharing the database must be upgraded.
Migration 12 fences operation ownership and resolution with explicit claims. Obsolete writers cannot take over or finalize a newer attempt; an original in-flight call can still record its response after an online upgrade. Recovery leaves unrelated errored-state edits for an ordinary run, whose grant can authorize them.
Migration 14 requires writer protocol 5 for resource writes, operation reservation/resolution and plan admission. This prevents an older writer from replaying an operation's kept write as an ordinary state edit. Upgrade all writers sharing the database. An original call already in flight may still record its response, provided its epoch and attempt have not been taken over.
The queue checks every unresolved operation's immutable footprint, at every stage, alongside live run grants and older waiting requests. There is no whole-app X exception. A compatible narrow request may pass, while a conflicting request waits holding nothing. Shared reads remain shared; an older conflicting writer prevents younger readers from overtaking it. Resolving one operation does not release a key retained by another. Missing legacy footprints are whole-app X.
Read-only planning/inspection and explicit recovery remain available while grants are blocked.
Use nf state operations and nf state recover; a refused whole-app grant reports the operation
IDs, addresses and stages. Mutator checks remain a second fence after queue admission. Deferred
nodes marked upstream_unresolved cannot run in that attempt; independent admitted patches can
proceed under their own coverage. The coverage audit and combined model/reference gates protect the opt-in
concurrent_applies path. Unsupported identities retain app-wide exclusion.
Migration 15 requires queue protocol 1 for inserting or updating run grants; obsolete writers cannot bypass operation-holder admission. Upgrade all writers sharing the database. Grant admission checks expiry again after obtaining the app counter lock, so waiting for that lock cannot grant an expired owner. Migration 16 requires operation/state writer protocol 6. A rollback-enabled create must retain its delete/restore coverage before its first call, including unchanged outgoing edges and the old adoption scope when restoring a re-created entry. Older writers cannot omit this coverage or dispatch operations under a newer admission. Original calls already in flight may still record their responses, with unchanged epoch/attempt and no recovery takeover. Queue protocol remains 1. Migration 17 requires operation/state writer protocol 7, retaining queue protocol 1. It adds pinned history checkpoints, monotonic operation reservation numbers and atomic restore receipts. Older writers cannot prune checkpoint evidence or bypass the new state-only restore role. An original in-flight call can still record its returned response under the existing unchanged-owner exception. Upgrade all writers sharing the database.
- Grant lifetime. Before a run mutates anything, it may cancel its entire grant and replan.
Once it dispatches a provider call or commits state, it retains that grant until it ends, even
if the operation later aborts or its writes are rolled back. A cancelled reservation that never
dispatched and a failed transaction leave replanning available. The read-only
runsview exposesmutation_started_atandmutation_cause; markers backfilled for older runs use migration time and causelegacy_mutation.
Quarantine and recovery
Cancelling a run does not prove its provider call stopped. A dispatched operation cannot be aborted, committed or reset before its response is recorded or recovery persists verified termination and a provider observation. PostgreSQL enforces this transition rule, including for older clients that use the same writer protocol. Never-sent reservations can abort; state-only imports and local moves can still commit without a mutating provider call.
Recovery stores its verified observation before publishing the resulting state. If that publication fails, the next recovery attempt can ingest the retained observation without repeating the provider read. A returned object accompanied by provider errors also remains available when publication fails: recovery records failed creates as tainted and failed updates as unconverged, without repeating their mutation.
An operation that is neither committed nor aborted holds its address. When its run's lease
expires and another run takes the app over, the address of every such operation whose call may
have been sent becomes uncertain. Later runs refuse to mutate a held address (the node fails
with "resolve it with nf state recover"; its dependents are skipped), and change the rest of the
app as usual. nf state force-unlock cannot clear an operation: it ends a run only when that run
holds no dispatched operations.
nf state operations # unresolved operations and the addresses they hold
nf state recover # resolve them all
nf state recover OP_ID --confirm-terminated
nf state recover OP_ID --import-id i-0abc123
Recovery is a run of its own. For each operation it takes recovery ownership: the operation's epoch and attempt advance independently of run registration, and the original run can no longer write it. Then:
| Stage | Resolution |
|---|---|
reserved |
Aborted: nothing was sent |
returned |
A known result is ingested and committed; unknown values require a verified read/import (an error with nothing returned is aborted) |
delete_committed |
Committed and reported: the replaced object is gone; the next plan creates its successor |
dispatched, delete_dispatched, create_dispatched |
Restore an identity-verified kept response, or require evidence of termination and refresh its object |
A kept response carries the original run, epoch, operation ID, address, action, immutable request digest and call stage. Recovery first takes the operation's explicit claim, checks those fields against the ledger and restores the response under that claim. A verified return establishes that the call ended; it does not need process-termination confirmation or another provider mutation. Normal result validation still applies. A response from a replacement's delete cannot complete its later create. Conflicting responses, mismatched identities and legacy evidence without these fields leave the call requiring verified provider recovery; they cannot replace a durable returned result.
Operation requests preserve unknown values as null plus explicit path markers, with an encoding
version, so PostgreSQL does not turn an unknown ID into the literal string "UNKNOWN". A literal
string remains valid. Unknown apply results are also retained with markers and stop the node
before it can commit them as state. Providerless recovery keeps such results quarantined. With
the app's providers, recovery can refresh a known object, or use --import-id when its identity
was unknown. Only a verified read with fully known values is ingested; an invalid create response
is tracked as tainted. An invalid update response remains unconverged after refresh, requiring
configuration reconciliation. A failed/absent read does not prove an unknown object never existed.
Recovery starts the app's providers only when an operation actually needs an eligible object probe, after checking kept responses and termination evidence. A run that can only quarantine unconfirmed calls, ingest known returns, or abort unsent reservations does not start providers. The first eligible probe loads providers once for that recovery invocation. If startup fails, operations that need those providers retain their holds; a later recovery invocation can retry.
Evidence of termination needs both:
- The processes are gone: the run's process and its provider plugin process are no longer
running on this host (recovery checks their pids), or the run recorded killing its providers
when it lost its lease. A run on another host needs
--confirm-terminated. - The call can no longer take effect:
operation_quiescencehas passed since dispatch, or the operator confirms with--confirm-terminated.
With evidence, recovery refreshes the object: an update or delete by the object it had; a create
by the identity its configuration gives (as adoption finds objects, netherframe.core.drift.locate),
or by --import-id. A create whose object cannot be found that way, and any operation without
evidence, stays quarantined: safe, but manual. Recovery is idempotent: resolved operations are
skipped, and an ingestion compares the row with what the operation expected.
Errored state
What a run could not commit (the database was unreachable, or the lease was lost) is written to
an owner-only journal at <outdir>/errored.tfstate.d/<run-hash>.json. Each run atomically replaces
its own cumulative snapshot, so concurrent runs cannot overwrite each other's evidence. The error
reports this complete journal's path. <outdir>/errored.tfstate remains an initial compatibility
snapshot, created only when that path is absent; it may contain fewer records than the journal.
Keep the whole directory available to recovery.
The next ordinary run that takes a grant reconciles plain records with their expected row versions
(per-row compare-and-swap) and reports conflicts. Operation-backed writes always remain bound to
their original operation, including after it aborts or commits. They are never replayed as plain
edits. nf state recover can restore a verified kept response into its operation ledger and ingest
it under that operation's inherited footprint. Recovery leaves unrelated plain edits for an
ordinary run whose grant authorizes them.
Journals and the compatibility snapshot are retained as evidence. Owner-only .processed markers
record individual handled records and the exact completed snapshot digest. A pending response
does not cause an already handled output to be applied again; a late response changes the snapshot
and remains discoverable. Malformed or unverified evidence is retained for review. Legacy files
without operation identity cannot establish that a provider call returned.
Recovery strategies
ROLLBACKdeletes what the failed apply created, then restores the rows as they were before the run: an entry the run created from nothing becomes a tombstone; an entry it re-created (its object was gone before the run,deleted_objects=recreate) gets its previous row back, so entries that consumed it keep a valid one. Outputs the run created are removed. A run that lost its lease never rolls back.CHECKPOINTpins the plan's closed resource/output write targets before its first mutation. The reportednf-graph-checkpoint:...reference identifies retained before-images in graph history, including intent, input proofs, status, private data and sensitive paths. A failed apply leaves its partial changes in state. Restore changes state only; infrastructure must already match the intended restored values.
Under an internal resource grant, a possible create carries conditional rollback_delete
permission. An ordinary delete remains outside that permission. Before reserving the create, the
backend derives its compensation footprint from the actual request and requires the complete
coverage; the immutable operation records rollback_enabled. A compensating delete names that
original create in rollback_of. Reservation and dispatch both require the same run/epoch, its
original committed attempt, a known returned object and the current object incarnation/identity.
An unresolved response, an import, another run or a recovery claim cannot authorize another call.
Rollback restores earlier resource/output intent and consumed-input evidence as fresh revisions. It removes outputs this run created within its admitted write set, and preserves outputs another run committed after its pre-run snapshot. A saved plan without compensation coverage selects app X before its first mutation; unknown pre-run provenance also keeps restoration serial. A grant never grows after effects. To intentionally re-create a rolled-back entry whose tombstone retains its intent, plan from a freshly pinned baseline.
Checkpoint restore
nf state --app demo checkpoint list
nf state --app demo checkpoint show nf-graph-checkpoint:CHECKPOINT_ID
nf state --app demo checkpoint restore nf-graph-checkpoint:CHECKPOINT_ID
# After reviewing the listed later writers and consumers:
nf state --app demo checkpoint restore nf-graph-checkpoint:CHECKPOINT_ID --force
Python callers use hybrid.restore_checkpoint(reference, force=False). List and show expose
references and conflict evidence without state values. A restore starts its own state-only run,
acquires one fixed grant over the actual before/after footprint, then checks the retained images,
later writers/consumers and unique cloud ownership inside its write transaction. Preview is
advisory; a new consumer appearing before grant acquisition is checked again. Restore cannot
dispatch provider calls. Missing ownership contracts require app X and unambiguous ownership;
ambiguous legacy identities must be normalized before restore.
Restore refuses later writers and consumers from other runs, including removed consumers and
dispatched calls that produced no committed row. Operation reservation counters establish ordering
without relying on timestamps. --force waives only those later-writer/consumer conflicts. It cannot
waive missing or changed history, a wrong state/lineage, identity conflicts, unresolved calls or
ownership/lease loss. Successful restore writes fresh revisions of its targets, preserving
unrelated rows. Original input proofs remain original; restored consumers can therefore be marked
stale_inputs for reconciliation. The receipt commits with those revisions, so a lost response can
be observed without repeating the write.
The newest five checkpoints are kept, plus older checkpoints whose origin is active, whose origin has unresolved operations, or whose completed restore run is still active. Each checkpoint pins its before-images and subsequent history/operation evidence needed to check consumption. Time-based history retention cannot discard that evidence. Older graph JSON snapshots are refused because they cannot prove their targets or subsequent consumers. Document backends keep their existing checkpoint format and behavior.
History and queries
nf state history stack.aws_instance.web # every version: actor, run, baseline, intent, operation
nf state history --run RUN_ID --since 42 --limit 100 --json
nf state history stack.aws_instance.web --values --json # masked attributes; no private state or provider identity
nf state history --cursor CURSOR # continue the same filters at the original frontier
nf state show --at 42 # state as of commit sequence 42
nf state show --at 7f3c9a... # as of the end of a run
nf state show --at 2026-11-04T10:00:00 # as of a time
nf state query "SELECT address, status FROM resources_current WHERE status <> 'ready'"
History pages include status, the run's baseline reference, intent and applied fingerprints,
consumed inputs and a continuation
cursor. A cursor is bound to the backend, state lineage and query filters. New commits do not
shift an existing page: subsequent pages stop at its original frontier and can split a multi-row
commit without skipping members. Repeat the same address, --run and --since filters with the
cursor. If pruning removes evidence between pages, start a fresh query; the cursor is rejected.
--values adds masked resource attributes and output values. Private state, provider identities
and metadata are omitted. show --at summarizes resource addresses and outputs; it does not print
potentially sensitive resource identifiers.
Pinned app and stack applies retain their branch origin before execution, under both app-wide and resource grants. It stays in history after the pin is released. An active run prevents releasing its origin pin. A run cannot replace its origin or add one after reserving operations or mutating state. Unpinned runs and older serial history report an unrecorded baseline. The reference describes the origin the run supplied; it does not certify that its checkout matched that origin.
nf state query runs in a read-only transaction, with a statement timeout (--timeout, default
30 seconds), as the read-only role (<schema>_reader), which can select only these views, with
sensitive values masked:
| View | Contents |
|---|---|
resources_current |
Live entries: address, type, provider, revision, incarnation, status, object identity, attributes (sensitive ones masked), dependencies |
outputs_current |
Live outputs; sensitive values masked |
history |
Every version with its sequence, time, actor, run, baseline, intent and operation; sensitive values masked |
runs |
Every run with its operation, actor, epoch, status, baseline and lease |
operations |
Every operation with its stage and outcome (no requests or results) |
leases |
Granted keys, modes, holder run IDs and queue tickets |
lease_queue |
Waiting requests and their ticket order; these runs hold no leases |
dependencies |
Committed reverse dependency targets, dependents and consumed revisions (when known) |
edge_generations |
Monotonic generations of concrete and scoped reverse dependency predicates |
checkpoints |
References, origin run/frontiers and target revision/digest manifests, without before-images |
checkpoint_restores |
Committed restore receipts and their resulting sequences |
Sensitive attributes are those the provider's schema marks sensitive, recorded with each row;
attributes are masked through nested objects and lists. The backend creates the role and grants
it to the connecting user when it may (it needs
CREATEROLE); otherwise a database administrator grants SELECT on the views to it, and
nf state query refuses to run without it. The base tables keep private data and unmasked values
for recovery; restrict them to the role that applies.
History is kept for history_retention_days (90 by default); each row's current version is
always kept, along with the last old version needed to reconstruct recent frontiers. nf state
show --at refuses an incomplete unpinned frontier. Baseline pins and checkpoint origins stay
available while retained; checkpoint consumer evidence, unresolved operations and compensation
requests of live runs are protected too.
nf state --app demo retention show --json # counts only; no evidence is deleted
nf state --app demo retention show --keep-days 30 # preview a one-time policy
nf state --app demo retention prune --keep-days 30 # preview and ask for approval
nf state --app demo retention prune --auto-approve --json
--keep-days must be at least one day and applies only to that invocation. Configure the ongoing
policy with nf --graph-history-retention-days, graph_history_retention_days in
[tool.nf.config] or history_retention_days on the backend. Normal run completion also performs protected
cleanup using that configured policy.
Pruning holds no apply grant during approval. The displayed UTC cutoff and committed frontier
stay fixed; pins and recovery protections are checked again under the database lock, so eligible
counts can change. Current resource/output rows, including tombstones, observations, metadata, baselines and migration
receipts remain. Version, operation and excess-checkpoint deletions commit together. In a prune
result, each eligible count is the number actually removed, and history_epoch advances if
anything was removed. JSON pruning requires --auto-approve to keep its output machine readable.
Destroy
Graph destroy plans without a grant, then acquires and validates one fixed grant before approval or provider deletes. Stack destroy protects the selected stacks' membership; whole-app destroy protects app membership and includes stored stacks that the checkout no longer declares. Every stored object still needs its original provider configuration and cloud namespace. A changed namespace, an unconfigured provider, an outside consumer or a provider-input dependency cycle fails before the first delete. A membership/row race during automatic preparation causes a bounded replan before approval.
Deletes run in reverse dependency order, including values consumed by provider configurations and their output provenance. Cleanup can remove only the captured outputs and data observations; an unrelated late observation is outside the capability. Output deletion has the same destructive reverse-dependency check as resource deletion. Approval timeout ends the entire unmutated run. Dispatched calls keep their operation footprints if a run fails or loses ownership.
The internal resource policy uses immutable admission for the stored destroy role. It validates inspected rows independently of branch intent, without creating a baseline pin. Unsupported ownership uses app X. Public destroy still selects app X while the remaining concurrency gates are open. Graph destroy records authoritative provider inputs regardless of whether the optional provenance report is displayed.
State administration
nf state --app demo taint infra.aws_ssm_parameter.entry
nf state --app demo untaint infra.aws_ssm_parameter.entry
nf state --app demo rm infra.aws_ssm_parameter.entry infra.output.entry_arn
Taint, untaint and removal validate their inspected rows under one fixed grant, then commit only
their finite write set. Removal leaves infrastructure running and refuses to leave a consumer
outside that set; remove its references first or include those entries in the same command.
Python callers use hybrid.forget_resources(addresses). Outputs can be removed along with resources.
Taint retains intent, private data, input proofs and any existing reconciliation status. It does
not turn a stale or unconverged entry into a reconciled one. These commands never replay unrelated
kept-state journals or send provider mutations.
The internal resource policy admits the inspected rows under the stored administrative run role. It validates the fixed write set, authoritative inputs and canonical ownership without requiring known configuration intent or creating a baseline pin. Taint, untaint and removal can therefore operate on unconverged imported entries; unknown intent remains unknown. Legacy ownership keeps the command under app X. Public administration currently retains app X along with ordinary applies; resource selection remains internal until the concurrency gates pass.
Import existing objects
nf state --app demo import infra.aws_ssm_parameter.entry /existing/parameter --auto-approve
nf state --app demo import infra.aws_ssm_parameter.entry --identity '{"name":"/existing/parameter"}'
The target must be declared in the app and absent from state. Supply exactly one import ID or
provider identity. In Python, call hybrid.import_resources([{ "address": address, "import_id": id }])
or supply "identity" instead of "import_id". The API reports successful and failed targets
separately; an error on one object preserves other successful imports. A provider whose configuration
still depends on an undeployed resource must be configured before its objects can be imported.
Preparation records the actual provider configuration inputs and validates its inspected rows under a fixed grant before approval. It freezes the selector without evaluating desired resource arguments. An opaque import ID need not be the canonical object key, so the internal resource policy reserves exclusive identity and adoption coverage for the configured namespace and resource type until the read returns. Other namespaces can proceed. The returned object must have a unique known canonical identity covered by the grant; a changed account, region or endpoint fails closed.
ImportResourceState and the verifying ReadResource are reads: an import has no dispatched stage
and does not modify infrastructure. Each result, including provider private data and identity, is
recorded durably before it commits. The imported entry has unknown desired intent and remains
unconverged until a reviewed apply reconciles its configuration. Import does not claim that the
app's current arguments are already applied, or taint an existing object when a response is lost.
Recovery uses the operation's saved selector to verify an unknown result.
Public imports currently use app X. Internal immutable resource admission validates the inspected state under its stored import role where contracts and authoritative inputs support it; legacy ownership retains app X. Earlier imports with unknown intent do not force the next import batch to take app X. Explicit imports require no branch baseline file or temporary pin.
Moving resources
nf state --app demo mv infra.aws_ssm_parameter.old infra.aws_ssm_parameter.new --auto-approve
Moves operate on inspected deployed state and require no branch baseline. Both addresses must
be managed resources in the same stack, the source must exist, and the target must be vacant
at that step. A same-type move preserves attributes, private state, identity and taint without
starting a provider. A cross-type move requires the target declared in the app and its provider
fully configured in the source object's cloud namespace. MoveResourceState converts the stored
state; it does not apply the target's desired arguments or mutate infrastructure.
Python callers submit ordered chains or swaps as one atomic group, through the app's configured graph-backed execution engine:
from nf.core.execution.hybrid import HybridExecutionMode
def swap_parameters(hybrid: HybridExecutionMode) -> dict[str, object]:
"""Swap two parameters' addresses in one transaction, through a temporary one."""
return hybrid.move_resources(
[
{"from": "infra.aws_ssm_parameter.a", "to": "infra.aws_ssm_parameter.temporary"},
{"from": "infra.aws_ssm_parameter.b", "to": "infra.aws_ssm_parameter.a"},
{"from": "infra.aws_ssm_parameter.temporary", "to": "infra.aws_ssm_parameter.b"},
],
auto_approve=True,
)
The backend validates every source, target and transitive consumer before approval. It reserves one durable operation before conversion reads and publishes the entire group in one transaction, including dependency and consumed-address rewrites. Consumers retain their values and intent but become stale; moved entries remain unconverged until a reviewed apply. Retargeted input proofs retain the original consumed revision as historical evidence, even when a new address happens to have the same revision number. Update code references before that apply.
A failed conversion leaves state unchanged. If a process exits before returning the group, recovery aborts the read-only operation. If the complete result was recorded, recovery commits the same full group without calling the provider again. Its fixed footprint remains held after the run ends, including consumers and conversion namespaces. Public moves currently use app X; internal resource admission can use the inspected closed set when ownership and input evidence are complete. Legacy evidence retains app X through recovery.
Migration
One-command onboarding
Start with the app's configured document backend, including S3, and run:
nf state --app demo onboard --graph graph.json
# Or try durable local PostgreSQL (requires Docker):
nf state --app demo onboard --local
graph.json describes the destination; the password comes from a file:
{"type": "postgresql-graph", "config": {"state_id": "demo", "host": "localhost", "database": "nf", "username": "nf", "password_file": "/run/secrets/nf-graph-password"}}
The command migrates the configured state through the normal fenced handoff, reviews and
applies reconciliation to establish current intent and canonical identity, then writes
nf.baseline. Review may include actual infrastructure changes if configuration or cloud state
has diverged. --auto-approve approves this reconciliation; imports still require the normal
import opt-in. --baseline-file FILE selects the baseline destination.
A durable routing receipt in .nf.out/graph-backends.json makes subsequent CLI commands use
the graph backend while retaining the original document source. Keep this directory, including
the private password file for --local. The local database uses a persistent Docker volume.
An interrupted handoff or reconciliation can be resumed with nf state --app demo onboard.
The original backend must stay configured until that handoff completes. Afterward, configure
the graph backend in the app for other machines; the project route is local to this checkout.
An empty graph backend refuses planning if the retained document backend (or the default
<outdir>/nf.tfstate) contains state. This prevents accidentally planning duplicate creates
between selecting graph storage and migrating the document state. Low-level migration commands
below remain available.
nf state migrate --to graph --source .nf.out/nf.tfstate # a document state file into the app's graph backend
nf state migrate --to document --path exported.tfstate # the graph state out to a document state file
Migration holds the graph's whole-app X grant and the document's lock through the handoff. It
refuses keyed addresses (web[0]), occupied destinations and unresolved graph operations. No
provider is called. The handoff proceeds through durable receipts:
- Stage an empty destination and block ordinary runs there.
- Fence the source, retaining its original resources, outputs, observations, private data and identity.
- Publish the destination and its receipt atomically, then acknowledge completion on the source.
The source stays fenced permanently; inspection and history remain available. A crash or lost response can leave both copies blocked until the migration resumes, but it does not leave two writable copies. Repeat the same command with the original source and destination to resume. Receipts bind the storage locations, snapshot digest and observed versions. A retry after publication preserves later destination writes. If the still-active source changes after an early staging failure, retry stages a fresh transfer under both locks before fencing that new snapshot.
Graph publication commits all rows and the receipt in one transaction. Document publication is
a conditional write. Graph receipts survive app metadata edits and history cleanup; nf state
query "SELECT * FROM state_transfers" inspects their phases without exposing state values.
Graph history, baseline pins and run grants stay in their original backend. Imported document
contents remain unconverged with unknown desired intent and input provenance until a reviewed
apply records them; unchanged attributes alone cannot claim configuration convergence.
Python callers use nf.core.execution.hybrid_graph_state.migrate_document_to_graph(source, target)
or migrate_graph_to_document(source, target). Built-in local, S3, GCS, Azure, Consul, PostgreSQL
document and HCP Terraform backends identify their actual storage locations. Custom document
backends must implement state_identity() without credentials and conditional writes. Local state
paths resolve aliases before locking or atomic replacement, so a symlink cannot leave the
canonical source writable.
Development migration 29 added immutable run-origin history and backfilled origins retained by
admitted plans. It left resource and input evidence intact. Older serial origins cannot be
reconstructed. Release schema 1 requires the release-1 writer and queue protocol.
New operation requests carry
identity_qualification_version=1, proving their durable footprint accounts for per-instance
eligibility. Older requests and digests remain immutable, but their effective exclusion is app X
until recovery resolves them. An older writer cannot dispatch, change state or acquire a grant;
an already-sent provider response can still be retained. The operation_leases view reports the
same effective exclusion used by admission. Saved plans use format 1. Ending a run and explicit force-unlock
remain cleanup operations; epoch-bound evidence that its providers were killed can be recorded
after lease loss. Baseline pins and history retention use their own administrative guards.
Canonical ownership selectors use the provider schema's wire coercions: a string attribute
configured as 123 or True reserves the same object as "123" or "true". Resources without
an identity contract retain app X for the entire operation, including after its run ends;
sibling mutations wait for its durable completion. This fallback limits parallelism until a
provider identity contract establishes narrower coverage.
Requests written before wire identity version 1 keep app X quarantine until recovery resolves them. Recovery leaves their request and digest unchanged. It checks termination before reading each dispatched call's object, saves that observation separately from a provider response, then ingests settled siblings. An interrupted recoverer resumes from those saved observations. A call whose termination or object cannot be established stays quarantined. The wider quarantine does not add state-write permissions to an older request: for example, an old update lacking membership coverage retains tainted tracking when its object is missing.
The schema-23 upgrade qualifies readiness recorded by older writers. A recovery read or a partial
error response establishes the object's tracked state, but does not prove its requested configuration
completed. The migration keeps a legacy ready flag only when a retained successful apply response
covers the same evaluated configuration and canonical cloud object. Missing, pruned or ambiguous
evidence makes the current row unconverged; a fresh provider plan can establish convergence.
A legitimate refresh showing manual drift stays certified when its configuration and object match.
This qualification changes operational readiness only. It preserves state values, fingerprints,
row revisions, the commit frontier, baseline pins and historical before-images. Saved plans that
assumed a ready target must be recreated. Certificates are retained with their historical versions,
so pruning a later operation journal cannot invalidate a certified checkpoint. Restoring an old
uncertified before-image remains unconverged, including with --force; checkpoint digests stay
unchanged. New confirmed applies and their checkpoints use the current protocol normally.
The migration and qualification commit together; an interrupted upgrade can be retried.
The schema-24 upgrade separately qualifies ephemeral input capture. An older operation can have valid wire identity but omit reads made by an ephemeral value's configuration or provider. New operations carry a capture marker; binding an older request does not invent one. Older requests whose before-image or template records ephemeral arguments retain app X exclusion until recovery settles them. Recovery keeps their request and digest unchanged, records unknown inputs and leaves their rows unconverged. Its broader read and reverse-edge coverage does not authorize unrelated row writes. Old returned move groups have changed neither state nor cloud objects: recovery aborts their obsolete manifest, and the move can be repeated against freshly inspected state.
Existing rows with ephemeral arguments receive unknown inputs and conservative reverse edges;
only ready becomes unconverged, preserving stronger status flags. State values, fingerprints,
row revisions, baseline pins and immutable history stay intact. Old checkpoint images receive
the same qualification in both grant preview and publication, including with --force and after
operation journals are pruned. The schema-23 certificates remain immutable. A reviewed apply
records fresh inputs, and its new checkpoints retain their readiness. The frontier, input/status
qualification and reverse-edge changes commit atomically with the upgrade.
Development migration 25 added opaque observations to development capture version 2. Earlier requests cannot attest those reads; their original marker and digest remain unchanged through recovery. The upgrade requalifies marked rows and old checkpoint images at its new frontier while preserving migration-24 history.
Development migration 26 closed the metadata inference used by those earlier upgrades. Missing
ephemeral_arguments cannot prove that runtime bodies or indirect observations consumed no
managed state. A metadata edit or restore could also copy an incomplete proof into a newer
sequence. The upgrade therefore establishes a new input frontier and qualifies every older
resource and output: inputs become unknown, reverse edges become conservative, and only ready
changes to unconverged. Stronger statuses, values, fingerprints, row revisions, baselines,
immutable history and configuration/object convergence certificates remain intact.
Development migration 26 introduced capture version 3. Requests with an older or missing marker retain app X until recovery; binding does not promote them or alter their digest. Recovery cannot turn their missing input evidence into a known empty proof. Old checkpoint images receive the same qualification at preview and publication, even after journal pruning. A fresh reviewed plan/apply can establish current inputs without an infrastructure change; its new checkpoints retain those proofs. Upgrade interruption rolls back the frontier, statuses, inputs and edges together.
Development migration 27 advanced input capture to version 4. Earlier capture could omit the inputs behind a stored observation or reuse a runtime computation from a different state or planning phase. The upgrade establishes a new input frontier and applies the same unknown-input qualification to every older resource/output row and checkpoint image, regardless of argument metadata. Capture-3 operations retain app X and unknown inputs during recovery; old returned move groups require a fresh inspected move. Original requests and digests remain intact. Migrations 1–26 retain their original SQL. A reviewed apply of the current configuration records fresh inputs; unchanged infrastructure does not require another managed provider call to become ready.
Development migration 28 advanced input capture to version 5. Expression memo hits previously omitted the reads
of operands already evaluated in the same configuration, and pre-run runtime caches could mistake
missing evidence for an empty proof. The upgrade qualifies older rows, checkpoint images and
recovered operations at a new input frontier, preserving migrations 1–27 and the same historical
values, revisions and digests. Older development graph plans require the capture-5 header.
Release graph plans and operation requests write input_capture_format: 1, with the same
capture guarantees. Recreate plans whose capture evidence is missing or outdated.
Sibling operation holds apply even when one run owns app X. A returned response keeps its value, membership and reverse-predicate protection until durable commit, so another task cannot stale a deleting row between its provider response and its state write. Independent outgoing edge patches on concrete keys commute within the same run; predicate readers and broad scopes still exclude them. Stored cross-run edge holds remain X.
Late responses from original calls already sent before upgrade are still retained for recovery. Recovery requires known configuration fingerprints and a successful managed apply before declaring those rows ready. Read-only imports, observations and incomplete updates remain unconverged; incomplete creates remain tainted.
Settings
concurrent_applies is an App setting with a CLI flag and a [tool.nf.config] key;
see Concurrent applies. It defaults off and requires a pinned branch origin.
Each setting below is a flag of nf (before or after the command), else its key in
[tool.nf.config] in pyproject.toml, else the argument of PostgreSQLGraphBackend, else the
default. Nothing is read from the environment. See Settings.
| Argument | Flag and key | Default | Meaning |
|---|---|---|---|
lease_ttl |
--graph-lease-ttl, graph_lease_ttl |
120 seconds | How long the lease lasts after each renewal |
lease_timeout |
--graph-lease-timeout, graph_lease_timeout |
0 seconds | Wait for the complete grant after unleased apply planning, per attempt; finite and non-negative; 0 tries once |
approval_timeout |
--graph-approval-timeout, graph_approval_timeout |
300 seconds | Deadline for each approval, including deferred rounds; finite and positive |
lease_renew_interval |
--graph-lease-renew-interval, graph_lease_renew_interval |
a quarter of the TTL | How often the heartbeat renews (must be under the TTL); a run that cannot renew within the TTL loses the app |
operation_quiescence |
--operation-quiescence, operation_quiescence |
provider_apply_timeout when set, else none |
Time after dispatch when a call can no longer take effect; without it, recovering a dispatched operation needs --confirm-terminated |
kill_providers_on_lease_loss |
--kill-providers-on-lease-loss, kill_providers_on_lease_loss |
on | Kill the run's provider processes when it loses its lease, and record it as evidence for recovery |
history_retention_days |
--graph-history-retention-days, graph_history_retention_days |
90 | How long versions are kept |
Connection settings: host, port, database, username and ssl_mode (or the flags
--postgresql-host, --postgresql-port, --postgresql-database, --postgresql-username,
--postgresql-ssl-mode and their postgresql_* keys), password_file (or
--postgresql-password-file, postgresql_password_file) or password_source, ssl_ca,
schema (default nf_graph), table_prefix (default nf_), reader_role.
Differences from document backends
- State is written row by row as each change completes, not every
state_persist_intervalseconds; a hard kill loses nothing that was committed, and every uncommitted mutation has an operation record. - Saved plans record the frontier, lineage and captured proofs. Serial plans validate their captured state; admitted resource plans permit unrelated commits when their per-key proofs hold.
- Two addresses cannot manage one object (
allow_duplicate_adoptioncannot override this). - The lock is a lease with an expiry, renewed by a heartbeat;
force-unlocktakes a run id and cannot end a run with dispatched operations. ROLLBACKrestores re-created entries' rows instead of removing them, and removes outputs the run created.
Integration checks
From the workspace root, with Docker and Terraform installed:
uv run poe test-integration-aws-graph
This runs the core AWS/FakeCloud suite with PostgreSQL graph state, including the Terraform
comparison cases. Every test has its own FakeCloud account. Rebuilt hybrid apps using the same
output directory share one graph state within that test; different directories use separate
state IDs. The fixture verifies that each hybrid instance actually uses a graph state engine.
pytest --nf-test-hybrid-state-backend local selects document state for the same test cases; the regular
test-integration-aws-fakecloud task retains that default.
Destroy orders consumers before their concrete managed inputs, including inputs inherited through data sources. The retained proofs preserve that ordering when cached observations or their constructs have disappeared. No-op rows needing reconciliation remain in the execution walk and do not increase the result's completed resource-change count. Ready, unchanged rows with concrete configuration and identical retained proofs skip the walk after checking current ownership.