Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

30K Daily Merges, 40% Fewer Rollbacks: Anthropic's AI Code Review System

Anthropic's AI-driven code review system handles 30,000 daily merges with 90% AI-written code while reducing rollbacks by 40% through a seven-layer defense pipeline, multi-agent review with voting, risk-based approvals, merge queues, and feature flags, with Java implementation examples.

One: The Data — How Extreme Is the Problem?

Before diving into the solution, consider the scale from Anthropic's official blog https://claude.dev/blog/solving-code-review-at-anthropic/:

Claude writes own code : 90% — main reviewer is now an Agent, not a human

Monorepo daily merges : 2,500 → 30,000+ — 12× increase in 4 months

Claude Code repo PRs (Jun–Sep) : Doubled — throughput exploded

Rollback rate : Down 40%+ — fewer human reviews, yet quality improved

Substantive review comments : 16% → 54% — AI review catches real bugs

Human review time per PR : Halved — real engineering hours saved

The key insight: throughput up 12×, rollback rate down . This proves "less human review" does not inevitably mean "worse quality" — provided you change the game.

The Critical Question Shift

Traditional code review assumes: "Someone read this code" ≈ "This code is safe" . Anthropic calls this an imprecise proxy . The real standard is not "was it read" but "was the risk intercepted".

What can go wrong with this change? Which layer — machine or human — is best suited to catch it?

Reframing the question transforms review from a final gate into a continuous spell-check. Most low-level errors are caught before the PR exists; humans only handle what machines cannot.

The objective function:

minimize human review time
subject to revert rate & incident rate not rising ← guardrail

Trap: If you merely cut review time and bad code reaches production, firefighting time explodes — you haven't saved time, just moved it. Revert/incident rates are the "anti-cheat" guardrails.

Code review also does two jobs: ① find/fix issues ② propagate context. After machines take over ①, ② is addressed separately later.

Two: Panorama — Seven-Layer Defense Pipeline

Architecture in one sentence: Layered defense, each layer catches a class of defects, leftovers caught by fast rollback. This is the Swiss-cheese model: each slice has holes, but stacked layers make penetration extremely unlikely.

Seven-layer defense pipeline diagram
Seven-layer defense pipeline diagram

Mnemonic: Validate, Review, Secure, Test, Approve, Queue, Canary, Rollback .

Layer 1 — Pre-PR : AI Agent + Developer — Local unit tests, build, checks; fresh-context sub-agent cross-reviews diff — Target: Syntax errors, basic logic flaws

Layer 2 — Post-PR creation : Multi-agent cluster — Parallel bug hunting, independent verification voting, severity-sorted output — Target: Business logic bugs, edge cases

Layer 3 — Post-PR creation : Security Agent + Rule Engine — Vulnerability scan, secret detection, dependency risk — Target: Security vulns, injection, compliance

Layer 4 — PR lifecycle : CI Pipeline — Compile, lint, type-check, full unit & integration tests — Target: Build failures, test failures, style violations

Layer 5 — Pre-merge : Risk Classifier + Matching Developers — Risk-based 0/1/2 human approvals; high-risk requires two — Target: Architecture soundness, business direction, core logic

Layer 6 — Merge & Release : Merge Queue + Release System — Re-run full checks against latest main; internal dogfood, staged rollout — Target: Multi-PR conflicts, wide user impact

Layer 7 — Post-deploy : Monitoring + On-call — Metric alerts, feature-flag kill switch, auto-rollback — Target: Escaped faults, blast-radius reduction

Key design principles:

Shift left: First three layers happen before humans see code.

Risk driven by change, not author: What you changed determines risk, not your seniority.

Agent approvals don't fill human slots: Automation can green-light low-risk changes but cannot satisfy "must have a human" requirements; product only emits findings, never approvals.

Approval bound to commit: New commits invalidate prior approvals.

Takeaway: Single gates are brittle; layered defense is robust. Every layer leaks some bugs, but almost no bug survives all seven.

Engineering Entry: Handling 30K Webhooks/Day

First hurdle for a self-built review platform: ingest tens of thousands of events/day with GitHub/GitLab retries. Three pillars — signature verification, idempotency, async processing :

@PostMapping("/webhook")
public ResponseEntity<Void> onEvent(@RequestBody byte[] body,
    @RequestHeader("X-Hub-Signature-256") String sig,
    @RequestHeader("X-GitHub-Delivery") String deliveryId) {

// 1. HMAC-SHA256 verify + constant-time comparison to prevent timing attacks
byte[] expected = hmacSha256(secret, body);
byte[] actual = HexFormat.of().parseHex(sig.substring("sha256=".length()));
if (!MessageDigest.isEqual(expected, actual)) {
    return ResponseEntity.status(401).build();
}

// 2. Idempotency: platform retries, use deliveryId SET NX + TTL dedup
Boolean first = redis.opsForValue()
    .setIfAbsent("wh:" + deliveryId, "1", Duration.ofHours(24));
if (Boolean.FALSE.equals(first)) {
    return ResponseEntity.ok().build();
}

// 3. Load shedding: push to MQ, return 200 immediately, review fully async
mq.send("pr-events", deliveryId, body);
return ResponseEntity.ok().build();
}

Two details matter:

Signature comparison uses MessageDigest.isEqual() for constant-time comparison ; many mistakenly use String.equals() which leaks timing information.

Model APIs are globally scarce; consumers need Semaphore bulkheads + token-bucket rate limiting — without it, peak traffic causes cascade failure.

Three: Layer 1 — Prove Correctness Before PR, Don't Just Say "Done"

Core principle: Don't let the Agent claim "I finished"; make it show runnable evidence.

Give Claude something executable — tests, builds, screenshots matching designs — and require it to paste the output, not just verbal confirmation. Boris Cherny (Claude Code author) says this alone improves result quality 2–3× . Verifying behavior, not trusting description, is perhaps the most critical engineering practice in the LLM era.

Second trick: Fresh-context sub-agent blind review . After writing, spin up a completely clean sub-agent to review the diff. It lacks the "I just wrote this, it's probably fine" bias and spots more issues.

Java implementation: organize validators as a chain of responsibility, returning structured evidence instead of raw booleans:

public interface PreCheck {
    // Key: return Evidence (command run / output / screenshot), not bare boolean
    Evidence verify(Diff diff, Context ctx);
}

public class AutoVerifyChain {
    private final List<PreCheck> chain; // run tests / build / screenshot diff / sub-agent blind review

    public VerifyReport run(Diff diff, Context ctx) {
        List<Evidence> evidences = chain.stream()
            .map(c -> c.verify(diff, ctx))
            .toList();
        boolean pass = evidences.stream().allMatch(Evidence::ok);
        // Highlight: evidence chain retained for human review & postmortems
        return new VerifyReport(pass, evidences);
    }
}
Technical highlight: Evidence chain has two benefits — humans read evidence not code during review; incidents can trace back to which verification step lied.

Another clever detail: When reviewers repeatedly flag the same issue, it's not the code's fault — it's the rule's fault. Fix at source: add a lint rule, update CLAUDE.md / REVIEW.md, codify into a skill, turning O(n) repeated corrections into a one-time root-cause fix. REVIEW.md is the rule file fed to AI reviewers, telling them what to focus on and what to ignore — noise reduction is immediate. Java project core snippet:

# Java Project Review Core Rules
## Must-Check High-Risk Items
1. NPE risk, especially collection access & external param calls
2. Transaction boundary errors: transaction not effective, exception not rolled back
3. Thread-safety issues: shared variable ops in concurrency
4. Slow SQL: full table scans, missing indexes, large transactions
5. Swallowed exceptions: empty catch blocks without logging or rethrow

## Explicit Ignore List
1. Pure formatting/naming — handled by lint
2. Legacy code outside current diff
3. Missing comments, aesthetic suggestions

## Output Requirements
- Every issue must include exact file+line+reproduction steps
- Lead with summary: "Found X critical issues, Y suggestions"
- If no blocking issues, explicitly state: "No blocking issues found"

Context explosion solution: large repo + large PR cannot feed all code to Agent. CLAUDE.md holds project conventions, REVIEW.md holds module-specific rules; each review loads only relevant sections, never the whole file .

Four: Layer 2 — AI Review: Multi-Agent Parallel + Quorum Voting

This is the core, most questioned layer. Design first, then data, then code.

Why Single Agent Fails

Single-agent review's problem isn't "can't see bugs" but confident hallucination . To avoid missing bugs, it flags everything — half are style nits or hallucinations, human effort wasted filtering noise.

Self-critique doesn't work: same agent validating its own findings equals same error model reinforcing itself — self-scoring preserves bias.

Anthropic splits "find bugs" and "reach conclusion" into two agent groups:

Multi-agent review flow
Multi-agent review flow

Four-step flow:

N Hunter Agents run in parallel , each responsible for a defect class (logic, security, concurrency, architecture).

Independent Verification Group votes on each finding , threshold required to pass.

Pure style/formatting/cleanup opinions discarded , don't disturb developers.

Survivors tagged, sorted by severity; critical issues always on top.

Often overlooked: verification agents don't just vote — they cross-check findings against actual code behavior (is that branch reachable? will that exception really be thrown?). This moves from "pattern matching" to "behavioral verification", eliminating many "looks like a bug but code never executes there" false positives.

Multiple agents may give different severities/descriptions for same issue. Aggregation layer does deduplication + highest severity + evidence alignment ; every finding must carry file:line and reproducible path, otherwise it's dropped.

Why "Independent Judgment" Matters

Technical highlight: If 3 verifiers use the same prompt and context, their errors are highly correlated — voting becomes theater. This is common-cause failure in distributed systems. Verifiers must have isolated contexts for votes to have statistical meaning.

Data from Production

Average review time ~ 20 minutes .

Small PRs (<50 lines) 31% flagged; large PRs (>1000 lines) 84% flagged; avg 7.5 issues/PR.

False positive rate < 1% .

Substantive review comments rose from 16% to 54%.

Java Implementation: Virtual Threads + Voting Consensus

Don't start with complex agent frameworks. Do three things: tool fallback, parallelization, voting convergence . Core skeleton:

// Review task: each agent owns one dimension
record Finding(String agent, String severity, String file, int line, String message) {}

interface ReviewAgent {
    String dimension();
    List<Finding> review(String diff, String repoContext);
}

public class ParallelCodeReviewOrchestrator {
    // Java 21 virtual threads: IO-heavy fan-out, no thread-pool tuning
    private final ExecutorService agentPool = Executors.newVirtualThreadPerTaskExecutor();
    private final List<ReviewAgent> agents;
    private final JudgeAgent judge;

    public ReviewResult review(String diff, String repoContext) throws Exception {
        // 1. Parallel dispatch: each agent reviews independently, non-blocking
        List<Future<List<Finding>>> futures = agents.stream()
            .map(a -> agentPool.submit(() -> a.review(diff, repoContext)))
            .toList();

        // 2. Collect candidates: single agent timeout/failure doesn't break whole
        List<Finding> candidates = futures.stream()
            .flatMap(f -> {
                try { return f.get(60, TimeUnit.SECONDS).stream(); }
                catch (Exception e) { return Stream.empty(); }
            })
            .toList();

        // 3. Vote + behavioral verification: Judge checks candidates against actual code paths
        List<Finding> verified = judge.voteAndVerify(candidates, diff, repoContext);

        // 4. Sort by severity, return high-signal results
        return new ReviewResult(verified.stream()
            .sorted((a, b) -> severityRank(b.severity()) - severityRank(a.severity()))
            .toList());
    }
}

Why virtual threads over traditional pools? Each agent call is mostly I/O wait (model response, code retrieval), CPU usage low. Virtual threads make "one thread per agent" zero mental overhead, code stays straightforward, no need to stuff logic into CompletableFuture callback chains.

Judge's voting logic needs no complex consensus; two rules suffice:

class JudgeAgent {
    // Rule 1: At least 2 agents independently report same location to keep
    // Rule 2: Verify each candidate against code's "actual execution path"
    List<Finding> voteAndVerify(List<Finding> candidates, String diff, String ctx) {
        return candidates.stream()
            .collect(Collectors.groupingBy(f -> f.file() + ":" + f.line()))
            .entrySet().stream()
            .filter(e -> e.getValue().stream()
                .map(Finding::agent).distinct().count() >= 2)
            .flatMap(e -> e.getValue().stream())
            .filter(this::verifyAgainstCodePath) // behavioral verification kills false positives
            .distinct()
            .toList();
    }
}

Advanced: Weighted Voting & Responsibility Boundaries

Two mechanisms worth adding on top of basic voting:

① Credibility Weighting. Track each agent's historical performance — human dispositions on its comments (fixed / false-positive / intentional / ignored) — distill into trust score; higher-trust agents carry more weight. Classic Bayesian thinking, core logic in few lines:

// Weighted vote per clustered candidate finding
double weightedAgree = votes.stream()
    .filter(FindingVote::isAgree)
    .mapToDouble(v -> reputationRepo.getTrustScore(v.getAgentId()))
    .sum();
double agreeRatio = weightedAgree / weightedTotal(votes);
if (agreeRatio < 0.5) continue; // weighted votes below half → discard as false positive

② Pre-existing Detection. Use JGit git blame; if problematic line's introducing commit predates PR base, tag Pre-existing — old bugs aren't the new author's fault . These get handled separately by nightly Agent scanning existing codebase. This detail decides whether engineers love or hate the bot.

Priority hardcoded: catch real bugs first, reduce review rounds later. Also run "known-clean PRs" as negative samples regularly to measure harmful alerts — false positive rate isn't guessed, it's measured.

Voting solved "false positives", but a deadlier problem looms: AI review may never converge.

Five: Deep Dive — Making LLM Review "Speak Human" in Java Projects

Before convergence, a prerequisite: what makes a review agent reliable? This section is pure Java hard-knocks.

Real case: team scripted git diff straight into LLM. Daily reports: "use var ", "missing blank line". When real killers appeared — @Transactional self-invocation failure , shared thread pool wiping MDC /TraceId — silence. Three days, developers muted the bot.

Remember: A muted bot is worse than no bot.

Root cause: three missing pieces:

What rules can decide, never bother LLM.

Don't just feed diff — if a shared Money class changed, feed upstream usages and internal conventions, otherwise it guesses from literal text.

Make model self-critique — raise doubts, seek counter-evidence, emit only high-confidence findings.

Separation of Concerns: Who Owns What

Worst experience: LLM and Checkstyle both flag "missing @Override ". Enforce single ownership:

Style : Checkstyle — Formatting, naming

Deterministic Bugs : SpotBugs / PMD — Fixed bug patterns

Architecture Boundaries : ArchUnit — Layer violations, dependency rules

Coverage/Integration : JaCoCo / Testcontainers — Coverage, integration tests

Semantic Layer : AI Agent — Logic, concurrency, transaction semantics

Risk Decision : Human — Tiering, final approval

One sentence: Deterministic → SAST, Non-deterministic → LLM. AI doesn't replace tools; it only fills the "semantic layer" tools can't see. No turf wars.

Context Trimming: Slice by AST, Not Character Count

Diff is 10 lines but touches a public method used by 20 services — can't fit all. Correct approach: trim context by call graph:

// Highlight: changedMethod modified, only pull in "who calls it" method bodies, control Context Window
CompilationUnit cu = StaticJavaParser.parse(sourceFile);

cu.findAll(MethodCallExpr.class).stream()
    .filter(mc -> mc.getNameAsString().equals(changedMethod))
    .map(mc -> mc.findAncestor(MethodDeclaration.class).orElseThrow())
    .map(MethodDeclaration::toString) // method body only, not whole class
    .limit(3) // prevent Token explosion: 1-degree callers, max 3
    .forEach(ctx.callerSnippets()::add);

With this, @Transactional self-invocation gets caught: diff only shows this.deduct(), but call graph pulls in "non-proxy entry in same class", plus a RAG-retrieved rule — "transactional methods must not self-invoke; use AopContext or split Service" — semantic stands. Not model enlightenment; context completed.

Business semantic blind spots same: "fulfillment order state machine cannot arbitrarily add enums" — model doesn't know. Vectorize internal design docs, historical CR comments, recall on-demand for few-shot.

Two-Stage Guard: Raise Doubts, Then "Disprove Yourself"

public record ReviewContext(
    String diff,
    List<String> callerSnippets, // AST-fetched upstream
    List<String> specHits,        // RAG-retrieved dev rules / historical CR
    String prFingerprint          // idempotency key
) {}

public record Issue(String file, int line, String reason,
    double confidence, boolean disproved) {}

@Component
public class SelfCorrectionGuard {
    private final LlmClient llm;

    public List<Issue> review(ReviewContext ctx) {
        // Round 1: scope strictly, explicit "don't steal Linter's job"
        var draft = llm.chat(FIND_PROMPT, ctx);

        // Round 2: parallel disproof via virtual threads, prefer miss over false alarm
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            return draft.issues().stream()
                .map(i -> executor.submit(() -> llm.chat(DISPROVE_PROMPT, ctx, i)))
                .map(CompletableFuture::join) // illustrative; prod needs timeout + fallback
                .filter(i -> !i.disproved())
                .filter(i -> i.confidence() >= 0.85)
                .limit(3) // max 3 per MR, prevent alert fatigue
                .toList();
        }
    }

    static final String FIND_PROMPT = """
    You are a Senior Java Reviewer, only report these 5 categories:
    Concurrency safety / Transaction boundaries / NPE guards / State machine integrity / Cross-service idempotency.
    Naming, whitespace, log format — never mention; Checkstyle owns them.
    Combine [Upstream Calls] and [Internal Rules] before concluding, output JSON.
    """;

    static final String DISPROVE_PROMPT = """
    Below is a raised doubt. Try hard to find counter-evidence:
    If upstream already locks / has guard / rule explicitly allows, set disproved=true.
    If unsure, also set true — one false alarm and devs never trust this bot again.
    """;
}

The two prompts are the soul. DISPROVE_PROMPT philosophy in one line: Prefer miss over false alarm. limit(3) and disproved fields born from real production pain.

Which comments stay, which go — quadrant diagram clarifies:

Comment classification quadrant
Comment classification quadrant

Async, Non-Blocking Merge

LLM review takes 8–20s; blocking MR draws ire, especially during freeze periods. Approach:

Webhook returns 202 immediately, pushes to MQ; async comment, no block .

Only high-risk @ -mentions humans.

Idempotency key prFingerprint = hash(repo + mr + headSha + diff) — three rapid commits don't triplicate identical comments.

Timeout degrades to "skip", not "error" — review is value-add, not a blocker.

One-liner: Rules block style → AST adds callers → RAG adds rules → Dual-agent disproof → Async keeps only 3.

Six: Convergence Battle — Preventing Two AIs From "Involution" to Death

Most fascinating and terrifying part of the system.

Real Crash: 50+ Rounds Overnight

Agent writes code + Agent reviews → two AIs can "involution" till dawn — one CLI PR ran 50+ review rounds in a single night . Each round fixed a bit, new "old issues" surfaced, finally stopped manually.

Post-mortem via git blame was brutal: 59% of repeatedly flagged issues existed since round 1 . Review wasn't finding new bugs; each round just resurfaced a few more old ones.

Deeper insight: Noise annoys humans; for Agents it's infinite-loop fuel. Agent authors diligently fix every nit, generating new commits, triggering new review rounds. Loop spins.

Four Convergence Valves

Hard Round Cap : Max 3 rounds; beyond that, author must rethink design, not keep patching

Incremental Review : Round 1 full scan; subsequent rounds only review new diff, no re-litigation

Batch Fix by Category : Same-class issues reported once; require all instances fixed in one go

Deduplication Filter : Issues already threaded / rejected by developer never re-reported

Data doesn't lie:

First-round pass rate: 65% → 78%

>=5 rounds share: 8.9% → 1.5%

Avg review rounds: 2.08 → 1.32

Why 3 rounds? Empirical: early rounds catch new issues; later rounds just repeat old ones, marginal returns near zero.

Java Implementation: Convergence Controller

/**
 * AI Review Round Convergence Guard — prevents Agent involution
 * Three valves: round cap + incremental review + fingerprint dedup
 */
public class ReviewConvergenceGuard {
    private static final int MAX_ROUNDS = 3;
    private final Set<String> reportedFindings = ConcurrentHashMap.newKeySet();

    public ReviewDirective direct(ReviewRound round) {
        // ① Circuit breaker: >3 rounds → stop, reassess design
        if (round.number() > MAX_ROUNDS) {
            return ReviewDirective.HALT_AND_REASSESS;
        }

        // ② Incremental review: round 2+ only sees new diff
        DiffScope scope = round.number() == 1
            ? DiffScope.full()
            : DiffScope.since(round.lastReviewedCommit());

        // ③ Fingerprint dedup: never re-report same issue (Set.add does idempotent dedup)
        List<Finding> fresh = round.findings().stream()
            .filter(f -> reportedFindings.add(fingerprint(f)))
            .filter(f -> f.category() != Category.STYLE) // style filtered out
            .toList();

        // ④ Report by category, not single point: force author to fix whole class at once
        return ReviewDirective.review(scope, Group.byCategory(fresh));
    }

    /** Fingerprint = rule + file + normalized snippet: line drift, whitespace changes don't affect dedup */
    private String fingerprint(Finding f) {
        return Hashing.sha256()
            .hashString(f.ruleId() + "|" + f.path() + "|"
                + f.snippet().replaceAll("\\s+", ""), StandardCharsets.UTF_8)
            .toString();
    }
}

Three details: fingerprint uses "rule + file + normalized snippet"; line drift and whitespace changes don't affect dedup . Fingerprint can also use Redis SET NX with TTL for cross-round persistence.

Circuit breaker semantics isn't error but HALT_AND_REASSESS — stop and re-evaluate design ; that's the correct degradation posture.

Extra safety: if duplicate issues exceed 50% this round, escalate to human — don't let machine idle-burn tokens.

Interview elevation: This essentially constructs a monotonically decreasing potential function for a potentially divergent iterative system — using "new and unreported finding count" as potential, it's non-increasing and eventually zero, guaranteeing convergence; hard round cap adds livelock insurance.

Seven: Risk-Based Approval — Good Steel on the Cutting Edge

Convergence solved; next is human allocation: tens of thousands of changes/day, even 1 human/PR queues explode.

Answer: tiering — and tier determined by change, not author .

Three-Tier Table

Low : Docs, copy, internal toggles, feature-flag-wrapped new logic → 0 humans : auto-checks green + trusted author → auto-merge

Medium : Regular biz features, cache logic, common utils → 1 human (submitter may count)

High : Payments, auth, CI workflows, auto-updaters, core architecture → 2 humans , mandatory path, never waived

Classification heuristics suffice: touching high-risk path → auto-upgrade; pure docs/config <200 lines → low; >1000 lines diff → at least medium.

Three Iron Laws

Author cannot self-assign risk level — classifier decides, sensitive paths force upgrade.

Bot approval ≠ human approval — Agent can green-light low-risk but cannot fill "must have a human" slot; who instructed the Agent = accountable human , occupies one approval seat.

One approval binds to one commit — new commit (especially Agent pushes, manual conflict resolutions) invalidates approval, requires re-sign.

Third law often overlooked. GitHub/GitLab branch protection + dismiss_stale_reviews=true implements this natively — no wheel reinvention.

Dual Classifier + Chain of Responsibility

First classifier reads diff → risk tier. Second classifier asks "this change is low-tier but should we exceptionally add a human?" — e.g., public API signature change upgrades even if path looks harmless.

Rule config (copy-ready):

# risk-rules.yaml — Risk Tiering Rules Example
risk-tiers:
  low:
    paths: ["docs/**", "**/*.md", "internal/playground/**"]
    files_behind_flag: true
    required_approvals: 0
  medium:
    paths: ["src/main/java/com/xxx/biz/**", "src/main/resources/**"]
    required_approvals: 1
  high:
    paths:
      - "src/main/java/com/xxx/billing/**"   # billing
      - "src/main/java/com/xxx/autoupdater/**" # auto-upgrade
      - ".github/workflows/**"               # CI pipelines
      - "src/main/java/com/xxx/auth/**"       # auth
    required_approvals: 2
    require_senior_reviewer: true

trusted_authors: ["alice", "bob"] # whitelist authors get lightweight path
agent_authors: ["claude-bot[bot]"]   # Agent authors must have human backing

Java side uses Chain of Responsibility + Strategy:

public enum RiskTier {
    LOW(0), MEDIUM(1), HIGH(2);
    final int requiredHumanApprovers;
    RiskTier(int n) { this.requiredHumanApprovers = n; }
}

public interface RiskClassifier extends Ordered {
    /** Hit returns RiskTier, else null passes to next classifier */
    RiskTier classify(ChangeContext ctx);
}

@Component
public class SensitivePathClassifier implements RiskClassifier {
    private static final Set<String> SENSITIVE_GLOBS = Set.of(
        "billing/**", "ci-workflows/**", "auth/**", "auto-updater/**");

    @Override
    public RiskTier classify(ChangeContext ctx) {
        boolean hit = ctx.getChangedFiles().stream()
            .anyMatch(path -> SENSITIVE_GLOBS.stream().anyMatch(path::matches));
        return hit ? RiskTier.HIGH : null; // sensitive path one-vote max
    }
}

@Service
public class RiskTierRouter {
    private final List<RiskClassifier> classifiers; // pre-sorted by order
    private final MlRiskModel mlModel;

    public RiskTier route(ChangeContext ctx) {
        RiskTier ruleLevel = classifiers.stream()
            .map(c -> c.classify(ctx))
            .filter(Objects::nonNull)
            .findFirst()
            .orElse(RiskTier.MEDIUM);

        // Model can only "upgrade" never "downgrade" — prefer false positive over false negative, fail-safe
        RiskTier mlLevel = mlModel.predict(ctx);
        RiskTier level = mlLevel.compareTo(ruleLevel) > 0 ? mlLevel : ruleLevel;

        // Second classifier safety net: low tier but touches public API signature → upgrade
        if (level == RiskTier.LOW && touchesPublicApiSignature(ctx.getDiff())) {
            level = RiskTier.MEDIUM;
        }
        return level;
    }
}

Two design highlights:

"Model only upgrades, never downgrades" : ML verdict and rule chain take the stricter — classic risk-control conservative strategy, equivalent to security's fail-safe principle.

Why Chain of Responsibility over if-else : Sensitive path list needs hot-reload and tiered management; chain makes each rule independently testable and pluggable.

Approval Expiry & Tier Strategy

New push → approvals instantly invalidated, tier recalculated:

void onNewPush(Pr pr, String newHeadSha) {
    // Approval bound to specific commit SHA: new push → all invalidated, re-sign
    approvalRepo.invalidateAll(pr.id());

    RiskTier tier = classifier.classify(pr.diff());
    if (sensitivePathMatcher.match(pr.changedFiles())) {
        tier = RiskTier.HIGH; // AntPathMatcher matches CODEOWNERS-style sensitive paths
    }

    int required = switch (tier) { // switch expression, tier = strategy
        case LOW     -> trustedAuthors.contains(pr.author()) ? 0 : 1;
        case MEDIUM  -> 1;
        case HIGH    -> 2;
    };
    // Bot approvals never consume human slots; human who directed Agent = accountable
    approvalPolicy.require(pr, required, /* humansOnly */ true);
}

Final pre-merge check enforces "approval bound to commit" via CAS:

// Review facts modeled as immutable events, persisted to Kafka for replay & eval
public sealed interface ReviewEvent permits Finding, Approval, PushInvalidated {}
record Approval(String reviewer, String commitSha, boolean human) {} // human=false doesn't count

boolean mergeAllowed(String prId, String headSha) {
    Approval a = approvalStore.get(prId); // Redis: pr:{id}:approval
    return a != null && a.human()
        && a.commitSha().equals(headSha) // only this exact commit, new push invalidates
        && findings.noOpenFindings(prId) // open bug/security findings block merge
        && ci.allGreen(prId);
}

Plus Trusted Author Whitelist : stable contributors get low-risk fast lane. But whitelist only relaxes "low-risk tier"; sensitive paths never trust individuals.

CI Layering Side Note

PR volume 10×, CI also gets hammered. Same tiering: low-risk runs light check suite, high-risk runs full, plus test sharding and caching. Java stack: SpotBugs + Checkstyle + ArchUnit guard boundaries, JaCoCo watches coverage, Testcontainers runs integration; dozens of checks parallel, merge queue serializes gatekeeping.

Eight: Merge Queue + Canary Release — Final Defense Before Merge

Classic Crash: Both Green, Merge Red

PR #1 changes method signature, tests green; PR #2 adds call to old signature, also green. Both merge → main explodes. Semantic conflict; each ran CI on stale base, never caught.

Solution: Merge Queue — re-run checks on "future main" .

Merge queue flow
Merge queue flow

Essence: shift PR from "snapshot validation on stale base" to serialized integration validation on latest main , equivalent to optimistic locking / serialized scheduling eliminating concurrent merge conflicts. Same idea as Kafka log serialization, Redis AOF — sacrifice some merge throughput for main-branch strong consistency . At 2× PR volume, this is the only way to keep main green.

Java core implementation:

public class MergeQueue {
    private final BlockingQueue<PullRequest> queue = new LinkedBlockingQueue<>();
    private final ReentrantLock mergeLock = new ReentrantLock();
    private final CIRunner ciRunner;

    public void enqueue(PullRequest pr) { queue.offer(pr); }

    // Single-threaded consumer guarantees serial merge into main
    public void consume() throws InterruptedException {
        while (true) {
            PullRequest pr = queue.take();
            mergeLock.lock();
            try {
                // KEY: re-validate against latest main HEAD
                if (ciRunner.revalidate(pr, mainBranch.head())) {
                    pr.mergeAndAdvanceMain();
                } else {
                    pr.dequeueAndNotify("Conflict with latest main, please rebase");
                }
            } finally {
                mergeLock.unlock();
            }
        }
    }
}

For high queue volume, advance to batch pre-merge: stack multiple PRs, validate together; if red, binary search to eject bad PR , rest merge normally; CI cost drops from O(n) to O(log n).

Three Post-Merge Life Preservers

Feature Flag internal dogfood first — new features hit employees first; bad news caught internally before users.

Staged rollout by channel — latest channel first, stable lags; risk exposed in small scope.

Second-level kill switch — incident → flip flag off, no code rollback, no re-release.

Kill Switch implementation: local cache + event broadcast:

@Service
public class FeatureFlagService {
    private final ConcurrentHashMap<String, Boolean> localCache = new ConcurrentHashMap<>();
    private final FlagRepository repository;

    /** Decision entry: local cache read, zero network overhead */
    public boolean isEnabled(String flag, String userId) {
        return localCache.getOrDefault(flag, false);
    }

    /** Incident response: on-call one-click kill, millisecond full effect */
    @Transactional
    public void killSwitch(String flag, String reason) {
        repository.update(flag, false, reason);
        localCache.put(flag, false);
        eventBus.publish(new FlagKilledEvent(flag, reason, Instant.now()));
        // Trigger postmortem: trace back "which layer should have caught this"
        postmortemTracker.record(flag, reason);
    }
}
Technical highlight: Kill switch needs no deploy, millisecond global effect. Rollback-ability is the prerequisite for speed — this is the confidence behind letting machines merge code.

Responsibility culture: low-risk auto-merge, who owns incidents? You land it, you own it — merger fixes. Four preconditions: changes small (easy review/debug/revert), everything reversible (flag/revert/canary in minutes), blast radius sets bar (wider impact → stricter review), blameless — postmortem asks "which layer should have caught it", system problem, not witch-hunt.

Nine: Metrics & Flywheel — Proving "Real Savings" Not "Cost Shifting"

Back to opening question: how to prove saved engineering hours, not just moved cost to firefighting?

Dual Metric Groups

North Star (Efficiency) : Human approvals per PR (median + P95) — Continuous decline, target ≤ 1

Efficiency : Human comment count, PR wait-for-review time, review rounds — Decline

Guardrail (Quality) : Rollback rate, production incident rate — Must never rise

Guardrail (Noise) : False positive rate (classified by human disposition) — Floor < 5%

Dashboard (Jun–Sep actuals):

Human approvals/PR  p50 | 1   p95 | 1   target <= 1
PR wait time        ▇▇▇▇ → ▇▏   significant drop
Revert rate         ▇▇▇▇ → ▇▏   -40%+   guardrail: rise = no savings
Incident rate       ▇▏ → ▇▏       must not rise

Circuit Breaker: What Anthropic Admits They Still Lack

They confess missing a circuit breaker — when revert rate climbs, only manual dashboard watching tightens policy; engineers want it automated.

Java-side fix: metrics + policy center:

// No deploy needed to react: flag kill in seconds; revert rate rise → auto-demote zero-human merges
@Scheduled(fixedDelay = 60_000)
void guardrail() {
    double revertRate = metrics.revertRate(Duration.ofHours(1));
    if (revertRate > SLO) {
        flags.disableAllNewBehavior(); // kill without deploy
        policy.tighten(/* requireSecondHuman */ true);
        alert.onCall(revertRate);
    }
}

One line: Capability must grow with guardrails. Before circuit breaker ready, don't boast "zero-human merge" — they're not fully opening that gate yet, waiting for this.

Eval Flywheel: Making System Self-Improve

Reviewer prompts, models, tools change daily; how ensure improvements not regressions? Ruthless answer: Incidents become test cases.

Eval flywheel diagram
Eval flywheel diagram

Four steps:

Every production incident/rollback, engineer confirms real bug & root cause.

Add to golden regression set, only grows, never shrinks .

Daily run review model against this set.

Any prompt/tool/model change must pass eval set first — score up → keep, score down → discard .

This applies ML regression eval to prompt engineering, giving a system with no explicit correct output a measurable regression baseline. One of the highest-leverage designs in the whole system.

Ten: Machines Read Code — How Does Human Knowledge Transfer Happen?

Back to the buried question.

Review's second function: context propagation. Nobody reads diffs anymore; new hires can't understand codebase; team loses collective code ownership — hidden cost many teams pay after automating review.

Anthropic's answer: Don't force humans to read diffs to learn code; let AI generate on-demand explainers.

Before touching a module, ask AI for an explainer — minutes later you have a tutorial reflecting current code reality.

Advanced: AI generates small visual artifacts — call graphs, data flows — learn in your preferred style.

Collaboration in open channels; public work makes others' activity visible.

"A one-line copy change teaches you nothing, but an explainer for the module you're about to change teaches you a lot."

Java team adoption: wire internal AI with /explain <module> command; call chains, class diagrams, key design decisions generated instantly — far more effective than forcing juniors to chew stale PRs.

Of course, architectural/design-pattern changes still mandate human review — trivial diffs to machines fine, team consensus on overall architecture must stay human.

Eleven: Rollout Roadmap — Don't Deploy All Seven Layers at Once

You might want to transplant all seven layers immediately. Don't. Follow this cadence:

Phase 1: Foundations (Do Now)

PR template adds three fields: how tested / risk tier / rollback plan.

CI mandatory: lint + unit tests + build package; red blocks.

All review threads must resolve before merge. CODEOWNERS config: billing/auth/CI workflow paths require senior approval.

Phase 2: Introduce AI

Plug in an AI Reviewer (Claude Code Action or self-hosted).

Repo root gets concise CLAUDE.md + REVIEW.md.

Pilot on one non-core repo for weeks, tune REVIEW.md for noise, then expand.

Round cap = 3; >3 rounds escalates to human.

Phase 3: Advanced

Automate risk tiering (heuristic classifier enough, skip ML initially).

Merge Queue to prevent merge conflicts.

Core changes get Feature Flags + Canary.

Incidents → eval set: leaked bugs become reviewer regression cases.

Phase 4: Continuous Ops

Dual-metric dashboard: approval latency + revert rate.

Trusted author mechanism: stable contributors get lightweight path.

Veteran advice:

Tools before process — stabilize local AI review, security scans, CI gates first, then process redesign.

Strict first, loose later — risk tiering starts strict, low-risk scope small; run a while, if revert rate hasn't risen, gradually relax; never reverse .

Data-driven — stare at two metrics: human review time (efficiency) and production rollbacks (quality); never trade quality for speed.

Don't lead with AI Reviewer — if only two things, I'd do CODEOWNERS matrix and one-click rollback first. No safety net + automation = accelerating off a cliff.

Startup phase guard two bottom lines: False positive rate < 5%, review never blocks . Hold these; rest is incremental iteration.

Twelve: Pitfall Cheat Sheet

Final table for implementation reference:

1. Throughput explosion, human review can't keep up → Seven-layer defense + shift review left to pre-PR — Machines handle volume, humans handle risk

2. AI review high false positives → Multi-agent voting + behavioral verification + drop style — Verifiers need context isolation, else common-cause failure

3. Agents involution, no convergence → 3-round cap + incremental diff + fingerprint dedup + batch by category — 59% of alerts are old code; stop re-litigating

4. Legacy code repeatedly blames new author → git blame → Pre-existing tag + nightly stock scan — Old bugs aren't new author's fault

5. One-size-fits-all approval slows flow → Change-based tiering + sensitive path forced human + trusted whitelist — Tier by change, not author

6. Approval expiry / Bot padding numbers → Approval bound to commit SHA, new push invalidates; Bot never consumes slot — dismiss_stale_reviews=true 7. Individual green, merge red → Merge Queue re-validates on latest main + binary search — Serialize for consistency

8. Escaped bug in production → Flag instant-kill + internal dogfood + staged rollout — Rollback-ability enables speed

9. Reviewer self-degrades → Incidents → eval set + daily scoring gate — Treat prompts as code

10. "Fake savings" trap → Guardrail metrics: revert rate / incident rate — Rise = cost shifting, not saving

11. Knowledge transfer broken → On-demand explainer + open channels + arch changes forced human — Learning method changed, not stopped

12. LLM and Linter fighting → Deterministic → SAST, Non-deterministic → LLM — Single ownership, no turf war

Closing

Compress the whole piece into five sentences:

Review is risk management, not gatekeeping — don't ask "did someone read it", ask "which risk belongs to which layer".

Machines read code, humans read risk; ship fast, roll back faster.

Convergence is the lifeline of Agent systems — without convergence mechanics, saved human hours get burned by two AIs fighting each other.

Guardrails are anti-cheat — if revert rate rises, saved review time just moved to firefighting.

Capability grows with guardrails — before circuit breaker ready, don't hype zero-human merge.

Source: Anthropic official blog "How the Claude Code team does code review" (Addy Osmani, Morgan Westlee Lunt, Qing Wang). Original: https://claude.dev/blog/solving-code-review-at-anthropic/

Review's essence is risk management, not ritual. Automate everything automatable; reserve humans for where judgment is truly needed.
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

JavaCI/CDAI code reviewmulti-agent systemfeature flagsAnthropicmerge queuerisk-based approval

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion