Skip to content
Latchkey

pytest "RecursionError: maximum recursion depth exceeded" in CI

Python hit its recursion limit during a test. Usually it’s genuine runaway recursion in the code under test, but it can also come from pytest comparing or rewriting deeply nested objects.

What this error means

A test (or collection) aborts with RecursionError: maximum recursion depth exceeded, often with a very long, repeating traceback. It may reproduce only on the larger inputs a CI run exercises.

pytest output
E       RecursionError: maximum recursion depth exceeded while calling a Python object
...
  File "app/tree.py", line 42, in walk
    return walk(node.child)
  File "app/tree.py", line 42, in walk
    return walk(node.child)
  [Previous line repeated 996 more times]

Common causes

Genuine infinite or deep recursion

A recursive function with no base case, a cyclic data structure, or input deeper than sys.getrecursionlimit() (default 1000) overflows the stack.

pytest comparing/repr-ing deep objects

A failing assert on a deeply nested or self-referential object can recurse during pytest’s rich comparison or repr, surfacing the limit there.

How to fix it

Fix the recursion in the code

This is a real code/logic error, not a transient one - add a base case, break the cycle, or convert to iteration. Don’t retry.

  1. Read the repeating frame in the traceback to find the recursive call.
  2. Add or correct the base case, or detect cycles in the data.
  3. For legitimately deep but finite recursion, consider an iterative rewrite.

Raise the limit only when recursion is genuinely deep

If the recursion is correct but legitimately deeper than 1000, raise the limit carefully.

Python
import sys
sys.setrecursionlimit(5000)

How to prevent it

  • Always include a base case and guard against cyclic inputs.
  • Prefer iteration for deep traversals.
  • Test with the input depths CI actually exercises.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →