Right Answer, Wrong Process: Agents Write Ceremonial Code

A coding agent writes a maintenance script. Every step you asked for is in it. The log reads well. The end state matches the test. And the script still does the work in an order that would have taken down production on a bad day.
We call this ceremonial code: the right rituals are present, but they do not gate anything. A check runs after the action it should guard. A failed precondition is caught, logged and ignored. Output tests cannot see it, and more reviewer agents help less than you would hope. What helps is writing the process down for the agent and then testing the process, not only the result.
What Ceremonial Code Looks Like
Take node maintenance on Kubernetes. The Safely Drain a Node guide says you "can use kubectl drain to safely evict all of your pods from a node before you perform maintenance on the node", and that safe evictions respect your PodDisruptionBudgets. Afterwards you run kubectl uncordon "to tell Kubernetes that it can resume scheduling new pods onto the node."
Here is a version an agent could plausibly hand back:
def patch_node(node):
kubectl("cordon", node)
upgrade_packages(node)
reboot_and_wait_ready(node)
try:
kubectl("drain", node, "--ignore-daemonsets")
except RuntimeError as e:
log.warning("drain failed, continuing: %s", e)
kubectl("uncordon", node)
Cordon, drain, upgrade, reboot, uncordon: all five steps are there. But the reboot kills the node's pods without any eviction or PodDisruptionBudget check, the drain afterwards is pure ritual, and a drain that fails only produces a warning. A test that checks the final state (new package version, node Ready, node schedulable) passes. Here is the version you wanted:
def patch_node(node):
kubectl("cordon", node)
kubectl("drain", node, "--ignore-daemonsets") # raises on failure; nothing below runs
upgrade_packages(node)
reboot_and_wait_ready(node)
kubectl("uncordon", node)
Same calls, same final state, very different blast radius.
Output Checks Cannot See the Path
DeepMind's Uesato and colleagues compared outcome-based and process-based supervision on math word problems. They found that "pure outcome-based supervision produces similar final-answer error rates with less label supervision", but "for correct reasoning steps we find it necessary to use process-based supervision." Their measure for this is trace error: the "fraction of problems with correct final answers for which the method produces at least one incorrect reasoning step." Models trained with reinforcement learning directly against final-answer correctness reached a best trace error of 12.4%, "compared to only 3.8% for our best process-based method." Right answer, wrong process, measured.
OpenAI's Let's Verify Step by Step reached a similar result for reward models: "process supervision significantly outperforms outcome supervision."
For coding agents the gap is wider, because a passing test can be gamed. ImpossibleBench by Zhong, Raghunathan and Carlini builds tasks where the unit tests contradict the spec, so any pass needs a shortcut, and it measures "an agent's 'cheating rate' as its pass rate on these impossible tasks." Green tests are evidence about the output. They say little about how the code got there.
Why More Critics Do Not Fix It
The natural reaction is to add reviewers: one critic, then two that cross-check each other. The research does not support betting on that.
Should we be going MAD? by Smit and colleagues benchmarked multi-agent debate and found that "multi-agent debating systems, in their current form, do not reliably outperform other proposed prompting strategies." In planning, which is the closest task to "do these steps in this order", Valmeekam, Marquez and Kambhampati found that "the LLM verifiers in that system produce a notable number of false positives", that "self-critiquing appears to diminish plan generation performance", and that the setup falls short "especially when compared to systems with external, sound verifiers."
The ceremonial script shows why. A critic asked "is this correct?" reads code that names every required step, handles errors and logs clearly. Without a reference for the correct order, the critic judges plausibility, and the script is plausible. Two such critics can agree and both be wrong. This is the same limit we described for clean-context critics: a second model removes the author's bias, it does not add knowledge the author lacked.
Give the Agent the Process: Annotated Pseudocode
The ordering knowledge lives in your head or your runbook. Write it down where the agent cannot miss it, as annotated pseudocode:
PROCEDURE patch_node(node)
1. cordon node # MUST run before 2: no new pods land here
2. drain node, honour PDBs # MUST succeed before 3. ON FAIL: stop, leave cordoned, report
3. upgrade packages # ONLY after 2 succeeded
4. reboot, wait for Ready # ON TIMEOUT: stop, leave cordoned, report
5. uncordon node # LAST step, ONLY after 4
INVARIANT: between 3 and 5, no workload pods run on node (DaemonSets excepted)
Then prompt for a mapping, not just an implementation: "Implement this procedure. Tag each block with the step number it implements. Do not reorder steps. Do not catch errors from a step marked MUST succeed."
Structure in the prompt helps. Prompting with Pseudo-Code Instructions (EMNLP 2023) found pseudo-code prompts beat natural language, with "an average increase (absolute) of 7-16 points in F1 scores for classification tasks", and that "code comments, docstrings, and the structural clues encoded in pseudo-code all contribute." Self-planning Code Generation splits work into a "planning phase and implementation phase" and reports "a relative improvement of up to 25.4% in Pass@1 compared to direct code generation." Neither paper tests ordering bugs, and the first used BLOOM and CodeGen, not current agents. Read them as support for giving structure, not proof that pseudocode fixes order.
The stronger argument is about information. Pseudocode written by a human who knows why drain comes before upgrade is an external reference, which a loop of models critiquing each other does not have. Do not let the agent write it: its plan has the same gaps as its code.
Verify the Process, Not Just the Output
Once the steps have numbers, you can test them. Python's unittest.mock already does most of the work: a parent mock records its children's calls in mock_calls, and for assert_has_calls, "If any_order is false then the calls must be sequential."
from unittest.mock import Mock, call, patch
import pytest
import maint
def run_with_mocks(m):
with patch.object(maint, "kubectl", m.kubectl), \
patch.object(maint, "upgrade_packages", m.upgrade), \
patch.object(maint, "reboot_and_wait_ready", m.reboot):
maint.patch_node("node-7")
def test_steps_run_in_order():
m = Mock()
run_with_mocks(m)
m.assert_has_calls([
call.kubectl("cordon", "node-7"),
call.kubectl("drain", "node-7", "--ignore-daemonsets"),
call.upgrade("node-7"),
call.reboot("node-7"),
call.kubectl("uncordon", "node-7"),
])
def test_failed_drain_stops_maintenance():
m = Mock()
def kubectl(*args):
if args[0] == "drain":
raise RuntimeError("cannot evict pod: PodDisruptionBudget")
m.kubectl.side_effect = kubectl
with pytest.raises(RuntimeError):
run_with_mocks(m)
m.upgrade.assert_not_called()
m.reboot.assert_not_called()
The ceremonial version fails both tests. The correct one passes both. Neither test looks at the final state.
A checklist for process review of agent code:
- Number the steps before any code. A human writes or approves the pseudocode.
- Assert order on side effects. Mock the calls that change the world and check the sequence.
- Make each guard fail. Inject a failure and assert that nothing after it runs. This catches try, log, continue.
- Delete each guard. If the suite stays green without it, nothing tests that guard.
- Give critics the reference. Ask for step ID, line numbers, and whether a failure there stops later steps. A mapping is checkable. "Looks good" is not.
- Freeze the tests. Run them from a checkout the agent cannot write to, as in our post on agent self-grading.
| Defect | Final-state test | Critic without a spec | Check that catches it |
|---|---|---|---|
| Steps present, wrong order | Passes | Can miss it: every step is there | Ordered call assertion |
| Guard error caught and logged | Passes | May read it as good error handling | Fault injection on the guard |
| Guard never exercised | Passes | Not visible in the diff | Delete the guard, expect red |
| Step skipped on a rare path | Passes on the happy path | Misses unread paths | Step IDs mapped to code |
| Test edited to fit the code | Passes | Sees a consistent diff | Frozen tests outside the workspace |
The Same Rule for Incident Agents
Investigations have a process too, and a correct root cause reached the wrong way is luck you cannot repeat. Akmatori writes the order into each run's instructions. Per the architecture docs, the generated AGENTS.md "Requires a runbook search, then a memory search, then a check of recent change events, before infrastructure tools." Akmatori also records which memories each run searched, read and cited. That is the pseudocode pattern applied to investigations: a written order to review a run against.
Outcome grading still has its place. SRE Bench uses a pinned judge model that compares each final report with the scenario's written root cause, and "Naming the broken component is not enough": the model must find why. Asking for the why moves grading toward the reasoning, not just the answer.
Conclusion
Ceremonial code passes every test that only looks at the result. More critics reading the same diff without a reference mostly add agreement. Write the process down as numbered, annotated pseudocode, make the agent map code to it, and test the order, the guards and the failure paths directly.
If your team wants AI-assisted incident workflows that follow a written investigation order, Akmatori helps SRE teams investigate alerts, coordinate response, and automate safe infrastructure actions. Powered by Gcore for global infrastructure reliability.
