12/12
Technical Architecture & AI Engineering · 7 min read

AI Code Review Audit: Cutting Over-Engineered AI Abstraction Bloat and Swallowed Errors

Eliminate speculative AI-generated AbstractFactory hierarchies, pass-through DTO mappers, and silent try/catch blocks to cut PR size by 50% and keep services debuggable at 2 AM.

Why This Matters at Engineering Leadership Scale

Because AI generates boilerplate instantly, PR sizes across many teams have jumped 40% to 80% while real feature delivery stayed flat. Left unchecked, AI defaults to six files, an AbstractWebhookProcessor, a WebhookProcessorFactory, duplicate DTO mappers, and defensive try/catch blocks that silently return null on failure.

At leadership scale, abstraction bloat is a reliability risk, not a style preference. Bloated 600-line diffs exhaust reviewers so real IDOR or concurrency bugs slip through. Worse, AI's "defensive" catch blocks swallow database outages and return 200 OK, causing silent data loss that surfaces weeks later during customer escalations.

Core Mental Model & Framework

Apply the "2 AM Debug Test" to every abstraction in an AI-assisted PR: "If we are paged at 2 AM, does this abstraction make the failure clearer or harder to trace?"

AI Bloat PatternWhy AI Generates ItProduction CostExact Refactoring Action
Single-impl interfaces & AbstractFactory (WebhookProcessorFactory for 1 provider)Mirrors textbook Java/C# patterns4 extra files of indirection; reviewer fatigueDelete factory & interface; write one direct function until a second real provider exists
Pass-through DTO mappers (mapInput -> mapCommand -> mapEntity)Prompt mentioned "clean architecture"Duplicates fields across 3 layers; silent field dropsValidate once with Zod at the boundary and pass typed objects directly
Swallowed errors in try/catch (catch (e) { console.error(e); return false; })AI tries to "prevent crashes"Turns DB outages into 200 OK; breaks webhook retries & alertsDelete speculative catch blocks inside helpers; propagate errors to central HTTP error middleware
Local EventEmitter inside CRUDSpeculative decouplingBreaks stack traces and linear flowCall downstream steps sequentially with explicit await

Step-by-Step Implementation Tutorial

1. Count Real Implementations Before Reading Line 1

Inspect the file tree first. If you see Abstract*, Base*, *Factory, or I*Handler backed by only one real implementation (not an explicit test seam like Clock), flag it for deletion immediately.

2. Audit the Bloated AI Diff vs. the Direct Refactored Handler

typescript
// =========================================================================
// BLOATED AI-GENERATED DIFF (DO NOT APPROVE)
// Single-implementation factory boilerplate + two swallowed-error bugs
// =========================================================================
export abstract class BaseWebhookProcessor<T> {
  abstract canHandle(eventType: string): boolean;
  abstract process(payload: T): Promise<boolean>;
}

class JiraPayloadMapper {
  map(raw: any): JiraIssueEvent | null {
    try {
      return { eventId: raw.id, tenantId: raw.tenantId, key: raw.issue.key, status: raw.issue.fields.status.name };
    } catch (err) {
      // BUG 1: Swallows bad payload silently and masks 400 error
      console.error("Mapping failed", err);
      return null;
    }
  }
}

class JiraComplianceProcessor extends BaseWebhookProcessor<JiraIssueEvent> {
  constructor(private readonly db: Pool) { super(); }
  canHandle(eventType: string) { return eventType === "jira:issue_updated"; }
  async process(evt: JiraIssueEvent): Promise<boolean> {
    try {
      await this.db.query(
        `INSERT INTO compliance_events (tenant_id, event_id, issue_key, status)
         VALUES ($1, $2, $3, $4) ON CONFLICT (tenant_id, event_id) DO NOTHING`,
        [evt.tenantId, evt.eventId, evt.key, evt.status]
      );
      return true;
    } catch (err) {
      // BUG 2: Swallows Postgres outage! Handler returns 200 OK so Jira never retries!
      console.error("DB insert failed", err);
      return false;
    }
  }
}

class WebhookProcessorFactory {
  private readonly list: BaseWebhookProcessor<any>[];
  constructor(db: Pool) { this.list = [new JiraComplianceProcessor(db)]; }
  get(type: string) { return this.list.find((p) => p.canHandle(type)) ?? null; }
}

export async function handleJiraWebhook(req: AuthenticatedRequest, res: Response, db: Pool) {
  const proc = new WebhookProcessorFactory(db).get(req.body?.webhookEvent);
  if (!proc) return res.status(200).json({ ignored: true });
  const mapped = new JiraPayloadMapper().map(req.body);
  if (!mapped) return res.status(200).json({ skipped: true });
  await proc.process(mapped);
  return res.status(200).json({ ok: true }); // Always 200 even when DB is down!
}

Now look at the refactored diff: 55% fewer lines, zero speculative classes, strict Zod validation, and clean error propagation to central error middleware (500) so Jira automatically retries after a DB blip.

typescript
// =========================================================================
// FIXED REFACTORED DIFF
// Direct, readable, zero swallowed errors, 55% smaller diff, full coverage
// =========================================================================
import { z } from "zod";

const JiraIssueWebhookSchema = z.object({
  id: z.string().min(1),
  webhookEvent: z.string(),
  issue: z.object({
    key: z.string().min(1),
    fields: z.object({ status: z.object({ name: z.string().min(1) }) }),
  }),
});

export async function handleJiraWebhook(
  req: AuthenticatedRequest, res: Response, next: NextFunction, db: Pool
) {
  try {
    if (req.body?.webhookEvent !== "jira:issue_updated") {
      return res.status(200).json({ status: "ignored" });
    }

    const parsed = JiraIssueWebhookSchema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: "Invalid webhook payload" });

    const { id: eventId, issue } = parsed.data;
    const tenantId = req.auth.tenantId; // Derived from verified webhook signature

    // Let DB outages bubble to next(err) -> 500 so Jira retries safely
    const result = await db.query(
      `INSERT INTO compliance_events (tenant_id, event_id, issue_key, status)
       VALUES ($1, $2, $3, $4)
       ON CONFLICT (tenant_id, event_id) DO NOTHING RETURNING event_id`,
      [tenantId, eventId, issue.key, issue.fields.status.name]
    );

    const status = result.rowCount === 0 ? "duplicate" : "recorded";
    return res.status(200).json({ status, eventId });
  } catch (err) {
    return next(err); // Central error middleware logs structured error + returns 500
  }
}

3. Coach Your Tech Lead Without Micromanaging Every PR

When a Tech Lead approves two bloated 500-line AI PRs, pair for 15 minutes on one merged PR and ask: "If we debugged this at 2 AM, which abstractions actually earn their keep, and what happens if Postgres drops inside that catch?" Then let the Tech Lead codify a 2-line PR norm banning single-implementation factories and silent catch blocks.

Worked Production Scenario: Before vs. After

Context: A compliance squad engineer opened a 650-line AI-generated Jira webhook PR across 7 files (AbstractWebhookHandler, WebhookProcessorFactory, JiraEventMapper, wrapper services). Buried inside the bloat were a missing tenant_id check and a catch { return false; } that silently dropped 41 compliance events during a 10-second staging DB failover.

After: During a 15-minute audit, the team deleted 240 lines of unused factory/mapper boilerplate and removed the swallowing catch blocks, landing a direct 180-line handler with 5 real integration tests.

MetricBeforeAfter
PR diff size & file count650 lines / 7 files180 lines / 2 files (-72%)
Dropped events during 10s DB failover41 lost (200 OK)0 lost (500 -> retried)
Reviewer audit time48 minutes (high fatigue)9 minutes (clear flow)
Bloated AI PRs approved next 2 sprints2 / sprint0

Common Failure Modes & Anti-Patterns

  1. Swallowing errors in helpers to "be safe": Returning null or false inside catch turns DB outages into silent data loss and suppresses alerts. Fix: Catch only to recover meaningfully, add domain context before re-throwing, or respond in central error middleware.
  2. Building a "Plugin Factory" for hypothetical providers: Speculating on future GitHub/Linear webhooks before requirements exist almost always guesses the wrong interface. Fix: Apply the Rule of Three - write direct functions for provider #1 and extract a shared interface only once provider #2 or #3 reveals the true seam.
  3. Rewriting bloated PRs yourself as the manager: Fixes one branch fast but turns you into a permanent bottleneck. Fix: Leave concrete comments explaining the 2 AM debug and retry failure risks, and let the author refactor in 25 minutes.

How to Handle Pushback in the Room

Skeptical Senior Engineer: "Deleting WebhookProcessorFactory violates Open/Closed Principle - what if Product adds GitHub webhooks next quarter?"

Calm Response: "Adding a direct handleGitHubWebhook function behind /webhooks/github is already open for extension and takes ten minutes when funded. Paying a 240-line indirection tax today slows every review now and usually guesses the wrong abstraction anyway."

Busy Tech Lead: "Copilot wrote those classes in ten seconds and tests pass - why spend 25 minutes refactoring working code?"

Calm Response: "Code is generated in ten seconds and read fifty times over two years, including during 2 AM outages. Deleting dead wrappers and silent catch blocks cuts review fatigue in half and keeps real bugs from hiding inside boilerplate."

Key Takeaways & This Week's Action Rep

  • Apply the 2 AM Debug Test: Delete single-implementation factories, interfaces, and identical pass-through mappers.
  • Ban silent error swallowing: Never allow catch (e) { console.error(e); return false/null; } in business helpers.
  • Shrink AI diffs to improve bug detection: Cutting 50% of boilerplate directly raises reviewer accuracy on security and race conditions.
  • Coach Tech Leads via 15-minute pairing: Build a shared squad standard instead of taking over PRs yourself.

This Week's Action Rep: Pick one recently merged AI-assisted PR over 300 lines. Pair with your Tech Lead for 15 minutes to cut speculative abstractions and silent catch blocks, and add "No single-implementation factories; no silent catch blocks" to your PR norm.