Skip to content

fix(container): detect nested circular dependencies - #2297

Open
osbre wants to merge 1 commit into
tempestphp:3.xfrom
osbre:fix/container-circular-dependency-chain
Open

fix(container): detect nested circular dependencies#2297
osbre wants to merge 1 commit into
tempestphp:3.xfrom
osbre:fix/container-circular-dependency-chain

Conversation

@osbre

@osbre osbre commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

The container could segfault (SIGSEGV, exit 139) instead of throwing CircularDependencyEncountered when a circular dependency was separated by a nested $container->get() call.

The main issue was that DependencyChain was being used both to track dependencies currently being resolved and to retain everything seen for error rendering. Those two use cases have different lifecycles, which caused both missed cycle detection and false positives.

Reproduction

final class AInitializer implements Initializer
{
    public function initialize(Container $c): A
    {
        $c->get(Unrelated::class); // unrelated, resolves fine
        $c->get(B::class);

        return new A();
    }
}

final class BInitializer implements Initializer
{
    public function initialize(Container $c): B
    {
        $c->get(A::class); // cycle back to A

        return new B();
    }
}

$container->get(A::class); // segfault, not an exception

Without the Unrelated resolution, the cycle is detected correctly, which is why the existing tests didn't catch this case.

Root cause

There were two separate issues:

  1. Nested get() calls reset the dependency chain.

    stopChain() unconditionally set $this->chain = null, so an inner get(Unrelated::class) cleared the ancestry of the outer resolution. The outer resolution then started with a fresh chain and eventually recursed until the stack overflowed.

    Regular constructor autowiring doesn't hit this because it goes through resolve() rather than get(), which is why the usual A → B → A case already worked.

  2. Dependencies were never removed from the chain.

    add() effectively treated "already in the chain" as "circular", even when that dependency had already finished resolving.

    Once the first issue was fixed, this exposed a false positive for ConsoleArgumentBag: the same already-resolved singleton could legitimately be reached twice on one path - once directly by ConsoleApplicationInitializer and once through ExecuteConsoleCommand::__construct.

Fix

The dependency chain is now treated as a properly balanced stack.

  • Added DependencyChain::pop(), with every add() now paired with a finally block.
  • get() and invoke*() restore the caller's chain instead of clearing it, so nested resolutions keep the parent's ancestry.
  • Removed the add() on already-resolved singletons. A singleton only enters resolvedSingletons after construction has completed, so it cannot be part of an in-flight cycle.

Tempest's existing per-parameter $this->clone() already keeps dependency branches isolated, so diamond dependencies continue to work correctly. Because each chain is branch-local and pushes are strictly nested, pop() can safely use a simple array_pop().

Performance

Removing entries by dependency name would cost roughly 5-6%, since it has to reconstruct a Dependency and redo reflection work. Relying on the LIFO property of the chain avoids that, and dropping the unnecessary singleton push keeps the whole change at parity:

Path Baseline This PR
Full autowire, no singletons 0.1689 ms 0.1698 ms
Singleton hit (typical request) 0.0206 ms 0.0189 ms (~8% faster)

The singleton speedup comes from removing the dead bookkeeping that was already happening before this PR.

Tests

Added two regression tests to CircularDependencyExceptionTest:

  • circular_dependency_after_a_nested_resolution_test - covers the nested-resolution segfault and now correctly throws CircularDependencyEncountered.
  • the_same_dependency_resolved_twice_in_one_chain_is_not_circular_test - verifies that one chain resolving the same dependency twice isn't treated as a cycle. It resolves from a single initializer on purpose: constructor parameters each get their own clone of the chain, so they can't catch a missing pop().

Notes

pop() runs from a finally, including when resolution fails. This is safe currently because exception messages are rendered in the exception constructor, before the dependency chain starts unwinding.

If we ever move to lazy message construction, this coupling could cause the rendered chain to lose entries. I'm happy to add a debug-mode assertion that the popped entry is the one we expect, if you'd prefer that extra guard.

@osbre
osbre requested a review from brendt as a code owner September 13, 2026 17:35
@github-actions

Copy link
Copy Markdown

Benchmark Results

Comparison of fix/container-circular-dependency-chain against 3.x (006169824ba6ae00edd0d87662f01bc6baddc401).

Open to see the benchmark results
Benchmark Set Mem. Peak Time Variability
QueryExecutionBench(benchExecuteInsert) - 4.404mb +0.05% 10.347μs -9.21% ±2.48% +133.75%
ViewRenderBench(benchControlFlow) - 44.503mb +0.00% 695.042μs -6.77% ±2.50% +7.39%
ContainerBench(benchResolveSingletonInstance) - 4.051mb +0.86% 0.962μs -33.08% ±1.17% +25.08%
ContainerBench(benchSingletonAttribute) - 4.132mb +0.05% 0.954μs -34.51% ±0.86% -50.81%
ContainerBench(benchResolveClosureSingleton) - 4.051mb +0.86% 0.961μs -33.55% ±0.29% -80.46%

Generated by phpbench against commit 382115f

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant