惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MyScale Blog
MyScale Blog
G
Google Developers Blog
B
Blog
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
V
Vulnerabilities – Threatpost
H
Hacker News: Front Page
T
Tor Project blog
P
Proofpoint News Feed
P
Privacy International News Feed
Recorded Future
Recorded Future
F
Fortinet All Blogs
量子位
博客园 - 聂微东
月光博客
月光博客
博客园 - Franky
SecWiki News
SecWiki News
G
GRAHAM CLULEY
腾讯CDC
Know Your Adversary
Know Your Adversary
宝玉的分享
宝玉的分享
The Cloudflare Blog
美团技术团队
小众软件
小众软件
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Threatpost
爱范儿
爱范儿
A
Arctic Wolf
博客园 - 叶小钗
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Project Zero
Project Zero
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
J
Java Code Geeks
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园 - 三生石上(FineUI控件)
PCI Perspectives
PCI Perspectives
Latest news
Latest news
V
V2EX
罗磊的独立博客
T
Threat Research - Cisco Blogs
Scott Helme
Scott Helme
S
Security Affairs
S
SegmentFault 最新的问题

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
How to read any legacy codebase. The archaeology playbook.
GDS K S · 2026-05-17 · via DEV Community

How to read any legacy codebase. The archaeology playbook.

Somewhere on a hard drive sits a folder of low resolution scans of Russian typewritten pages from the 1950s. The pages describe PP-BESM, the first high level programming language compiler ever built in the Soviet Union, designed by Andrey Ershov. A developer who goes by xavxav is rebuilding it. Not emulating it. Rebuilding it, line by line, from the scans. The repo is real, the VM runs, the PP-3 phase has an initial pass. You can clone it.

That project is the extreme version of every "I cannot read this codebase" problem you will ever have at work. Same shape, more dust. The PP-BESM author published a writeup last month that, once you strip the Cold War aesthetic, reads like the cleanest manual on legacy codebase archaeology I have read in years.

This article is that manual, generalized, with the techniques you can apply this week on whatever inherited PHP, COBOL, Perl, or Java 6 repo is currently your problem.

TL;DR

Stage What you do Why
1. Boundaries map inputs, outputs, side effects you cannot understand the inside until you know the outside
2. Harness build a way to run the code in isolation the loop is the whole game
3. Bisection narrow the search to the load bearing 10 percent most code is glue
4. Naming rename systematically as you understand you are leaving notes for future you
5. Types add types where there are none, even loose ones types are documentation that runs
6. Tests as ground truth write tests that lock in observed behavior refactoring without tests is fiction
7. Document negotiations comment the why, never the what the why is what time erases

The order matters. Skipping ahead is how teams spend six months on "modernization" and end up with a worse version of the same system.

1. Boundaries before internals

The first move on any unfamiliar codebase is not to read the code. The first move is to draw the boundary.

For a web service: what HTTP routes exist, what does each one return, what database tables get touched, what external APIs get called, what writes to disk, what fires events. For a CLI: what arguments does it accept, what files does it read, what does it write, what is the exit code matrix. For a library: what is the public API, what does it depend on, what does it monkey-patch.

You can do this without understanding a single function inside the code. The tools:

# HTTP routes for a Node service
grep -rE "router\.(get|post|put|delete)|app\.(get|post)" --include="*.{js,ts}" src/

# Database tables touched
grep -rE "FROM|UPDATE|INSERT INTO|DELETE FROM" --include="*.{sql,js,ts,py}" .

# External API calls
grep -rE "axios|fetch\(|http\.request" --include="*.{js,ts}" src/

# Files read or written
grep -rE "fs\.(read|write)|open\(" --include="*.{js,ts,py}" .

Enter fullscreen mode Exit fullscreen mode

Write the answers down. This is your map. You cannot understand the internals until you know where the doors are.

For the PP-BESM project, the boundary was the BESM machine model. You cannot read a 1955 compiler without knowing the instruction set of the machine it targets. xavxav reconstructed that from a separate set of documents before touching the compiler source. Same pattern, smaller stakes.

2. Build a harness, even a bad one

The highest payoff move on a legacy codebase, by a wide margin, is to get any version of the code running in isolation, with one input and one observable output, before you try to understand any of it.

For a web service, that means a docker-compose that spins up the app and its database with a single command, with one curl that exercises one route. For a CLI, that means a one-liner that runs the binary with a representative input and pipes the output somewhere you can read it. For a library, that means a five line consumer that imports the library and calls the one function you care about.

If this is impossible, the rest of the audit will also be impossible. Spend a day building the harness. It is the loop.

# A minimal harness for a legacy Python script
mkdir -p harness
cat > harness/run.sh <<'EOF'
#!/bin/bash
cd "$(dirname "$0")/.."
python3 ./scary_script.py --input fixtures/sample.csv > /tmp/out.txt
diff /tmp/out.txt fixtures/expected.txt
EOF
chmod +x harness/run.sh

Enter fullscreen mode Exit fullscreen mode

You now have a one-command loop. Every change you make from here on can be tested against harness/run.sh. The harness is your safety net.

xavxav's harness for PP-BESM is the BESM virtual machine he built. Every change to the compiler can be tested by running a tiny Soviet-era program inside the VM and watching the result. The VM is more important than any single piece of the compiler source.

3. Bisection beats reading top to bottom

The instinct on a new codebase is to read the entry point and follow the call graph. This is wrong almost every time. Most legacy code is glue. The interesting logic, the part that actually does the work, lives in 10 to 20 percent of the files. The other 80 to 90 percent shuffles data between the interesting parts.

The fastest way to find the interesting parts is bisection.

# What touched the database in the last year?
git log --since="1 year ago" --name-only --pretty=format: \
  | grep -E "schema|migration|model" | sort -u

# Where do the longest files live? long usually means interesting
find . -name "*.py" -not -path "*/node_modules/*" \
  -exec wc -l {} \; | sort -rn | head -20

# What gets imported the most? heavily imported usually means load bearing
grep -rE "^import|^from" --include="*.py" . | awk '{print $2}' \
  | sort | uniq -c | sort -rn | head -20

Enter fullscreen mode Exit fullscreen mode

Each of those commands narrows the search. The longest file is often the dumping ground. The most imported module is often the actual brain of the system. The files that show up in every migration are the ones the schema can't live without.

For PP-BESM the bisection target was PP-3, the last compiler phase. xavxav knew the early phases were better documented in the existing literature. The interesting unknown was the last phase. He focused there first.

4. Naming as you go

Every time you understand a function, rename it. Every time you understand a variable, rename it. Do this in a branch, and commit often.

The temptation is to read the whole codebase first and rename later. This is wrong. You will forget what you understood. You will lose hours of context. The rename is the note you are leaving for future you and the next person.

// before
function process(x, y) {
  const r = x.filter(z => z.s > y).map(z => z.id)
  return db.query(r)
}

// after, you understood this is fetching active user ids over a score threshold
function fetchActiveUserIdsAboveScore(users, threshold) {
  const qualifyingIds = users
    .filter(user => user.score > threshold)
    .map(user => user.id)
  return db.query(qualifyingIds)
}

Enter fullscreen mode Exit fullscreen mode

A good rule: if you cannot rename a function meaningfully, you do not understand it yet. Keep reading. Once you can rename it, do it immediately, then commit with a message that captures what you learned.

xavxav's rename pass on PP-BESM was a translation pass, but the principle is the same. Russian identifiers became English identifiers. Cryptic three letter mnemonics became words. The code became readable because someone took the time to make it readable.

5. Types as living documentation

If the codebase is dynamically typed, add types. If the types are wrong, fix them. Even loose types beat no types, because types are the documentation that runs.

// before, no types
function calculate(data, config) {
  return data.items.reduce((acc, item) => {
    return acc + item.price * (config.taxRate + 1)
  }, 0)
}

// after, types you can refactor against
type LineItem = { price: number; quantity: number; }
type TaxConfig = { taxRate: number; }
type Order = { items: LineItem[]; }

function calculateTotalWithTax(order: Order, config: TaxConfig): number {
  return order.items.reduce((acc, item) => {
    return acc + item.price * (config.taxRate + 1)
  }, 0)
}

Enter fullscreen mode Exit fullscreen mode

For Python, add type hints. For PHP, use PHPStan or Psalm. For old JavaScript, migrate file by file to TypeScript with allowJs: true. The types do not need to be perfect on day one. They need to exist.

The reason this matters more than people think: types compile. Comments do not. A wrong comment lives forever. A wrong type breaks the build. Types are the only documentation format that the compiler keeps honest.

6. Tests as ground truth, even for behavior you do not love

Before you refactor anything, write tests that lock in the observed behavior, including the parts that look like bugs.

This is the most counterintuitive rule on the list. Junior engineers want to fix the bugs immediately. The right move is to write a test that proves the bug exists first, then keep that test passing while you refactor, then change the test deliberately at the end if the bug should be fixed.

# pin the current behavior, even if it is wrong
def test_calculate_returns_negative_for_empty_orders():
    """
    BUG-LIKE: empty orders currently return -1 instead of 0.
    Some downstream system depends on this. Do not change without
    coordinating with the billing team.
    """
    result = calculate([], TaxConfig(rate=0.1))
    assert result == -1

Enter fullscreen mode Exit fullscreen mode

The test does two things. It tells future you that the behavior is intentional, not an accident. It also acts as the alarm if a "small refactor" breaks the contract.

xavxav's tests for PP-BESM are not unit tests in the modern sense. They are small Soviet-era programs run through the VM with their expected output captured. Same idea, smaller scope. Pin the behavior, refactor against the pin, change the pin deliberately.

7. Comment the negotiations, never the obvious

Your future maintainer can read the code. They cannot read your decision tree. The comments that survive a decade are the ones that capture why a particular choice was made, especially when the choice looks weird.

Bad comment: // increment counter. The code already says that.

Good comment: // We round down because the billing team expects integer cents only. // Historical: float cents caused the May 2023 reconciliation incident.

The good comment is a note from one engineer to another about a constraint that is not visible in the code. The constraint is real. The constraint will outlive the engineer who introduced it. The comment is the only place it lives.

Run this drill on your legacy codebase: find every place where the code looks slightly odd. A magic number, a hardcoded check, a try/except that swallows a specific exception, a special case for one customer ID. Each one of those is a negotiation that someone made with reality. If the comment is missing, add it once you figure out the negotiation.

# bad
TIMEOUT = 47

# good
# Set to 47 seconds because their auth gateway has a 50 second hard limit
# and we observed 1-2 second jitter from our load balancer. See incident
# 2024-03-15. Do not raise without coordinating with the partner team.
TIMEOUT = 47

Enter fullscreen mode Exit fullscreen mode

Stitching the playbook together

The seven stages are not parallel. They build on each other. The boundary work tells you where to put the harness. The harness lets you bisect. The bisection tells you what to name. The names tell you what to type. The types tell you what to test. The tests give you the safety to comment confidently.

The same loop runs at every scale. xavxav is running it on a 70 year old compiler with the source on paper. You can run it on a 12 year old Rails app with the source on GitHub. The shape is identical.

A practical first week, if you are inheriting a legacy codebase tomorrow:

Day 1: Boundaries. Draw the map. Do not read internals.
Day 2: Harness. Get any version running with one command.
Day 3: Bisection. Find the 10 percent that does the work.
Day 4: Naming + types. Make the 10 percent readable.
Day 5: Tests. Pin the observed behavior before refactoring.

Week 2 onward: refactor against the pins, comment the negotiations.

Enter fullscreen mode Exit fullscreen mode

By the end of week one you will know more about the codebase than the engineer who wrote it, because the engineer who wrote it never had the map. They built the system one room at a time. You are reading the architecture in two weeks because the map is part of the work.

The honest take

Most engineers will tell you they hate legacy codebases. They say this because the only legacy codebases they have seen are the ones nobody bothered to read. A codebase that someone has actually understood, mapped, harnessed, and pinned behavior on, is a perfectly pleasant place to work. The unpleasantness is not in the age of the code, it is in the absence of the archaeology.

The PP-BESM project will probably never have a million users. It will not show up in your dependency tree. It will not raise a Series A. The project still ranks among the most interesting software writing happening in 2026, because the goal is preservation rather than growth, and because the technique generalizes. The output is not a product. The output is a playbook.

That playbook works on the codebase that sits in your own repo right now, the one with a legacy/ directory nobody touches. Spend a week on it. The legacy directory will become an asset instead of a liability.

Question for the comments: what is the oldest piece of code you have ever read seriously, and which of the seven stages did you skip?


GDS K S · thegdsks.com · follow on X @thegdsks

Every codebase ends up as archaeology eventually. The question is whether anyone bothers to dig.