Skip to content

Conversation

@riunyfir
Copy link

PR Message

  • Description:
    This change introduces a contextvars-based re-entrancy guard in RootListenersTracer and AsyncRootListenersTracer to prevent listener callbacks (on_start, on_end, on_error) from invoking nested listeners. When multiple custom PII middlewares are stacked, listener implementations may indirectly trigger another chain/graph run and reattach listeners, forming a loop that eventually leads to a GraphRecursionError in LangGraph. The guard blocks listener re-entry within the same execution context, breaking the unintended cycle while preserving normal listener behavior.

    Changes:

    • Add a ContextVar _IN_LISTENER with scoped set/reset around listener invocations.
    • Short-circuit listener execution if already inside a listener context.
    • Apply the same protection to both sync and async tracers.

    Rationale:

    • Prevent implicit “listener -> re-run -> listener …” loops that inflate recursion depth and trip LangGraph’s recursion_limit.
    • Provide a safe, minimal, and backwards-compatible safeguard without altering public APIs.

    Backwards compatibility:

    • Fully backwards compatible. Existing listeners that do not re-enter will behave unchanged. Listeners that attempted to re-enter will now no-op on nested calls, avoiding unbounded recursion.

    Tests/validation:

    • Manually verified with multiple stacked PII middlewares where listeners previously re-entered and caused GraphRecursionError; the behavior is now stable and non-recursive.
    • Lint passes locally.
  • Issue: GraphRecursionError when adding multiple custom PIIMiddleware #33740

@riunyfir riunyfir requested a review from eyurtsev as a code owner October 30, 2025 13:47
@github-actions github-actions bot added the core Related to the package `langchain-core` label Oct 30, 2025
@codspeed-hq
Copy link

codspeed-hq bot commented Oct 30, 2025

CodSpeed Performance Report

Merging #33745 will not alter performance

Comparing riunyfir:GraphRecursionError (2718206) with master (75fff15)

⚠️ Unknown Walltime execution environment detected

Using the Walltime instrument on standard Hosted Runners will lead to inconsistent data.

For the most accurate results, we recommend using CodSpeed Macro Runners: bare-metal machines fine-tuned for performance measurement consistency.

Summary

✅ 13 untouched
⏩ 21 skipped1

Footnotes

  1. 21 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

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

Labels

core Related to the package `langchain-core`

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant