← All articles

An Oracle That Never Ships

A small Haskell model that never reaches production, a PHP system that does, and why half of what Volvo found were errors in the standard

17 min readsoftware-testinghaskellfunctional-programmingsoftware-architectureartificial-intelligence

Machine-translated from Spanish. Read the original

ByFederico Sawady O'ConnorRagnagrok Academy

In First the Filter, Then the Generator I ended with a plan for a gift card system built in Laravel, the most widely used web framework in the PHP world. The first step was to write a model of the system's core in Haskell and use it to check the real system against. Haskell came in "as a filter, not as the implementation".

I said it in one paragraph and moved on. This article is that paragraph, slowly and with code that runs, about a model that never ships (it never goes to production, never serves a customer) and whose only job is to say what the real system should answer.

The oracle problem

In testing, an oracle is whatever tells you whether an answer is correct. It sounds like a detail, but it's the hard part.

Generating test cases is cheap. QuickCheck, the property-based testing tool I wrote about in QuickCheck vs. Traditional Testing as a Deterministic Harness in the GenAI Era, makes up thousands of inputs per second. The expensive part is knowing, for each one, what should have happened.

There are three ways to answer that, from least to most ambitious:

  • A unit test has the answer written by hand ("if I sell a card for 100 and redeem 30, the balance is 70"). It covers that case and no other.
  • A property test has a rule that always holds ("a code is never redeemed more than once"). It covers millions of cases, but checks only one thing about each.
  • A model is a second program, small and obviously correct, that says exactly what the system has to answer to any sequence of operations. It checks everything, in every case that gets generated.

The model isn't a prototype or a rewrite. It's a specification you can run.

The model

To show it, I built a small proof of concept with a single gift card. The whole model, in Haskell, is this:

data Status = Available | Sold | Expired

data Card = Card
  { status   :: Status
  , balance  :: Int
  , redeemed :: [Int]  -- redemptions not yet reversed, most recent first
  }

data Command = Sell Int | Redeem Int | Reverse | Expire | Balance

data Response
  = Ok | Funds Int | Insufficient | NotSold
  | AlreadySold | IsExpired | NothingToReverse

step :: Command -> Card -> (Response, Card)
step cmd card = case (cmd, status card) of
  (Balance, _) -> (Funds (balance card), card)

  (Sell n, Available) -> (Ok, card { status = Sold, balance = n })
  (Sell _, _)         -> (AlreadySold, card)

  (Redeem n, Sold)
    | n > balance card -> (Insufficient, card)
    | otherwise        -> (Ok, card { balance = balance card - n
                                    , redeemed = n : redeemed card })

  (Reverse, Sold) -> case redeemed card of
    n : rest -> (Ok, card { balance = balance card + n, redeemed = rest })
    []       -> (NothingToReverse, card)

  (Expire, Sold) -> (Ok, card { status = Expired })

  (_, Available) -> (NotSold, card)
  (_, Expired)   -> (IsExpired, card)

Even if you don't know Haskell, it reads. A card is available, sold or expired, and it has a balance. Five things can be done to it, which are to sell it for an amount, redeem an amount, reverse the last redemption (say, because the merchant cancelled the purchase), expire it, and check the balance. The step function says, for each combination of command and status, what gets answered and how the card ends up.

Every line is a business decision. The last one, for example, says that nothing is done to an expired card, no redemptions, no reversals. That decision is mine, I made it while writing the model, and in a moment it's going to matter.

The model doesn't touch a database, doesn't look at the clock, doesn't send emails. Data in, data out. It's the pure core from First the Filter, except this time it never goes to production.

Making them argue

The "real" system in the proof of concept is a toy service in PHP with an SQLite database, the size of a Laravel controller. It answers over HTTP at /sell?amount=10, /redeem?amount=3, /reverse, /expire and /balance. I left two errors in it on purpose, the kind I see in real systems; I'm not saying which yet.

The comparison is called lockstep testing. The description in the quickcheck-lockstep library is spot on. According to it, you generate a random sequence of calls, run it against the system and against the model, and compare the responses.

Written by hand with QuickCheck, no libraries, it's this:

-- The adapter: one command, one HTTP request.
send :: Manager -> String -> Command -> IO Response
send http base cmd = do
  req <- parseRequest (base ++ path cmd)
  read . BL.unpack . responseBody <$> httpLbs req http

prop_agrees :: Manager -> String -> [Command] -> Property
prop_agrees http base cmds = monadicIO $ do
  run (reset http base)
  actual <- run (mapM (send http base) cmds)
  let expected = responses cmds
  monitor (counterexample (report cmds expected actual))
  assert (actual == expected)

prop_agrees starts from a new card, sends a sequence of commands to the PHP over HTTP, asks the model for the answers that should have come back (responses applies step command by command) and demands that they be equal. QuickCheck takes care of making up the sequences, with sales, redemptions, reversals and expirations in any order and number.

In a real Laravel app the adapter is the same, with one HTTP request per command or a call into the service layer.

What it found

First run. After a few dozen sequences a disagreement shows up, and QuickCheck shrinks it down to the minimum. That's called shrinking. If the failing sequence had thirty commands, it tries removing and simplifying until it can't remove anything else without the error going away. This is what it shows:

[Sell 1,Expire,Reverse]
command       model               system
Sell 1        Ok                  Ok
Expire        Ok                  Ok
Reverse       IsExpired           NothingToReverse   <--

Sell, expire, reverse. The model says "the card is expired"; the PHP says "there's nothing to reverse".

This isn't a bug. It's a question. What happens if a merchant cancels a purchase made with a card that later expired? Does the balance go back to a card that can no longer be used? Is it rejected? Does the customer get the money back some other way? Nobody had decided. The model had to say something, because step has to answer for every combination. The PHP said something too, but without anyone noticing, because its /reverse only checks that the card isn't available, and never looks at whether it expired. With a redemption before the expiration, the PHP gave balance back to an expired card.

I decide the model's answer stands, change the PHP to do the same, and run again:

[Sell 1,Redeem 1,Reverse,Reverse]
command       model               system
Sell 1        Ok                  Ok
Redeem 1      Ok                  Ok
Reverse       Ok                  Ok
Reverse       NothingToReverse    Ok   <--

Now it is a bug, and an expensive kind. Sell, redeem, reverse, reverse again, and the PHP gives the same redemption back twice. It looks for "the last redemption" without checking whether it was already reversed, so the money comes back every time someone presses the button. The fix is one condition in a query (AND reversed_at IS NULL).

The third run gives +++ OK, passed 1000 tests. A thousand random sequences, all answered the same by both, in about forty seconds of HTTP requests.

Both failures were four commands or fewer. Neither is hard to understand once you see it. What's hard is thinking of writing that test, because nobody writes "reverse twice" or "reverse after expiring" by hand until it happens to them in production.

Volvo and AUTOSAR

This isn't a trick that only works on a toy. The largest project done with QuickCheck up to that point is exactly this pattern, at industrial scale, and John Hughes, one of the two authors of QuickCheck, tells the story in Experiences with QuickCheck (2016).

Modern cars have between 50 and 100 processors, and many manufacturers base their software on AUTOSAR, a standard that defines, among other things, the "basic software" that runs on each of them, such as the communication stacks, routing or diagnostics. Several suppliers sell implementations of the standard, and a car usually mixes several of them. If they don't follow the standard, two processors may not understand each other, and it's not even easy to tell whose fault it is.

Volvo Cars wanted to test whether its suppliers' code conformed to the standard, and paid Quviq, Hughes's company, to write QuickCheck models. The models didn't go into any car. They were only there to be compared against the suppliers' C code.

Hughes describes one of the errors, in the stack for the CAN bus, the wire over which almost every part of the car talks. Each message has an identifier that is also its priority (the lower, the more urgent). The failure QuickCheck found, once shrunk, was four steps long:

  1. Send a message with identifier 1. The bus is now busy.
  2. Send one with identifier 2. It waits.
  3. Send one with identifier 3. It waits too.
  4. Confirm that 1 went out. Now 2 should go out.

Out went 3. The standard allows identifiers of two sizes, and that implementation marked the long ones with an extra bit that it forgot to ignore when comparing priorities. Message 2 used the long format and so, as far as the queue was concerned, it was the least urgent of all. Hughes's advice is "don't adjust the volume during emergency braking".

And then the numbers, in his words:

For this project we read around 3,000 pages of PDFs (the standards documents). We formalized the specification in 20,000 lines of QuickCheck code. We used it to test a million lines of C code in total, from 6 different suppliers, finding more than 200 problems—of which well over 100 were ambiguities or inconsistencies in the standard itself!

Well over 100 out of more than 200 means that about half of what they found weren't the suppliers' errors. They were errors in the document everyone was trying to comply with. There's one more detail in the same text. When the AUTOSAR consortium released six "official" test cases for the CAN stack, the team showed that three of them weren't consistent with the standard.

And another figure, about cost. In the cases where they could compare against traditional test suites, the model code was an order of magnitude smaller, and tested more.

Why half were errors in the standard

Volvo's story is the proof of concept's first failure, times a hundred. The model mostly didn't find badly written code, but rather that the specification didn't say what everyone thought it said.

Hughes explains it in the conclusions of the same text, where he says that errors are found by comparing two independent descriptions of the desired behavior, the implementation and the specification, and it's the inconsistencies between the two that reveal them. And to people who ask him whether it wouldn't be great to synthesize the code straight from the specification, he says no, because "we would just replace buggy code with buggy specifications".

There's a name for this, the specification gap. Every verification technique checks a statement you wrote. Types, tests and even a mathematical proof show that the code does what you said. None of them tells you whether what you said was what you wanted. If the business rule was misunderstood, the proof is perfect and the system is wrong.

A model doesn't close that gap either. What it does is concentrate it in a place where you can look at it. Instead of the business rules being scattered across controllers, jobs and queries, they're in forty lines you can read in one sitting. And every time the model and the system disagree, someone has to decide which of the two is right. Sometimes it's the system. Sometimes it's the model. And sometimes, as with the expired card, neither, because nobody had asked the question.

That decision gets paid for once, when the model is written. The alternative is finding it out in production.

Why Haskell, if production is PHP?

I could write the model in PHP. But a model in PHP, written by the same team, with the same habits, tends to have the same holes as the code it's trying to verify. What makes an oracle valuable is that it's independent.

Haskell also helps exactly where a model needs it. Data types with several shapes (Available | Sold | Expired) and pattern matching turn forgetting a case into a compiler warning instead of silence. And a function like step can't touch the world even if it wanted to, because the language won't let it.

And since the model never ships, all the usual reasons not to use Haskell go away. Performance doesn't matter, because it serves no traffic. Whether there are people to hire who know it doesn't matter, because the system is still an ordinary Laravel app, and whoever maintains it doesn't have to touch the model to fix a bug. There's no rewrite, because you don't need to turn Laravel into something else to get the guarantees. You need a model and an agreement check.

A command interface, before the first test

For the model and the system to argue, both have to speak the same language (sell, redeem, reverse, expire). That forces the real system to have those operations as a real domain interface, and not as logic spread across five controllers and a job.

That pressure is good on its own. A good part of the benefit arrives before the first test runs.

Detecting and preventing

The model detects, that is, it finds disagreements after the code exists. Preventing, making the error impossible to even write, is better. But the cost differs depending on what you want to protect:

kind of rule example what pays off
local, about a single value an amount is never negative; the currency travels with the amount prevent: value types in PHP, CHECK constraints in the database
global or over time a card's lifecycle; sequences of redemptions and reversals; expirations detect with the model

For local rules, preventing is cheap and worth it. For the others, preventing in PHP is very expensive, and detecting with a model costs a fraction of that.

The two also feed each other. The model says what must always be true, and that can often be pushed down into the database. After the double reversal, for example, there's an obvious rule the schema didn't have, that the balance can never exceed what was sold.

CHECK (balance BETWEEN 0 AND sold_amount)

It doesn't catch every double reversal, because if the repeated redemption is small, the balance can stay below the amount sold. But many of them go from money silently given away to an error that fires on the spot.

What it costs

Two codebases that drift apart. This is the main risk. The model has to cover only the core where the rules that matter live (money, lifecycle, expirations). If it starts following screens and reports, the design is lost.

Concurrency. The lockstep testing in this article is sequential, with one client and one request at a time. It doesn't see the double redemption from two branches at the same time that I talked about in First the Filter. For that there's a second phase, which runs commands in parallel and checks that the result can be explained by some sequential order; quickcheck-state-machine has it built in. Hughes tells in the same text how he used that technique with Klarna, a Swedish payments company that had spent a year with a database that got corrupted every couple of months, and the person responsible for that database had spent six weeks at Klarna hunting for the error, with the theory that it struck when the file reached 1 GB. QuickCheck found it with a database of at most one record and five or six calls. But I wouldn't start there, because the sequential phase catches most logic errors.

Who maintains the model. A Haskell model that blocks deploys and that only one person knows how to maintain is a real risk. Three things reduce it, which are using boring Haskell, with no type tricks, readable almost as pseudocode; saving every failing sequence as an ordinary regression test in PHP, so a failure can be understood and fixed without knowing Haskell, and what's been accumulated isn't lost if the model is left without an owner; and documenting the model as what it is, the specification of the domain.

It's slow. Each sequence resets the database and talks HTTP. Forty seconds for a thousand sequences on a toy is several minutes on a real system. It runs in continuous integration or overnight, not on every save.

And with agents

This is what improves the most when the code is written by agents.

An executable model is the ideal specification for an agent, because it checks itself. An agent implementing a feature in Laravel doesn't have to convince anyone that it works, just keep agreeing with the model. It's the mechanism that can't be talked into anything, the one I wrote about in Convincing a Machine.

The model is also small. It can be reviewed with paranoia once, instead of being reviewed wearily on every change. The adapter and the code that wires it up, on the other hand, are mechanical work, the kind agents do well.

There's one condition, which is that the agent doing the implementation doesn't touch the model. If it can edit the oracle, a disagreement can be resolved from either side, and the wrong side is usually easier.

Where I'd start

  1. The command interface. It pays off even if you never write the model.
  2. A sequential model of the lifecycle. Sale, redemption, reversal, expiration. Nothing else.
  3. Every failure, a regression test in PHP. The model generates; PHP keeps.
  4. Concurrency, last. Or never, if the database already settles the races that matter.

The model doesn't go to production. What goes to production are the decisions it forced you to make.


The proof of concept, with the model, the PHP service, the two errors and a script that reproduces the three runs, is at github.com/Ragnagrok/an-oracle-that-never-ships.

References

  • Hughes, J. (2016). Experiences with QuickCheck: Testing the Hard Stuff and Staying Sane. In A List of Successes That Can Change the World, LNCS 9600, pp. 169–186. Springer. DOI · PDF
  • Arts, T., Hughes, J., Norell, U. & Svensson, H. (2015). Testing AUTOSAR Software with QuickCheck. IEEE ICST Workshops 2015. DOI
  • Hughes, J. & Bolinder, H. (2011). Testing a Database for Race Conditions with QuickCheck. ACM SIGPLAN Erlang Workshop 2011.
  • Claessen, K. & Hughes, J. (2000). QuickCheck: A Lightweight Tool for Random Testing of Haskell Programs. ICFP 2000. DOI
  • de Vries, E. (2022). Lockstep-style testing with quickcheck-dynamic. Well-Typed · quickcheck-lockstep
  • quickcheck-state-machine: state machine testing, with parallel execution. Hackage
The code

Everything this article claims, in code that runs. Clone it, break it, open an issue.

Ragnagrok/an-oracle-that-never-ships
Support the blog

If this article was useful to you, you can sponsor the blog on GitHub. It helps me keep writing.