First the Filter, Then the Generator
A pure core, a shell that talks to the world, and why I wouldn't rewrite a system with agents before I could say what has to be true
Machine-translated from Spanish. Read the original

There's a temptation I hear about more and more often. You have a system that works, written years ago in a language that no longer excites you, and now you have agents that write code at an absurd speed. Why not rewrite the whole thing, properly this time, in Rust or Haskell?
I want to explain why I wouldn't, and what I'd do instead. To do that I'll use a concrete case I know well, a platform for gift cards, vouchers and discounts, built in Laravel, the most widely used web framework in the PHP world. But the reasoning applies to almost any system that handles money, inventory or bookings.
Where the real risk is
The first step is to look at the system and separate two things that are almost always mixed together.
Most of it is what I'll call the shell, that is, the portal each merchant logs into, user sign-up, roles and permissions, branches, the spreadsheets people upload, the reports they download. It's a lot of code, but it's code that looks like any other web application. If something goes wrong there, you see it right away and you fix it. Laravel is very good at this.
And then there's a small core where the real risk lives:
- The life cycle of each code (available, sold, redeemed or expired), with steps that can't be undone.
- The balance of each gift card and the amounts of each batch.
- Expiration dates, which can be counted from the sale or be a fixed date.
- Settlement, which sets how much each merchant gets paid, and when.
A bug in the shell is a button that doesn't work. A bug in the core is a code redeemed twice, a balance that doesn't add up, or a merchant you overpaid. They're silent bugs, the kind nobody sees until someone does the math.
So the question isn't "what language do I rewrite the system in?". It's "how do I make sure the core does what it's supposed to do?".
A pure core and a shell that talks to the world
There's a way of organizing code that helps a lot with that question. Gary Bernhardt named it functional core, imperative shell in 2012.
The idea is to separate deciding from doing.
The core decides. It receives a fact ("this code was sold", "someone wants to redeem this other one") and returns what needs to be done, such as changing the state, notifying someone or rejecting the request. But it doesn't do it itself. It doesn't touch the database, it doesn't send emails, it doesn't check the time. It just takes data in and hands data back.
The shell does. It reads what's happening in the world, passes it to the core, and carries out what the core decided, whether that's saving to the database, sending the email or answering the web request.
Why go to all that trouble? Because a core like that is the easiest thing there is to understand and to test. Give it the same thing and it always returns the same thing. It doesn't depend on what's in the database or what time it is. You can test it millions of times per second without starting up anything.
In the Rust world this pattern has a name of its own, sans-IO ("without input/output"), and it's used in very serious projects. There are complete implementations of network protocols (QUIC, the protocol behind HTTP/3, or WebRTC, the one behind video calls in the browser) written as cores that never touch the network. You hand them the bytes that arrived and they hand you back the bytes that need to be sent. The part that actually talks to the network is a separate shell.
What it looks like
A small example, the life cycle of a gift card code, in Rust:
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Codigo { Disponible, Vendido, Canjeado, Vencido }
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Evento { Venta, Canje, Vencimiento }
enum Comando { Avisar(Codigo), Rechazar(Evento) }
// The core: no network, no database, no clock. Takes an event, returns decisions.
fn step(codigo: Codigo, evento: Evento) -> (Codigo, Vec<Comando>) {
use Codigo::*;
match (codigo, evento) {
(Disponible, Evento::Venta) => (Vendido, vec![Comando::Avisar(Vendido)]),
(Vendido, Evento::Canje) => (Canjeado, vec![Comando::Avisar(Canjeado)]),
(Disponible | Vendido, Evento::Vencimiento) => (Vencido, vec![]),
(Disponible, Evento::Canje) | (Vendido, Evento::Venta) | (Canjeado | Vencido, _) => {
(codigo, vec![Comando::Rechazar(evento)])
}
}
}Even if you don't know Rust, you can read it (the names are in Spanish, and a Codigo is a code, its states are available, sold, redeemed and expired, the events are sale, redemption and expiry, and the commands are notify and reject). A code is in one of four states. Three things can happen to it. The step function says, for each combination of state and event, which state it moves to and what needs to be done. If it's available and gets sold, it becomes sold and someone is notified. If it's sold and gets redeemed, it becomes redeemed, and if it expires before being redeemed, it becomes expired. Any other combination (redeeming something that wasn't sold, selling something expired) is rejected.
Correction (November 25, 2026). The first version only described the sale and the redemption and said any other combination is rejected, but an available or sold code that expires becomes expired. The example also didn't compile together with the test further down, because the types were missing
DebugandPartialEq, which let you print them and compare them with==, and the test used anevento()function that wasn't written anywhere. Now the example and the test have what they were missing, just like the repo. I found it in a review of the series, and it doesn't change the argument.
And there's a detail that matters. If tomorrow someone adds a fifth state and forgets to say what happens with it, the program doesn't compile. The compiler forces you to cover every case. When the repo adds a fifth state, Frozen, without touching step, the compiler answers that the pattern (Code::Frozen, _) is not covered. In the repo the names are in English, and Codigo is called Code.
Correction (November 25, 2026). The first version of the example ended with a catch-all case,
(c, e) =>, which rejected any combination not listed above it. With that catch-all, a fifth state still compiled and was silently rejected, so the paragraph above wasn't true. Now the example also spells out the combinations that get rejected, with no catch-all for the state, and the repo checks that a new state without its cases doesn't compile. I found it in a review of the series.
Making sure the core can't touch the world
Separating deciding from doing is a good intention. The problem is that intentions get forgotten, especially when the one writing the code is an agent in a hurry to make a test pass. What stops a database query from showing up tomorrow in the middle of the core "because it was easier"?
In Haskell, the language itself prevents it, because the type of every function says whether it can touch the world or not, and a function declared pure can't do input/output, except through a named back door, unsafePerformIO, which Safe Haskell closes. Rust doesn't have that (I compare the two in more detail in A Filter You Can't Turn Off). But it has a trick.
Correction (November 25, 2026). The first version said that in Haskell a pure function can't do input/output even if it wants to. It can, with
unsafePerformIO, which compiles without a warning; what closes it is compiling with Safe Haskell, a compiler option that forbids it. I found it in a review of the series.
In Rust, code is organized into packages called crates, and each one declares which other packages it depends on. If the core lives in its own package and that package doesn't depend on any database or networking library, the core can't use them, because it has nothing to do it with. If someone tries to slip in a database query, it doesn't compile. And there are tools that check that list of dependencies on every change and reject the forbidden ones.
But an empty list isn't enough on its own, because Rust's standard library always comes included, and it has files (std::fs), networking (std::net) and the clock (std::time). Two more lines are needed at the top of the package. One is #![no_std], which leaves out the standard library and all of that with it, and the other is #![forbid(unsafe_code)], which closes another door, calling straight into C code. Not even that closes them all, because #![no_std] only stops bringing in the standard library by default, and an extern crate std; line in the core brings it back and compiles. That door is closed by a check that runs on every change and rejects that line.
In other words, even though Rust doesn't carry the distinction between pure and impure in its types, each package's list of dependencies, with no standard library, no unsafe and that check, plays that role. One of those doors is closed not by the language but by a script that runs on every change, so that script is part of the filter and has to be looked after as such.
The repo's check.sh tries to dirty the core in all of those ways. In its output, gate is the check and rejected/ holds the attempts that shouldn't compile. What interests me most are the two lines that say compiles, because they are the doors the language leaves open:
ok the gate rejects a dependency: gate: giftcard-core must not depend on anything, found: rusqlite
ok the gate rejects removing no_std: gate: core/src/lib.rs lost #![no_std]
ok the gate rejects bringing std back: gate: core/src may bring in no crate but alloc and no other file, found core/src/escape.rs:4: extern crate std;
ok rejected/clock.rs doesn't compile: unlinked crate `std`
ok rejected/database.rs doesn't compile: unlinked crate `rusqlite`
ok rejected/ffi.rs doesn't compile: usage of an `unsafe extern` block
ok rejected/files.rs doesn't compile: unlinked crate `std`
ok gate/extern_std.rs compiles despite no_std and forbid(unsafe_code): only the gate stops it
ok without #![no_std], rejected/files.rs compiles: an empty dependency list alone doesn't stop file I/OCorrection (October 30, 2026). The first version of this section said an empty dependency list was enough to keep the core from touching files, the network or the clock. It isn't, because without
#![no_std]a core with zero dependencies can read a file. I found it while turning the article into code that runs; the repo has the core, the attempts to dirty it that don't compile, and the double redemption from further down, reproduced.
Correction (November 25, 2026). The previous version of this section said
#![forbid(unsafe_code)]closed the last door and that an agent couldn't dirty the core even if it wanted to. It isn't so, because#![no_std]doesn't forbid the standard library, and withextern crate std;the core can read files again without touchingunsafe. I found it in a review of the series, and the repo's check let that line through. Now the repo rejects it, and keeps the attempt among the ones the check must stop.
How you test a core like that
A core shaped like "state and event go in, state and decisions come out" is the ideal place for property tests, which I talked about in QuickCheck vs. Traditional Testing as a Deterministic Harness in the GenAI Era. Instead of writing a few example cases by hand, you write a rule that must always hold, and the tool generates hundreds of random cases trying to break it.
Correction (November 25, 2026). The first version said the tool generates thousands of cases.
proptesttries 256 per run unless you ask for a different number (with thePROPTEST_CASESenvironment variable), and the repo uses that value, so it's hundreds of sequences, not thousands. The argument doesn't change. I found it in a review of the series.
For example, the rule that no matter what sequence of events happens to a code, it's never redeemed more than once. In Rust, with the proptest library:
use proptest::prelude::*;
fn evento() -> impl Strategy<Value = Evento> {
prop_oneof![Just(Evento::Venta), Just(Evento::Canje), Just(Evento::Vencimiento)]
}
proptest! {
#[test]
fn se_canjea_a_lo_sumo_una_vez(eventos in prop::collection::vec(evento(), 0..50)) {
let mut codigo = Codigo::Disponible;
let mut canjes = 0;
for e in eventos {
let (siguiente, _) = step(codigo, e);
if siguiente == Codigo::Canjeado && codigo != Codigo::Canjeado {
canjes += 1;
}
codigo = siguiente;
}
prop_assert!(canjes <= 1);
}
}The tool makes up sequences of up to fifty events (sales, redemptions, expirations, in any order and number), feeds them to the core, and checks the rule. If it finds a sequence that breaks it, it shrinks it down to the smallest possible example and shows it to you. There's no need for test databases or for simulating anything, because the core doesn't depend on anything that would need simulating.
To know whether the rule has teeth, the repo also runs it against a mutant core, a copy with a deliberate bug, which lets an already redeemed code be sold again. The property catches it, and proptest shrinks the failure to four events, [Sale, Redemption, Sale, Redemption].
In Building or Pruning the Infinite I said that with a system you only know by how it responds, the only thing you can do is observe it, and that the complete guarantee would be observing it in every possible situation. Nobody does that by hand. A property test does it thousands of times per second. It's not the complete guarantee, but it gets much closer to it than any human review.
The shell, on the other hand, ends up so thin and so much like any other web application that there you really can let the agent work with peace of mind.
What no language gives you
So far, it all sounds like the language solves the problem. But the most serious risk in a gift card system isn't even in the language.
It's double redemption, which happens when two branches, at the same moment, redeem the same code. Each one checks the database, sees that the code is sold and not yet redeemed, and redeems it. Each one's core made the right decision with what it knew. And the code got redeemed twice.
Rust doesn't protect you from this. Its guarantees are about what happens inside one running program, and this race happens between two programs, in the database. The same goes for Haskell, for TypeScript, or for whatever language you like. It gets solved in the database, with constraints the database itself enforces, with transactions, and with an update that only takes effect if the code hasn't been redeemed yet (UPDATE ... WHERE canjeado IS NULL), so that of the two branches only one wins.
The repo reproduces the race step by step, with both branches reading first and writing afterwards, so the result doesn't depend on luck:
$ cargo run -q -p giftcard-shell
Naive: two branches redeem the same code, 2 gift(s) handed over
Conditional: two branches redeem the same code, 1 gift(s) handed overNaive saves the state the core decided on, and two gifts are handed over for the same code. Conditional saves with UPDATE ... WHERE redeemed_at IS NULL, and one is handed over. The core is the same in both cases.
It's worth keeping in mind every time someone says a language "is safer". It's safer for certain things. Your business rules don't come included.
The plan
So what would I do with the Laravel system? Something a lot less spectacular than rewriting it.
- Model before code. I'd write a model of the core in Haskell, which isn't the system but a small, pure description of how it should behave. And I'd use QuickCheck, the original property-testing tool, to compare the real system against that model, generating sequences of sales, redemptions and expirations, sending them to the actual Laravel app through its web interface, as if it were just another client, and seeing whether what it answers matches what the model says. Including simultaneous redemptions from two branches. Haskell comes in as a filter, not as the implementation.
- Decide with data. If the properties pass and Laravel isn't causing pain, there's nothing to migrate. If bugs show up, they get fixed in Laravel, and now with a safety net that didn't exist before.
- If the core grows, extract instead of rewrite. If someday redemption and settlement get complex enough, they're pulled out into a separate service, with a pure core in Haskell or Rust, and Laravel stays as the shell. Martin Fowler called this strangler fig, after the strangler fig tree, a plant that grows around an old tree, branch by branch, until one day the old tree no longer holds anything up and the fig is still standing. The system gets replaced bit by bit, without a day when everything gets switched off.
Step one is the important one, and it's the one that always gets skipped. A rewrite done by agents without properties written in advance is a walk in the dark. The new code will be different from the old one, and you'll have no way of knowing whether it's better or worse, because you never wrote down what "correct" means. The agent is a formidable generator. But a generator without a filter only produces more things, not better ones.
First the filter. Then, if needed, the generator.
References
- Bernhardt, G. (2012). Functional Core, Imperative Shell (screencast). Destroy All Software · Boundaries (talk, SCNA 2012). Video
- Claessen, K. & Hughes, J. (2000). QuickCheck: A Lightweight Tool for Random Testing of Haskell Programs. ICFP 2000. DOI
- Fowler, M. (2004, revised in 2024). Strangler Fig. martinfowler.com
- quinn: a Rust implementation of QUIC with a sans-IO core (
quinn-proto). GitHub - str0m: a sans-IO implementation of WebRTC in Rust. GitHub
Everything this article claims, in code that runs. Clone it, break it, open an issue.
Ragnagrok/first-the-filter-then-the-generatorIf this article was useful to you, you can sponsor the blog on GitHub. It helps me keep writing.