#4607·opentofu

tofu plan runs for hours in DestroyEdgeTransformer: whole-graph Cycles() evaluated once per inter-provider destroy edge

Author: dee-kryvenkoCreated Sep 26, 2026Updated Sep 29, 2026

OpenTofu Version

OpenTofu v1.12.6

The same code is present on main (internal/tofu/transform_destroy_edge.go:138).

Summary

On a root module with ~20k resource instances across two providers, a plan that destroys ~13k instances does not complete. After the plan walk finishes and every provider process has exited, tofu spends hours on a single thread inside:

Context.Plan → checkApplyGraph → ApplyGraphBuilder.Build → DestroyEdgeTransformer.Transform
  → tryInterProviderDestroyEdge → AcyclicGraph.Cycles → StronglyConnected

tryInterProviderDestroyEdge tentatively connects a destroy edge and then calls g.Cycles(), a strongly-connected-components pass over the entire graph, to decide whether to keep the edge. Transform calls it once for every (destroyer, destroyer-of-a-stored-dependency-address) pair whose two ends use different providers. Pairing is by resource config address, not by instance, so a for_each resource with N instances that depends on a for_each resource with M instances of another provider produces N × M calls. Here that is 413,136 whole-graph SCC passes.

Replacing the whole-graph SCC with a local reachability test brings the phase from more than 4.5 hours to 2 minutes with an identical plan.

OpenTofu Configuration Files

Minimal shape: two for_each resources from different providers, the second referencing the first per key.

hcl
resource "a_thing" "parent" {
  for_each = local.keys
  # ...
}

resource "b_document" "doc" {
  for_each = local.keys
  content  = a_thing.parent[each.key].id
}

Remove most keys from local.keys and run tofu plan. Every b_document.doc[k] stores a_thing.parent (the config address, no index) in its state dependencies, so the transformer pairs each destroyed document with every destroyed parent, not only parent[k].

In the real module, 453 destroyed provider-B instances each store two provider-A addresses that have 453 destroyers each, plus a few small ones:

Stored dependency address Destroyers under it Pair checks
module.<leaf>.a_thing.parent 453 205,209
module.<leaf>.a_thing.parent_policy 453 205,209
two mid-level addresses 2 each 1,812
two top-level addresses 1 each 906
Total cross-provider tryInterProviderDestroyEdge calls 413,136

State: 20,515 instances, 2,574 resource blocks, ~47 MB JSON.

Debug Output

SIGQUIT dump taken 2 minutes into the post-provider phase (-refresh=false, all provider processes already exited). The only non-idle goroutine:

goroutine 3933 [runnable]:
runtime.mapaccess1(...)
github.com/opentofu/opentofu/internal/dag.(*Graph).downEdgesNoCopy(...)
github.com/opentofu/opentofu/internal/dag.stronglyConnected(...)
github.com/opentofu/opentofu/internal/dag.StronglyConnected(...)
github.com/opentofu/opentofu/internal/dag.(*AcyclicGraph).Cycles(...)
github.com/opentofu/opentofu/internal/tofu.(*DestroyEdgeTransformer).tryInterProviderDestroyEdge(...)
github.com/opentofu/opentofu/internal/tofu.(*DestroyEdgeTransformer).Transform(...)
github.com/opentofu/opentofu/internal/tofu.(*BasicGraphBuilder).Build(...)
github.com/opentofu/opentofu/internal/tofu.(*ApplyGraphBuilder).Build(...)
github.com/opentofu/opentofu/internal/tofu.(*Context).applyGraph(...)
github.com/opentofu/opentofu/internal/tofu.(*Context).checkApplyGraph(...)
github.com/opentofu/opentofu/internal/tofu.(*Context).Plan(...)
github.com/opentofu/opentofu/internal/backend/local.(*Local).opPlan.func2()

A run with -target=b_document.doc produced the identical stack after 11 minutes; targeting does not avoid the path.

Process sampling during the phase (1 s samples over 40 s): one runnable thread in 39 of 40 samples, RSS flat, zero page faults, no provider processes. Single-threaded compute.

Expected Behavior

Apply-graph validation should cost roughly proportional to graph size, not to (cross-provider destroy pairs) × (graph size). A plan destroying ~13k instances should finish in minutes.

Actual Behavior

Apply-graph check v1.12.6 v1.12.6 with the change below
Duration > 4 h 36 min, killed by a 5 h job timeout 2 min 0 s
Whole plan (-refresh=false) never finished 5 min 2 s

Output with the change: Plan: 0 to add, 0 to change, 13024 to destroy. No diagnostics.

413,136 reachability checks in 120 s is about 290 µs each. The unpatched run implies at least 40 ms per Cycles() call (16,560 s / 413,136, unfinished).

Steps to Reproduce

  1. Create state for the configuration above with several hundred keys.
  2. Remove most keys from local.keys.
  3. tofu plan -refresh=false
  4. Provider processes exit within minutes, then tofu sits on one busy thread with no output. kill -QUIT shows the stack above.

Additional Context

Current code:

go
e := dag.BasicEdge(from, to)
g.Connect(e)
// ...
if fromProvider != toProvider && len(g.Cycles()) > 0 {
    g.RemoveEdge(e)
}

called from Transform per cross-provider pair, pairing by config address:

go
for _, resAddr := range ri.StateDependencies() {
    for _, desDep := range destroyersByResource[resAddr.String()] {
        t.tryInterProviderDestroyEdge(g, desDep, des)

Cost is O(P × (V + E)), where P is the number of cross-provider pairs and is itself quadratic in instance counts.

The check is local. Before g.Connect(e) the graph is acyclic, so adding from -> to creates a cycle iff there is already a path to -> ... -> from, i.e. from is reachable from to. AcyclicGraph.Ancestors(to) computes that set with a depth-first walk bounded by to's dependency closure, which is small for a destroy node.

Proposed change, built and measured (numbers above):

go
if fromProvider != toProvider {
    anc, _ := g.Ancestors(to)
    if anc.Include(from) {
        log.Printf("[DEBUG] DestroyEdgeTransformer: skipping inter-provider edge %s->%s which creates a cycle",
            dag.VertexName(from), dag.VertexName(to))
        g.RemoveEdge(e)
    }
}

Semantics are unchanged: the edge is removed exactly when it would have closed a cycle. All eight existing TestDestroyEdgeTransformer_* cases pass with this edit.

Pairing destroyers by instance rather than by config address would also remove the quadratic factor in P, but is a larger change and not needed for the immediate fix.

Note that Context.Plan runs checkApplyGraph, so this cost is paid during plan, and ApplyGraphBuilder pays it again during apply.

References

None found for tryInterProviderDestroyEdge, DestroyEdgeTransformer, StronglyConnected, or slow/hanging plans on destroy. Closest is #1559, a different transformer with quadratic behaviour on large graphs.