Subchapter 27.3
references/clustering/terraform/depth-calculation.mdMarkdown5 KBView on GitHub
Assigns topological depth to every resource via Kahn’s algorithm (longest path variant).
Higher depth = later in deployment sequence.
All resources with:
address, typedependencies[] array (addresses of resources this one depends on)For each resource:
dependencies[] arrayin_degree[resource] = count_of_incoming_edgesCreate queue of all resources with in_degree = 0.
These are depth 0 (no dependencies).
Assign: depth[resource] = 0 for all queued resources.
While queue not empty:
depth[D] = max(depth[D], depth[R] + 1)in_degree[D] -= 1in_degree[D] becomes 0: Enqueue DNote: “Resources that depend on R” means all resources X where X’s dependencies[] contains R. This correctly assigns higher depths to dependent resources (which must deploy later).
If queue empties but unassigned resources remain:
unknown_dependency or LLM-inferred edges over deterministic edges)depends_on overrides.”All resources have assigned depth field.
Verify: Every resource has depth ∈ [0, max_depth].
function calculateDepth(resources) {
// Build graph
in_degree = {}
depends_on = {}
dependents_of = {} // Reverse adjacency: resource → resources that depend on it
for each resource R:
in_degree[R] = count incoming edges
depends_on[R] = R.dependencies[]
dependents_of[R] = []
// Populate dependents_of (reverse edges)
for each resource R:
for each D in R.dependencies[]:
dependents_of[D].append(R)
// Initialize depth 0
depth = {}
queue = [R for R in resources if in_degree[R] == 0]
for each R in queue:
depth[R] = 0
// Process queue (longest path variant)
while queue not empty:
R = queue.dequeue()
for each D in dependents_of[R]: // Iterate resources that depend on R
depth[D] = max(depth[D], depth[R] + 1)
in_degree[D] -= 1
if in_degree[D] == 0:
queue.enqueue(D)
// Cycle check (bounded: max 3 attempts)
if any resource not assigned depth:
if attempt >= 3:
STOP("Unresolvable circular dependency. Manual review required.")
edge = find_lowest_confidence_edge_in_cycle()
if edge.confidence == 1.0:
STOP("Cycle contains only deterministic edges. Manual review required.")
remove(edge)
return calculateDepth(resources, attempt + 1) // Retry
return depth
}Resources and dependencies:
A: depends on [] → depth 0
B: depends on [A] → depth 1
C: depends on [A] → depth 1
D: depends on [B, C] → depth 2Queue trace:
Final: A:0, B:1, C:1, D:2 ✓
Resources sorted by ascending depth can deploy in order:
Deploy depth 0: A
Deploy depth 1: B, C (parallel OK)
Deploy depth 2: DNo dependency violations; parallelism at same depth.