Backtestspytestrun-20261106-234554#8321

Issue #8321 Merged fix PR #14781 Run 6 Nov 2026 · run-20261106-234554 pytest-dev/pytest

Exceptions without a traceback print multiple times if chained

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

Both patches stop the duplication for the issue's exact example (independent tests for the plain chain pass on both). Patch B does so by passing chain=False to format_exception in the no-traceback fallback only. That leaves the same root cause in the exception-group branch, which also calls format_exception with chaining enabled and even formats the outer excinfo.value instead of the current chain element `e`, so a traceback-less exception group in a chain still gets its chain printed twice; the independent test test_exception_group_without_traceback_in_chain fails on B and passes on A. B's chain=False would also drop the __cause__/__context__ of exception-group members if a group ever hit the fallback. Patch A addresses the root cause in both call sites with a helper that nulls only the top-level cause/context on a TracebackException, preserving member chains, and fixes the excinfo/excinfo_ mix-up. Its tests cover the issue example, group chain non-duplication, and member chains still shown; the adjustment to the existing exceptiongroup test expectation (matching the E-prefixed SyntaxError line) follows from no longer natively rendering the chain and is consistent. B's changelog and AUTHORS entries are good convention, but they do not outweigh an incomplete fix. A wins on correctness and test coverage.

Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.

Solve

6m 4s

Wall-clock time in the container

Full test suite

No new failures

290 passed · 13 skipped · 303 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

153vs 73 merged

Changed lines, ours vs merged

Minimal example:

def test_errors():
    ex1 = ValueError("abcd")
    ex2 = IndexError("efgh")
    ex3 = KeyError("ijkl")
    ex4 = RuntimeError("mnop")
    ex1.__cause__ = ex2
    ex2.__context__ = ex3
    ex3.__cause__ = ex4
    raise ex1

Which has the following output:
<details>
<summary>Expand</summary>

RuntimeError: mnop

The above exception was the direct cause of the following exception:
RuntimeError: mnop

The above exception was the direct cause of the following exception:

KeyError: 'ijkl'

During handling of the above exception, another exception occurred:
RuntimeError: mnop

The above exception was the direct cause of the following exception:

KeyError: 'ijkl'

During handling of the above exception, another exception occurred:

IndexError: efgh

The above exception was the direct cause of the following exception:

    def test_errors():
        ex1 = ValueError("abcd")
        ex2 = IndexError("efgh")
        ex3 = KeyError("ijkl")
        ex4 = RuntimeError("mnop")
        ex1.__cause__ = ex2
        ex2.__context__ = ex3
        ex3.__cause__ = ex4
>       raise ex1
E       ValueError: abcd

test.py:9: ValueError

</details>

What's happening is a little clearer when running with colourful output, the first, third and sixth "the above exception" lines are highlighted, but the rest are plain. Seems at each step of the chain, the full traceback for that exception is output, which includes that of any that happened higher in the chain. This only happens if __traceback__ is None, in practice I found this by messing with it on caught exceptions.

<details>
<summary>System details</summary>

Windows 10

> python --version
Python 3.9.0
> pip list
Package      Version
------------ -------
atomicwrites 1.4.0
attrs        20.3.0
colorama     0.4.4
iniconfig    1.1.1
packaging    20.9
pip          21.0.1
pluggy       0.13.1
py           1.10.0
pyparsing    2.4.7
pytest       6.2.2
setuptools   52.0.0
toml         0.10.2
wheel        0.36.2

</details>

The two patches

Our patch+146 −7
src/_pytest/_code/code.pyindex 3c453b15d..093ba8ceb 100644@@ -17,6 +17,7 @@ from traceback import extract_tb from traceback import format_exception from traceback import format_exception_only from traceback import FrameSummary+from traceback import TracebackException from types import CodeType from types import FrameType from types import TracebackType@@ -871,6 +872,21 @@ class ExceptionInfo(Generic[E]): TracebackFilter: TypeAlias = bool | Callable[[ExceptionInfo[BaseException]], Traceback]  +def _format_exception_unchained(+    exc: BaseException, tb: TracebackType | None+) -> list[str]:+    """Format ``exc`` natively, without its own ``__cause__``/``__context__``.++    The chain is walked (and rendered) by ``repr_excinfo`` itself, so it must+    not be repeated here. ``chain=False`` can't be used for that, because it+    would also drop the chains of the sub-exceptions of exception groups.+    """+    te = TracebackException(type(exc), exc, tb, compact=True)+    te.__cause__ = None+    te.__context__ = None+    return list(te.format())++ @dataclasses.dataclass class ExceptionInfoFormatter:     """Helper object to format ExceptionInfo's and individual exception parts@@ -1205,17 +1221,15 @@ class ExceptionInfoFormatter:                 reprtraceback: ReprTraceback | ReprTracebackNative                 if isinstance(e, BaseExceptionGroup):                     # don't filter any sub-exceptions since they shouldn't have any internal frames-                    traceback = filter_excinfo_traceback(self.tbfilter, excinfo)+                    traceback = filter_excinfo_traceback(self.tbfilter, excinfo_)                     extraline = (                         "All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames."                         if not traceback                         else None                     )                     reprtraceback = ReprTracebackNative(-                        format_exception(-                            type(excinfo.value),-                            excinfo.value,-                            traceback[0]._rawentry if traceback else None,+                        _format_exception_unchained(+                            e, traceback[0]._rawentry if traceback else None                         ),                         extraline=extraline,                     )@@ -1226,7 +1240,9 @@ class ExceptionInfoFormatter:             else:                 # Fallback to native repr if the exception doesn't have a traceback:                 # ExceptionInfo objects require a full traceback to work.-                reprtraceback = ReprTracebackNative(format_exception(type(e), e, None))+                reprtraceback = ReprTracebackNative(+                    _format_exception_unchained(e, None)+                )                 reprcrash = None             repr_chain.append((reprtraceback, reprcrash, description)) testing/code/test_excinfo.pyindex 883a7c5f9..cb3479135 100644@@ -1592,6 +1592,48 @@ raise ValueError()             ]         ) +    def test_exc_chain_repr_without_traceback_not_duplicated(self) -> None:+        """Exceptions without a traceback in a chain are shown exactly once,+        not once per later exception in the chain."""+        ex1 = ValueError("abcd")+        ex2 = IndexError("efgh")+        ex3 = KeyError("ijkl")+        ex4 = RuntimeError("mnop")+        ex1.__cause__ = ex2+        ex2.__context__ = ex3+        ex3.__cause__ = ex4++        with pytest.raises(ValueError) as excinfo:+            raise ex1++        r = excinfo.getrepr()+        file = io.StringIO()+        tw = TerminalWriter(file=file)+        tw.hasmarkup = False+        r.toterminal(tw)+        output = file.getvalue()++        cause = "The above exception was the direct cause of the following exception:"+        context = "During handling of the above exception, another exception occurred:"+        assert output.count("RuntimeError: mnop") == 1+        assert output.count("KeyError: 'ijkl'") == 1+        assert output.count("IndexError: efgh") == 1+        assert output.count(cause) == 2+        assert output.count(context) == 1+        matcher = LineMatcher(output.splitlines())+        matcher.fnmatch_lines(+            [+                "RuntimeError: mnop",+                cause,+                "KeyError: 'ijkl'",+                context,+                "IndexError: efgh",+                cause,+                "*raise ex1",+                "E*ValueError: abcd",+            ]+        )+     def test_exc_chain_repr_cycle(self, importasmod, tw_mock):         __tracebackhide__ = True         mod = importasmod(@@ -1829,7 +1871,7 @@ def _exceptiongroup_common(     result = pytester.runpytest()     match_lines = []     if inner_chain in ("another", "from"):-        match_lines.append(r"SyntaxError: <no detail available>")+        match_lines.append(r"E\s+SyntaxError: <no detail available>")      match_lines += [         r"  + Exception Group Traceback (most recent call last):",@@ -1867,6 +1909,87 @@ def test_exceptiongroup(pytester: Pytester, outer_chain, inner_chain) -> None:     _exceptiongroup_common(pytester, outer_chain, inner_chain, native=False)  +def test_exceptiongroup_chain_not_duplicated(pytester: Pytester) -> None:+    """Each exception in a chain containing an exception group is shown once."""+    pytester.makepyfile(+        """+        import sys++        if sys.version_info < (3, 11):+            from exceptiongroup import ExceptionGroup++        def test() -> None:+            try:+                try:+                    raise KeyError("first")+                except KeyError as e:+                    raise ExceptionGroup("group", [ValueError("member")]) from e+            except ExceptionGroup as e:+                raise IndexError("last") from e+        """+    )+    result = pytester.runpytest()+    assert result.ret == 1+    output = result.stdout.str()+    assert output.count("KeyError: 'first'") == 1+    assert output.count("Exception Group Traceback") == 1+    assert output.count("ValueError: member") == 1+    assert (+        output.count(+            "The above exception was the direct cause of the following exception:"+        )+        == 2+    )+    result.stdout.re_match_lines(+        [+            r"E\s+KeyError: 'first'",+            r"The above exception was the direct cause of the following exception:",+            r"  \+ Exception Group Traceback \(most recent call last\):",+            r".*ExceptionGroup: group \(1 sub-exception\)",+            r"    \| ValueError: member",+            r"The above exception was the direct cause of the following exception:",+            r"E\s+IndexError: last",+        ]+    )+++def test_exceptiongroup_member_chain_shown(pytester: Pytester) -> None:+    """The chain of a sub-exception is still shown when the group is chained."""+    pytester.makepyfile(+        """+        import sys++        if sys.version_info < (3, 11):+            from exceptiongroup import ExceptionGroup++        def test() -> None:+            member = ValueError("member")+            member.__cause__ = KeyError("inner-cause")+            try:+                raise KeyError("outer-cause")+            except KeyError as e:+                raise ExceptionGroup("group", [member]) from e+        """+    )+    result = pytester.runpytest()+    assert result.ret == 1+    output = result.stdout.str()+    assert output.count("KeyError: 'outer-cause'") == 1+    assert output.count("KeyError: 'inner-cause'") == 1+    assert output.count("ValueError: member") == 1+    result.stdout.re_match_lines(+        [+            r"E\s+KeyError: 'outer-cause'",+            r"The above exception was the direct cause of the following exception:",+            r"  \+ Exception Group Traceback \(most recent call last\):",+            r".*ExceptionGroup: group \(1 sub-exception\)",+            r"    \| KeyError: 'inner-cause'",+            r"    \| The above exception was the direct cause of the following exception:",+            r"    \| ValueError: member",+        ]+    )++ def test_exceptiongroup_short_summary_info(pytester: Pytester):     pytester.makepyfile(         """ 
Merged fix · PR #14781+72 −1
AUTHORSindex 2154e3bab..d43b41324 100644@@ -440,6 +440,7 @@ Sankt Petersbug Saravanan Padmanaban Sean Malloy Segev Finer+SemTiOne Serhii Mozghovyi Seth Junot Shantanu Jainchangelog/8321.bugfix.rstnew file mode 100644index 000000000..7a91fa6aa@@ -0,0 +1 @@+Fixed exception chains being duplicated in the traceback output when an exception in the chain (``__cause__``/``__context__``) has no traceback of its own, and that exception is itself linked to further exceptions.src/_pytest/_code/code.pyindex 3c453b15d..e37a1324c 100644@@ -1226,7 +1226,9 @@ class ExceptionInfoFormatter:             else:                 # Fallback to native repr if the exception doesn't have a traceback:                 # ExceptionInfo objects require a full traceback to work.-                reprtraceback = ReprTracebackNative(format_exception(type(e), e, None))+                reprtraceback = ReprTracebackNative(+                    format_exception(type(e), e, None, chain=False)+                )                 reprcrash = None             repr_chain.append((reprtraceback, reprcrash, description)) testing/code/test_excinfo.pyindex 883a7c5f9..d3872068a 100644@@ -1592,6 +1592,73 @@ raise ValueError()             ]         ) +    def test_exc_chain_repr_without_traceback_multiple_links(self) -> None:+        """+        Exceptions without a traceback that are themselves part of a longer+        chain must not have their remaining chain printed twice: once by+        Python's own ``traceback.format_exception`` (used as a fallback when+        an exception has no ``__traceback__``) and once more by pytest's own+        chain-walking loop (#8321).+        """+        exc1 = ValueError("abcd")+        exc2 = IndexError("efgh")+        exc3 = KeyError("ijkl")+        exc4 = RuntimeError("mnop")+        exc1.__cause__ = exc2+        exc2.__context__ = exc3+        exc3.__cause__ = exc4++        try:+            raise exc1+        except ValueError:+            excinfo = ExceptionInfo.from_current()++        r = excinfo.getrepr()+        file = io.StringIO()+        tw = TerminalWriter(file=file)+        tw.hasmarkup = False+        r.toterminal(tw)++        output = file.getvalue()+        for message in (+            "ValueError: abcd",+            "IndexError: efgh",+            "KeyError: 'ijkl'",+            "RuntimeError: mnop",+        ):+            assert output.count(message) == 1, (+                f"{message!r} should appear exactly once in the output, "+                f"got {output.count(message)} occurrences:\n{output}"+            )+        assert output.count("The above exception was the direct cause") == 2+        assert output.count("During handling of the above exception") == 1++    def test_exc_chain_repr_mixed_traceback(self) -> None:+        """+        An exception without a traceback whose chain member has a traceback+        must have that member printed once, in pytest's own style.+        """+        exc1 = ValueError("outer without traceback")+        try:+            raise RuntimeError("inner with traceback")+        except RuntimeError as exc:+            exc1.__cause__ = exc+        try:+            raise exc1+        except ValueError:+            excinfo = ExceptionInfo.from_current()++        r = excinfo.getrepr()+        file = io.StringIO()+        tw = TerminalWriter(file=file)+        tw.hasmarkup = False+        r.toterminal(tw)++        output = file.getvalue()+        assert output.count("ValueError: outer without traceback") == 1+        assert output.count("RuntimeError: inner with traceback") == 1+        assert output.count("The above exception was the direct cause") == 1+     def test_exc_chain_repr_cycle(self, importasmod, tw_mock):         __tracebackhide__ = True         mod = importasmod(