Software Architecture
Migrating legacy code with AI without losing control: parity, characterization tests and strangler fig
OpenAI says GPT-6.1 Sol migrates COBOL programs, the classic case of legacy code, with 97.9% accuracy. The number is real, but it comes from high reasoning effort on an in-house evaluation with hidden tests. At low effort, accuracy is 86.6%. The same announcement warns that applying it to production software "still requires expert review and testing against the system's business rules and dependencies".
That warning is the part that matters on a real migration. In a small test bench of ours, a rewrite of an interest calculation passed the 20 demo cases and failed 5017 of 10,000 realistic ones, each by one cent. The net sum of those differences was +17 cents: in the batch total, the error almost vanishes.
OpenAI's number, read in full
The evaluation asks models to move COBOL programs to other languages without changing what they do: "Our second evaluation asks models to migrate COBOL programs to C++, Java, Kotlin, Python, or Rust while preserving what each program does." The tests are hidden and require byte-for-byte parity on outputs: "A migration is considered successful only if all tests pass." The figures going around, checked against the source:
| Figure | What the source says | Condition |
|---|---|---|
| 97.9% | "At higher reasoning effort, accuracy reaches 97.9%, nearly saturating the evaluation." | High effort, without saying which level. OpenAI's own hidden tests |
| 86.6% | "86.6% accuracy at low reasoning effort" | Low effort. At that setting GPT-5.6 Sol gets 5.4%, and GPT-6.1 Sol costs 39% less |
| 72.1% on COBOL | "including COBOL (10.9% to 72.1%)" | That's MultiLangBench, a different test: building a SQLite-compatible database engine, at maximum effort and with another model, GPT-6 Astra. It measures the share of tests passed |
| Agents settle 80% of the questions in the discovery phase | None. A team says it on social media, about its own projects | Experience, not a published measurement: not used as data here |
OpenAI publishes the MultiLangBench test suite on GitHub, but for the COBOL evaluation it links no cases and no code. We don't know how many programs it has, how big they are, or which exact level "higher reasoning effort" means. The figure describes that evaluation, not your system.
The expensive part is understanding the old code
Writing the new code is the cheap part. OpenAI's own announcement says why understanding the old code is the expensive one: "documentation may be incomplete, original developers may have left the company, and important business rules may only exist in code." Anthropic's article on COBOL puts it another way: "understanding what the code does is the most expensive step." It also names what static analysis misses: "these implicit dependencies don't show up in static analysis because they involve data shared through files, databases, or global state." Both companies sell models. In his piece on the strangler fig pattern, Martin Fowler says it this way: "Replacements seem easy to specify, but often it's hard to figure out the details of existing behavior."
OpenAI gives an example of the typical risk: "COBOL's fixed-point arithmetic discards excess decimal digits unless rounding is explicitly requested. A rewrite that rounds those values instead can run without errors while producing different financial results." The IBM manual sets two rules that apply silently. Without ROUNDED, extra decimals are dropped: "truncation occurs unless ROUNDED is specified". Without ON SIZE ERROR, when the result doesn't fit, "truncation rules apply and the value of the affected resultant identifier is computed". IBM shows it with a BINARY field: +12345 moved to S99 becomes +45. The emulator applies that loss of leading digits.
A test bench: the rewrite that passes the demo
The bench emulates in Python a COBOL step COMPUTE INTEREST = BALANCE * RATE * DAYS / 360 without ROUNDED or ON SIZE ERROR. Balance is S9(7)V99, rate 9V9(4), days 9(3) and interest S9(5)V99: 5 integer digits and 2 decimals. The reference truncates cents, drops the integer digits that don't fit, and rejects with ERR-DATA anything not in the exact format; that reject is the emulator's own choice. It isn't COBOL: there was no compiler. It follows IBM's text, but intermediate precision, the sign of a negative zero and what a real program does with non-numeric data may differ.
The first rewrite is the one you'd write without thinking: float, round() to two decimals, no lost digits. It reads well and raises no errors:
def record(line: str) -> str:
try:
acct, balance, rate, days = line.split(";")
value = round(float(balance) * float(rate) * int(days) / 360, 2)
except ValueError:
return f"{line.split(';')[0][:8]:<8} ERR-DATA"
sign = "-" if value < 0 else "+"
digits = f"{round(abs(value) * 100):07d}"
return f"{acct:<8}{sign}{digits}"
The inputs are four seeded sets: 20 demo cases, 10,000 random ones across the full field ranges (many don't fit S9(5)V99), 10,000 realistic ones that always fit, and 14 hostile ones. The golden master is the reference's output; each candidate gets the same cases and is compared byte by byte:
== happy / interest_naive.py
parity OK: 20 input lines, 340 output bytes identical
== happy / interest_ported.py
parity OK: 20 input lines, 340 output bytes identical
== random / interest_naive.py
parity FAILED: 9919 output line(s) differ; expected 170000 bytes, got 196502 bytes
== random / interest_ported.py
parity OK: 10000 input lines, 170000 output bytes identical
== realistic / interest_naive.py
parity FAILED: 5017 output line(s) differ; expected 170000 bytes, got 170000 bytes
== realistic / interest_ported.py
parity OK: 10000 input lines, 170000 output bytes identical
== hostile / interest_naive.py
parity FAILED: interest_naive.py exited with 1
== hostile / interest_ported.py
parity OK: 14 input lines, 247 output bytes identical
The 20 demo cases pass because they produce exact cents: they never hit truncation or overflow. In the realistic set, half the records change by one cent. round() goes to the nearest cent and truncation goes toward zero. When the leftover is more than half a cent, the naive version gives one cent more on a positive balance and one cent less on a negative one:
line 1
in b'Q0000000;-74288.28;0.0594;362'
exp b'Q0000000-0443723'
got b'Q0000000-0443724'
line 5
in b'Q0000004;20648.06;0.0356;314'
exp b'Q0000004+0064114'
got b'Q0000004+0064115'
On top of that, round() breaks ties toward even ("if two multiples are equally close, rounding is done toward the even choice") and works on the binary value of the float. Across all 10,000 records:
lines differing: 5017
actual - expected = -1 cent(s): 2500
actual - expected = +1 cent(s): 2517
negative balance: 2500
zero or positive balance: 2517
net sum of differences: +17 cents
5017 records are wrong and the differences nearly cancel out: +17 cents in total. A reconciliation by totals with a tolerance signs off on a migration that is wrong for half the accounts; an exact one sees the 17 cents, but not which of the 5017 accounts are wrong. In the random set, 9919 of 10,000 differ: 9846 because of overflow and 73 because of rounding. Where the reference keeps 7 digits, the naive version writes all it has and breaks the fixed record width.
The hostile inputs show something else: what the new code accepts that the old one rejected.
| # | Input | Case | Reference and fixed | Naive |
|---|---|---|---|---|
| H1 | H0000001;1000.00;0.0500;30 | ordinary input | H0000001+0000416 | H0000001+0000417 |
| H2 | H0000002;2009.70;0.0500;36 | exact result 10.0485 | H0000002+0001004 | H0000002+0001005 |
| H3 | H0000003;9999999.99;9.9999;999 | doesn't fit S9(5)V99 | H0000003+9722472 | H0000003+27749722472 |
| H4 | H0000004;-1500.00;0.0700;31 | negative balance | H0000004-0000904 | H0000004-0000904 |
| H6 | H0000006;١٠٠٠.00;0.0500;30 | balance in Arabic-Indic digits | H0000006 ERR-DATA | H0000006+0000417 |
| H7 | H0000007; 1000.00;0.0500;30 | space before the balance | H0000007 ERR-DATA | H0000007+0000417 |
| H8 | H0000008;1_000.00;0.0500;30 | balance with an underscore | H0000008 ERR-DATA | H0000008+0000417 |
| H9 | H0000009;1E3;0.0500;30 | balance in exponent notation | H0000009 ERR-DATA | H0000009+0000417 |
| H10 | H0000010;NaN;0.0500;30 | balance NaN | H0000010 ERR-DATA | crashes: ValueError, exit code 1 |
| H11 | H0000011;1000.00;0.0500;30\r | CRLF line ending | H0000011 ERR-DATA | H0000011+0000417 (separate run) |
| H14 | H0000014;1000.5;0.0500;30 | balance with one decimal | H0000014 ERR-DATA | H0000014+0000417 (separate run) |
H5, H12 and H13 (zero days, one field missing, one extra) are left out: both versions agree. On NaN, the naive version crashes with "ValueError: cannot convert float NaN to integer" and the batch stops: H11 to H14 are not processed in that run, and the table shows their output from a separate run. The Arabic-Indic digits in H6 are the same problem as Unicode digits in .NET: a conversion that accepts more scripts than the format expects.
The second rewrite fixes what parity found: Decimal, truncation with ROUND_DOWN ("Round towards zero."), digits dropped with modulo 10^5, and ASCII validation before converting. The validation is needed because the Decimal constructor is lenient too: it parses the text "after leading and trailing whitespace characters, as well as underscores throughout, are removed".
def record(line: str) -> str:
match = FIELDS.fullmatch(line)
if match is None:
first = line.split(";")[0]
acct = first if ACCT.fullmatch(first) else "????????"
return f"{acct:<8} ERR-DATA"
with localcontext() as ctx:
ctx.prec = 31
raw = Decimal(match["balance"]) * Decimal(match["rate"]) * int(match["days"]) / 360
cents = raw.quantize(Decimal("0.01"), rounding=ROUND_DOWN)
kept = abs(cents) % MODULUS
sign = "-" if cents < 0 and kept != 0 else "+"
return f"{match['acct']:<8}{sign}{int(kept * 100):07d}"
It passes all four sets and 12 more hostile inputs of our own, such as a BOM or full-width digits, with the same output as the reference. That proves equality with the emulator, not with real COBOL. And the reference and the rewrite come from the same reading of the spec, so a shared misunderstanding passes parity. It's the same risk as asking an AI for the code and for its tests.
Test the checker too
parity.py has two modes. record saves the reference output and the sha256 of the cases file. compare feeds that same file, as is, to the candidate and compares the outputs without trimming spaces or fixing line endings. It exits with 0 if everything matches, 1 if anything differs or the candidate fails, and 2 if the cases file isn't the one that was recorded:
import hashlib
import subprocess
import sys
def run(program: str, cases: bytes) -> bytes:
done = subprocess.run([sys.executable, "-I", program], input=cases,
capture_output=True, check=False, timeout=120)
if done.returncode != 0:
sys.stderr.write(done.stderr.decode("utf-8", "replace"))
print(f"parity FAILED: {program} exited with {done.returncode}")
raise SystemExit(1)
return done.stdout
def read(path: str) -> bytes:
with open(path, "rb") as f:
return f.read()
def line_count(data: bytes) -> int:
# A last line without "\n" still counts as a line.
return data.count(b"\n") + (1 if data and not data.endswith(b"\n") else 0)
def main() -> int:
if len(sys.argv) < 5 or sys.argv[1] not in ("record", "compare"):
print(__doc__)
return 2
if sys.argv[1] == "record":
reference, cases_path, golden_path = sys.argv[2:5]
cases = read(cases_path)
output = run(reference, cases)
with open(golden_path, "wb") as f:
f.write(output)
with open(golden_path + ".cases-sha256", "w", encoding="ascii") as f:
f.write(hashlib.sha256(cases).hexdigest() + "\n")
print(f"recorded {line_count(output)} lines, {len(output)} bytes")
return 0
golden_path, candidate, cases_path = sys.argv[2:5]
max_shown = int(sys.argv[5]) if len(sys.argv) > 5 else 5
expected = read(golden_path)
cases = read(cases_path)
try:
recorded_hash = read(golden_path + ".cases-sha256").decode("ascii").strip()
except FileNotFoundError:
print(f"setup error: {golden_path}.cases-sha256 missing; run record again")
return 2
if hashlib.sha256(cases).hexdigest() != recorded_hash:
print(f"setup error: {cases_path} is not the cases file {golden_path} was recorded from")
return 2
actual = run(candidate, cases)
if actual == expected:
print(f"parity OK: {line_count(cases)} input lines, {len(expected)} output bytes identical")
return 0
exp_lines, act_lines = expected.split(b"\n"), actual.split(b"\n")
in_lines = cases.split(b"\n")
total = max(len(exp_lines), len(act_lines))
diffs = [i for i in range(total)
if i >= len(exp_lines) or i >= len(act_lines) or exp_lines[i] != act_lines[i]]
print(f"parity FAILED: {len(diffs)} output line(s) differ; "
f"expected {len(expected)} bytes, got {len(actual)} bytes")
for i in diffs[:max_shown]:
exp = exp_lines[i] if i < len(exp_lines) else "(missing)"
got = act_lines[i] if i < len(act_lines) else "(missing)"
inp = in_lines[i] if i < len(in_lines) else "(none)"
# Output line i maps to input line i only when the program writes one line per input line.
print(f" line {i + 1}\n in {inp!r}\n exp {exp!r}\n got {got!r}")
return 1
if __name__ == "__main__":
sys.exit(main())
Its first version dropped blank lines when comparing but not when recording, so it passed a candidate that crashed on a blank line. The version above feeds the same file in both modes, and on 10 hostile inputs it does what it should: a candidate that writes CRLF fails, so does one that crashes on a blank line, a correct candidate passes with a file that has no final newline or has blank lines, and a cases file other than the recorded one is a setup error.
A process with human checkpoints
AI speeds up discovery and testing, but some decisions have an owner. This order comes from the OpenAI and Anthropic guides and from the incremental migration patterns:
- Discover with AI, review with people. OpenAI's cookbook asks in phase 2: "Capture what the pilot flow actually does today: programs, jobs, data flows, and business rules." The output is a document with open questions, and a person reviews it.
- Tell business rules from defects. Fowler warns that much of the old behavior shouldn't survive: "much of that behavior is stuff that isn't really wanted, so building it is a waste." Someone with business authority decides.
- Pin current behavior before touching anything. A characterization test, or golden master, records what the system does today. It doesn't say whether that's right: "characterization tests do not verify the correct behavior of the code". Use three kinds of input: business cases, random values across each field's range, and hostile ones. If the output has dates or ids, mask them in both the golden master and the new output. AI can propose the tests, but in Anthropic's words "Your team decides whether those tests are sufficient". It's the same idea as the deterministic tests on AI-written SQL.
- Compare byte by byte and record by record. That's what OpenAI's evaluation requires, and what in the bench separates 5017 failures from a total that almost balances.
- Migrate piece by piece behind a façade. In the strangler fig pattern, "the façade incrementally shifts requests from the legacy system to the new system", as Microsoft's guide puts it. Anthropic suggests starting with "a single component or workflow that has clear boundaries and moderate complexity".
- Run old and new side by side before cutting over. Phase 4 of the cookbook: "Implement the modern pilot, run it in parallel with the COBOL version, and show that outputs match for the planned scenarios." In production, Scientist (Ruby) calls the old path "control" and the new one "candidate", and by default compares them with
==. - When a test goes red, decide whether you meant it. The Stack Overflow blog sums it up: "A red characterization test doesn't mean "bug." It means "behavior changed." And the very next question is always, did we mean that?" You keep the quirk or fix it on purpose, and write down who decided.
Parity for one piece isn't parity for the system
OpenAI measures output parity on individual programs, and this bench does the same with one calculation. Promising that the whole system will behave as before is something else, and "Patterns of Legacy Displacement" lists it as a cause of failure: "A third key factor in several of the failures was the desire for Feature Parity with the existing set of systems and business processes." Parity lets you move one piece without surprises. What gets kept is decided by the people in step 2.
Running both systems has its own costs. Microsoft's guide warns: "Make sure that the façade doesn't become a single point of failure or a performance bottleneck." Shared data is a risk too: "Consider how to handle services and data stores that both the new system and the legacy system might use. Make sure that both systems can access these resources at the same time." And the transition code gets thrown away at the end, though for Fowler it pays off: "the reduced risk and earlier value from the gradual approach outweigh its costs."
What this bench doesn't cover
- Equivalence. 10,000 random cases find frequent differences, not the one input in millions.
- Other outputs.
parity.pyonly compares standard output: no written files, database rows, queues or calls to other systems. - Encodings. It reads and writes UTF-8. It doesn't handle EBCDIC, packed decimal (COMP-3) or binary fields, which the cookbook lists as an upfront decision: "Notes about how legacy encodings such as packed decimals or EBCDIC fields will be represented."
- Large batches. It loads whole outputs into memory and stops each program after 120 seconds.
- Other languages.
run()launchespython -I. To compare a COBOL binary with a Java service, change that function.
Frequently asked questions
Does the pattern work if I can't change the old system?
Partly. Microsoft says so: "To disable migrated features and redirect internal calls, you need to be able to modify the legacy system." You can still record the golden master, since it only needs to run the old system and save its output. And for a small system, the same guide advises against the pattern: "You migrate a small system and replacing the whole system is simple."
Conclusion
The 97.9% says a model migrates almost every program in that evaluation. It doesn't say which rules of the old code to keep, or whether your tests will catch a one-cent difference. People decide that, with characterization tests and record-by-record comparison.
Before you ask a model for the first line, pick a small piece and record its golden master.
References
- Advancing coding in low‑resource programming languages (openai.com)
- How AI helps break the cost barrier to COBOL modernization (claude.com)
- Code modernization (developers.openai.com)
- Enterprise COBOL for z/OS 6.4 Language Reference (ibm.com, PDF)
- Strangler Fig (martinfowler.com)
- Patterns of Legacy Displacement (martinfowler.com)
- Strangler Fig pattern (learn.microsoft.com)
- The regression tests nobody writes: capturing how software actually behaves (stackoverflow.blog)
Tags
Share this post
Subscribe
Get the latest posts delivered right to your inbox.
Leave a comment