Skip to content

Circular Dependency Resolution in netherframe

This document describes how netherframe finds circular dependencies, breaks them, and writes a phased Terraform/OpenTofu export that Terraform accepts phase by phase.

Overview

Terraform applies a configuration in one pass, ordered by its references, and rejects one whose references form a cycle (Error: Cycle: aws_security_group.a, aws_security_group.b). A stack reading another stack's outputs also needs that stack applied first. When an app has cycles, synthesis writes the affected stacks as several configurations, phases, applied in order to the same state, none of which has a cycle.

Finding Cycles

import tempfile

from nf.core import App, Stack
from nf.providers.hashicorp.aws import SecurityGroup

app = App(nf_id="app")
stack = Stack(nf_scope=app, nf_id="security")

web = SecurityGroup(nf_scope=stack, nf_id="web", name="web")
database = SecurityGroup(nf_scope=stack, nf_id="database", name="database")
web.ingress = [{"from_port": 443, "to_port": 443, "protocol": "tcp", "security_groups": [database.ref_id_]}]
database.ingress = [{"from_port": 5432, "to_port": 5432, "protocol": "tcp", "security_groups": [web.ref_id_]}]

with tempfile.TemporaryDirectory() as outdir:
    app.synth(outdir=outdir)

The dependency analyzer builds one graph of the app's constructs and outputs: an edge for each reference in a construct's configuration and each entry of its depends_on. Tarjan's algorithm finds its strongly connected components once; each one of two constructs or more is a cycle. The stacks whose constructs refer to each other in a cycle are found the same way.

Breaking Cycles

Each cycle is broken at a set of its real edges (a feedback arc set, found with the greedy method of Eades, Lin and Smyth and checked to leave the cycle acyclic):

  • A reference is cut by leaving it out until the construct it refers to exists. This is what cycles are broken at by preference: the configuration ends as written.
  • A depends_on entry is cut only when no reference can be: it is dropped from every phase (setting it again would close the cycle), with a warning.
  • A reference in an argument the construct cannot be written without is never cut: a required argument of its class (a generated class's keyword arguments without a default), count, for_each, lifecycle, provider or a provisioner. Neither is a reference to an ephemeral resource, whose values are never recorded.

A cycle every edge of which must stay cannot be broken: synthesis fails naming it, rather than writing a configuration Terraform rejects.

ValidationError: The dependency cycle aws_iam_role.a -> aws_iam_role.b -> aws_iam_role.a cannot be
broken: each of its references is in an argument its construct cannot be written without ...

Hybrid execution ignores the same edges (select_cycle_breaking_edges), applying a construct without the references the plan leaves out, and setting them at the next plan.

Phases

Without its breaking edges the graph is acyclic, and each construct gets a level in dependency order. A stack gets a phase per level at which it has constructs or references to set, and its phases are cumulative: a phase holds every construct of the phases before it, so none destroys what an earlier one created.

For a cycle within a stack there are two phases:

  1. Phase 1 creates every construct, without the references that close the cycle, and records the values of the constructs they refer to as sensitive outputs of the stack (nf_recorded_<address>).
  2. Phase 2 sets those references from the recorded values, read from the stack's own state through a terraform_remote_state data source (data.terraform_remote_state.nf_phases), rather than by referring to the constructs, so it has no cycle either.

For the security groups above, phase 1 creates database without its rule and web with its rule naming database; phase 2 gives database its rule from web's recorded id. After phase 2, terraform plan shows no changes.

Stacks that read each other's outputs in a cycle are applied a phase at a time: each phase comes after the phases of the other stacks holding what it reads (after in the manifest), and the app's apply-all.sh interleaves them in that order.

Strategies

PhasePlanner.create_plan(app, strategy) takes:

  • auto (the default) or minimal: as few phases as the cycles need;
  • level_based: a phase per dependency level within the stacks that are phased.

Limitations

  • A stack keeping its state in a state_store cannot record values (terraform_remote_state cannot read a state store), so a cycle within it cannot be exported; synthesis says so.
  • A change that replaces a construct whose values are recorded reaches the constructs reading them at the next apply of the last phase.
  • Applying an earlier phase again takes out the references it leaves out until the later phases are applied.

Phase Files

app/
└── security/
    ├── backend.tf.json      # the state storage, shared by every phase
    ├── export-manifest.json
    ├── README.md
    ├── PHASED_EXECUTION.md
    ├── phase1/
    │   ├── backend.tf.json  # linked to ../backend.tf.json
    │   └── nf.tf.json
    ├── phase2/
    │   ├── backend.tf.json
    │   └── nf.tf.json
    ├── apply.sh   # runs the phases in order
    ├── destroy.sh # runs the destroy steps
    └── plan.sh

Terraform runs in a phase directory, so relative paths are written relative to it: a local backend's state is ../terraform.tfstate (the stack directory's state), and so on. A stack without a backend gets a local one, as its phases must share their state.

Export Contract

export-manifest.json (format nf-phased-terraform-export, version 1) is the machine-readable contract:

  • phases: each phase's resources, the references it leaves out (deferred_references) or reads from recorded values (recorded_references), and the phases of other stacks to apply before it (after);
  • apply_order: the phases, in order;
  • destroy_steps: undo the phases in reverse, each later one by applying the one before it (which takes out what it added, references that close cycles included), then destroy the first, so nothing is destroyed while another construct still refers to it;
  • recorded_values: the data source reading recorded values, and the output recording each construct's;
  • backend: where the state storage is configured, never its settings.

Debugging

from nf.core import App, Stack
from nf.core.phases.analyzer import DependencyAnalyzer
from nf.core.phases.planner import PhasePlanner
from nf.providers.hashicorp.aws import SecurityGroup

app = App(nf_id="app")
stack = Stack(nf_scope=app, nf_id="security")
web = SecurityGroup(nf_scope=stack, nf_id="web", name="web")
database = SecurityGroup(nf_scope=stack, nf_id="database", name="database")
web.ingress = [{"from_port": 443, "to_port": 443, "protocol": "tcp", "security_groups": [database.ref_id_]}]
database.ingress = [{"from_port": 5432, "to_port": 5432, "protocol": "tcp", "security_groups": [web.ref_id_]}]

analysis = DependencyAnalyzer().analyze_app(app)
for cycle in analysis.resource_cycles:
    print(cycle.get_description(), "broken at", cycle.breaking_edges)

plan = PhasePlanner().create_plan(app)
for phase in plan.phases:
    print(f"{phase.stack_id} phase {phase.number}: {len(phase.resources)} resources, after {phase.after}")

Performance

Cycles are found once, in O(V + E). Each is ordered greedily in O((V + E) log V) in its size, and each edge the order cuts is checked with one search, so only the edges a cycle needs are cut. Levels are assigned in one pass, in dependency order. The same app synthesizes to the same bytes whatever the hash seed.