DEV Community

orenlab
orenlab

Posted on

Why Your Python Dead Code Detector Is Wrong About FastAPI, SQLAlchemy, and Half Your Codebase

Static analysis tools that only search for direct calls produce false positives. Here is what reachability-aware dead code detection looks like — and why getting it right matters more than ever in AI-assisted development.


Most dead code detectors answer the same question the same way: find the symbol, search for calls, report if nothing is found.

That works well for simple scripts. It breaks fast in real Python applications.

And in 2026, when AI coding agents use static analysis output as context for decisions, a false positive is no longer just an annoyance. It is a bug waiting to be confidently introduced.


Why "find calls" is not enough

Tools like vulture and pyflakes are genuinely useful. They answer the direct-call question correctly and fast. The problem is that direct calls are not the whole story in modern Python.

Real applications are full of code that is never called by name:

  • FastAPI route handlers are registered through decorators and invoked by the framework routing layer
  • Starlette middleware methods are called by the runtime, not by application code
  • SQLAlchemy TypeDecorator hooks are triggered by the ORM during query binding and result hydration
  • Pydantic validators are discovered through model metadata at class construction time
  • Aiogram message handlers are registered through router observers
  • Dependency injection containers wire providers at composition time, not at call sites
  • Public package APIs may be exported through __all__ or lazy __getattr__ without a single explicit import in the same codebase

If your dead code tool only searches for explicit symbol references, every one of these patterns is a potential false positive.

And once a tool produces enough false positives, engineers stop trusting it entirely — which is the worst possible outcome, because the real dead code stays in the codebase forever.


Why this is a bigger problem if you use AI coding assistants

There is a second, newer dimension to this.

AI coding agents increasingly use static analysis output as context for automated decisions. When an agent sees a function flagged as dead code, it may suggest deleting it. If that function is actually a FastAPI route handler, an Aiogram message handler, or an ORM lifecycle hook, the agent will remove something real — confidently, because the tool said so.

A noisy report annoys a human developer. A human developer reads the code and figures it out.

A noisy report misleads an agent. An agent acts.

The more AI-assisted coding workflows rely on static signals, the more those signals need to be careful, explainable, and conservative. A dead code report that feeds into an agent's context is closer to executable code than to a suggestion.


The tempting trap: name-based heuristics

When false positives pile up, the easy fix is to add suppressions.

If a function name starts with get_, maybe a framework uses it. Skip it.

If the file is named routes.py, do not report anything in it.

If a method is called dispatch, it is probably fine.

This makes reports quieter. It does not make them more honest. You are trading false positives for hidden real dead code, and the tool becomes progressively less useful the more you suppress.

The hard part is not making fewer reports. The hard part is making fewer wrong reports without burying genuine findings behind broad exemptions.


Reachability, not vibes

The direction we took in CodeClone is symbol reachability.

Instead of asking "does any code call this function by name?", we ask a different question:

Is there deterministic evidence that this symbol is reachable at runtime?

That evidence can come from many places: a direct function call, a framework registration decorator, a base class contract, a runtime hook signature, a dependency injection provider binding, a __all__ export, or a carefully bounded getattr dynamic dispatch. The analyzer builds a reachability model over these edges and only reports a symbol as dead when it finds no evidence of runtime participation.

This is still static analysis. It does not execute the program. It cannot perfectly model every Python runtime pattern in existence.

But it is substantially better than pretending that only direct calls exist.


What real false positives look like in practice

Consider a FastAPI route handler:

router = APIRouter()

@router.get("/metrics")
async def get_metrics() -> dict[str, object]:
    return {"ok": True}
Enter fullscreen mode Exit fullscreen mode

Nobody calls get_metrics() by name. The framework matches HTTP requests to it through the registered route. A naive analyzer reports an unused function.

The same pattern with Aiogram:

router = Router()

@router.message(Command("start"))
async def cmd_start(message: Message) -> None:
    await message.answer("Started")
Enter fullscreen mode Exit fullscreen mode

And with SQLAlchemy runtime hooks:

class OrjsonJSON(TypeDecorator[object]):
    impl = JSON

    def process_bind_param(self, value: object, dialect: object) -> object:
        return encode(value)

    def process_result_value(self, value: object, dialect: object) -> object:
        return decode(value)
Enter fullscreen mode Exit fullscreen mode

process_bind_param and process_result_value are never called directly. SQLAlchemy calls them during query execution. A reachability-aware analyzer recognizes the TypeDecorator base class contract and treats these methods as live. A call-site analyzer reports them as unused.


An important distinction worth making explicit

We do not want CodeClone to say:

This symbol is definitely alive.

That claim is too strong for static analysis. Python is too dynamic.

We want it to say:

There is concrete evidence that this symbol participates in runtime reachability, so reporting it as dead code would be misleading.

That distinction matters for trust. Static analysis tools earn credibility by being careful about what they assert, not by being comprehensive. A conservative, evidence-based report that engineers trust completely is worth more than a comprehensive report that engineers learn to ignore.


What changed in CodeClone 2.0.2

In 2.0.2 we extended the reachability model to cover the patterns that produce the most false positives in real Python codebases.

The main additions: FastAPI route decorators and typed route wrapper patterns, Aiogram router and dispatcher observer decorators, Starlette BaseHTTPMiddleware.dispatch, Flask and aiohttp route registration, SQLAlchemy TypeDecorator runtime hooks, Pydantic model validators and runtime hooks, __all__ public re-exports, PEP 562 lazy module exports through __getattr__, and guarded dynamic dispatch patterns where getattr is followed by a callable check.

The result is intentionally boring: fewer false positives, without converting dead code detection into a list of broad suppressions.

For users upgrading from 2.0.1: if your dead code count goes down, that is expected and correct. It means the reachability model learned more about how your codebase connects to runtime behavior, not that detection became weaker.


Dead code gates in CI only work if engineers trust them

This is worth saying directly.

If a CI pipeline fails because process_bind_param looks unused to the linter, engineers learn to ignore the gate. Or they add a # noqa comment. Or they disable the check altogether.

All three outcomes are worse than not having the check.

A dead code gate in CI needs a false positive rate low enough that every finding is treated as credible. When that bar is met, dead code checks become genuinely useful in automated pipelines — including pipelines where an AI agent is part of the review process.

When it is not met, the check becomes noise, and noise gets turned off.


The principle

A symbol should be reported as dead only when the analyzer cannot find deterministic reachability evidence for it.

Not every Python runtime pattern can be statically modeled. But every supported pattern should be based on concrete, traceable evidence — a decorator we recognize, a base class contract we understand, a dependency graph edge we can follow.

That is the line between static analysis you can act on and a collection of heuristics that produces noise at scale.


Closing

Dead code detection in Python is not a grep problem.

It is closer to building a small reachability model of how real applications connect symbols to runtime behavior: direct calls, framework registration, dependency injection, runtime hooks, public exports, and bounded dynamic dispatch.

Tools like vulture get you a long way there, and fast. The remaining false positives come from the parts of the runtime that reveal themselves only through structural analysis — framework contracts, base class hierarchies, decorator semantics.

That is the gap CodeClone is trying to close.

Not by claiming to solve the unsolvable. By being honest about what evidence it has found, and conservative about what it reports without it.


CodeClone is a structural review layer for Python. The 2.0.2 release notes and full reachability documentation are in the repository.

Top comments (0)