My AI Agent Tried to Replace Django’s SQL Compiler With 38 Lines of Code
Two minutes earlier, the editor had been three lines away from overwriting django/db/models/sql/compiler.py with a thirty-eight line stub. That file is Django’s SQL compiler. Around 1,500 lines of core ORM logic that every Django query runs through. The only thing that stopped the overwrite was a filesystem guard called new_file_already_exists_skipping_write, a conditional I had written months earlier for a completely different reason.
Here is what the stub looked like:
class SQLCompiler:
"""Standard SQL compiler."""
def __init__(self, query, connection, using):
self.query = query
self.connection = connection
def get_order_by(self):
# TODO: implement
return []
class SQLCompiler:
"""Standard SQL compiler."""
def __init__(self, query, connection, using):
self.query = query
self.connection = connection
def get_order_by(self):
# TODO: implement
return []
The sandbox tests passed. The system reported success. Nothing in the pipeline caught it.
What the system is
The project is called Cyclops. A local coding agent: no API calls, no cloud inference, no data leaving the machine. An RTX 4080, Ollama running locally, a Flask repo as a testbed, and later Django’s actual source code as the benchmark.
The pipeline has eight components: a planner that breaks goals into ordered tasks, a navigator that maps tasks to files using a code graph with around 5,000 edges, an impact analyzer that estimates what a change will touch before any edit happens, an editor that generates diffs, a verifier that runs changes in a sandbox, a semantic verifier that checks whether the goal was actually achieved, and a supervisor that decides whether to retry or stop. There is also a model registry, a symbol graph, rollback snapshots, diff validators, and rules that refuse destructive edits.
My internal harness scored it at 80/100. I ran it against SWE-bench, which uses real Django bugs with real test suites. It scored zero. I ran it again. Still zero.
Where each layer broke
The navigator failure was the clearest one to diagnose. The sqlmigrate bug required editing django/core/management/commands/sqlmigrate.py. The agent edited django/utils/log.py instead.
The reason: I had built a fallback into the navigator for when symbol matching fails. If nothing in the code graph matches a task’s target symbols, fall back to keyword matching across the whole graph. The task description mentioned “transactional DDL,” “rollback behavior,” and “database connection features.” The word “connection” appeared in log.py inside AdminEmailHandler.connection. That was enough. The navigator picked the wrong file with complete confidence.
Removing the fallback fixed it. If symbols don’t match, the system now returns nothing and escalates. Silence is safer than a confident wrong answer. File navigation accuracy improved immediately, without touching the model.
The compiler near-miss came from a different gap, one level lower. If a target file did not exist, the editor silently switched into “create new file” mode, even when the operation was a modification. So a 1,500-line production file could be replaced with a 38-line stub, the sandbox tests would pass against the stub, and the run would report COMPLETED. I added one rule: if a file is missing during a MODIFY operation, fail loudly. No silent recovery, no reinterpreting intent. That closed an entire class of failure that had been invisible.
The semantic verifier had a different problem. Its job was to check whether a patch matched the goal, which it did by pulling required strings from the problem description and verifying they appeared in the output. If the bug description said “the path can be example_dir“, the verifier required example_dir in the patched code. If it said “SQLCompiler thinks the clause was already seen,” the verifier treated “thinks” as a technical requirement. It was checking prose for literal strings, not verifying intent. I rewrote it so only identifiers that appear in the symbol graph count as requirements. Everything else gets ignored.
The funniest failure was django__django-11019: a subtle ordering bug in Media._merge_lists producing false MediaOrderConflictWarning when independent media lists were combined. The fix required touching the merge algorithm. What the agent produced instead:
class MediaOrderConflictWarning(RuntimeWarning):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warnings.warn(
"Media order conflict detected. "
"Please check your media definitions."
)
class MediaOrderConflictWarning(RuntimeWarning):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warnings.warn(
"Media order conflict detected. "
"Please check your media definitions."
)
A warning class that warns about itself. The merge algorithm was untouched. The system marked the run successful.
The model is the least interesting part
I started with a 30B thinking model. One planning step for a task like “add logging middleware” took nine minutes. Switched to a 7B coder model: fast, but it would silently skip requirements partway through tasks. Settled on a 14B quantized model, which barely fit on the GPU and forced me to cut the context window from 20K to 12K tokens to avoid falling back to CPU. That context window reduction mattered more than any prompt engineering I did across the entire project.
The real constraint with local models is not which model performs best in benchmarks. It is what is the largest model you can run while leaving enough context for the model to actually reason about the task at hand. On this hardware, that number was 14B Q4.
A weaker model with strict system design beat a stronger model with loose design every time. The routing logic, file selection strategy, fallback behavior, validation layers, sandbox design, rollback handling, how confidence scores get interpreted: that is what determines whether the system is safe. The model is the most replaceable component in the whole stack.
What the near-miss actually taught me
AI agents do not fail with obvious errors. They fail with total conviction, producing outputs that look correct until you read the logs carefully enough to see what actually happened. If the system around the model is built to trust that conviction, every failure looks like success.
The part of Cyclops I trust most is not the model. It is the parts that say stop, do not guess, do not proceed, do not overwrite. A thirty-eight line stub nearly replaced 1,500 lines of Django’s SQL compiler. A conditional I wrote months earlier for a completely different reason was the only thing that stopped it.
Build the restraint first. The intelligence is easy to add later.
Cyclops is in active development. The repo is at:
The technical findings document covers every failure in detail, including the ones that are not fixed yet.


