Skip to content

Exception: Could not find mutant for type error #541

Open

Description

@nedbat

To reproduce:

% git clone https://github.com/nedbat/acidica
% cd acidica
% git checkout 3a142e473e319718edf42f514cbde304061d5b75
% uv venv -p 3.14
% source .venv/bin/activate
% uv sync
Resolved 29 packages in 8ms
warning: Skipping installation of entry points (`project.scripts`) for package `acidica` because this project is not packaged; to install entry points, set `tool.uv.package = true` or define a `build-system`
Prepared 4 packages in 217ms
Installed 27 packages in 77ms
 + ast-serialize==0.6.0
 + click==8.4.2
 + coverage==7.15.0
 + iniconfig==2.3.0
 + libcst==1.9.0
 + librt==0.13.0
 + linkify-it-py==2.1.0
 + markdown-it-py==4.2.0
 + mdit-py-plugins==0.6.1
 + mdurl==0.1.2
 + mutmut==3.6.0
 + mypy==2.3.0
 + mypy-extensions==1.1.0
 + packaging==26.2
 + pathspec==1.1.1
 + platformdirs==4.11.0
 + pluggy==1.6.0
 + pygments==2.20.0
 + pytest==9.1.1
 + pytest-cov==7.1.0
 + pyyaml==6.0.3
 + rich==15.0.0
 + setproctitle==1.3.7
 + textual==8.2.8
 + ty==0.0.58
 + typing-extensions==4.16.0
 + uc-micro-py==2.0.0

% uv pip install -e .
Resolved 1 package in 7ms
      Built acidica @ file:///private/tmp/acid2/acidica
Prepared 1 package in 792ms
Installed 1 package in 2ms
 + acidica==0.1.0 (from file:///private/tmp/acid2/acidica)

% pytest
====================================================================== test session starts =======================================================================
platform darwin -- Python 3.14.4, pytest-9.1.1, pluggy-1.6.0
rootdir: /private/tmp/acid2/acidica
configfile: pyproject.toml
plugins: cov-7.1.0
collected 140 items

tests/test_programs.py ................................................................................................................................... [ 93%]
.........                                                                                                                                                  [100%]

====================================================================== 140 passed in 0.12s =======================================================================

% mypy --strict src tests
Success: no issues found in 9 source files

% mutmut run
⠹ Generating mutants
    done in 6770ms (8 files mutated, 0 ignored, 0 unmodified)
⠙ Filtering mutations with type checker
Traceback (most recent call last):
  File "/private/tmp/acid2/acidica/.venv/bin/mutmut", line 10, in <module>
    sys.exit(cli())
             ~~~^^
  File "/private/tmp/acid2/acidica/.venv/lib/python3.14/site-packages/click/core.py", line 1569, in __call__
    return self.main(*args, **kwargs)
           ~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "/private/tmp/acid2/acidica/.venv/lib/python3.14/site-packages/click/core.py", line 1490, in main
    rv = self.invoke(ctx)
  File "/private/tmp/acid2/acidica/.venv/lib/python3.14/site-packages/click/core.py", line 1970, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
                           ~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^
  File "/private/tmp/acid2/acidica/.venv/lib/python3.14/site-packages/click/core.py", line 1353, in invoke
    return ctx.invoke(self.callback, **ctx.params)
           ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/private/tmp/acid2/acidica/.venv/lib/python3.14/site-packages/click/core.py", line 907, in invoke
    return callback(*args, **kwargs)
  File "/private/tmp/acid2/acidica/.venv/lib/python3.14/site-packages/mutmut/__main__.py", line 1002, in run
    _run(mutant_names, max_children)
    ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/private/tmp/acid2/acidica/.venv/lib/python3.14/site-packages/mutmut/__main__.py", line 1031, in _run
    mutants_caught_by_type_checker = filter_mutants_with_type_checker()
  File "/private/tmp/acid2/acidica/.venv/lib/python3.14/site-packages/mutmut/mutation/file_mutation.py", line 494, in filter_mutants_with_type_checker
    raise Exception(
    ...<3 lines>...
    )
Exception: Could not find mutant for type error /private/tmp/acid2/acidica/mutants/src/acidica/interpreter.py:892 (Cannot determine type of "subline").
Probably, a code mutation influenced types in unexpected locations.
If your project normally has no type errors and uses mypy/pyrefly, please file an issue with steps to reproduce on github.

Activity

  1. Otto-AA commented on Aug 8, 2026

    @Otto-AA
    Collaborator

    Hello, thank you for the issue and reproduction steps!

    I've minimized the repro, and it boils down to this source code:

    class StatementPointer:
        def stmt(self) -> None:
            print(self.subline) # pragma: no mutate
            self.subline += 1
    
        def jump(self) -> None:
            self.subline = 0 # pragma: no mutate

    getting mutated to this (simplified) code:

    from typing import reveal_type
    
    # ...
    
    class StatementPointer:
        # @_mutmut_mutated(mutants_xǁStatementPointerǁstmt__mutmut)
        def stmt(self) -> None:
            print(self.subline) # pragma: no mutate
            self.subline += 1
        def xǁStatementPointerǁstmt__mutmut_1(self) -> None:
            print(self.subline) # pragma: no mutate
            self.subline = 1
    
        def jump(self) -> None:
            self.subline = 0 # pragma: no mutate
    
    
    # ...

    The original code is simple enough and mypy infers int for self.subline (see https://mypy-play.net/?gist=f01653dc7d5ddbbe881d1dd79a5afd0a). The mutated code errors with Cannot determine type of "subline" [has-type] (see https://mypy-play.net/?gist=a052f1f19c96d02476165a118d5d4200).
    I guess that this could still be inferred as int (as pyrefly does), but mypy likely just gives up because it's too complex.

    The workaround would be to explicitly declare the type, so mypy does not need to infer it from its usages:

    class StatementPointer:
        subline: int
    
        # ...

    I can't think of an automated fix in mutmut. We could for sure improve the documentation and error message.
    For instance, we could suggest that when a "Cannot determine type of" error occurs, you can explicitly declare the type in your class.

  2. nedbat commented on Aug 8, 2026

    @nedbat
    ContributorAuthor

    Thanks for digging into it. As a work-around, I've made this local change to mutmut to ignore the exception:

      @ src/mutmut/mutation/file_mutation.py:675 @ def filter_mutants_with_type_checker() -> dict[str, FailedTypeCheckMutant]:
                           (m for m in mutated_methods if m.line_number_start <= error.line_number <= m.line_number_end), None
                       )
                       if mutant is None:
      +                    continue
                           raise Exception(
                               f"Could not find mutant for type error {error.file_path}:{error.line_number} ({error.error_description}). \n"
                               "Probably, a code mutation influenced types in unexpected locations. \n"

    This seems reasonable to me: if you can't figure out which mutant to exclude, then don't exclude any mutant. You still get most of the benefit of the type checking.

  3. nedbat commented on Aug 8, 2026

    @nedbat
    ContributorAuthor

    The problem with suggesting how I can change my product code is that it will be hard to explain in general when a mutant can't be found. It's not clear at all to me how the code is changed for mutation, so it's difficult to debug why the type checker failed for the mutated code when it was fine for the original code.

  4. Otto-AA commented on Aug 9, 2026

    @Otto-AA
    Collaborator

    Thanks for digging into it. As a work-around, I've made this local change to mutmut to ignore the exception:
    ...
    This seems reasonable to me: if you can't figure out which mutant to exclude, then don't exclude any mutant. You still get most of the benefit of the type checking.

    You can do so, but this can skip valid mutants. The exception is an indicator that our expectations are broken with your code and we have no idea if this feature will work correctly for other mutants + type errors, or if we accidentally skip valid mutants because we think that they caused type errors (even if they did not).

    The feature is modeled around the idea that adding a new function can only create type errors in the new function, so type errors of mutated functions stay locally inside the function. The exception is raised if this is not true, and code outside of a mutated function also gets type errors. Then mutated_func_1 could cause type errors everywhere, including in mutated_func_2. I thought that's true for mypy and pyrefly, but apparently for mypy it's not always true.

    The problem with suggesting how I can change my product code is that it will be hard to explain in general when a mutant can't be found. It's not clear at all to me how the code is changed for mutation, so it's difficult to debug why the type checker failed for the mutated code when it was fine for the original code.

    I agree, letting the user debug type errors in the mutated code is not the way to go.

    I'd suggest that we:

    1. Update the exception message. It should be clear that the type checking feature does not work correctly with your code, because we got an unexpected type error. Currently, it sounds like we'd only miss one mutation with type errors, not like the feature in general errored.
    2. If it is a Cannot determine type of "foo" error, let the user know that in class Bar they could add foo: <expected-type> to make the type explicit.
    3. Maybe add an option to allow skipping the error (the continue) but warn that this may skip valid mutants
  5. nedbat commented on Aug 9, 2026

    @nedbat
    ContributorAuthor

    You can do so, but this can skip valid mutants. The exception is an indicator that our expectations are broken with your code and we have no idea if this feature will work correctly for other mutants + type errors, or if we accidentally skip valid mutants because we think that they caused type errors (even if they did not).

    I don't all the internals here obviously, but I can't see how the continue would cause a skip of valid mutants. The continue is the same as the current exception: it causes us to keep a mutant rather than skip it.

    Perhaps you mean: if we can't find the mutant, then in a larger perspective, there's something we're not understanding about the mapping from original code to mutants to type errors, and so the entire analysis is suspect in small ways. That is true. But my impression using mutmut is that it's impossible for it to fully understand the effects of mutation and accurately indicate real bugs. There will always be some investigation needed by the author, and that investigation will always has times where mutmut was doing the wrong thing (surviving mutations that do not indicate a bug). Including some mutants that should be excluded, and possibly skipping some valid mutants, doesn't change that. Keeping this exception adds to the developer's burden to understand mutmut's internals.

    I tried adding self.subline = 0 to my code, and noticed that self.line_num also didn't have an assignment in the constructor, so I added it. When I did both, I got a different type error from mutmut, but this one had no variable name, and of course the line numbers were completely different than my source code. If I hadn't just added those two assignments, I would have been totally lost how to fix the problem. My only option then would be to completely disable the type checking.

    In this case, I figured removing the self.line_num assignment would fix it, which it did, but it did not raise my confidence in mutmut, my type checker, or my code.

    Maybe the type checking feature needs an option to be strict (keep this exception) or flexible (use the continue).

  6. nedbat commented on Aug 9, 2026

    @nedbat
    ContributorAuthor

    When I did both, I got a different type error from mutmut, but this one had no variable name, and of course the line numbers were completely different than my source code.

    My bad: when I added the self.line_num = 0 to the constructor, I had an unnoticed mypy error on my original code.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions