We used the Logos platform to formally verify an AI-driven migration of a SAS credit-risk scoring pipeline to Python. Starting from the pipeline's documentation, we formalised its requirements, fixed bugs in the SAS, and verified the result against those requirements. We then proved that the Python port matches the corrected SAS within the scope of the verification. This post walks through each stage of that workflow and explains what level of assurance it provides.
The first two stages follow Parts I and II of our previous post, Verifying a codebase for the pricing of interest rate options: extracting and certifying a specification, then verifying code against it. This post adds Part III, proving that the Python port matches the corrected and verified SAS program.
The codebase
The legacy system is an open-source SAS credit-risk pipeline, turintech/sas-migration (branch initial, commit 9f40a81): about 1,900 lines in four programs covering feature engineering, stepwise logistic regression, model metrics (AUC, KS, PSI, deciles, calibration) and scoring of new applicants. It runs on the 150,000 loan records of Kaggle's Give Me Some Credit competition and writes its results as CSV files and printed tables.
- The documentation. A model card and a README describe what the pipeline should do, how missing incomes are imputed, how the risk score and grade are derived, which metrics are reported and how. These are statements of intent that the underlying SAS program should satisfy.
- The port. Claude agents migrated the pipeline to Python (about 4,200 lines, polars and numpy), following a rulebook of SAS semantics. A parity judge ran both programs and compared every output file; it passed on all 64 file comparisons across ten runs.
- The question. Does the Python do what the SAS does on every input the pipeline is meant to accept, not only on the data it was tested on? And does the SAS do what its documentation says?
Everything below was done by a swarm of Logos agents, each with a single role: formalisers, reviewers, translators, provers and coding agents. Members whose work must stay independent never see each other's inputs. Provers worked in parallel, one per contract, started and assigned by the Logos orchestrator. They did not message each other; a lemma one prover proved went into the blueprint, where the others could use it.
Formalising the documentation
The first stage turned the documentation into formal contracts. The swarm's formaliser, which saw only the model card and the README, never any code, formalised 26 requirements in Lean.
A reviewer from the swarm, independent of the formaliser, checked each Lean statement against the documentation before a human agent signed it off. In the same gate, a human agent set the boundary of the migration: which code is verified and which parts are kept opaque and trusted, such as the logistic regression fit, numpy's linear algebra and reading and writing CSV files. This was the only point in the workflow where a human decided; every later stage ran automatically without human sign-off.
Provers from the swarm then proved that the pipeline satisfies all 26 requirements at once, so the specification asks for nothing impossible, and that valid inputs exist. The result was a certified specification of what the pipeline is meant to do, independent of either implementation.
Verifying the SAS program
The second stage checked the legacy code against the certified specification, which needed a faithful Lean model of the SAS program.
The swarm translated the SAS with agents and checked the translation with AI reviewers and fuzzing (see AWS's Lean Into Verified Software Development).
The swarm's SAS translator, which never saw the Python port, wrote each SAS step as Lean, following a rulebook of SAS behaviours (missing values, PROC IMPORT type guessing, PROC LOGISTIC's tie rule). Two independent reviewers then tried to break each unit. Each unit was then fuzzed against SAS on real rows and generated edge cases, and accepted only when its outputs matched.
Each of the 26 requirements became a contract on the Lean model of the SAS program. The swarm's provers disproved some of these requirements and pointed at 15 bugs in the original code. Each was fixed and all the contracts were eventually proved in Lean.
Here is one example.
Risk grades. The SAS graded applicants on their credit score, while the documentation grades them on their default probability. An applicant with a 20% default probability got grade A (approve, 5% interest) instead of C (review, 9%).
1. What the documentation says. The model card gives the grading rule as a table:
| Risk Grade | Score Range | Default Probability | Interest Rate | Recommendation |
|------------|-------------|---------------------|---------------|----------------|
| A | 750+ | < 10% | 5.0% | Approve |
| B | 700-749 | 10-15% | 7.0% | Approve |
| C | 650-699 | 15-25% | 9.0% | Review |
| D | 600-649 | 25-35% | 12.0% | Decline |
| E | 550-599 | 35-50% | 15.0% | Decline |
| F | < 550 | > 50% | 20.0% | Decline |The table states two rules at once, a score range and a default-probability range, and they disagree. The documented score is 600 + 250 × (1 − p). It reaches 750, the bottom of grade A, at p = 40% before rounding. The probability column assigns grade A only below 10%. The formaliser flagged the conflict, and the Logos human agent ruled that the probability column is the requirement.
2. The requirement in Lean. For every valid input and fitted model, Q18 says that each row with a numeric default probability in a returned score table gets the grade of its probability band.
def Q18 (P : Pipeline) : Prop :=
∀ (train test : Tabular.Table ℝ) (seed : ℕ), InputOK train test →
∀ (F1 F2 : Tabular.Table ℝ) (m : P.Model), Fitted P train seed F1 F2 m →
∀ S : Tabular.Table ℝ,
(P.score m F1 = some S ∨ P.score m F2 = some S ∨ P.scoreTest m test train = some S) →
∀ s ∈ S, ∀ p : ℝ, num s "pd_logistic" = some p →
(p < 0.10 → str s "risk_grade" = some "A") ∧
(0.10 ≤ p ∧ p < 0.15 → str s "risk_grade" = some "B") ∧
(0.15 ≤ p ∧ p < 0.25 → str s "risk_grade" = some "C") ∧
(0.25 ≤ p ∧ p < 0.35 → str s "risk_grade" = some "D") ∧
(0.35 ≤ p ∧ p ≤ 0.50 → str s "risk_grade" = some "E") ∧
(0.50 < p → str s "risk_grade" = some "F")3. The contract. The contract on the SAS program says that the SAS pipeline, as modelled in Lean, meets Q18:
theorem sas_Q18 (…the parameters of the SAS model…) (hLinks : SasLinks …) :
CreditRisk.Q18 (sasPipeline …)4. What the SAS did. The original code graded on the score:
credit_risk_score = round(base_score + score_range * (1 - pd_logistic));
/* Assign risk grades */
if credit_risk_score >= 750 then risk_grade = 'A';
else if credit_risk_score >= 700 then risk_grade = 'B';
else if credit_risk_score >= 650 then risk_grade = 'C';
else if credit_risk_score >= 600 then risk_grade = 'D';
else if credit_risk_score >= 550 then risk_grade = 'E';
else risk_grade = 'F';5. The counterexample. Logos disproved the contract with a single row. With p = 0.20, the score is 800, so the SAS gave grade A, where Q18 requires C. After rounding, grade A covered probabilities up to about 40.2%. Nonmissing probabilities always gave scores of at least 600, so these rows could never get E or F. Rows with a missing probability fell through to F.
6. The fix. The corrected SAS grades on the probability, and the contract is now proved:
if missing(pd_logistic) then risk_grade = 'F';
else if pd_logistic < 0.10 then risk_grade = 'A';
else if pd_logistic < 0.15 then risk_grade = 'B';
else if pd_logistic < 0.25 then risk_grade = 'C';
else if pd_logistic < 0.35 then risk_grade = 'D';
else if pd_logistic <= 0.50 then risk_grade = 'E';
else risk_grade = 'F';Other notable examples of bugs we caught include:
Population stability. The population stability index (PSI) measures how far the scores of the validation data have moved from those of the training data, by comparing the share of each that falls in the same ten score bands. The SAS ranked each data set separately into ten groups. With few tied scores, each group held about 10% of its own data, so even large changes in the scores could leave PSI near zero. The model card's "excellent stability" (PSI 0.0013) came from this calculation. The fix sets the band boundaries using the training scores and places the validation scores in those same bands.
Imputation. A missing monthly income is filled with the median income of the applicant's age group. When scoring new applications, the SAS took those medians from the file being scored instead of the training data, so an applicant's score depended on who else was in the same file. Worse, when nobody in an age group of that file reported an income, the missing incomes in that group stayed missing. The fix reads the training medians, with the overall training median for an age group that has none.
Migrating to Python
The third stage started from the verified SAS program. Coding agents ported it to Python, 4,200 lines of polars and numpy, with Anthropic's Claude-native code migration kit: a rulebook of SAS behaviours, then per unit an implementer, two adversarial reviewers and a fixer, and a parity judge that runs both programs and compares every output file. Logos then proved that the port does exactly what the verified SAS program does.
The port was translated into Lean the same way as the SAS, so the two Lean models went through identical checks. An independent translator worked from the Python code for the port, reducing the chance of carrying assumptions over from the SAS translation.
The swarm's provers, the only role that read both sides, then stated 30 equality contracts as Lean theorems. Most compare the modelled outputs for every valid input. The rest cover what those comparisons rely on, such as both programs picking the same training rows and the port always finishing. The following contract compares the test prediction tables:
theorem E6_score_test (py : PyParams) (sas : SasParams)
(hLinks : PyLinks py) (hPaired : Paired py sas)
(train test : Tabular.Table ℝ) (seed : ℕ) (hOK : CreditRisk.InputOK train test) :
∀ (F1 F2 : Tabular.Table ℝ) (m : Sas.Model ℝ),
(sasPipelineOf sas).features train seed = some (F1, F2) →
(sasPipelineOf sas).fit F1 = some m →
(pyPipeline py).scoreTest m test train = (sasPipelineOf sas).scoreTest m test trainThe theorem assumes the Python model links (PyLinks), the pairing between the implementations (Paired), valid input, and successful SAS feature generation and fitting. Given that fitted SAS model, the two Lean models return the same prediction table or both return no table. CSV writing stays outside the proof boundary.
The agent-only migration was not correct. Every parity test had passed, yet the provers disproved contracts and found 13 bugs in the port. A coding agent fixed each one, the parity judge ran again, and all 30 contracts were eventually proved, so the 26 requirements proved of the SAS hold of the port too. Here is one of those bugs.
ROC ties. The port decided ties between probabilities pair by pair with a tolerance of 1e-8, where SAS groups near-equal probabilities with a slightly larger tolerance. For two applicants 1.02e-8 apart, the port computed an AUC of 1 and SAS 0.5.
1. What SAS does. PROC LOGISTIC groups near-tied probabilities: scanning from the largest down, a value joins the current group while it is within ROCEPS of the group's largest value. The SAS model in Lean, with ROCEPS as measured by running SAS:
def rocTops {α : Type} [RealLike α] (ps : List α) : List α :=
((sortBy (fun p => some p) ps).reverse).foldl
(fun acc p =>
match acc with
| [] => [p]
| top :: _ =>
if ((3184525836262887 : α) / (302231454903657293676544 : α)) < top - p then p :: acc
else acc)
[]2. What the port did. It compared every event with every non-event, pair by pair, with a tolerance of 1e-8:
_TIE_EPS = 1e-8 # A8: SAS tie fuzz
def _pairs(y: pl.Series, score: pl.Series) -> _Pairs:
...
ev = np.sort(ss[yy == 1])
ne = np.sort(ss[yy == 0])
lo_ne = np.searchsorted(ne, ev - _TIE_EPS, side="left")
le_ne = np.searchsorted(ne, ev + _TIE_EPS, side="right")
conc = int(lo_ne.sum())
tied = int((le_ne - lo_ne).sum())3. The counterexample. The equality of the training AUC could not be proved. Logos returned two applicants with default flags 0 and 1 and probabilities 0.5 and 0.5000000102. Their gap, 1.02e-8, is above the port's tolerance and below SAS's 1.054e-8, so the port counted a concordant pair (AUC 1) and SAS a tied one (AUC 0.5).
4. The fix. A coding agent rewrote _pairs to group as SAS does, the parity judge passed again, and the contract was proved.
5. Why the tests passed. On the real data the port's rule changed 5 of 280 tied pairs, which moved the AUC by 2.2e-9: invisible at four decimals, and a tolerance had been added to the one printed cell that showed it. A test only agrees on the data it runs; a proof has to hold on every valid input, so it fails exactly where a test never looks.
What comes next
This credit-risk pipeline of 1,900 lines of SAS was a warm-up. We are now running the Logos system on much larger codebases with our clients, and across more pairs of programming languages. We are also building deterministic translators for more of these languages. Each replaces agent translation, reviews and fuzzing with a translation that is correct by construction, so migrations get faster and their guarantees even stronger.