A regex engine that cannot blow up

The query layer reads text, builds a shape from it, and runs the shape. This lesson does the same for a pattern: text in, a small machine out, then the machine runs.
On 2 July 2019, Cloudflare released a new firewall rule that held a regular expression: a short pattern that says which text to match. Cloudflare’s own report says its service went down for 27 minutes, and an engineer told the report’s author that the company had lost 80% of its traffic. The pattern was not wrong. The engine that ran it can take longer and longer on some texts, with no limit.
By the end of this lesson you will be able to write a regex engine in about 100 lines of Python that parses a pattern, builds a machine from it, and runs that machine in time that grows in a straight line with the text. You will also be able to show, with counted steps, why the usual way of running a regex can take days on a 50-letter text.
The history (optional)
Ken Thompson described the machine used here in “Regular expression search algorithm”, Communications of the ACM 11(6), June 1968, pages 419 to 422. In January 2007 Russ Cox wrote “Regular Expression Matching Can Be Simple And Fast”, which showed that Perl needed over sixty seconds for a 29-character match that Thompson’s method does in about twenty microseconds, and that Java, PHP, Python and Ruby had the same weakness. The Cloudflare report is “Details of the Cloudflare outage on July 2, 2019”. Its fix list includes switching to the re2 or Rust regex engines, “which both have run-time guarantees”. Nothing later in this lesson depends on this story.
Before you start. An interpreter of your own showed how text becomes a list of tokens and then a tree, and how a program walks that tree. This lesson uses the same two steps on a pattern. The Page at 3 a.m. (Incident Response) told the Cloudflare outage as an incident. Here we open the one regex inside it. Recursion & Dynamic Programming showed that a function which calls itself twice can do an enormous number of calls. That is the whole reason for the blow-up.