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

Agent-Driven Code Governance: 43% Business Code Reduction in Tencent Backend

Tencent's advertising team built an agent-based continuous code governance process that reduced business code by 43.42%, improved architecture health from 53.5 to 69.1, cut microservices from 25 to 16, and eliminated 85% of unreferenced functions through scheduled scanning, rule-based agent execution, and automated line-by-line review with deterministic evidence.

Background: Code Entropy in Long-Lived Backend Systems

Long-term iteration in engineering leads to layer violations, deepening module coupling, and accumulation of dead code — collectively called code rot or "entropy increase." The adoption of AI coding tools accelerated code production but also sped up dead code accumulation. Traditional periodic manual reviews and dedicated refactoring projects suffer from late detection, deferred scheduling, and high verification costs. Moreover, dead code harms coding agents by polluting context, mixing obsolete logic into retrieval results, and causing agents to reference deprecated patterns.

The team observed that dead code continuously regenerates: deleting an interface makes its sole callers unreferenced, creating new dead code. Therefore, they turned governance into a scheduled, multi-round, incremental agent process.

Overall Approach: Four Pillars

1. A Ruler: Ideal Layering and Health Scoring

Humans define an ideal layering (e.g., interface layer only validates and orchestrates; cross-service logic in business layer; DB access in data layer; common utils contain no business logic). A health score (0–100) is computed from 6 dimensions and 18 sub-dimensions via static scans:

Functional Layering (20%): layering violations, directory/responsibility misplacement.

Service Design (18%): duplicate interfaces, missing implementation layers, deep nesting, private protos.

Service Dependencies (12%): cross-service code references, dependency cycles, direct DB/middleware access.

Code Robustness (22%): large files/functions, cyclomatic complexity, deep nesting, duplicate blocks, similar functions/structs, static analysis issues.

Code Timeliness (18%): unreferenced functions, structs, variables, constants.

Observability & Fault Tolerance (10%): raw logs, missing monitoring, ignored errors, missing goroutine recovery, lost error wrapping, empty contexts.

Scoring uses a three-step method: (1) compute issue density per sub-dimension (issues/total), (2) map density to score via fixed anchor points (0%→100, 1%→95, 3%→90, 6%→80, 10%→70, 20%→60, 35%→40, 50%→20, 100%→0) with linear interpolation, (3) weighted average across sub-dimensions and dimensions. Every issue is tied to concrete file, function, line number — no evidence, no task.

2. A Sequence: Align First, Then Outside-In

Align first: flatten directories, merge duplicate data layers, unify interface definition locations, eliminate reverse dependencies. This step barely reduces code but makes subsequent scans more accurate and deletion boundaries clearer.

Then outside-in: whole service → zero-traffic interfaces → static dead code (functions, structs, variables, constants) → dynamic dead code → duplicate/similar code merging. Outer-layer deletions release inner-layer dead code for the next scan round. Static before dynamic because static dead code is decidable from source alone, with clear boundaries and low risk.

3. A Boundary: Humans Set Rules, Agents Execute Within Rules

Humans define rules: what counts as deletable (conditions and exclusions), what evidence proves safety (review rules), which changes require human sign-off (billing, permissions, schema). These are high-risk, accountable judgments codified as reviewable, revisable rules.

Agents decide what to change: scanning identifies rule matches, splits into independent tasks by risk level (R1–R4); code modification chooses exact lines and cleans related references; review agent verdicts each changed line with evidence. These judgments are high-volume and repetitive, suited for agents.

Agent decisions are constrained by three guardrails: (1) No crossing boundaries — only rule-matched code is proposed, no edits outside task scope, agents never modify rules. (2) Evidence required — every decision maps to file, function, line with verifiable deterministic evidence; lines without evidence are rejected. (3) Independent review — code modification and review are done by separate agents; lines lacking evidence go to humans; sensitive areas force human confirmation.

Rules evolve only through human maintenance. False positives/negatives and doubts found during execution are assessed by humans to decide rule revisions. Agent capability improves via human rule updates, not self-adjustment.

4. A Closed Loop: Scheduled Continuous Operation

The loop runs on a schedule: Scheduled Scan (Architecture Optimization Agent runs scan rules, scores full codebase, creates/updates tasks by diffing against previous run) → Task Splitting (same agent grades risk R1–R4, breaks large tasks into independent parallel units) → Code Modification (Task Execution Agent deletes/migrates code, cleans references and tests, creates MR after compile+test pass) → Review (Review Agent periodically pulls pending MRs, applies review rules line-by-line with evidence; only fully evidenced MRs pass, others escalate only doubtful lines to humans) → Replay Verification (few cases) (Replay Verification Service compares new/old responses on sampled production traffic for logic-changing tasks) → Rule Revision (Humans inspect review doubts and false positives, update scan/review rules; agent capability iterates via rule changes).

The review agent is used because architecture optimization MRs are numerous, large, and similar; their correctness is largely provable with deterministic evidence (reference counts, equivalence checks, config values, traffic data). Line-by-line evidence-based review is cheaper than human reading. Replay verification is reserved for logic changes; entropy-reduction tasks mostly delete/move code with expected behavioral equivalence.

Industry Comparison: Architecture Optimization Agent vs. Google Sensenmann vs. Meta SCARF

Sources: Google Testing Blog "Sensenmann: Code Deletion at Scale" (2023); Will Shackleton et al., "Dead Code Removal at Meta: Automatically Deleting Millions of Lines of Code and Petabytes of Deprecated Data," ESEC/FSE 2023; Meta Engineering blog "Automating dead code cleanup" (2023).

What it does: Architecture Optimization Agent — 6-dim health scoring; layer alignment, service/interface retirement, static/dynamic dead code cleanup, duplicate detection; task splitting, agent code change, review agent line-by-line verification. Sensenmann — finds code not linked into any binary or long-unrun; auto-proposes deletions. SCARF — identifies and deletes deprecated product code and data (including DB tables) together; includes product retirement workflow.

Decision basis: Architecture Optimization Agent — type-based reachability, AST references, 180-day call volume, feature flag values, production coverage. Sensenmann — build dependency graph + binary run logs. SCARF — symbol dependency graph + production usage data + application semantics.

Deletion granularity: Architecture Optimization Agent — service, interface, function, struct, logic branch. Sensenmann — build target (library, binary). SCARF — symbol, file, data table.

Scale: Architecture Optimization Agent — single Go repo ~1M lines, net ~300k lines removed. Sensenmann — billion-line monorepo, ~5% of C++ deleted. SCARF — 5 years, >100M lines auto-deleted.

Strengths: Architecture Optimization Agent — beyond deletion: governs layering and service structure, continuous health metric; fine-grained to function/branch; low integration cost (existing monitoring + config center); agents clean references and tests together. Sensenmann — simple, reliable signal ("not linked, not run"); proven at scale and duration. SCARF — deletes code and data together; combines static, dynamic, app semantics; high-confidence languages can auto-merge without review.

Weaknesses: Architecture Optimization Agent — validated on one Go repo only; every MR needs review agent verification, no auto-merge; no data asset deletion; dynamic dead code and duplicate merging just starting. Sensenmann — requires Bazel build graph and unified run logs; granularity stops at build target, cannot delete functions/branches; only deletes, no structural governance. SCARF — depends on Glean indexing and internal infra, high build-out cost; only dead code/data, no architecture structure.

Summary: Sensenmann suits large monorepos with unified build/run logs, reliable but coarse; SCARF suits product retirement with code-data coupling, highest automation but heavy infra; Architecture Optimization Agent targets single microservice repos, low integration cost, fine granularity, and covers structural governance.

Case Study: Material Library Backend (May–Oct 2026)

The material library manages ad creatives (upload, storage, transcoding, tagging, review) and serves the ad delivery system. Its Go microservice repo had ~1.009M lines (.go/.proto/.sh), ~254k business lines (excluding proto and tests), 25 microservices across 6 mid-level directories, two duplicate data layers, 56 circular dependencies, 1,094 unreferenced functions, health score 53.5.

Quantitative Results (Oct 15 vs. May 1, same scan rules)

All code lines: 1,008,707 → −300,105 (−29.75%)

Excluding proto: 631,055 → −234,265 (−37.12%)

Business code (excl. proto & tests): 254,235 → −110,380 (−43.42%)

Architecture health: 53.5 → 69.1 (+29.15%)

Microservices: 25 → 16 (−36%)

External interfaces: 483 → 291 (−40%)

Cross-module circular deps: 56 → 10 (−82%)

Unreferenced functions: 1,094 → 161 (−85%)

Cross-service direct code refs: 122 → 36 (−70%)

Net deletion lines are from governance MRs (deletions minus additions). New business features (Material Agent, Creative Asset Library) launched concurrently; their additions are not subtracted. Direct version comparison shows business code dropped from ~254k to ~165k lines (~35% reduction).

Health Score Evolution by Dimension

Functional Layering: 41.1 → 75.5. Main driver: directory flattening, data layer merge, business code moved out of common packages.

Service Design: 36.1 → 67.2. Main driver: 9 services retired, ~200 interfaces removed.

Service Dependencies: 57.4 → 54.1. Cross-service refs and cycles reduced, but service count dropped faster, raising cycle-ratio from 36% to 43.8%; slight decline.

Code Robustness: 73.7 → 77.1. Duplicate/similar code scanned but not yet merged; large files remain.

Code Timeliness: 63.5 → 73.5. Mass cleanup of unreferenced functions, structs, constants.

Observability & Fault Tolerance: 42.8 → 51.9. Not covered in this round.

Sources of Code Reduction

Structure alignment — net negative (migration/merging), but enabled accurate later scans.

Whole service / zero-traffic interface retirement — large deletions in all-code metric (interface defs, generated code, tests removed together); smaller share in business code.

Static dead code cleanup — largest contributor to business code reduction; many functions became unreferenced only after outer interfaces/services were removed.

Dynamic dead code — only 3 pilots so far; low line count but high entropy value (see §7).

Duplicate/similar code merging — scanned, not yet executed.

Timeline of Health Score and Key Actions

May 1: 53.5 (baseline) — 25 services / 483 interfaces / 1,094 unref funcs

Jun 1: 55.0 — May: decouple reverse deps, externalize hardcoded data — 24 / 483 / 1,131

Jul 1: 66.6 — Jun: retire 8 zero-traffic services; flatten dirs; merge two data layers; unify interface defs; first zero-traffic interface wave — 16 / 331 / 1,510

Aug 1: 67.2 — Jul: first static dead function wave; first feature-flag cleanup; test framework migration — 18 / 335 / 734

Sep 1: 66.3 — Aug: second zero-traffic interface wave; whole service retirements — 16 / 287 / 934

Oct 1: 68.4 — Sep: second static dead function wave; three feature-flag categories; unreferenced structs/constants; first dynamic dead code pilot — 16 / 291 / 473

Oct 15: 69.1 — Oct: third static dead function wave; third dynamic dead code pilot — 16 / 291 / 161

Key observations: (1) Biggest jump (+11.6) during alignment phase (Jun–Jul), contributing 75% of total gain. (2) Post-Jul, slow climb (66–69) as static dead code cleanup concentrated in Sep+ while new business features introduced fresh issues. (3) Unreferenced functions rose to 1,510 by Jul 1 because service/interface retirements orphaned their callees; subsequent waves brought them down.

Layer-by-Layer Technical Implementation

1. Alignment: Put Code Back Where It Belongs

Scan violations via text search (lower-layer imports upper, non-data-layer DB access, cross-service imports) and build service dependency graph from imports to detect cycles. Migrate with git mv to preserve history, batch-update import paths, move protos to top-level and regenerate stubs. Verify with compile, static checks, tests.

2. Whole Service & Zero-Traffic Interface Retirement

Criterion: zero calls in last 180 days (daily query, any day with calls retains). 180 days covers quarterly/holiday low-frequency scenarios.

Process: delete interface definition → regenerate code → delete implementation → fix compile errors at registration/call sites. If all interfaces of a service are zero-traffic, retire the whole service.

Cascade: deleted interfaces leave internal callers unreferenced → become static dead code for next layer.

Tech: extract registered HTTP routes from tRPC generated code; query monitoring platform daily for 180 days, union; diff against full set; flag sparse-call interfaces as low-frequency (observe only).

3. Static Dead Code

Only source analysis needed; clear boundaries; done before dynamic.

Unreferenced functions: from all entry points (main, init, package var initializers, interface methods, reflection-by-name), propagate reachability via call graph using Go type information (go/types) at object level (not name). Unreachable = dead. Single pass finds whole dead call chains. Tests do not count as references — only business code calls count; dead function's tests are deleted together (explains high test deletion ratio).

Unreferenced structs/variables/constants: AST-based (go/ast) type-reference counting (field types, params, composite literals, type assertions). Classified into: directly deletable, only referenced in tests, only in generated code.

Multi-round necessity: outer-layer retirements (interfaces, dynamic dead code) create new unreferenced code; re-scan after each outer wave.

Go's official deadcode tool overlaps ~90% on function-level; custom build adds struct/var/const tracking and connected-component task splitting.

4. Dynamic Dead Code (Branch-Level)

Code with source references and compile-time reachability but never executed in production. Requires runtime data.

Feature-flag branches after full rollout: pull live config from config center; auto-discover ~10 flag-evaluation functions; map call sites to config items; evaluate actual matching logic to determine always-on/always-off; exclude kill-switch, fallback, emergency flags; delete dead branch and flag check.

Zero-coverage code: deploy coverage-instrumented build; collect execution counts; find zero-coverage functions and zero-count blocks within executed functions; require consistency across ≥2 instances; error fallbacks, default, panic-recovery marked for business confirmation.

Staged removal: entry points first return explicit error; confirm no residual traffic; then physically delete.

5. Duplicate & Similar Code Merging (Scanned, Pending Execution)

Detected every scan, fed into Code Robustness score. Deferred until after dead code cleanup to avoid merging soon-to-be-deleted code.

Duplicate code blocks (token-level): token sequence match, >50 tokens identical. Scan result (Oct 15): 177 files (was 362), 27.6% of Go files.

Similar functions (semantic): semantic vector 40% + call-chain 25% + control-flow skeleton 20% + signature 15%; composite confidence ≥90%. Scan result: 225 pairs (was 385), 74 cross-file, 97 with confidence ≥95%.

Similar structs (semantic): semantic vector 35% + field-type combo 30% + field-name 20% + field-count 15%; only structs with ≥4 fields. Scan result: 81 pairs (was 71), 77 cross-file, 43 with confidence ≥95%.

Examples: two DB driver dirs each had identical connection-string building, init, index-rename functions; two video service clients defined same upload-completion request struct; client layer and a service's model layer defined identical image-query struct. Similar struct count didn't drop with code removal because new business added new structs — this problem recurs continuously.

Planned execution: (1) Scan: token duplicates + semantic similarity with call-chain/control-flow/signature/fields. (2) Filter & confirm: keep high-confidence cross-file candidates; human confirms same business semantics. (3) Merge & review: place common code per ideal layering; agent extracts common impl, replaces callers; review agent verifies behavioral equivalence line-by-line.

6. Review: Review Agent Periodic Line-by-Line Verification

Agent-submitted MRs are not human-read line-by-line. Review Agent pulls pending MRs on schedule, applies human-defined review rules. Goal: "no missed judgments."

Line coverage: every changed line gets a verdict; line-by-line ledger ensures 100% coverage, no sampling.

Evidence first: safety verdict requires verifiable deterministic evidence: multi-env config actual values, 180-day traffic union, AST reference counts, compile/test results, AST equivalence before/after migration. "Looks fine" is not evidence.

One-veto: only if all lines have evidence does MR pass; any line without evidence → whole MR to human, with doubtful lines commented by file/line.

Tool failure = no pass: if config center, monitoring, compiler, etc. unavailable, affected lines treated as "no evidence," not default-pass.

Evidence per task type:

Feature-flag retirement: live/pre-prod/sandbox config actual values; empty-value behavior; post-deletion control-flow direction matches value.

Zero-traffic interface: monitoring 180-day daily traffic union; no residual route registration.

Dead code / unreferenced symbols: AST reference count = 0; supplementary scan for reflection, config-driven, generated-code references.

File/function split, directory migration: symbol set and function body structure identical pre/post; imports closed; compile passes.

Proto migration & codegen: generated code matches re-generated from proto; external routes and field numbers unchanged.

All types: per-package compile, static check, format check, tests pass (flaky tests re-run multiple times).

Reference judgment always uses AST, not text search (text cannot distinguish comments, strings, same-name symbols). Platform AI review serves only as fallback signal: hits → human confirm; no hit → not evidence of safety. Mandatory human confirmation for lines touching money, billing, permissions, auth, crypto, rate-limit thresholds, DB schema.

Challenges and Solutions

Proving code truly unused: source may show no refs but runtime reflection/config-driven/serialization may invoke; source shows refs but production never executes. Solution: separate static and dynamic evidence, cross-validate. Static analysis uses type-object matching, treats reflection calls and interface implementations as liveness roots. Dynamic evidence requires multi-instance consistency.

Preventing agent from deleting live code: agent decides what to change; errors possible; untraceable decisions hinder postmortem. Solution: human rules set boundaries; agent stays inside; every decision carries verifiable evidence; separate agents for code change and review; no-evidence lines escalate to humans.

Dynamic data completeness: traffic and coverage depend on collection; low-frequency scenarios (quarterly events, special customer flows) may be missed. Solution: zero-traffic = 180 days no calls; coverage requires multi-instance, multi-build consistency; no conclusion when data incomplete.

Delete one, break many: dead functions call each other; deleting one causes compile errors; large single changes hard to review. Solution: compute connected components via call graph among dead code; each component = one task; verify each task independently compilable, mergeable, rollbackable.

Existing tools limited: official deadcode finds unreachable functions but misses exported structs/vars/consts; no task splitting, no evidence; zero-traffic, feature-flags need live data — static tools can't produce. Solution: function-level can use or cross-check official tool; rest custom-built (reference stats, task splitting, evidence collection; ablation study in §4).

Feature-flag misjudgment: ~10 different flag-evaluation function styles; config formats vary (allowlist, suffix, wildcard); literal value inspection error-prone. Solution: auto-discover all flag functions; unregistered ones human-confirmed then added; evaluate using actual matching logic; verify pulled config count matches config center total.

Review workload: agent produces MRs fast; large deletions, similar content; human line-by-line reading slow. Solution: review agent scheduled rule-based line-by-line verification; every line needs deterministic evidence else whole MR to human with only doubtful lines listed; runtime deletions first return error; replay verification only for logic-changing tasks.

Duplicate merge trade-offs: similar functions/structs may belong to different businesses, diverge later; mechanical merge increases coupling; merge changes callers, riskier than delete. Solution: do after dead code cleanup to avoid merging soon-to-be-deleted code; only high-confidence cross-file candidates listed; human confirms same business semantics before task creation.

New cleanable code appears after cleanup: deletions cascade-release new deletable code; concurrent new business generates fresh dead code. Solution: scheduled scans, multi-round iterations; diff against previous run to only add/update tasks; unified score tracks trend.

Next Steps: Dynamic Dead Code Governance & Duplicate Merging

Current deletions are mainly static dead code and zero-traffic interfaces — clear boundaries, deterministic evidence. Dynamic dead code (source-reachable, compile-reachable, never executed in production) is considered highest-value:

Interleaved with live code: static dead code often in isolated blocks; dynamic dead code sits inside daily-executed functions, mixed in same if/else, forcing developers to constantly discern active branches.

Generated by user behavior shifts: when users stop using a feature, its handling logic stops executing but rarely gets cleaned. Faster product evolution → faster accumulation.

Invisible to conventional methods: static analysis sees references; code review sees normal business branches; only production data reveals non-execution.

Cascades downstream: deleting a branch often orphan its called functions, used structs, config items → triggers new static dead code wave.

Typical sources and evidence:

Feature-flag full-rollout old branch: flag fully on/off, other if/else branch never runs — evidence: config center live values.

User-abandoned behaviors: entry exists but users no longer use certain operation/parameter combo (upload method, material format, filter) — evidence: production coverage + business telemetry.

Legacy compatibility logic: branches for old client versions, data formats, protocol fields; old versions have zero traffic — evidence: production coverage + request version distribution.

Retired business residual branches: interface reused by other features, but internal branches for retired business/stopped partner channels never execute — evidence: production coverage.

Post-migration dual read/write: after storage migration, read/write to old storage remains — evidence: production coverage + old storage access volume.

One-off campaigns / temporary logic: event-ended campaign logic or temporary data-fix special handling not reclaimed — evidence: production coverage + event timeline.

Unused parameter/config branches: code supports multiple enum values/config combos; production only uses a subset — evidence: production coverage + request parameter distribution.

Error fallbacks, degradation, emergency kill-switch branches with zero coverage are normal and retained.

Roadmap

Expand collection: deploy coverage-instrumented builds on core services; accumulate long-window data covering quarterly/low-frequency scenarios.

Refine to branch-level: extend from function-level to branch-level, finding never-entered branches inside executed functions.

Fuse business data: combine business telemetry and request param distributions to distinguish "user no longer does this" from "inherently low-frequency" — latter retained.

Staged removal: entry points first return explicit error; observe; then physical delete.

Chain to static cleanup: after dynamic dead code removal, re-scan static dead code for next round.

Then merge duplicates: once dead code cleanup converges, execute duplicate/similar merging per §5.5 steps.

About this article

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

static analysisdynamic analysisdead code eliminationcode review automationagent-based automationarchitecture health metricscode governancemicroservice refactoring

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion