Very thorough exploration of the desloppify codebase. I need to understand:
How language plugins work - look at desloppify/lang/python/ and desloppify/lang/typescript/ - what's the interface? How does a detector plug in?
How existing detectors work - read through the key ones: smells.py, unused.py, deps.py, graph.py, complexity.py - what patterns do they follow? What do they return?
How findings are structured - what does a "finding" look like? Check state.py for the data model.
How the scan pipeline works - check plan.py and scan.py (or wherever the pipeline orchestration lives) to understand how detectors are called and results merged.
What AST infrastructure exists - does anything already parse Python ASTs? Check deps.py especially since it was recently switched to AST-based parsing.
What's in scoring.py and how dimensions work - do detectors map to scoring dimensions?
The FunctionInfo dataclass - where is it defined, what fields does it have?
Zone classification - how does zones.py work and how do zones affect what gets analyzed?
For each, give me the key file paths, line numbers, function signatures, and data structures. I need enough detail to design a new detector that plugs into this system.
Assistant
I'll conduct a thorough exploration of the desloppify codebase architecture. Let me start by mapping the key files and structures.
Assistant
Let me adjust my approach:
Assistant
Now let me explore the structure systematically:
Assistant
Perfect. Now let me read the key files to understand the architecture:
Assistant
Excellent. Now let me read more about findings structure and the scan pipeline:
Assistant
Now let me look at the Python language plugin structure and some example detectors:
Assistant
Now let me check zones.py and some more detector examples:
Assistant
Perfect. Now let me look at the TypeScript plugin structure and a couple more detector examples:
Assistant
Now let me look at a couple more detector examples to understand the patterns:
Assistant
Now let me check the TypeScript language plugin structure more thoroughly:
Assistant
User
Assistant
User
Assistant
Assistant
Now let me look at how detector phases are structured and how findings flow through the system.
Assistant
Now let me also look at how make_finding works in state.py for the finding ID scheme.
Assistant
Perfect. Now let me create a comprehensive summary document based on all the information I've gathered. Let me compile the final response with all the key details.
Comprehensive Architecture Guide for Desloppify
Based on my thorough exploration, here's everything you need to design a new detector that plugs into the desloppify system:
1. LANGUAGE PLUGINS ARCHITECTURE
Plugin Structure
Each language plugin lives in desloppify/lang/{language}/ and requires:
T3: Needs judgment (smells, near-dupes, single-use, small cycles)
T4: Major refactors (structural decomposition, large import cycles)
Zone Integration
Zone is stamped on findings in plan.py (lines 80-89):
python
for f in findings:
f["lang"] = lang.name
if lang._zone_map is not None:
zone = lang._zone_map.get(f.get("file", ""))
f["zone"] = zone.value
# Apply zone policy confidence downgrades
policy = ZONE_POLICIES.get(zone)
if policy and f.get("detector") in policy.downgrade_detectors:
f["confidence"] = "low"
def build_dep_graph(path: Path) -> dict:
"""Build dependency graph using AST parsing."""
py_files = find_py_files(path)
graph: dict[str, dict] = defaultdict(lambda: {
"imports": set(), "importers": set(), "deferred_imports": set(),
})
for filepath in py_files:
content = Path(abs_path).read_text()
tree = ast.parse(content)
source_resolved = resolve_path(filepath)
# Collect top-level function/class line ranges
top_level_scopes = []
for node in ast.iter_child_nodes(tree):
if isinstance(node, (ast.FunctionDef, ast.ClassDef)):
top_level_scopes.append((node.lineno, getattr(node, "end_lineno", node.lineno)))
# Walk all import nodes
for node in ast.walk(tree):
if not isinstance(node, (ast.Import, ast.ImportFrom)):
continue
is_deferred = any(start <= node.lineno <= end
for start, end in top_level_scopes)
if isinstance(node, ast.ImportFrom):
# Handle relative/absolute imports
targets = _resolve_python_from_import(...)
for target in targets:
graph[source_resolved]["imports"].add(target)
if is_deferred:
graph[source_resolved]["deferred_imports"].add(target)
elif isinstance(node, ast.Import):
for alias in node.names:
target = _resolve_python_import(...)
graph[source_resolved]["imports"].add(target)
return finalize_graph(dict(graph))
Potentials = "things checked for issues" — used to compute pass rates per dimension. For file-based detectors like smells, the potential is file count; findings per file are capped at 1.0 weight in scoring.
class FileZoneMap:
def __init__(self, files: list[str], rules: list[ZoneRule],
rel_fn=None, overrides: dict[str, str] | None = None):
# Built at scan time: lang._zone_map = FileZoneMap(...)
def get(self, path: str) -> Zone:
"""Get zone for a file. Returns PRODUCTION if not classified."""
def counts(self) -> dict[str, int]:
"""File count per zone."""
def production_count(self) -> int:
def non_production_count(self) -> int:
Zone Policies
python
@dataclass
class ZonePolicy:
skip_detectors: set[str] # Detectors to skip entirely
downgrade_detectors: set[str] # Detectors downgraded to "low" confidence
exclude_from_score: bool # Whether to exclude from health scoring
ZONE_POLICIES = {
Zone.PRODUCTION: ZonePolicy(), # All detectors run, counted in score
Zone.TEST: ZonePolicy(
skip_detectors={"dupes", "single_use", "orphaned", "coupling"},
downgrade_detectors={"smells", "structural"},
exclude_from_score=True,
),
Zone.CONFIG: ZonePolicy(
skip_detectors={...},
exclude_from_score=True,
),
Zone.GENERATED: ZonePolicy(skip_detectors={...}, exclude_from_score=True),
Zone.VENDOR: ZonePolicy(skip_detectors={...}, exclude_from_score=True),
Zone.SCRIPT: ZonePolicy(downgrade_detectors={"structural"}),
}
Zone Integration in Phase Runners
python
# Build zone map (automatic in plan.py _generate_findings_from_lang)
if lang.zone_rules and lang.file_finder:
files = lang.file_finder(path)
lang._zone_map = FileZoneMap(files, lang.zone_rules, rel_fn=rel,
overrides=zone_overrides)
# Filter entries by zone policy
zone_entries = filter_entries(lang._zone_map, entries, detector_name)
# Adjust potential (subtract non-production files)
potentials = {
"structural": adjust_potential(lang._zone_map, file_count),
}
# All findings get zone stamped (plan.py lines 80-89)
for f in findings:
zone = lang._zone_map.get(f.get("file", ""))
f["zone"] = zone.value
def generate_findings(path: Path, *, include_slow: bool = True, lang=None,
zone_overrides: dict[str, str] | None = None,
) -> tuple[list[dict], dict[str, int]]:
"""Run all phases and convert results to normalized findings."""
# 1. Build zone map if rules exist
if lang.zone_rules and lang.file_finder:
files = lang.file_finder(path)
lang._zone_map = FileZoneMap(files, lang.zone_rules, rel_fn=rel,
overrides=zone_overrides)
# 2. Filter phases by speed
phases = lang.phases
if not include_slow:
phases = [p for p in phases if not p.slow]
# 3. Run each phase
findings: list[dict] = []
all_potentials: dict[str, int] = {}
for i, phase in enumerate(phases):
result = phase.run(path, lang)
if isinstance(result, tuple):
phase_findings, phase_potentials = result
all_potentials.update(phase_potentials)
else:
phase_findings = result
findings += phase_findings
# 4. Stamp language and zone on findings
for f in findings:
f["lang"] = lang.name
if lang._zone_map is not None:
zone = lang._zone_map.get(f.get("file", ""))
f["zone"] = zone.value
# Apply zone policy confidence downgrades
policy = ZONE_POLICIES.get(zone)
if policy and f.get("detector") in policy.downgrade_detectors:
f["confidence"] = "low"
return findings, all_potentials
9. KEY PATTERNS FOR NEW DETECTORS
Pattern 1: Raw Detector Function
python
def detect_something(path: Path, ...) -> tuple[list[dict], int]:
"""
Returns: (entries, total_items_checked)
Where entries is list[dict] with detector-specific fields.
"""
entries = []
# ... detection logic
return entries, total_count
Pattern 2: Entry Normalization Function
python
def make_something_findings(entries: list[dict], stderr_fn) -> list[dict]:
"""Transform raw detector entries into normalized findings."""
results = []
for e in entries:
results.append(make_finding(
"detector_name", # Must match detector ID
e["file"],
e["name_or_id"],
tier=tier_int,
confidence="high" | "medium" | "low",
summary="Human-readable description",
detail={...}, # Structured data
))
stderr_fn(f" -> {len(results)} findings")
return results
_extra_exclusions = [] # Global mutable state
# In detectors, ALWAYS import the module and access via module:
from .... import utils as _utils_mod
if _utils_mod._extra_exclusions:
# Check exclusions
if any(_utils_mod.matches_exclusion(filepath, ex) for ex in _utils_mod._extra_exclusions):
continue
FunctionInfo Access Pattern
When using extractor output, use attribute access (FunctionInfo is a dataclass):
python
# From dupes.py phase_dupes:
if lang._zone_map is not None:
functions = [f for f in functions
if lang._zone_map.get(getattr(f, "file", "")) not in EXCLUDED_ZONES]
Path Resolution Pattern
python
from desloppify.utils import resolve_path, rel, PROJECT_ROOT
# Always resolve absolute paths for graph keys:
source_resolved = resolve_path(filepath)
# Always use rel() for finding output:
results.append(make_finding("detector", rel(filepath), ...))
content = Path(abs_path).read_text()
tree = ast.parse(content)
for node in ast.walk(tree):
if isinstance(node, (ast.Import, ast.ImportFrom)):
# Handle import node
String Line Detection
Python smells.py has _build_string_line_set() to track multi-line strings so regex checks don't false-positive inside docstrings:
python
string_lines = _build_string_line_set(lines)
for match in re.finditer(pattern, content):
line_no = content[:match.start()].count('\n')
if line_no in string_lines:
continue # Skip matches inside multi-line strings
11. FILE LOCATIONS QUICK REFERENCE
Purpose
File Path
LangConfig base
desloppify/lang/base.py
Detector base classes
desloppify/detectors/base.py
Finding creation
desloppify/state.py (line 216)
Zone system
desloppify/zones.py
Scoring & dimensions
desloppify/scoring.py
Scan pipeline
desloppify/plan.py
Python language plugin
desloppify/lang/python/__init__.py
TypeScript language plugin
desloppify/lang/typescript/__init__.py
Python dep graph (AST)
desloppify/lang/python/detectors/deps.py
Python extractors
desloppify/lang/python/extractors.py
Python smells
desloppify/lang/python/detectors/smells.py
Graph algorithms
desloppify/detectors/graph.py
Complexity detection
desloppify/detectors/complexity.py
Large file detection
desloppify/detectors/large.py
God class detection
desloppify/detectors/gods.py
This should give you everything you need to design a new detector that integrates seamlessly with the desloppify system!
You are thinking through the design of a "Dict Key Flow Tracer" detector for Python — a tool that tracks where dictionary keys are written and read across a codebase and finds dead writes, missing reads, and data flow anomalies.
Think from the perspective of a profoundly precise, exhaustive engineering mind. Cover every edge case, every failure mode, every subtlety of Python's dynamic nature. Be brutally honest about what's hard and what's impossible.
Context
This will be a new detector in the desloppify codebase — a Python CLI tool for code health. The system:
Uses ast.parse() already for import detection
Has language plugins with DetectorPhase runners
Returns findings as dicts with detector/file/tier/confidence/summary/detail
Has zone classification (production/test/config/generated)
Has FunctionInfo/ClassInfo dataclasses for extraction
Each phase runner returns (findings, potentials)
The Problem
In Python codebases, dicts are the universal data bus. Keys get written in one function/file and consumed (or not consumed) in another. Common bugs:
Dead writes: payload["key"] = value where no downstream consumer ever reads "key"
Missing reads: a consumer does params.get("key") but no producer ever writes "key"
Redundant transforms: data is processed, passed through, then re-processed
Key typos: "lora_names" vs "lora_name" (singular/plural mismatches)
Your task
Think through EXHAUSTIVELY:
AST-level detection: What AST node types correspond to dict key writes and reads? Think about EVERY way a Python dict key can be accessed:
d["key"] = val (subscript assign)
d.get("key")
d.get("key", default)
d.pop("key")
d.setdefault("key", val)
d.update({"key": val})
key in d
d["key"] (subscript read)
**d (unpacking — consumes all keys)
dict(key=val) (constructor)
{"key": val} (literal)
d |= {"key": val} (merge)
What about getattr(d, "key") on dict subclasses?
What about TypedDict?
Scope tracking: How do we know which dict a key belongs to?
Variable aliasing: config = settings; config["key"] = val
Function parameter passing: def process(params): params["key"]
Return values: d = build_config(); d["key"]
Class attributes: self.config["key"]
Module-level: DEFAULTS["key"]
Dict comprehensions
What about **kwargs?
Cross-file tracing: How do we track a dict from creation to consumption?
Function call chains: f(d) → g(d) → h(d)
Serialization boundaries: json.dumps(d) → DB → json.loads(s)
Precision/recall tradeoffs: What's the right strategy?
Start ultra-conservative (only flag when VERY confident)?
Or cast a wide net and use confidence levels?
What heuristics reduce false positives?
Data structures needed: What intermediate representations?
How to represent "dict identity" across scopes?
How to represent key access patterns?
How to merge information across files?
Computational complexity: For a 500-file codebase, what's the performance like?
AST parsing cost
Cross-reference resolution cost
Memory usage for the flow graph
What's actually achievable vs theoretical: Be honest about what a static tool can do vs what requires runtime analysis.
Think deeply. Be thorough. Output your complete analysis as a design document. Don't write code — think through the design space exhaustively.
Dict Key Flow Tracer: Exhaustive Design Analysis
1. AST-Level Detection: Every Way a Dict Key Can Be Written or Read
1.1 Key Writes (Producers)
Subscript assignment — ast.Assign / ast.AugAssign with ast.Subscript target
python
d["key"] = val # Assign where target is Subscript(value=Name("d"), slice=Constant("key"))
d["key"] += val # AugAssign, same structure
d["key"] |= val # AugAssign with BitOr — could be nested dict merge
The AST structure is clean here. The slice node is a Constant(value="key") for string literals. Easy to detect. But immediately: d[some_var] = val — the slice is a Name, not a Constant. We can only trace literal string keys. This is a fundamental limitation that affects everything downstream.
Dict literal construction — ast.Dict
python
{"key": val} # Dict(keys=[Constant("key")], values=[...])
{"key": val, **other} # keys will have a None entry for the **other spread
{**a, "key": val, **b} # Mixed — None entries interleaved
Critical subtlety: ast.Dict nodes appear in many contexts:
Standalone assignment: d = {"key": val} — the dict identity is d
Return value: return {"key": val} — identity depends on what the caller binds it to
Argument: func({"key": val}) — identity depends on the parameter name in the callee
Nested: outer["section"] = {"key": val} — nested dict, key belongs to a sub-dict
update() argument: d.update({"key": val}) — key is being written to d, not to the literal
Each context requires different handling. The literal itself is a write, but what dict it writes to depends on data flow.
dict() constructor — ast.Call with func resolving to dict
python
dict(key=val) # Call(func=Name("dict"), keywords=[keyword(arg="key", value=...)])
dict(key=val, **other) # keywords includes keyword(arg=None, value=Name("other"))
dict([("key", val)]) # Positional arg — list of tuples. Nearly impossible to trace statically.
dict(zip(keys, values)) # Completely opaque.
Only dict(key=val) keyword form is tractable. The keyword.arg gives us the key name as a string. But we can't even be 100% sure dict refers to the builtin — it could be shadowed. In practice, we should assume it's the builtin unless we see an explicit dict = something_else in scope.
d.update() — ast.Call where func is Attribute(value=..., attr="update")
python
d.update({"key": val}) # Arg is a Dict literal — can extract keys
d.update(key=val) # Keyword args — can extract from keyword.arg
d.update(other_dict) # Arg is a Name — keys are whatever other_dict has. Opaque unless we trace other_dict.
d.update([(k, v) for ...]) # Completely opaque.
We can handle the first two forms. The third requires cross-reference to other_dict's known keys. The fourth is hopeless.
This is both a read AND a write. It reads the key (to check existence) and conditionally writes. For our purposes, it's a write (it can produce the key) and a read (the caller expects to get a value back, and the key name must be meaningful).
d |= {"key": val} and d = d | {"key": val} — PEP 584 merge (Python 3.9+)
python
d |= {"key": val} # AugAssign(target=Name("d"), op=BitOr(), value=Dict(...))
d = d | {"key": val} # Assign(targets=[Name("d")], value=BinOp(left=Name("d"), op=BitOr(), right=Dict(...)))
d = {"key": val} | d # Order matters! Right side wins on conflicts.
The |= form is AugAssign. The | form is BinOp(op=BitOr()). Both operands could be dicts. We need to check if either side is a dict literal or a known dict variable. The merge semantics mean the right-hand side's keys overwrite the left's — relevant for dead-write detection (if the same key appears on both sides, the left's write is dead for that key).
Unpacking into a new dict — {**d, "key": val}
This is a Dict node where keys contains None entries (for **d spreads) and Constant entries for explicit keys. The explicit keys are writes. The **d spread is a read of all keys from d and a write of all those keys into the new dict. This is a "pass-through" — it copies keys we may not know about.
collections.defaultdict and collections.OrderedDict
These are dict subclasses. defaultdict(list) creates keys on read access (d["key"] auto-vivifies). This means a subscript read on a defaultdict is also a write. We generally can't distinguish defaultdict from dict without tracing the constructor, which is fragile. This is a source of false positives: we might flag d["key"] as a read with no matching write, but it's actually an auto-vivifying write.
Heuristic: if we see d = defaultdict(...) or d = collections.defaultdict(...), mark d as auto-vivifying and suppress "missing write" warnings for subscript accesses on it.
TypedDict
python
class Config(TypedDict):
key: str
other: int
This declares keys at the class level. The class body contains ast.AnnAssign nodes where target is a Name and annotation is a type. These are key declarations — both implicit writes (the TypedDict defines the expected key set) and implicit reads (any code creating an instance must provide these keys).
Detection: we need to identify TypedDict subclasses. The base class could be:
TypedDict (if imported directly)
typing.TypedDict
typing_extensions.TypedDict
A user-defined subclass of TypedDict
We'd need to track imports to resolve this. The functional form Config = TypedDict("Config", {"key": str}) is also possible but rarer.
TypedDict is actually extremely valuable for this detector — it's the closest thing to a schema declaration. If a TypedDict defines keys {a, b, c} and consumers only read {a, b}, key c might be dead. If consumers read {a, b, d}, key d is a missing-key bug.
This is a read. The presence of a default argument doesn't change that. But it does signal that the caller is uncertain whether the key exists — which is useful metadata. A d.get("key") without a default returns None on miss, which is often a latent bug if the caller doesn't check.
d.pop("key") and d.pop("key", default)
A read-and-delete. It's a consumer. It removes the key, so downstream code can no longer read it. This affects flow analysis: after d.pop("key"), the key is no longer in d.
key in d — ast.Compare with In operator
python
"key" in d # Compare(left=Constant("key"), ops=[In()], comparators=[Name("d")])
"key" not in d # Compare with NotIn
This is a read in the sense that code is checking for the key's existence. It's a weaker signal than an actual value read, but it means the code cares about whether the key is present. Useful for reducing false positives: if there's an "key" in d check before d["key"], the code is being defensive.
d.keys(), d.values(), d.items()
These read all keys (or all values, or both). They're bulk consumers. for k, v in d.items() reads every key. This is important: any code that iterates over a dict's items is a consumer of all keys, which means we can't flag any write as dead if the dict is ever iterated.
Destructuring / unpacking
python
{**d} # In a dict literal — reads all keys
func(**d) # In a call — reads all keys as keyword arguments
a, b = d["x"], d["y"] # Multiple subscript reads
**d in a call is especially important: it passes all of d's keys as keyword arguments to func. If we know func's signature, we can determine which keys are consumed. But **kwargs in the callee swallows everything.
del d["key"]
python
del d["key"] # Delete(targets=[Subscript(..., ctx=Del())])
This is a "consume and destroy." The key must exist (or it raises KeyError). It's a read (asserts existence) and a mutation (removes the key).
json.dumps(d), pickle.dumps(d), etc.
Serialization reads all keys. But we can't easily detect "this argument to json.dumps is the dict we're tracking." We'd need to trace the variable to the call. If we do trace it, we know it's a bulk consumer.
getattr(d, "key") on dict subclasses / objects with __getattr__
For plain dicts, getattr accesses the dict's methods, not its keys. getattr(d, "get") returns the get method. But for types.SimpleNamespace, argparse.Namespace, or custom classes that store data in __dict__, getattr accesses what are effectively dict keys. We should NOT track getattr for plain dicts. For SimpleNamespace or argparse.Namespace, it's relevant but that's a different detector.
However: some codebases use attrdict-style wrappers where d.key is equivalent to d["key"]. We can't detect this without knowing the class hierarchy. This is an explicit non-goal for v1.
1.3 Ambiguous / Dual-role Operations
Operation
Read?
Write?
Notes
d.setdefault("k", v)
Yes
Yes (conditional)
Reads to check, writes if absent
d.pop("k")
Yes
No (deletes)
Reads value, removes key
d.pop("k", default)
Yes (weak)
No (deletes if present)
Won't raise if missing
d.update(other)
Reads other
Writes to d
Dual-role on different dicts
`d
= other`
Reads other
Writes to d
**d in {**d, "k": v}
Reads all of d
Writes to new dict
d.copy()
Reads all
Creates new dict
Shallow copy — shared references
1.4 Patterns That Defeat Static Analysis
Dynamic key construction:
python
d[f"prefix_{name}"] = val # Key is f-string — content unknown
d[key_var] = val # Key is a variable
d[CONSTANT] = val # Key is a module constant — traceable if we resolve it
d[obj.attr] = val # Key is an attribute — hard to trace
d[func()] = val # Key is a function return — opaque
Only Constant (string literal) keys are tractable. Everything else is a black hole. We should record "this dict has dynamic key writes/reads" as metadata, which lowers our confidence for any findings on that dict.
**kwargs passthrough:
python
def middleware(**kwargs):
# kwargs has unknown keys
return inner_func(**kwargs)
kwargs is a dict with completely unknown keys. Any function with **kwargs is a potential passthrough for any key. This is extremely common in Python codebases (decorators, middleware, wrapper functions). We must recognize **kwargs parameters and mark those dicts as having unknown key sets.
vars() and __dict__:
python
vars(obj)["key"] = val # Writing to an object's __dict__
obj.__dict__["key"] = val # Same thing
obj.__dict__.update(d) # Merging a dict into object attributes
vars() returns a dict, but it's the object's attribute dict. This bridges dict-key space and attribute space. It's rare enough that we can probably ignore it in v1, but we should not flag vars() return values.
exec() / eval():
python
exec(f'd["{key}"] = {val}') # Dict modification via exec. Completely opaque.
Thankfully rare. We can't do anything about this. If we detect exec/eval in a function that also uses a tracked dict, we could lower confidence.
Framework-specific patterns:
python
# Django
settings.DATABASES["default"]["ENGINE"] # Nested dict access on a module-level object
request.POST["key"] # Django request dict
request.session["key"] # Session dict
# Flask
app.config["KEY"] # Flask config
g.key # Flask global — not a dict
# Celery
@task
def process(data): # data comes from a message queue — opaque origin
data["key"]
These are all dicts, but their key sets are defined by external systems (database schemas, HTTP forms, config files). Flagging "missing write" for request.POST["username"] would be noise — the write happens in the browser's form submission. We need to recognize common framework patterns and either exclude them or mark them as having external producers.
2. Scope Tracking: Identifying Which Dict a Key Belongs To
This is the hardest problem. The fundamental question: when we see d["key"], which dict is d?
2.1 Dict Identity Model
We need an abstraction for "which dict is this." Options:
Option A: Variable-name-based identity (naive)
Treat the variable name as the dict identity. config["key"] belongs to "the config dict." Simple, fast, high false positive rate. Two unrelated functions both using a local variable named config would be treated as the same dict.
Option B: Scope-qualified name identity (practical)
Identity = (file, function/class, variable_name). So mymodule.py::build_config::config is different from mymodule.py::process::config. This handles local variables well but breaks down with:
Aliasing: x = config; x["key"] — x is a different name but the same dict
Parameter passing: def f(params): params["key"] — params is a parameter, the actual dict depends on the caller
Returns: config = build() — the dict comes from build()'s return value
Option C: Abstract dict objects with flow-sensitive tracking (ideal but expensive)
Create abstract dict objects at creation points (literals, dict() calls) and track them through assignments, parameter passing, and returns. This is essentially a simplified pointer analysis. It's what a real static analysis framework (like pytype or mypy) does, but it's expensive and complex to implement.
Recommended: Option B with targeted enhancements
Use scope-qualified names as the primary identity, with specific heuristics for common patterns:
Aliasing within a function: Track x = y assignments and unify their identities. This is cheap (linear scan of assignments in a function body).
Parameter-to-argument binding: When we see f(my_dict), and f has parameter params, we can create a binding f::params → caller::my_dict. This requires matching call sites to function definitions.
Return value binding: When we see d = build_config(), and build_config returns a dict literal or a known dict, we can bind caller::d → build_config::return_value.
self.x attributes: Treat self.config as a class-level identity: MyClass.config. All methods accessing self.config in MyClass share the same dict identity.
2.2 Intra-function Aliasing
python
def process():
config = load_config() # config is bound to return value of load_config
settings = config # settings aliases config
settings["key"] = val # This is a write to config's dict
local = {} # local is a new dict
local.update(config) # local gets config's keys (but is a separate dict)
Within a single function, we can track simple aliasing (x = y where y is a known dict). But local.update(config) is a key-copying operation — local gets the same keys but is a different object. We'd need to propagate known keys from config to local.
This is getting into data-flow analysis territory. For v1, I'd suggest:
For self.x patterns, we can unify all accesses across methods of the same class. The identity is Pipeline.config. This is a very common pattern and very tractable — we just need to:
Identify the class
Collect all self.config[...] accesses across all methods
Unify them under one dict identity
Complication: inheritance. If SubPipeline(Pipeline) adds self.config["extra"] = val, that's the same dict (assuming __init__ calls super().__init__()). We'd need class hierarchy resolution. For v1, we could treat each class independently and accept the imprecision.
Module-level dicts have a clear identity: module::DEFAULTS. Cross-file access is through imports, which we can trace (since we already have import detection in deps.py). This is the most tractable cross-file scenario.
Mutation of imported module-level dicts is a code smell in itself, but it happens. We need to track writes from importing modules too.
2.5 **kwargs and Function Signatures
python
def create_user(**kwargs):
# kwargs is a dict — but what keys does it have?
name = kwargs["name"] # Read of "name"
email = kwargs.get("email") # Read of "email"
# Caller:
create_user(name="Alice", email="alice@example.com", role="admin")
At the call site, keyword arguments are effectively dict writes. In the callee, kwargs reads are dict reads. If we can connect call sites to function definitions:
Call site writes: name, email, role
Function reads: name, email
Dead write: role (written at call site, never read in function)
This is actually one of the most valuable patterns to detect! **kwargs is where key typos and dead writes are most common. The connection requires matching calls to definitions, which we do across files via the import graph.
But: if the function does **kwargs passthrough (inner_func(**kwargs)), then role isn't dead — it's passed to inner_func. We'd need to trace the chain. And if any function in the chain does **kwargs passthrough, we lose track.
Heuristic: if a function both receives **kwargs and passes **kwargs to another call, mark it as a passthrough and don't flag dead writes. Only flag dead writes in "terminal" functions that consume kwargs without passing them on.
2.6 Dict Comprehensions
python
result = {k: v for k, v in items if condition} # Keys are dynamic — opaque
result = {name: func(name) for name in KNOWN_NAMES} # Keys come from KNOWN_NAMES — opaque unless KNOWN_NAMES is a literal
mapping = {"a": 1, "b": 2}
inverse = {v: k for k, v in mapping.items()} # Keys are values of mapping — opaque
Dict comprehensions almost always produce dynamic keys. We should recognize them and mark the resulting dict as having an unknown key set. Don't try to trace comprehension keys.
This is the easiest case. We resolve the import, find the dict definition, and connect reads to writes. The existing import detection in deps.py gives us the import graph.
Requires: (1) resolving the import of build_config, (2) analyzing build_config to find its return dict, (3) connecting the call site's variable to the returned dict's keys.
Step 2 is non-trivial. build_config might conditionally return different dicts, or build a dict incrementally:
python
def build_config():
d = {}
d["key"] = "value"
if something:
d["timeout"] = 30
return d
For this, we'd need intra-procedural analysis of build_config to collect all possible keys written to the returned dict. This is doable but adds complexity.
Class instantiation with dict attributes (covered above in 2.3)
3.2 What's Partially Tractable
Multi-hop function chains:
python
def create(d):
d["created_at"] = now()
return enrich(d)
def enrich(d):
d["enriched"] = True
return validate(d)
def validate(d):
if "created_at" not in d: # Read
raise ValueError
d["validated"] = True
return d
Each hop adds keys. To trace the full key set, we need to analyze the chain in order. This is essentially inter-procedural data flow analysis. It's tractable for short chains (2-3 hops) but becomes expensive for deep call graphs.
Strategy: limit to N hops (e.g., 3) and mark anything deeper as "unknown additional keys possible."
Dict passed through containers:
python
items = [{"key": val} for val in values] # List of dicts
for item in items:
item["key"] # Read
The dict goes into a list and comes back out. Static analysis can sometimes handle this (the list is a homogeneous collection of dicts with known keys), but it's fragile. If items is modified between creation and iteration, all bets are off.
3.3 What's Intractable
Serialization boundaries:
python
# Producer
data = {"key": "value"}
redis.set("mykey", json.dumps(data))
# Consumer (possibly different process)
raw = redis.get("mykey")
data = json.loads(raw)
data["key"] # How do we know this "data" connects to the producer's "data"?
There's no static link between the producer and consumer. The data goes through an external system (Redis, database, message queue, file on disk). This is completely opaque to static analysis.
We could detect the pattern (json.dumps/json.loads, pickle, etc.) and note "this dict is serialized, so its consumers may be elsewhere." But we can't trace the actual flow.
Dynamic dispatch / plugin systems:
python
handler = get_handler(event_type) # Returns a function based on runtime value
handler(data) # Which function gets called? Unknown.
Monkey-patching and runtime modification:
python
import module
module.SETTINGS["injected_key"] = True # Modifying another module's dict at runtime
We CAN detect this (it's an attribute access chain ending in a subscript write), but connecting it to the target module requires resolving module.SETTINGS, which means tracing the import and the attribute access.
4. False Positive Analysis
4.1 Major False Positive Sources (Ranked by Severity)
1. Dynamic keys (CRITICAL)
If a dict has any dynamic key writes, we can't know its full key set. Flagging a "dead write" for a literal key when there are also dynamic reads like d[variable] is wrong — the dynamic read might be reading that key.
Mitigation: if a dict has ANY dynamic key access (read or write), significantly lower confidence on all findings for that dict. Maybe only report if the literal key analysis alone shows anomalies AND there are no dynamic accesses.
2. **kwargs passthrough (CRITICAL)
python
def wrapper(**kwargs):
# We see reads for "a" and "b" but not "c"
a = kwargs["a"]
b = kwargs["b"]
inner(**kwargs) # But inner() might read "c"!
If **kwargs is passed to another function, all keys are potentially consumed. We MUST detect passthrough and suppress dead-write warnings.
Passthrough detection: look for **kwargs (or **some_var where some_var is the **kwargs parameter) in any call within the function. Also check for kwargs.update(), dict(**kwargs), {**kwargs}, etc.
3. External consumers (HIGH)
python
response_data = {"status": "ok", "data": result, "metadata": meta}
return jsonify(response_data) # Consumed by HTTP client — we'll never see the read
Any dict that crosses an I/O boundary (HTTP response, database write, file write, logging, queue publish) has external consumers. We must recognize I/O functions and mark those dicts as having external consumption.
Common I/O sinks: json.dumps, jsonify, response.json(), cursor.execute (with dicts), logging.*, print, write, queue publish methods, etc.
4. Test fixtures (MEDIUM)
python
# test_processor.py
def test_process():
data = {"key": "test_value", "extra": "ignored"}
result = process(data)
assert result["key"] == "test_value"
Tests deliberately create dicts with specific key sets to test specific code paths. A key written in a test that's not read by the test might be consumed by the function under test. This is normal.
Mitigation: Use zone classification. If the file is in the "test" zone, lower confidence or apply different rules. Specifically, don't flag dead writes in test dicts that are passed to production functions.
5. Config/settings dicts (MEDIUM)
python
CONFIG = {
"feature_a_enabled": True,
"feature_b_enabled": False, # Only read in feature_b.py, not in this file
"max_retries": 3,
}
Config dicts often have keys that are consumed in many different files. A key might appear dead in isolation but be consumed in a file we haven't traced. This is especially true for module-level config dicts.
Mitigation: be very conservative about module-level dicts with UPPER_CASE names. They're likely config. Only flag dead writes if we've done exhaustive cross-file tracing and still find no reader.
6. Metaprogramming / reflection (LOW but devastating when it occurs)
python
for key in expected_keys:
if key not in d:
d[key] = default_values[key]
This reads and writes dynamic keys. We can't trace it. If we see loop-based dict manipulation, we should mark the dict as having dynamic access patterns.
4.2 False Negative Sources (Things We'll Miss)
Dynamic key construction that happens to match a literal key elsewhere
Dict access through deeply nested function chains (beyond our trace depth)
Keys added by decorators or metaclasses
Dict modification in __init_subclass__, __set_name__, or other dunder methods
Keys added by third-party library functions
Conditional key writes where the condition is always true in practice
5. Precision/Recall Strategy
5.1 Recommended Approach: Ultra-Conservative with Confidence Tiers
Given the extreme difficulty of this problem, I recommend starting with very high precision (low false positive rate) at the cost of recall. Users will abandon the tool if it produces noise.
Tier 1 — High Confidence (report as findings):
TypedDict violations: a TypedDict declares keys {a, b, c}, but construction sites provide {a, b, d}. Key c is missing, key d is extraneous. This is almost certainly a bug.
Same-function dead writes: d["key"] = val followed by d["key"] = other_val in the same function with no read in between. The first write is dead.
**kwargs with known callers: all call sites provide name= and email=, but the function reads kwargs["username"]. This is a typo/mismatch.
Key typos with high string similarity: d["lora_names"] write and d["lora_name"] read (or vice versa) on the same dict, with Levenshtein distance 1-2.
Tier 2 — Medium Confidence (report as potentials):
Class-level dead writes: self.config["key"] is written in one method but never read in any method of the class. Requires no dynamic access patterns on self.config.
Module-level dict dead writes: DEFAULTS["key"] is written but no file in the codebase reads DEFAULTS["key"] (requires cross-file tracing).
Missing reads: d.get("key") but no write of "key" is found anywhere in the dict's lineage. Only if the dict has no dynamic key writes and no **kwargs sources.
Tier 3 — Low Confidence (report only with verbose flag):
Cross-function dead writes where the function chain is > 2 hops
Dicts with some dynamic access that still have suspicious patterns
Near-miss key names across different dicts (potential confusion)
5.2 Confidence Modifiers
Each finding starts at a base confidence and gets adjusted:
Factor
Adjustment
Dict has dynamic key access
-40%
Dict has **kwargs source
-30%
Dict is serialized (json/pickle)
-50%
Dict is passed to unknown function
-20%
Dict is in test zone
-20%
Dict has TypedDict annotation
+30%
All access is within one function
+20%
All access is within one class
+10%
Key is a string literal
+10% (baseline)
Near-match key exists
+15% (for typo detection)
5.3 What NOT to Flag
Explicitly exclude:
Any dict that's a function return value consumed by json.dumps, jsonify, or similar serialization
This phase is O(|imports| * |functions|) roughly. For a 500-file codebase with ~50 functions per file, that's 25K functions and maybe 100K import relationships. Manageable.
Phase 3: Key set analysis
For each dict identity (after merging aliases):
Collect all known key writes (the "write set")
Collect all known key reads (the "read set")
Compute:
Dead writes: write_set - read_set (keys written but never read)
Missing reads: read_set - write_set (keys read but never written)
Consistent keys: write_set ∩ read_set
Apply confidence modifiers based on dict properties
Run typo detection on near-misses (Levenshtein on dead writes × missing reads)
Phase 4: Finding generation
Convert anomalies into findings with appropriate tier and confidence.
6.3 Typo Detection
For near-miss detection between write_set and read_set:
code
For each dead_write_key in (write_set - read_set):
For each missing_read_key in (read_set - write_set):
distance = levenshtein(dead_write_key, missing_read_key)
if distance <= 2 and distance / max(len(dead_write_key), len(missing_read_key)) < 0.3:
report potential typo
Also check:
Singular/plural: "name" vs "names", "item" vs "items"
Underscore variants: "user_name" vs "username"
Case variants: "userId" vs "user_id" (camelCase vs snake_case)
Common prefixes/suffixes: "get_key" vs "key", "key_list" vs "keys"
The Levenshtein computation is O(|dead_writes| * |missing_reads| * max_key_length), which is tiny.
7. Computational Complexity
7.1 Per-file AST Parsing
Already done for other detectors. Cost: ~10-50ms per file for parsing, ~5-20ms for walking. For 500 files: ~5-25 seconds total. Not a concern.
7.2 Key Access Extraction
Linear in AST size. Each node is visited once. O(N) where N is total AST nodes across all files. For a 500-file codebase with average 500 lines per file (250K lines), there might be ~1M AST nodes. Walking them takes a few seconds.
7.3 Cross-file Linking
The import graph is already built. Matching calls to definitions is O(|calls| * |definitions in imported modules|). With an index from function name to definition, this is O(|calls|) amortized. For 500 files with ~100 function calls each: 50K lookups. Trivial.
7.4 Memory Usage
Per-file data:
~50 dict identities per file (generous estimate) → 25K total
~200 key accesses per file → 100K total
~20 flow edges per file → 10K total
Each object is maybe 200 bytes. Total: ~27MB. Acceptable.
7.5 Overall
This detector should add less than 10 seconds to a 500-file scan and use less than 50MB of additional memory. The bottleneck is AST parsing, which is already amortized with other detectors.
8. What's Actually Achievable vs. Theoretical
8.1 Definitely Achievable (v1)
Same-function dead writes: d["key"] = x then d["key"] = y with no read in between. Pure AST, no cross-reference needed. Very high precision.
TypedDict schema violations: if a TypedDict declares keys and an instantiation/access uses wrong keys. Requires TypedDict detection + import resolution.
Key typos within a file: same dict (by name) has d["foobra"] write and d["foobar"] read (or similar near-miss). High precision with Levenshtein.
self.x dict key consistency within a class: all methods accessing self.config[...] — collect write keys and read keys, find mismatches. High precision because class scope is well-defined.
**kwargs dead keys for single-file call chains: caller passes func(a=1, b=2, c=3), callee only reads kwargs["a"] and kwargs["b"]. Detectable if both are in the same file or connected via imports. Very useful.
Module-level dict dead keys: DEFAULTS = {"a": 1, "b": 2, "c": 3} where c is never read in the codebase. Requires cross-file key read collection. Medium precision (external consumers are possible).
8.2 Achievable with Effort (v2)
Cross-file dict passing through function calls: build_config() returns {"a": 1}, caller accesses config["b"]. Requires return-type propagation across modules. Medium precision.
Dict builder pattern analysis: functions that incrementally build a dict (d = {}; d["a"] = 1; d["b"] = 2; return d). Requires intra-procedural flow analysis. Doable but complex.
Redundant key transforms: d["processed"] = process(d["raw"]) followed later by d["processed"] = process(d["raw"]) again. Requires value-level tracking, not just key-level. Hard.
8.3 Theoretically Possible but Impractical for a Lint Tool
Full inter-procedural dict tracking: tracking a dict through 5+ function hops, including conditional writes, loop-based construction, and exception handlers. This is what a real abstract interpreter does (e.g., pytype). Thousands of engineer-hours to build properly.
Dict-through-container tracking: dict goes into a list, comes back out. Requires container type abstraction.
Dynamic key resolution: resolving d[SOME_CONSTANT] where SOME_CONSTANT = "key" is defined elsewhere. Requires constant propagation, which is a whole sub-analysis.
8.4 Fundamentally Impossible with Static Analysis
Runtime-determined dict keys: d[user_input] = val. The key depends on runtime input.
Serialization boundary crossing: dict serialized to JSON/DB/queue and deserialized elsewhere. No static link exists.
Monkey-patched dict contents: third-party code modifies a dict at runtime.
Eval/exec-based dict manipulation: keys constructed and accessed via string evaluation.
Framework magic: Django model ._meta.fields, SQLAlchemy column introspection, etc. Keys come from database schema, not Python source.
9. Integration with Existing Desloppify Architecture
9.1 Detector Phase
This should be a new DetectorPhase in the Python language plugin. It fits naturally as a post-scan analysis phase because it needs:
The AST (already parsed for other detectors)
The import graph (from deps.py)
Zone classification (from zones.py)
Function/class info (from FunctionInfo/ClassInfo dataclasses)
9.2 Finding Format
python
{
"detector": "dict-key-flow",
"file": "path/to/file.py",
"line": 42,
"tier": "T2", # or T3 for lower confidence
"confidence": 0.75,
"summary": "Dead dict key write: 'unused_key' is written to self.config but never read in class Pipeline",
"detail": "Key 'unused_key' is written at line 42 but no read of this key was found in any method of Pipeline. Write set: {a, b, unused_key}. Read set: {a, b}.",
"category": "dead-write", # or "missing-read", "key-typo", "schema-violation"
}
9.3 What to Store in State
The dict key analysis results should be storable in state for incremental analysis:
This allows re-analysis when only some files change: if a file that reads from a dict changes, we only need to re-analyze that file and re-run the key set comparison.
9.4 Zone-Aware Behavior
production zone: full analysis, all findings reported
test zone: suppress "dead write" findings (tests deliberately create dicts with specific shapes), but keep "missing read" and "key typo" findings
config zone: suppress "dead write" for module-level dicts (config keys may be consumed externally), but keep "key typo"
generated zone: skip entirely
vendor zone: skip entirely
10. Phased Implementation Plan
Phase 1: Foundation (highest value, lowest risk)
Implement key access extraction from AST (all the node types from Section 1)
Same-function dead writes (overwritten keys)
Same-function key typo detection (Levenshtein on write/read sets for same variable)
self.x class-level key consistency
Basic **kwargs terminal analysis (function receives **kwargs, doesn't pass it on, and doesn't read a key that callers provide)
Expected precision: >90%. Expected recall: low (only catches the obvious cases). But these obvious cases are often real bugs.
Phase 2: Cross-file (medium value, medium risk)
Module-level dict cross-file read/write analysis
Return-value dict tracking (1 hop: d = build(); d["key"])
Conditional key write analysis (keys written in if/else branches)
Framework-specific exclusion patterns
11. Open Design Questions
Should dict identity use SSA form? If d is reassigned (d = {}; ...; d = other_dict), the name d refers to two different dicts. SSA would give them distinct identities (d_1, d_2). This increases precision but adds implementation complexity. Probably worth it for v2.
How to handle dict.copy() and copy.deepcopy()? The copy creates a new dict with the same keys. Should we propagate the key set to the copy? Probably yes for dict.copy() and copy.copy(). For deepcopy(), the keys are the same but the values are independent — key-level analysis is the same.
Should we track None returns? If build_config() can return None in some cases, then d = build_config(); d["key"] might be a TypeError (subscripting None), not just a missing key. That's a different detector though.
How to handle ChainMap, MappingProxyType, and other dict-like objects? Probably out of scope for v1. They're rare enough to not matter for most codebases.
Should we distinguish between d["key"] (raises KeyError on miss) and d.get("key") (returns None on miss)? Yes — the former is a hard read (the code REQUIRES the key to exist), while the latter is a soft read (the code tolerates the key being absent). Dead-write analysis should weight hard reads more heavily than soft reads. A key that's only soft-read might be legitimately optional.
What about try: d["key"] except KeyError? This is equivalent to d.get("key") — a soft read. We'd need to detect the try/except pattern around subscript access. Doable with AST analysis but adds complexity.
Should we track key values or just key names? Just names for v1. Tracking values would enable detecting "key always has the same value" (potential constant extraction) or "key value is always None" (potential dead code), but that's a much harder analysis.
12. Honest Assessment
What this detector can realistically catch (high confidence):
Overwritten dict keys in the same function (same key assigned twice, first value never read)
Key name typos (edit distance 1-2 between a write and a read on the same dict)
**kwargs mismatches where all callers and the callee are visible
TypedDict schema violations
Class self.x dict keys that are written but never read (or read but never written) across all methods
What this detector will struggle with (medium confidence, many false positives):
Cross-file dict key flow beyond 1 hop
Module-level config dicts where consumers are spread across the codebase
Dicts that participate in any dynamic patterns
What this detector cannot do (don't even try):
Track dicts through serialization
Handle dynamically constructed keys
Analyze dicts that cross process/service boundaries
Trace through eval/exec
Handle metaclass or descriptor-based dict manipulation
The sweet spot is intra-class and single-hop cross-function analysis. This is where the signal-to-noise ratio is highest and the implementation complexity is manageable. The Phase 1 deliverables alone would catch a meaningful class of bugs that no existing linter targets well.
The key insight is that this is NOT a general-purpose data flow analysis. It's a targeted detector that looks for specific, high-value patterns in dict key usage. By being selective about what we analyze and aggressive about suppressing findings when uncertainty is high, we can build something useful without trying to solve the halting problem.
You are thinking through the design of a "Dict Key Flow Tracer" detector for Python — a tool that tracks where dictionary keys are written and read across a codebase and finds dead writes, missing reads, and data flow anomalies.
Think from the perspective of a brilliant, artistic developer. You care about elegance, ergonomics, the "shape" of the problem. You think in metaphors and first principles. You ask "what would make this genuinely useful and delightful?" You see the forest, not just the trees. You optimize for the 80/20 — maximum insight with minimum complexity.
Context
This is a new detector for desloppify — a Python CLI code health tool. The existing architecture:
Language plugins with DetectorPhase runners
AST parsing already used for imports (deps.py)
Findings have detector/file/tier/confidence/summary/detail
Zone classification (production/test/config/generated)
Import graph already computed
FunctionInfo/ClassInfo dataclasses exist
Phase runners return (findings, potentials)
State persistence for incremental analysis
The Problem
Dicts are Python's universal data bus. The LoRA handler codebase had bugs where:
segment_payload["lora_names"] was written but the handler never read it (dead write)
Download logic happened twice because a dict was processed, passed through a queue, then re-processed
7 copy-pasted blocks varied just enough to dodge syntax-based dupe detection
Your task
Think about this from first principles. Don't start with AST nodes — start with the USER EXPERIENCE:
What would a developer actually want to know? Not "here are 47 dict key access anomalies" — what's the distilled insight? Think about what makes a finding actionable vs noise.
The 80/20 of dict tracing: What's the minimum viable analysis that catches the MOST valuable bugs? What if we skip the hard parts entirely and still get 80% of the value?
The shape of the problem: Dicts in Python serve different roles:
Config dicts (settings, defaults)
Payload/message dicts (data passed between systems)
State dicts (accumulated during processing)
Schema dicts (TypedDict, structured data)
Should we treat them differently? Is "role" detectable?
Metaphors and mental models: What's the right way to think about dict key flow? Is it like a type system? A protocol? A contract? A conversation between producer and consumer? How does the metaphor guide the design?
What makes this genuinely different from existing tools? mypy, pyright, pylint — they don't do this well. Why not? What's the gap? And what would fill it in a way that's not just "mypy but worse"?
Ergonomics of output: When this detector fires, what should the developer SEE? Think about the narrative. Not just "dead write at line 42" but something that tells a story: "this key travels from A through B to C, but C never reads it."
Integration with the existing narrative system: Desloppify has a coaching/narrative system. How does dict key flow analysis feed into the overall health story? Is it its own dimension? Part of "coupling"? Part of "code quality"?
The simplest possible implementation that's still useful: What if you had ONE AFTERNOON to build this? What would you build? No cross-file tracing, no pointer analysis — just the simplest useful thing.
What to explicitly NOT build: What's tempting but not worth it? Where do diminishing returns hit hard? What would make this tool over-engineered?
The "aha" moment: What's the one finding type that would make a developer go "holy shit, how did it find that?" That's what we should optimize for.
Think beautifully. Think practically. Output your complete design vision.
Dict Key Flow Tracer: A Design Vision
Starting from the Human Experience
Let me begin where it matters: a developer staring at a bug that cost them four hours.
The bug was simple. A dict was assembled in one function, passed through two layers of indirection, and consumed in a third. Somewhere along the way, a key was renamed from "lora_names" to "lora_ids" on the write side, but the read side still expected "lora_names". No error. No crash. Just silent None from .get(), and a subtle behavioral regression that only surfaced under specific conditions.
No existing tool catches this. mypy doesn't, because the dict is typed as dict[str, Any] or not typed at all. pylint doesn't, because it operates per-statement, not per-flow. pyright gets closer with TypedDict, but only if you've already done the hard work of declaring the schema — and if you had that discipline, you probably wouldn't have the bug.
The gap is this: existing tools analyze dict access as syntax. The bugs live in dict access as semantics — as data flow.
The Metaphor That Unlocks Everything
A dict isn't a data structure. It's a conversation.
One piece of code says: "I'm putting lora_names in here, and I expect someone downstream to use it." Another piece of code says: "I expect lora_names to be in here, because someone upstream promised it."
The bugs happen when the conversation breaks down:
Hallucination (missing key read): someone listens for a voice that never spoke
Echo (redundant write): the same thing gets said twice, wasting breath
Dialect drift (near-miss keys): the same concept gets called different names in different places
This conversational metaphor is powerful because it immediately suggests what the output should look like. Not "dead write at line 42" but:
Unheard message: segment_payload["lora_names"] is written at handler.py:89 but never read in any consumer of segment_payload. Did you mean to use it in download.py:process_segment()?
The metaphor also tells us what NOT to do: we don't need to trace every dict operation. We need to find broken conversations.
The 80/20: What Catches the Most Bugs With the Least Machinery
Here's the critical insight: the hardest part of dict tracing is aliasing and cross-function flow. But the most valuable bugs don't require solving that.
Let me stratify the value:
Tier 1: Single-scope write/read mismatch (80% of value, 20% of effort)
Within a single function (or a function and its immediate callers/callees), look at a dict that is:
Created (literal {} or dict())
Written to (subscript assignment, .update(), ** spread)
Read from (subscript read, .get(), in check, destructuring)
Then answer: are the written keys and read keys the same set?
This is shockingly powerful because the most common pattern is: build a dict, pass it somewhere, consume it. And the build + consume often happen close together — same function, or one call apart.
Tier 2: "Schema-shaped" dict detection (15% of value, 30% of effort)
Some dicts have a stable schema — the same keys appear across multiple instances. These are TypedDicts that nobody bothered to formalize. Detect these patterns and flag when one instance deviates from the schema.
This catches the copy-paste variants. Seven blocks that all build a dict with keys ["name", "path", "weight", "type"], but one of them spells it "weights" (plural). That's the bug.
Tier 3: Cross-module flow tracing (5% of value, 50% of effort)
Following a dict through function boundaries, queues, serialization. This is where you need pointer analysis, call graphs, and a PhD. Don't build this. Not now. Maybe not ever. The ROI is terrible.
The Simplest Implementation That's Still Genuinely Useful
One afternoon. What do I build?
Let me think about what the AST actually gives us cheaply.
Now I have a thorough understanding of the codebase architecture. Let me compose the design vision.
Dict Key Flow Tracer: A Design Vision
I. Starting from the Human Experience
A developer stares at a bug that cost them four hours.
The bug was simple. A dict was assembled in one function, passed through two layers of indirection, and consumed in a third. Somewhere along the way, a key was renamed from "lora_names" to "lora_ids" on the write side, but the read side still expected "lora_names". No error at runtime. No crash. Just silent None from .get(), and a subtle behavioral regression that only surfaced under specific conditions.
No existing tool catches this. mypy doesn't, because the dict is typed as dict[str, Any] or not typed at all. pylint doesn't, because it operates per-statement, not per-flow. pyright gets closer with TypedDict, but only if you've already done the hard work of declaring the schema -- and if you had that discipline, you probably wouldn't have the bug.
The gap: existing tools analyze dict access as syntax. The bugs live in dict access as semantics -- as data flow.
II. The Metaphor: Dicts as Conversations
A dict is not a data structure. It is a conversation.
One piece of code says: "I'm putting lora_names in here, and I expect someone downstream to use it." Another piece of code says: "I expect lora_names to be in here, because someone upstream promised it."
The bugs are breakdowns in conversation:
Monologue -- dead write: someone speaks, nobody listens.
Hallucination -- missing key read: someone listens for a voice that never spoke.
Echo -- redundant write: the same thing gets said twice.
Dialect drift -- near-miss keys: the same concept spelled differently in producer vs. consumer (lora_names vs lora_ids, file_path vs filepath).
This metaphor is powerful because it immediately dictates the shape of the output. Not "dead write at line 42" but:
Unheard message: payload["lora_names"] is written at handler.py:89 but never read by any consumer of payload in the same scope. Did you mean to read it in process_segment()?
And it tells us what NOT to do: we don't need to trace every dict operation. We need to find broken conversations.
III. Why Existing Tools Fail Here (and the Real Gap)
mypy and pyright fail because they treat dicts as opaque dict[str, Any] unless you've explicitly declared a TypedDict. They are forward-declared systems: you tell the type checker what the shape is, and it verifies conformance. But the whole point of using a plain dict is that you didn't want to pre-declare the schema. The tool needs to work backward: observe the actual usage patterns and infer the implicit contract.
pylint and ruff fail because they operate statement-by-statement. They can tell you x is unused, but they can't tell you d["x"] is written but never read -- that requires connecting writes to reads across the scope.
The gap is inferred structural typing from usage patterns. Not "you said this dict is shaped like X and it isn't" but "based on how you use this dict, here's the shape I infer, and here's where it's inconsistent."
This is categorically different from mypy. It's not a worse mypy. It's a different tool for a different problem: the problem of implicit contracts.
IV. The 80/20: Value Tiers and What to Actually Build
Here's the critical insight: the hardest part of dict tracing is aliasing and cross-function flow. But the most valuable bugs don't require solving that.
Tier 1: Single-scope write/read set mismatch (80% of value, 20% of effort)
Within a single function body, find dicts that are:
Created -- literal {}, dict(), dict(a=1, b=2)
Written -- d["key"] = val, d.update({...}), dict comprehension
Read -- d["key"], d.get("key"), "key" in d, d.pop("key")
Then answer the question: are the written keys and the read keys the same set?
This alone catches:
Dead writes (key written, never read downstream in the same function)
Hallucinated reads (key read but never written in the same function -- likely passed from outside, but if the dict was created in this function, that's a bug)
The constraint "within a single function" makes this tractable with pure AST analysis. No pointer analysis. No call graph. Just ast.walk over each FunctionDef.
Tier 2: Schema consensus across multiple construction sites (15% of value, 30% of effort)
Some dicts are constructed repeatedly with the same shape -- this is an implicit TypedDict. When seven copy-pasted blocks all build {"name": ..., "path": ..., "weight": ..., "type": ...} but one spells it "weights", that's the bug.
This is the "copy-paste variant" detector. It doesn't need flow analysis. It needs:
Cluster dict literals by their key sets (Jaccard similarity)
Find clusters where one member deviates from the consensus
This catches the LoRA handler's seven copy-pasted blocks. And it integrates beautifully with the existing dupe detector -- it's finding duplication at the data shape level rather than the code text level.
Tier 3: Cross-function/cross-module flow (5% of value, 50% of effort)
Following a dict through return -> assignment -> function argument -> attribute access chains. This requires either:
Interprocedural analysis (call graph + points-to analysis), or
Don't build this now. The ROI is terrible. Maybe never. The few bugs it catches that Tier 1 and 2 miss are better found by TypedDict migration tooling (a different tool entirely).
V. The Roles of Dicts (and Whether to Detect Them)
Dicts in Python serve fundamentally different roles:
Role
Example
Key set stability
Write/read locality
Care about dead writes?
Config
settings = {"debug": True, "port": 8080}
Very stable
Written once, read everywhere
Not really -- config keys are often optional/unused-but-available
Payload/message
msg = {"type": "download", "url": ...}
Stable per message type
Written in producer, read in consumer
YES -- this is where bugs live
State accumulator
results = {}; results[key] = compute(...)
Dynamic
Written and read in same scope
Less useful -- keys are data-dependent
Schema/record
{"id": 1, "name": "foo", ...}
Very stable
Varies
YES for schema consensus
Kwargs/options
**kwargs, options = {}
Dynamic
Pass-through
No -- too dynamic
Role detection is partially possible and partially necessary. The key heuristic:
Literal-key dicts (all keys are string constants) are likely config, payload, or schema. These are worth analyzing.
Dynamic-key dicts (keys are variables or computed) are state accumulators or caches. Skip them.
The filter is simple: only analyze dicts where we can statically determine the key names. This naturally excludes the roles where our analysis would be noisy and includes the roles where it's valuable.
VI. The "Aha" Moment
The one finding type that makes a developer say "holy shit, how did it find that":
Schema drift in dict cluster: 7 dict literals share keys {name, path, weight, type} across handler.py, loader.py, cache.py. But handler.py:142 uses weights (plural) instead of weight. This is likely a typo causing silent KeyError/None.
This is the "aha" because:
It crosses file boundaries (feels magical) but doesn't require flow analysis (just clustering)
It identifies the outlier, not the majority -- it says "6 agree, 1 disagrees, here's the disagreement"
It catches a class of bug that no existing tool detects
The fix is always a one-character change -- maximum actionability
The second "aha":
Unheard message: build_payload() at handler.py:89 writes payload["lora_names"] but this key is never read in the function body. The dict is returned -- if consumers need this key, consider a TypedDict; if they don't, this is dead code.
This is actionable because it tells a story -- it explains the implications, not just the symptom.
VII. The Simplest Useful Implementation (One Afternoon)
Here's what I'd build first, structured as an AST visitor.
Phase 1: Single-function dict key analysis
Walk each FunctionDef. For each local variable that's assigned a dict literal or dict() call:
Collect all writes: Subscript assignments where the slice is a Constant(str).
Collect all reads: Subscript loads where the slice is a Constant(str), .get("key") calls, "key" in d.
Compute: written - read (dead writes), read - written (external dependencies or bugs if dict was created here), near-misses (edit distance <= 2 between any written key and any read key).
This is ~150 lines of AST walking. It uses the same pattern as _detect_ast_smells in the existing smells.py -- walk the tree, pattern match, accumulate findings.
Phase 2: Dict literal clustering
Across all files in the scan, collect every dict literal where all keys are string constants. Build a key-set fingerprint. Cluster by Jaccard similarity >= 0.8. Within each cluster, find outlier key sets (keys present in < 30% of cluster members, or absent from < 30%). Report those as schema drift.
This is ~100 lines. It uses the same file-iteration pattern as detect_smells.
Finding format (integrates with existing make_finding):
python
# Dead write
make_finding(
"dict_keys", file, f"dead_write::{var_name}::{key}",
tier=3, confidence="medium",
summary=f'Dict key "{key}" written to `{var_name}` but never read in {func_name}()',
detail={"kind": "dead_write", "variable": var_name, "key": key,
"write_line": 42, "function": func_name},
)
# Schema drift
make_finding(
"dict_keys", file, f"schema_drift::{cluster_id}::{key}",
tier=2, confidence="high",
summary=f'Schema drift: "{key}" appears in 1/7 dict literals sharing keys '
f'{{name, path, weight, type}} — did you mean "{consensus_key}"?',
detail={"kind": "schema_drift", "cluster_size": 7, "outlier_key": key,
"consensus_key": consensus_key, "consensus_keys": [...],
"other_sites": [{"file": ..., "line": ...}, ...]},
)
Integration point: New DetectorPhase("Dict key flow", _phase_dict_keys) added to PythonConfig.phases. New detector name "dict_keys". Fits into the existing "Code quality" dimension alongside "smells" -- or a new "Data flow" dimension at tier 3.
VIII. What to Explicitly NOT Build
Cross-function dict tracing via call graph. Tempting. Seductive. Not worth it. The call graph already exists for import analysis, but following a specific dict variable through function calls requires full points-to analysis. Python makes this nearly impossible due to dynamic typing, *args/**kwargs, decorators, closures. You'd spend 80% of effort on 5% of value.
Dict mutation tracking (d.update, d |= other, del d[key]). These are important in theory but rare in the patterns where dict key bugs actually occur. The typical bug pattern is: build a dict literal, pass it somewhere, read it. Not: incrementally mutate a dict through a complex control flow. Track d["key"] = val and d.update({"key": val}) but don't try to track d.update(other_dict) where other_dict is a variable.
Control-flow-sensitive analysis. "This key is only written in the if branch but read unconditionally" -- yes, this is a real bug class, but it requires building a CFG. Way too much complexity for this detector. Leave it for mypy/pyright with TypedDict.
JSON schema inference / validation. Tempting to extend this to "infer the schema of dicts read from JSON files" but that's a different tool entirely.
Dict subclass / UserDict analysis. The surface area is too wide and the payoff too small. Stick to plain dict and {}.
Self.attrs-as-dict analysis.self.__dict__ manipulation, setattr/getattr patterns -- yes these are conceptually similar but mechanically different. Different detector.
IX. Narrative Integration
The existing narrative system in narrative.py maps detectors to tools and guidance. Dict key flow fits naturally:
python
DETECTOR_TOOLS["dict_keys"] = {
"fixers": [],
"action_type": "refactor",
"guidance": "fix dict key mismatches — dead writes are likely dead code, "
"schema drift suggests a typo or missed rename"
}
For scoring, dict key findings belong in the "Code quality" dimension alongside smells. Both are per-file signals about code correctness. Adding "dict_keys" to the Dimension("Code quality", 3, ["smells", "react", "dict_keys"]) list makes it contribute to the overall health score naturally.
Alternatively -- and I think this is more interesting -- dict key analysis could seed a new "Data contracts" dimension. This dimension would be tier 3, and could eventually encompass TypedDict compliance, API response shape validation, and serialization format consistency. Starting it with just dict key flow gives it room to grow.
The coaching narrative should surface dict key findings as data integrity issues:
"Your code quality is strong, but there are 3 implicit data contracts that aren't being enforced. Consider adding TypedDict declarations for the dict shapes in handler.py and loader.py -- desloppify found keys that are written but never read, suggesting stale data fields."
This positions the tool not just as a bug finder but as a migration advisor -- it identifies dicts that should be TypedDicts and gives you the evidence for why.
X. The Shape of the Code
Here's how the implementation would be structured, following existing patterns:
code
desloppify/
lang/python/
detectors/
dict_keys.py # The detector (AST analysis + clustering)
# Touched files:
lang/python/__init__.py # Add DetectorPhase
scoring.py # Add to dimension or create new one
narrative.py # Add DETECTOR_TOOLS entry
dict_keys.py would export two functions mirroring the existing detector pattern:
python
def detect_dict_key_flow(path: Path) -> tuple[list[dict], int]:
"""Analyze dict key write/read patterns across Python files.
Returns (entries, total_files_checked) where entries are:
- dead_write: key written but never read in the same scope
- phantom_read: key read from a locally-created dict but never written
- schema_drift: dict literal key set deviates from cluster consensus
- near_miss: written key within edit distance 2 of a read key (or vice versa)
"""
The AST visitor would be a single class:
python
class DictKeyVisitor(ast.NodeVisitor):
"""Track dict creation, key writes, and key reads within a function scope."""
def __init__(self):
self.scopes: list[DictScope] = [] # stack of function scopes
def visit_FunctionDef(self, node): ...
def visit_Assign(self, node): ... # d = {}, d["k"] = v
def visit_Subscript(self, node): ... # d["k"] (read vs write via ctx)
def visit_Call(self, node): ... # d.get("k"), d.update({...})
Where DictScope is a small dataclass:
python
@dataclass
class DictScope:
func_name: str
func_line: int
dicts: dict[str, TrackedDict] # variable name -> tracked dict
@dataclass
class TrackedDict:
name: str
created_line: int
locally_created: bool # True if we saw `d = {}` or `d = dict()`
writes: dict[str, int] # key -> line number
reads: dict[str, int] # key -> line number
After visiting, analysis is straightforward set arithmetic:
python
dead_writes = tracked.writes.keys() - tracked.reads.keys()
phantom_reads = tracked.reads.keys() - tracked.writes.keys() # only if locally_created
near_misses = [(w, r) for w in dead_writes for r in phantom_reads
if levenshtein(w, r) <= 2]
For schema clustering, a second pass collects all dict literals (not requiring function-scoped tracking), fingerprints them, and runs a simple greedy clustering algorithm.
XI. Confidence Calibration and Noise Reduction
The biggest risk is false positives. Here's how to keep signal-to-noise high:
Suppress if:
The dict is returned or yielded (consumer is external -- we can't see the reads)
The dict is passed to a function call as an argument (consumer is the callee)
The dict variable name matches common "config" patterns (config, settings, defaults, options, kwargs)
The dict has fewer than 3 keys (too small to be interesting)
The function is __init__ or setUp (dicts stored as attributes are read elsewhere)
Boost confidence if:
The dict is both created AND fully consumed in the same function (closed system)
A near-miss pair exists (strong signal of typo)
Schema drift cluster has 5+ members (strong consensus)
Tier assignment:
Near-miss / schema drift with high cluster confidence: Tier 2, high confidence (likely bugs)
Dead write in closed-scope dict: Tier 3, medium confidence (likely dead code, possibly intentional future-proofing)
Phantom read from locally-created dict: Tier 2, high confidence (almost certainly a bug -- you created the dict and then read a key you never wrote)
XII. What "Genuinely Useful and Delightful" Looks Like
The output shouldn't just flag problems. It should tell stories. Here are the narrative templates:
Dead write (monologue):
code
Dict key "lora_names" written at handler.py:89 but never read.
payload = {"lora_names": names, "model_id": mid, "weight": w}
^^^^^^^^^^^^^^^^^^^^^^^^ this key is written
... payload["model_id"] is read at line 94
... payload["weight"] is read at line 97
... payload["lora_names"] is never read
→ If returned/passed to another function, consider TypedDict to enforce the contract.
→ If unused, this is dead code — remove it.
Schema drift (dialect):
code
Schema drift: 6 of 7 dict literals use key "weight", but handler.py:142 uses "weights".
Consensus keys: {name, path, weight, type} (6 sites)
Outlier at handler.py:142: {name, path, weights, type}
^^^^^^^ did you mean "weight"?
Other construction sites:
loader.py:23, loader.py:67, cache.py:11, handler.py:45, handler.py:88, handler.py:200
Phantom read (hallucination):
code
Dict key "status" read at handler.py:104 but never written.
payload = {"type": "download", "url": url} # created at line 98
... if payload["status"] == "ready": # read at line 104 — but "status" was never set
→ This will raise KeyError. If using .get(), it returns None silently.
XIII. Summary: The Design in One Paragraph
Build a single-file AST-based detector that tracks dict variable creation, literal-key writes, and literal-key reads within function scopes. Report dead writes, phantom reads from locally-created dicts, and near-miss key pairs (likely typos). Separately, cluster dict literals across the codebase by key-set similarity and report outliers as schema drift. Integrate as a new DetectorPhase in the Python pipeline, contribute to the "Code quality" scoring dimension, and generate narrative-rich findings that tell the story of each broken conversation. Explicitly skip cross-function flow tracing, control-flow sensitivity, and dynamic-key analysis. Ship Tier 1 in an afternoon. Consider Tier 2 (clustering) as a fast follow. Never build Tier 3.
The design principle throughout: find the broken conversations, not every dict access. Maximum insight, minimum machinery.