Skip to content

Add Container.validate() for cycle detection#176

Closed
lesnik512 wants to merge 3 commits intomainfrom
feat/cycle-detection
Closed

Add Container.validate() for cycle detection#176
lesnik512 wants to merge 3 commits intomainfrom
feat/cycle-detection

Conversation

@lesnik512
Copy link
Copy Markdown
Member

@lesnik512 lesnik512 commented May 1, 2026

Summary

  • Add Container.validate() method that walks the provider graph via DFS and detects circular dependencies, raising RuntimeError with the full cycle path (e.g. "CycleA -> CycleB -> CycleA")
  • Add validate=False parameter to Container.__init__ for opt-in validation at creation time
  • Add get_dependencies() method to AbstractProvider and Factory to expose dependency edges without accessing internals
  • Add __iter__ to ProvidersRegistry for clean graph traversal
  • Zero runtime cost — validation only runs when explicitly requested

Test plan

  • Cycle detection raises with correct path for A -> B -> A cycle
  • validate=True flag triggers detection at container creation
  • Valid dependency graphs pass without error
  • All existing tests pass
  • Linters and type checker pass

Track the resolution stack per-thread via threading.local shared across
the container tree.  When a provider is encountered that is already
being resolved on the current thread, raise RuntimeError with the full
cycle path (e.g. "CycleA -> CycleB -> CycleA") instead of hitting a
RecursionError.
@lesnik512 lesnik512 self-assigned this May 1, 2026
lesnik512 added 2 commits May 1, 2026 15:38
Measure the per-call overhead of the threading.local cycle guard
(~140 ns/call). Net effect vs original unfixed code is still positive
since fixes #2-#4 saved ~350 ns on the hot path.
@lesnik512 lesnik512 changed the title Detect circular dependencies at resolve time Add Container.validate() for cycle detection May 1, 2026
@lesnik512 lesnik512 closed this May 1, 2026
@lesnik512 lesnik512 deleted the feat/cycle-detection branch May 1, 2026 13:44
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