Engineering practice · Advanced
When AI Review Loops: Finding the Root Cause Instead of Adding Guards

Repeated review findings are often treated as missing conditionals. Sometimes they are evidence that the system is built around the wrong ownership, state, or trust assumption. This guide shows how to distinguish the two without losing review history or counting the same defect repeatedly.
An AI reviewer that reports the same issue after several “fixes” is not necessarily being stubborn. The loop may be exposing a premise that every patch leaves intact. If a policy decision is made in the wrong layer, if one object owns state that belongs elsewhere, or if a workflow assumes an event is unique when it is delivered at least once, another guard can hide the symptom without changing the failure path.
The useful question is not “How many guards should we add?” It is: What invariant does the review keep trying to recover, and where should that invariant be made true?
This article presents a repeatable method for answering that question. It uses a small, deliberately generic case rather than a claim about any particular customer system. The commands are examples you can adapt; no command shown here is presented as having been run against a production repository.
What a review loop actually is
A review loop is a sequence in which a finding is reported, a change is made, the change is reviewed again, and an equivalent or closely related finding returns. The key property is not that the wording is identical. The key property is that the same failure mechanism remains reachable.
A loop can be healthy. A reviewer may be correctly asking for a missing test, a missing error path, or a more precise boundary. It becomes diagnostically important when each patch:
- adds a local check without changing the data flow;
- moves the finding to a neighboring function;
- reduces the visible symptom but leaves the invalid state representable;
- creates another exception path that the reviewer immediately flags; or
- causes the same underlying issue to appear under several labels.
Those patterns suggest a possible flawed architectural premise: an assumption about ownership, ordering, identity, authority, or lifecycle that is inconsistent with the actual system.
The distinction: missing guard versus wrong premise
A missing guard usually has a narrow shape:
- An otherwise valid state transition has one unhandled input or boundary condition.
- The correct owner of the rule is already clear.
- Adding the check makes the invalid transition impossible or produces the intended failure.
- The change does not require duplicating policy in several callers.
A wrong premise has a broader shape:
- The rule is enforced in multiple places because no layer is authoritative.
- The system represents states that should be impossible, then relies on callers to avoid them.
- The patch changes symptoms but not the transition or ownership model.
- Each new guard creates another ordering, retry, or consistency question.
- The reviewer keeps finding the same invariant violated through a different path.
The difference can be stated as a testable hypothesis:
Guard hypothesis: one reachable path lacks a local condition.
Premise hypothesis: the system’s model permits or routes an invalid class of states, so multiple paths can violate the same invariant.
Do not decide between these hypotheses from the review wording alone. Preserve the evidence and trace the invariant through the repository.
A concrete case: duplicate side effects after retried events
Consider this illustrative workflow:
- An external event says that an order is ready for fulfillment.
- An event handler loads the order.
- The handler calls a fulfillment service.
- The handler records that the event was processed.
The reviewer reports that the same event can trigger fulfillment twice. The first response adds a check:
if (event.processed) {
return;
}
fulfillment.create(order);
event.processed = true;
A second review points out that two workers can read processed = false before either writes true. The next patch adds a lock around the check. A later review observes that the lock does not cover the external side effect, or that the lock is local to one process. Another patch checks the fulfillment provider before creating a request. The reviewer then asks what happens if the provider accepts the request but the response is lost.
These findings are related because the system assumes that “the handler ran once” is the same as “the side effect happened once.” That is not a safe assumption for a retried, at-least-once event flow.
The missing guard may be real in one location, but the recurring issue is more likely the premise that a mutable event flag can serve as the sole identity and transaction boundary for an external side effect.
Preserve review history before changing code
Review history is evidence. If each iteration overwrites the previous finding with “fixed,” the team loses the information needed to identify a loop.
For every finding, record a stable review record with at least:
| Field | Purpose | Example |
|---|---|---|
| Finding ID | Stable identity across wording changes | REV-042 |
| Observed invariant | What must remain true | One business operation per external event identity |
| Evidence | Specific path, state, test, or log | Two workers can pass the pre-check |
| Patch effect | What the change actually prevents | Stops sequential duplicate handling only |
| Residual path | How the issue can still occur | Concurrent workers and lost provider response |
| Disposition | Current decision | Open, accepted risk, duplicate, or resolved |
A finding provenance record should distinguish “the code changed” from “the invariant was validated.” Those are different claims.
A minimal line-oriented record can be kept in a review directory:
{
"id": "REV-042",
"first_seen": "2026-11-30",
"invariant": "One fulfillment operation per event identity",
"evidence": [
"Handler checks a mutable processed flag before an external call",
"The flag is written only after the call returns"
],
"attempts": [
{
"commit": "example-1",
"change": "Added processed pre-check",
"residual": "Concurrent workers can both pass"
}
],
"status": "open",
"next_question": "Where is operation identity claimed atomically?"
}
The commit value above is illustrative. In a real repository, use the actual revision identifier and link to the relevant diff.
Normalize findings before counting them
AI review output often varies in wording. “Duplicate fulfillment,” “repeated webhook,” and “missing idempotency” may be three descriptions of one defect. Conversely, two similar-looking findings may concern different invariants.
Normalize each finding into five parts:
- Trigger: what input, retry, race, or failure starts the path?
- State: what state exists before the operation?
- Transition: what action changes state or causes a side effect?
- Invariant: what must be true after all permitted interleavings?
- Evidence: which code, test, trace, or configuration supports the claim?
For the case above:
Trigger: the same event is delivered more than once
State: no durable claim exists for the event's operation identity
Transition: handler calls the external fulfillment API
Invariant: one accepted operation for one business identity
Evidence: check and mark are separate from the external call
Two findings should be treated as duplicates only when they share the same invariant and failure mechanism. Similar nouns are not enough.
Trace the invariant upstream
The central technique is to move from the symptom toward the earliest point where the system could make the invariant true.
Start with the failing behavior, then ask:
- Who creates the identity of the operation?
- Who decides whether the operation is allowed?
- Who owns the durable state that records the decision?
- Which boundary can retry, reorder, duplicate, or partially fail?
- Can the invalid state be represented after the proposed patch?
This is a search exercise, not a guessing exercise. Useful repository commands include:
# Find event entry points and processing markers
rg -n "webhook|event|processed|handled|delivery" src tests
# Find external side effects
rg -n "createFulfillment|send|publish|charge|capture|enqueue" src
# Find persistence boundaries and transaction usage
rg -n "transaction|BEGIN|COMMIT|atomic|lock|unique|idempot" src migrations tests
# Inspect the history of the relevant code
git log --oneline --all -- src/path/to/handler
git log -p --follow -- src/path/to/handler
These commands show where to look; they do not prove that a repository has the required behavior. Evidence still needs to be read and connected into a path.
Draw the path in plain language before proposing a fix:
delivery
-> parse event
-> derive operation identity
-> claim identity?
-> call external provider
-> persist provider result
-> acknowledge delivery
If the claim is absent, or if two workers can claim the same identity, the root cause is upstream of the final “already processed” guard.
Look for architectural smells that produce review loops
A repeated finding is more likely to indicate a flawed premise when one or more of these smells is present.
Policy is copied into callers
If every caller must remember to check authorization, lifecycle, uniqueness, or ownership, the system has no authoritative enforcement point. Adding another caller guard may reduce one path while leaving the policy unenforceable elsewhere.
State is recorded after an irreversible effect
When a remote request, message publication, or financial action happens before durable local state is recorded, a lost response can create uncertainty. A later retry cannot know whether the effect happened. A local boolean cannot retroactively make the remote operation atomic.
Identity is inferred from mutable fields
Names, timestamps, current status, and mutable payload fields are poor substitutes for an operation identity. If retries must be recognized, the identity should be explicit and stable for the operation’s lifetime.
Impossible states are easy to construct
If constructors, repositories, or public methods can create objects that violate the domain’s basic rules, every consumer becomes a potential guard site. A local check is then compensation for an overly permissive model.
Every fix adds another exception
Exception paths are not automatically bad. The warning sign is a growing set of special cases that all explain why the normal state model cannot be trusted.
Choose the correct root-cause level
Not every repeated finding requires redesign. Classify the proposed change by the level at which it acts:
| Level | Typical change | Question to ask |
|---|---|---|
| Input | Reject malformed payloads | Does valid input still reach an invalid state? |
| Boundary | Authenticate or authorize a request | Can another entry point bypass the same rule? |
| Domain | Make an invalid transition unrepresentable | Is the invariant enforced by the owner of the state? |
| Persistence | Add a uniqueness constraint or atomic claim | Does the storage operation match the concurrency requirement? |
| Integration | Use an idempotency key or reconciliation process | What happens when the remote result is unknown? |
| Operations | Retry, alert, or replay a message | Can recovery repeat the effect safely? |
A guard at the wrong level may still pass a narrow test. The root-cause question is whether the rule remains true when another caller, worker, retry, or failure mode is introduced.
Designing a root-level fix for the illustrative case
For an at-least-once event flow, a stronger design separates operation identity, claim, side effect, and reconciliation.
One possible sequence is:
- Derive a stable operation key from the event’s identity and business operation.
- Atomically insert or claim that key with a uniqueness constraint.
- If the key is already completed, return a successful duplicate response.
- If the key is in progress, follow the system’s explicit retry or lease policy.
- Call the provider using the same stable idempotency key when supported.
- Persist the provider result and the local operation state.
- Reconcile ambiguous outcomes instead of blindly repeating the side effect.
The exact implementation depends on the provider and storage system. The architectural improvement is that operation identity is explicit and the uncertainty boundary is acknowledged.
A conceptual schema might look like this:
operation (
operation_key unique not null,
event_id not null,
kind not null,
status not null,
provider_reference,
attempt_count not null,
last_error,
created_at not null,
updated_at not null
)
This is a design sketch, not a migration ready for deployment. Field names, constraints, leases, and recovery semantics must be adapted to the actual system.
Validate fixes at the invariant level
A patch is not root-cause validated because the original review sentence disappears. Validate the invariant against the failure modes that caused the loop.
For the example, a verification matrix could include:
| Scenario | Expected property | Evidence to collect |
|---|---|---|
| Sequential duplicate delivery | No second business operation | Operation record and provider reference |
| Concurrent duplicate delivery | Only one worker claims the operation | Database constraint result and worker traces |
| Failure before provider call | Retry remains safe | Operation state and retry behavior |
| Provider accepts, response is lost | Recovery does not create a second effect | Provider lookup or reconciliation evidence |
| Provider rejects | Failure is recorded without false completion | Stored status and error classification |
| Different event for same business operation | Identity policy is explicit | Key derivation and domain decision |
Use tests that exercise interleavings, not only ordinary sequential calls. A test that invokes the handler twice in sequence does not establish safety against two workers reading the same state concurrently.
A useful assertion is not merely “the second call returns early.” It is “the system contains one accepted operation for the defined identity, regardless of delivery duplication.”
Use review diffs as experiments
Each patch in a loop is an experiment. Record what it changed and what it did not change.
Hypothesis:
A processed flag prevents duplicate fulfillment.
Change:
Add a pre-check and set the flag after the provider call.
Observed result:
Sequential duplicate is suppressed.
Unchanged assumption:
Check and side effect are not one atomic operation.
New experiment:
Claim a unique operation key before the side effect,
then define recovery for an unknown provider result.
This format prevents hindsight. It also helps reviewers discuss evidence instead of debating whether a patch “looks safer.”
When the same finding returns, compare the failure mechanism, not just the diff. If the mechanism is unchanged, stop adding local guards and reopen the premise.
Failure cases and misleading signals
The reviewer repeats a valid finding because the patch is incomplete
Repetition alone does not prove architectural failure. A finding may return because the first patch changed one caller but missed a second caller, omitted a required test, or introduced a regression. Confirm the path before escalating to redesign.
The wording changes but the invariant does not
Different language can hide one finding. Normalize by trigger, state, transition, invariant, and evidence. Do not count comments as independent defects until their mechanisms are distinct.
A larger redesign hides the original defect
Architectural changes can make review harder if they remove the original evidence. Keep the old finding linked to the new ownership or state model, and demonstrate which invariant is now enforced where.
A database constraint is mistaken for complete idempotency
A uniqueness constraint can prevent duplicate local records. It does not automatically prevent duplicate remote effects, especially when the remote call and local transaction cannot commit atomically.
Retries are treated as exceptional
In distributed workflows, retries are normal behavior. If correctness depends on a request arriving exactly once, the premise should be challenged before another guard is added.
AI-generated confidence replaces evidence
Statements such as “this is now safe” are not verification. Ask for the path, state transition, concurrency assumption, and test or operational evidence supporting the claim.
A reproducible investigation workflow
The following workflow is intentionally mechanical. It makes the investigation repeatable across languages and review tools.
1. Freeze the finding history
Export or copy each review result, preserving its timestamp, revision, location, and exact wording. Assign a stable ID if the tool does not provide one.
2. Extract the invariant
Rewrite each finding as a statement that could be true or false. Avoid vague labels such as “unsafe” or “needs validation.”
3. Build the execution path
Identify entry points, state reads, state writes, side effects, retries, and acknowledgment boundaries. Include alternate callers and background workers.
4. Identify the owner
Find the layer that has enough authority to enforce the invariant for all callers. If no layer has that authority, document the ownership gap as part of the defect.
5. Write the premise explicitly
Examples include:
- “This event is delivered once.”
- “This status can only be changed by this handler.”
- “The provider response always arrives.”
- “All callers perform the same authorization check.”
- “This mutable field uniquely identifies the operation.”
Then mark each premise as guaranteed, assumed, or contradicted by evidence.
6. Propose the smallest root-level change
“Root-level” does not mean “largest.” It means the smallest change that makes the invariant true at its owner and closes the relevant alternate paths.
7. Verify failure modes
Test duplicates, concurrency, retries, partial failure, malformed input, alternate entry points, and recovery. Match each test to a previously recorded evidence gap.
8. Re-review with history attached
Ask the reviewer to assess the invariant and the verification matrix. Link the old finding to the new evidence rather than starting a fresh conversation with no context.
How to tell whether the loop is closed
A review loop is closed when all of the following are true:
- The finding has a stable identity and preserved history.
- The invariant is stated precisely.
- The failure mechanism is no longer reachable under the documented threat and failure model.
- The authoritative owner enforces the rule for every relevant entry point.
- Tests or other evidence cover the interleavings and partial failures that motivated the finding.
- Residual risks are explicit rather than hidden behind a “fixed” label.
A loop is not closed merely because the AI reviewer changes its wording, lowers severity, or stops mentioning one file.
Limitations
This method cannot infer an organization’s business policy. Whether two events represent one business operation or two legitimate operations is a domain decision. The article also does not prescribe a particular database, message broker, provider, programming language, or AI review tool.
Some distributed failures cannot be eliminated; they can only be made observable and recoverable. In those cases, the correct result may be an explicit reconciliation workflow and an accepted residual risk, not a claim of absolute exactly-once behavior.
Finally, review history is only as reliable as the evidence attached to it. A log line, generated summary, or passing unit test may be insufficient for a concurrency or integration claim. Record what was actually checked, what was simulated, and what remains unverified.
Final checklist
- Did we preserve every version of the finding?
- Did we normalize repeated comments by invariant and failure mechanism?
- Did we identify the earliest point where the invariant can be enforced?
- Did we state the architectural premise that may be false?
- Does the proposed guard change the state model or only hide one path?
- Can concurrent workers, retries, and partial failures still violate the invariant?
- Do tests validate the business property rather than one implementation detail?
- Are unresolved assumptions and residual risks recorded?
When AI review loops, treat repetition as a signal to inspect the model beneath the patch. A missing guard is local. A flawed premise repeats because the system keeps making the same invalid state or transition available. Preserving history, naming the invariant, tracing ownership, and verifying failure modes turns that repetition into useful architectural evidence.
Continue with the engineering guides or look up terms in the glossary.