Keeping AI Code Generation Honest: A Deterministic Control Plane for Multi-Agent LLM Workflows
A deterministic Python control plane uses state machines, independent reviewers, and bounded retries to make LLM code generation more reliable.
The Problem With Letting the Model Decide
If you've tried to automate code generation with an LLM agent, you've probably hit this failure mode: the agent correctly handles all 10 steps of a task on Monday, then silently skips 3 of them on Tuesday for a nearly identical task. Nothing crashes. The output looks plausible. The gap only surfaces in review — or worse, in production.
This is the core tension in agentic code generation. LLMs are excellent at the creative work (reading a spec, writing plausible code) and unreliable at the procedural work (always running every check, never skipping a gate, stopping after N retries instead of looping forever). When you hand both responsibilities to the same agent, the procedural guarantees are only as good as the model's mood that day.
Our team builds data pipeline modules on a config-driven compute platform. Each new module — a cost forecast, a volume estimate, a revenue allocation — follows the same skeleton: load tables, apply joins, compute formulas, write outputs. Roughly 60% of the work is predictable boilerplate, and it was eating 2–4 weeks of engineering time per module. Perfect candidate for AI automation. But we weren't willing to trade weeks of engineering for a pipeline that quietly drops a null check.
The solution wasn't a smarter prompt. It was moving all the guarantees out of the agent and into deterministic code.
The Architecture: Control Plane vs. Knowledge Plane
We split the system into two layers that are deliberately kept separate:
The control plane is a plain Python state machine. It owns what runs next and whether it's allowed to proceed. It advances a task through a fixed sequence of gates, dispatches the right agent at each gate, counts retries, escalates to a human after a fixed budget, and persists state to disk so a run survives across sessions. Critically, it never writes production code and never publishes anything. It prints the next gated step plus a ready-to-dispatch prompt, records the result, and moves the marker.
The knowledge plane is a set of skill files (structured markdown) that teach the agents how to do each step well — the architecture patterns, the validation checklist, the edge cases to watch for.
The division of labor is the whole point:
The control plane decides what runs and whether it passed. The skill files decide how it's done well. When the two disagree, the control plane wins.
Because gate order, retry budget, and escalation live in code — not in a prompt the model can reinterpret — agent behavior becomes predictable, auditable, and structurally unable to skip a step.
The Gate Sequence
Every module moves through a fixed pipeline:
input → analyzed → user-confirmed → generated → validated → tested → dq-ready → cr-ready → done
The state machine enforces this order. An agent cannot jump from generated straight to done. It cannot reach validated without having produced something at generated. The gates are the contract, and the contract is executable.
Let me walk through the interesting gates.
Grounding Before Planning (input → analyzed)
The first agent — the Analyzer — takes the uploaded logic (a spec, a SQL script, a spreadsheet of formulas) and produces a structured execution plan: every input table, every transformation, every null check, every conditional branch.
But before it plans anything, it grounds itself against reality. For every table the logic references, it makes a read-only metadata call to the live data catalog to pull the real column names, types, and grain. It never invents a schema. If the logic references a column the catalog doesn't have, it emits [SCHEMA MISMATCH] and asks instead of guessing. If a table isn't registered at all, it emits [NOT SUBSCRIBED] and halts planning for that table.
This grounding step is what makes a whole class of bugs visible at plan time — including the one that motivated the project (more on that below). The verified plan becomes the ground truth everything downstream validates against.
The One Human Gate on the Frontnd (analyzed → user-confirmed)
The execution plan is shown to a human before a single line of code is written. This is deliberate: a misread requirement is cheapest to fix here, before generation, testing, and review have compounded on top of it. The control plane simply stops and waits. No amount of agent confidence advances past this line — only a person does.
Generation, Then Adversarial Review (generated → validated)
A second agent — the Code Writer — takes the confirmed plan and generates the module: dataset configs, metric formulas, compute functions, the job orchestrator.
Then the key move: a third agent — the Reviewer — is dispatched as a fresh, independent agent that did not write the code. It checks the generated output against the Analyzer's plan through a fixed multi-point checklist:
- Completeness (every planned step is present)
- Null safety
- Filter correctness
- Join correctness
- Output schema — including a lossy-cast check
- Anti-patterns
- Caching correctness
- Architecture compliance
- A behavioral check that actually runs the happy-path test
The Reviewer denies by default. If the plan identified 10 steps and the code covers 8, it rejects — with specific, targeted feedback. If a null check present in the source is missing from the output, it rejects.
This is the single most important design decision in the system, so it's worth stating as a principle:
The agent that writes code never grades its own work. The agent that fixes a rejection never grades its own fix.
Self-review by an LLM is theater — the model that just confidently produced wrong code is the same model asked to confidently bless it. Separation of writer and reviewer, enforced by the control plane spawning distinct agents, is what gives the check teeth.
The Retry Loop With a Budget
On rejection, the control plane increments a retry counter and bounces the module back to generated with a "pending fix" flag. The next dispatch is a targeted fix pass — minimal changes to only the cited issues, not a full rewrite — followed by a fresh review by (again) an independent reviewer.
This loops until the Reviewer approves — in practice, 1–2 iterations — or the control plane escalates to a needs-human state after 3 attempts. It never loops forever, because "3 attempts then escalate" is a Python integer comparison, not a judgment call the model gets to make.
Human at the Exit, Too (cr-ready → done)
When review passes, a code review is created for engineers. They review pre-validated, reviewer-approved code — not raw first-pass output. Publishing is a human action. The agents never push to production. That boundary lives outside the agents by design.

Why This Beats a Single Powerful Agent
You might ask: with a strong enough model, why not just prompt one agent to "generate the module, validate it thoroughly, and retry if needed"?
Because every guarantee in that sentence is soft. "Validate thoroughly" is aspirational. "Retry if needed" has no ceiling. "Don't skip steps" is a hope. The moment the task varies, the soft guarantees bend.
Moving those guarantees into a state machine makes them hard:
|
Concern
|
Left to the agent
|
In the control plane
|
|---|---|---|
|
Gate ordering
|
Model may reorder or skip
|
Structurally impossible to skip
|
|
Retry budget
|
Model may loop or give up early
|
Fixed count, then escalate
|
|
Writer/reviewer separation
|
Same context, self-blessing
|
Distinct agents, fresh context
|
|
Crash recovery
|
Lost on session end
|
State persisted to disk
|
|
Production boundary
|
Model could push
|
No publish capability exists in the loop
|
The agents still do what they're good at — reading messy specs, writing idiomatic code, inferring edge cases. They just don't get to decide whether they're allowed to proceed.
A Concrete Payoff: The Lossy-Cast Regression
The bug that started all of this: a decimal value silently cast to an integer, which truncated flag columns across dozens of tables. It wasn't caught by a compiler. It slipped through review. It surfaced only after more than a dozen production investigations.
In this system, that exact regression is guarded in two independent places:
- The Reviewer's output-schema check flags lossy casts at review time, working from the real column types the Analyzer pulled from the catalog.
- The test generator carries it as a known-bug regression pattern, so a test for it is written automatically.
The grounding step is what makes this possible — because the Analyzer resolved real types up front, a decimal → int mismatch is visible from the start rather than discovered in production.
Results and Honest Caveats
We validated the approach on a genuinely complex, production-grade module: multiple compute stages, ~10 surcharge components, ~120 output metrics across 8 config files.
- ~85% of the module was generated correctly out of the box.
- ~15–25% still required manual review for business-specific edge cases.
- Engineering effort dropped substantially versus a full manual build.
The honest caveat: this is not "fire the engineers." It's "stop making engineers do the boilerplate." The remaining edge-case work is exactly the work you want skilled humans on. And every gap we find gets fed back into the skill files as a reviewed change — so the knowledge plane improves module over module while the control plane stays fixed.
Takeaways for Your Own Agentic Workflows
If you're building LLM code generation (or any high-stakes agentic workflow), the transferable lessons are:
- Separate orchestration from cognition. Put sequencing, retries, and escalation in deterministic code. Let the model do the creative work only.
- Make gates unskippable, not just documented. A checklist in a prompt is a suggestion. A state machine is a contract.
- Never let an agent grade its own work. Spawn a fresh reviewer with no stake in the output, and make it deny by default.
- Bound your retries in code. "Try a few times then escalate" must be an integer comparison, not model discretion.
- Keep humans at the expensive-to-reverse boundaries — confirming intent up front, and publishing to production at the end.
- Ground the model in real state before it plans. Read the actual schema/environment; make the agent flag mismatches instead of inventing.
The agent accelerates. The control plane keeps it honest. Neither is optional
Opinions expressed by DZone contributors are their own.