Preface
Petri nets were invented in 1962. They predate Unix, the internet, and object-oriented programming. For most of their history, they lived in academic papers — a formalism known to theorists but invisible to working programmers.
This book argues they deserve wider use, and it makes one claim about why. A system built from parts has to be written down in some notation for composition, and several are in use: cospans of sets, string diagrams, ZX-style spiders, operad wiring diagrams, incidence matrices. Each was designed for its own community, and each has its own rules for what “plug these two together” means. The open Petri net — places, transitions, arcs, and a boundary of places left open for gluing — has a presentation in every one of them, and the claim is that each presentation is faithful and that gluing two open nets along a shared place gives the same net in all of them. What is checked by machine is narrower than the claim, and the next paragraph says exactly what it is. We call that claim being a canonical carrier for compositional systems: one structure, many faithful presentations, and one meaning of composition across all of them.
The evidence is public, in pflow-native’s composition views. They draw two compositions ten ways — as a cospan, as spiders, as an operad wiring diagram, as a string diagram, as the flat net, as a net with boundaries, as lenses, as incidence matrices, as runs (processes) and as composition laws — and the two are a model bundle, orders, which links a queue, a resource pool and a payment saga, and a search plan, connect4, which assembles a Connect-4 solver from pieces. A reference tool checks each part. go-pflow checks the bundle: its verdicts on all 5,576 possible links between the ports of six subnets, on eleven flatten cases (one refused, four glued along shared places) and on four scenario runs are recorded in a receipt, and pflow-native, which composes with pflow-rs, matches every one. pflow-rs checks the plans: its verdicts on 289 plans are a second receipt, made before pflow-rs changed some of them on purpose, so the test names each difference and asserts its count: of the 289 plans, 197 get the same verdict and 92 differ, 89 because pflow-rs changed on purpose (seven kinds of change, each counted) and 3 only in the wording of a refusal of a malformed plan, which comes from how pflow-native builds pflow-rs. The receipt holds parse, check and solver-construction verdicts; the solver’s printed values and node counts are not compared, and this is pflow-rs against its own earlier verdicts, not a second implementation. Chyp checks what follows from the composition laws — event links as synchronising spiders, and how plan pieces chain, meet and wrap: given the laws as rules, it checks each rewrite, while the laws themselves are stated, not checked against go-pflow or pflow-rs. Upstream Chyp computed its verdicts on four theories, 33 rewrites, of which the 30 meant to hold are valid and the three negative controls are rejected; pflow-native draws them and does not re-check them. Each view records what it draws as a scene manifest, and the goldens hold 100 of them, ten views of two compositions in five states: pflow-native’s test redraws each one headless and requires it to equal its golden, pflow.xyz’s browser views are held to the same file, and screenshots show all ten views of both compositions (the Boundaries view has nothing to draw for the search plan). What none of this checks is that each notation, composing by its own rules, reaches the same net. Every view but Laws, which draws Chyp’s precomputed exports, draws the one composite pflow-native computes (the flat net, or the plan’s net), so the views agree by construction, and the cross-check is between two implementations of the gluing, go-pflow’s and pflow-rs’s. Faithfulness, that a presentation loses nothing, is not tested here either. The views’ Chyp theories are also not the ones in chyp-rs (below). chyp-rs states its own laws on the same four subjects, and upstream Chyp agrees with it on every step of those, but it has not been run on the views’ theories: their source files are not published, only Chyp’s exports of them, and three of the four use typed wires, which chyp-rs leaves out. Chapter 20 applies the same discipline to runtimes.
A model written this way is also a value, not a program. It is a document: it can be hashed, diffed, composed with another model by sharing a place, and checked by a machine that has never seen any of our code. That is what lets one document be a state machine that handles concurrency, a workflow engine with formal guarantees, a simulation model that converts to differential equations, and a specification from which a running application, a kernel-checked theorem and a zero-knowledge proof are derived rather than written.
We call the practice built on it Metamodel. The plain definition is the literal one: a model for making models. Its vocabulary is place, transition, arc and guard, with local rules for how two models fit together, and it is not a model of any particular thing — not a coffee shop, not a token. The pflow ecosystem is where it is tested. You draw a net in a browser editor, simulate it and generate an application, all from the same JSON-LD model, and pflow-polyglot holds twenty implementations of one model in four languages to one golden trace (Chapter 20). The domains the same vocabulary has already been tiled across — a coffee shop, a token standard, a poker game, a drum machine, and the infrastructure that serves this book — are the evidence that it travels.
What This Book Claims, and What It Does Not
The title says universal, and the word needs fencing before Chapter 1 uses the formalism for anything. The claim is about composition: among notations for systems built from parts, the open Petri net is one structure that all of them can carry without loss. It is not a claim about computation, and not a claim about every kind of system.
The scope is systems built from parts — components with state, events that change it, and resources or conditions that two components can share. A queue, a protocol, a recipe, a game, a ledger and a chemical reaction network all fit. A system whose meaning sits in a continuous field, in a learned weight matrix or in unstructured text does not become a Petri net by being drawn as one, and the book makes no claim about those.
Several limits are worth naming now, because later chapters lean on them.
Ordinary place/transition nets are not Turing-complete. Their reachability problem is decidable (Mayr 1981; Kosaraju 1982), which is a real strength: “can this workflow finish?” has an algorithm. The algorithm is impractical in the worst case, though. Reachability is Ackermann-complete (upper bound Leroux and Schmitz 2019; lower bound Czerwiński and Orlikowski 2021, and independently Leroux 2021), and even coverability is EXPSPACE-complete (Lipton 1976; Rackoff 1978). The tools in this book explore bounded nets of modest size and stop at a configurable state limit (Chapter 1), which is an engineering bound, not a decision procedure for every net.
Extensions buy expressiveness and spend the guarantees. An inhibitor arc tests a place for zero, and inhibitor arcs on just two places are enough to simulate a two-counter machine (Minsky 1967), so nets with inhibitor arcs are Turing-complete and their reachability is undecidable (Chapter 4). A guard over typed data, such as balances[from] >= amount, is a predicate the incidence matrix cannot see. Both kinds of contextual test also leave the free symmetric monoidal category that makes composition well behaved (Appendix E). The canonical-carrier claim covers place, transition and arc. The guard is the fourth term of the token language and the one that steps outside the claim; a model that uses one is checked by exploring states, not read off the structure.
Faithful means faithful to a pair of matrices, not to their difference. The incidence matrix of Chapter 2 records net change, so a self-loop cancels to zero and two different nets can share a . The presentation that carries a net without loss is the pair of input and output matrices together with the boundary. Gluing along a shared place is the composition the presentations are meant to agree on. Fusing two transitions into a rendezvous, Chapter 4’s EventLink, is a second kind of composition, and it has a string-diagram presentation of its own: the link is a synchronising spider on the transitions’ event ports, a special commutative Frobenius algebra. chyp-rs, a Rust port of Chyp’s checker, takes the Frobenius, commutativity and speciality rules as given and checks that the laws which make that presentation well behaved follow from them — two connected sync points fuse into one, their legs are unordered, and fusing three transitions gives the same sync point whichever pair is fused first (laws/sync_spiders.chyp). A rendezvous still refines rather than extends, so the safety-not-liveness caveat below applies to it as well.
Composition preserves safety and not liveness, and safety only for one kind of composition. Fusing transitions can only restrict what each component can do, so a property of the form “no reachable marking looks like this” survives; go-pflow checks this on one bundle, which is a test, not a proof for every bundle. Gluing along a shared place is weaker, because the other side can add tokens to that place or take them away: a component’s conservation law survives when the other side has an invariant that agrees with it on the shared places — the case the Lean theorem invariant_lift proves (proofs/PflowProofs/InvariantLift.lean) — and not otherwise. “This transition can always fire again” survives neither: Appendix E glues one netting transition onto a settlement cycle whose every transition is live, and the composite reaches a dead marking in four firings.
None of this is new mathematics. The free-category theorem is Meseguer and Montanari’s and Sassone’s, open nets as cospans are Baez and Master’s, and the decidability results are decades old; Appendix E lists the references. What this book adds is a working ecosystem in which the same document passes through each of these readings, and the implementations are made to agree by machine.
Who This Book Is For
You know how to program but haven’t encountered Petri nets before — or you’ve seen the formalism and wondered what it’s good for in practice.
The examples are in Go and JavaScript. The mathematics uses standard notation — vectors, matrices, differential equations. Where a result comes from code, the chapter links the code or model that produces it, so you can run it yourself.
How to Read This Book
There are two paths through the material:
- Theory track: Read Parts I and III for the mathematical foundations and advanced topics — formal definitions, incidence matrices, ODE solvers, invariants, and the categorical reasons composition works.
- Hands-on track: Skim Part I for vocabulary, then go to Part II’s worked examples (coffee shops, games, biochemistry) and Part IV’s tooling guides.
Part I: Foundations
Chapters 1-4 introduce the formalism. Places, transitions, arcs — structure — and tokens, the state that moves through it. Then firing rules, incidence matrices, and conservation laws. Then the conversion of discrete nets to continuous ODE systems via mass-action kinetics. Finally, the token language DSL, which adds the fourth primitive — the guard — and typed composition.
Part II: Applications
Chapters 5-10 apply the formalism to six domains: resource management (coffee shop), game mechanics (tic-tac-toe), constraint satisfaction (sudoku), combinatorial optimization (knapsack), biochemistry (enzyme kinetics), and complex state machines (Texas Hold’em). Each chapter builds a complete model from scratch, simulates it, and analyzes the results.
Part III: Advanced Topics
Chapters 11-16 push the formalism further. Process mining discovers nets from event logs. A net’s topology is enough to generate its proof circuit and, once moves and goals are labelled, its ODE rates. Exponential weights encode scoring systems. JSON-LD makes nets self-describing and content-addressable. Zero-knowledge proofs appear here as that generated circuit: a derived artifact, not a destination.
Part IV: Building with pflow
Chapters 17-20 cover the ecosystem tools. The visual editor for designing nets interactively. The hosted service that runs a stored model as seeded what-ifs and checks it. The Go library’s API and package structure. And the parity tests that hold implementations to one golden output — two at first, twenty by the end. The Epilogue names the claim the whole book has been making.
The pflow Ecosystem
The projects referenced throughout this book form a unified ecosystem:
| Project | Purpose | URL |
|---|---|---|
| go-pflow | Core library — ODE simulation, reachability, process mining | github.com/pflow-xyz/go-pflow |
| pflow.xyz | Visual browser-based editor for designing nets | pflow.xyz |
| pflow-polyglot | One model, five forms, ten languages, one golden trace | github.com/pflow-xyz/pflow-polyglot |
| sim.pflow.xyz | Hosted what-if simulation and verification of stored models, with an MCP server | sim.pflow.xyz |
The editor and the library share the same JSON-LD model format, and go-pflow converts it into the model format sim.pflow.xyz stores and runs (parser.ModelFromJSON). A net designed in the editor can be simulated by the library without format conversion. The model is the source of truth.
Conventions
- Code examples appear inline for short snippets and in separate files for longer programs
- Mathematical notation uses standard linear algebra: bold lowercase for vectors (), uppercase for matrices ()
- Cross-references link between chapters: “the coffee shop model (Chapter 5)” or “mass-action kinetics (Chapter 3)”
- Go code uses the
go-pflowlibrary API; JavaScript uses the pflow.xyz browser modules - JSON-LD models use
@context: "https://pflow.xyz/schema"; the few snippets in other vocabularies (schema.org, in Chapter 16) name their own context
Acknowledgments
This book grew from blog posts, documentation, and working code written over two years. The pflow ecosystem is open source, and the ideas draw on sixty years of Petri net theory — from Carl Adam Petri’s 1962 dissertation through the process mining work of Wil van der Aalst and the categorical semantics of Meseguer, Montanari and Sassone.
The best way to learn is to build. Open pflow.xyz in a browser, draw a net, and press play. The mathematics follows.
License
To the extent possible under law, the author has dedicated this book to the public domain under the CC0 1.0 Universal dedication. You may copy, modify, translate, redistribute and build on it for any purpose, with no permission and no attribution required. The Go code that builds the book and the site is separate and is released under the MIT license; see the repository.
Why Petri Nets?
Learning objective: Understand what Petri nets offer over flowcharts, state machines, and ad-hoc modeling.
You already know how to model systems. You’ve drawn flowcharts on whiteboards, sketched state machines in design docs, and built ad-hoc abstractions in code. These tools work for small systems. This chapter is about where they break, and what Petri nets offer instead.
The Problem with Informal Models
Every software project starts with a model, whether the team knows it or not. Someone draws boxes and arrows on a whiteboard. Someone else writes a state machine in an enum. A third person embeds the workflow directly in if-else chains. All three believe they’re describing the same system.
They usually aren’t.
Informal models fail in predictable ways:
Flowcharts can’t express concurrency. A flowchart is a sequence with branches. It handles “do A then B” and “do A or B” well enough. But “do A and B at the same time, then wait for both to finish” requires awkward workarounds — swim lanes, join bars, footnotes — and real systems are concurrent.
State machines explode. A state machine with boolean variables has possible states. A system tracking 10 independent conditions has 1,024 states. Most of those states are meaningless combinations, but the machine doesn’t know that. You end up either enumerating impossible states or pretending they can’t happen.
Ad-hoc models can’t be analyzed. When the workflow lives in code — scattered across handlers, middleware, and database triggers — there’s no way to ask “can this system deadlock?” or “is this queue bounded?” You find out in production.
The root problem is the same in each case: the model doesn’t capture the structure of the system it represents. Concurrency, resources and state are left implicit, and you can’t analyze what you haven’t modeled.
A Brief History
In 1962, Carl Adam Petri submitted his doctoral dissertation, Kommunikation mit Automaten (Communication with Automata), to the Technical University of Darmstadt. He was 36 years old, and he had been thinking about the problem for over a decade — his first sketches of what would become Petri nets date to 1939, when he was thirteen.
Petri’s insight was simple to state: concurrent systems need a model where multiple things can be true at the same time. State machines force you to enumerate every combination of conditions as a single global state. Petri’s nets decompose the state into independent pieces — places — each holding its own local truth. The interactions between these pieces are explicit in the structure of the net.
The formalism found its first serious applications in hardware design, where concurrency is unavoidable. By the 1980s they were in wide use for manufacturing systems and communication protocols, and workflow modeling took them up in the 1990s. Business process notations such as BPMN describe their execution in terms of tokens moving through a diagram, and a common way to analyze such a diagram formally is to translate it into a Petri net, even though most practitioners never see that net.
Petri spent his career at the GMD (German National Research Centre for Computer Science) in Bonn, refining the theory and advocating for precise models of concurrent systems. He died in 2010. The formalism he created — places, transitions, and the flow of tokens between them — is still the base that colored, timed and stochastic Petri nets extend, and it is the base this book builds on.
Places, Transitions, Arcs, Tokens
A Petri net has exactly four kinds of things:
Places are drawn as circles. A place represents a condition that can be true or false, a resource that can be available or consumed, a state that a piece of the system can be in. Think of a place as a container.
Tokens are drawn as dots inside places. Tokens represent the current state of the system: which conditions hold, how many resources are available, where entities are in a process. The distribution of tokens across all places is called the marking — it’s the complete snapshot of the system at a moment in time.
Transitions are drawn as rectangles (or bars). A transition represents an event, an action, something that happens, such as registering a user or brewing a coffee. A transition changes the state of the system by moving tokens around.
Arcs are arrows connecting places to transitions and transitions to places. An arc from a place to a transition means “this transition needs a token from this place.” An arc from a transition to a place means “this transition produces a token in this place.” Arcs define the flow — who needs what, and who produces what.
That is the whole vocabulary of an ordinary Petri net. A traffic light, a biochemical pathway and a poker game are all built from these four elements, and so is anything else that decomposes into parts with local state and shared resources, the scope the Preface sets.
One distinction is worth fixing now, because the rest of the book leans on it. Places, transitions and arcs are structure — they are what a model is. Tokens are state — the marking is what a model is doing right now, and it changes on every firing while the structure does not. Structure is what composes: leave some places open as a boundary and two nets can be glued along them, which is the operation every compositional notation in the Preface agrees on. The alphabet this book builds with is therefore three structural terms plus one more that arrives in Chapter 4: the guard, a condition on when a transition may fire. Place, transition, arc, guard — four primitives, and no fifth. Everything else, from balances to brew to the tic-tac-toe move X00, is what a domain sounds like once it has been written in them. The guard is not on the same footing as the other three, though. The incidence matrix of Chapter 2 records places, transitions and arcs; a guard is a predicate on the marking that the matrix does not see, so a property that depends on a guard is checked by exploring states rather than by linear algebra, and a guarded net leaves the structure that makes composition well behaved. Appendix E states exactly where that line falls.
The Firing Rule
The one rule that makes the whole thing work:
A transition fires when every input place has at least one token. When it fires, it removes one token from each input place and adds one token to each output place.
This single rule gives you sequencing (token moves from A to B), concurrency (two transitions can fire independently if they don’t share input places), synchronization (a transition with two input places waits for both), and resource management (a place with tokens represents available resources).
Weighted Arcs
Sometimes a transition needs more than one token from a place, or produces more than one. A number on an arc — its weight — specifies how many tokens are consumed or produced. An arc with weight 3 from a place to a transition means “this transition needs 3 tokens from this place to fire.” The firing rule generalizes accordingly: a transition is enabled when each input place holds at least its arc’s weight, and firing removes that many tokens and adds each output arc’s weight to its place. The rule above is the case where every weight is 1; Chapter 2 gives the formal version.
Your First Net: A Traffic Stoplight
A traffic light cycles through three states: green, yellow, red. At any moment, exactly one light is on. Here’s the Petri net:
*
[Green]--> [go_yellow] --> [Yellow]--> [go_red] --> [Red]--> [go_green]
^ |
+--------------------------------------------------------------+
Three places: Green, Yellow, Red. Three transitions: go_yellow, go_red, go_green. One token, starting in Green.
The token’s position tells you which light is on. Fire go_yellow and the token moves from Green to Yellow. Fire go_red and it moves from Yellow to Red. Fire go_green and it cycles back to Green.
The same net is in go-pflow as examples/stoplight/petri_net.go, with the token starting in Red and the transitions named RedToGreen, GreenToYellow and YellowToRed; its test checks the shape — three places, three transitions, six arcs (petri_net_test.go).
For one light, a state machine would work as well. The net’s advantage shows in three properties that follow from its structure:
Conservation. Each transition takes one token from one place and puts one token into the next, so no firing changes the sum . It starts at 1 and stays at 1: exactly one light is on in every reachable marking. That follows from the arcs alone, with no runtime check. Chapter 2 restates the argument in matrix form, as a P-invariant with and .
Impossible states are unreachable. A hand-written state machine for this light keeps the color in a variable, and a bug can set it to something outside the three valid values. In the net you can write down a marking with tokens in both Green and Red, but its token sum is 2, so the conservation law rules it out of every run that starts from the initial marking. The bad state is excluded by a property you can check rather than by a convention you have to keep.
Composability. Want to model an intersection? Add a second traffic light net. Connect them with a coordination mechanism — a shared place that ensures one direction is red when the other is green. Each light keeps its internal structure; the coordination is explicit in the arcs between them.
An Intersection
Two lights need to coordinate. To keep the example small, each light here has only red and green. We add a shared place Intersection_Free that acts as a mutual exclusion lock. Written as each transition’s inputs and outputs:
go_green_A: Red_A + Intersection_Free --> Green_A
go_red_A: Green_A --> Red_A + Intersection_Free
go_green_B: Red_B + Intersection_Free --> Green_B
go_red_B: Green_B --> Red_B + Intersection_Free
initial marking: Red_A = 1, Red_B = 1, Intersection_Free = 1
The token in Intersection_Free is consumed when one light turns green and returned when it turns red. Every transition moves that one token between Intersection_Free and a Green place, so the token count of Intersection_Free, Green_A and Green_B together stays at its initial value of 1, and the two lights are never green together. As with the single light, this is derived from the arcs by hand. The same net, with idle/busy in place of Red/Green and sem in place of Intersection_Free, is the mutexNet fixture in go-pflow’s verify/verify_test.go: TestMutualExclusionProvedStructurally requires the verifier to prove “at most one of busy1, busy2” from the semaphore invariant rather than by enumerating states, and TestMutualExclusionRefutedWithCounterexample removes the semaphore arcs from one client and requires a replayable firing sequence that makes both busy (the tests are cited, not re-run for this chapter).
This pattern — a shared resource place controlling access — models mutexes, semaphores, limited capacity, and turn-taking. It returns as turn control in Chapter 6: Game Mechanics — Tic-Tac-Toe.
Small Models, Not Large Language Models
Say “model” in a meeting today and most people hear “large language model”: billions of parameters, opaque weights, probabilistic outputs. Petri nets are a different kind of model, small and executable, and inspectable all the way down.
A coffee shop with five ingredients and five recipes is ten places and five transitions (Chapter 5). The tutorial Texas Hold’em model of Chapter 10, a simplified five-player table with all four betting rounds, has 18 places and 32 transitions. A Sudoku solver is larger but still finite and fully visible.
Small models offer properties that large models do not:
| Property | Large Language Models | Petri Nets |
|---|---|---|
| Inspectable | Not in practice | Yes — read the topology |
| Composable | Awkward | Native — connect shared places |
| Provable properties | Limited | Yes — invariants from the structure; reachability and deadlock by exploring states |
| Executable | Via code generation | Directly — tokens flow |
| Deterministic | Not in general | Yes, given the same firing sequence |
A Petri net model lets you answer questions before writing implementation code:
Reachability: “Given this initial state, can the system reach that target state?” This tells you whether a workflow is completable, whether a game has a winning move, whether an order can be fulfilled from current inventory.
Boundedness: “Does the system stay within limits?” This tells you whether a queue can overflow, whether a resource pool is properly managed, whether your system is closed or leaking.
Deadlock and liveness: “Can the system get stuck?” Deadlock-freedom means no reachable marking leaves every transition disabled. Liveness is stronger: every transition can always fire again, from every reachable marking. go-pflow’s pflow verify checks deadlock-free directly and this textbook liveness as l4-live, computed from the terminal strongly connected components of the reachability graph. Its property named live is the weaker check that every transition fires from some reachable marking, and the code’s own comment warns that a proved live does not imply deadlock-freedom (verify/property.go).
These are questions about the model’s state space, so they can be asked before the implementation exists. They are answered in two different ways. Invariants come from the incidence matrix by linear algebra and hold for any initial marking. Reachability, boundedness and deadlock are decided by exploring the reachable markings (reachability/analyzer.go), which finishes for a bounded net of modest size and otherwise stops at a configurable state limit (10,000 states by default) and marks the result truncated; an unbounded net is caught instead by a finite witness, a firing sequence that strictly grows the marking (the Karp–Miller criterion; reachability/coverability.go).
Exploring states is a decision procedure only in principle. Reachability for ordinary nets is decidable but Ackermann-complete in the worst case, so for a net of real size the state limit, not the theory, is what ends the search. An inhibitor arc or a data guard removes even the in-principle guarantee (Chapter 4).
Models as Specification
Here’s the workflow this book advocates:
- Sketch the net — places for states and resources, transitions for events
- Simulate — run the ODE solver to see if tokens flow the way you expect
- Analyze — check invariants, reachability, boundedness
- Generate code — derive the implementation from the validated model
The model becomes the specification and the code a derived artifact, regenerated when the model changes. When model and implementation disagree, the model wins, because it is the artifact whose properties you checked. In most software the code is the model, and the specification, if there is one, drifts out of date.
The rest of this book shows what this looks like in practice, from a coffee shop inventory system to a kernel-checked theorem and a zero-knowledge proof of a game move, all built from the same four primitives: places, transitions, arcs, and guards.
Try it live: Draw the traffic light in the browser editor at pflow.xyz (Chapter 17: The Visual Editor — pflow.xyz): three places, three transitions, one token in
Green. The editor fills enabled transitions green; click one to fire it and watch the token move.
The Mathematics of Flow
Learning objective: Read and write the formal notation; understand firing rules and state equations.
Chapter 1 introduced Petri nets informally — circles, bars, arrows, dots. That’s enough for intuition, but not enough for analysis. To prove that a system can’t deadlock, that a resource pool never loses a unit, or that a workflow always terminates, you need precise definitions. This chapter provides them.
The notation looks heavier than it is. Everything here follows from two ideas: a net is a bipartite graph with weights, and a marking is a vector of integers. The rest is matrix arithmetic.
The Formal Definition
A Petri net is a 5-tuple:
Where:
- is a finite set of places
- is a finite set of transitions
- is the flow relation — the set of arcs
- is the arc weight function
- is the initial marking
Two constraints keep things clean: (nothing is both a place and a transition) and (the net isn’t empty).
That is the whole definition. Places are where tokens live. Transitions are what moves them. Arcs say who connects to whom. Weights say how many tokens an arc carries. The initial marking says where tokens start.
Presets and Postsets
Every transition has inputs and outputs, written in a compact notation:
- — the preset of (input places)
- — the postset of (output places)
The same notation works for places:
- — transitions that feed into
- — transitions that feeds into
The bullet notation reads naturally: means “what comes before ,” and means “what comes after .”
Markings and the State Vector
A marking assigns a non-negative integer to each place — how many tokens it holds. Since a net has places, we can write the marking as a column vector:
This is the state vector. It captures everything about the system’s current state. Two markings are equal if and only if every place has the same token count in both. For the nets of this chapter there is no state outside the vector.
The initial marking is the starting state. For the traffic light from Chapter 1:
Every marking you can reach by firing transitions is a point in — non-negative integer coordinates, one per place. The set of all reachable markings, starting from , is the reachability set . For the traffic light, contains exactly three points: the token in Green, the token in Yellow, the token in Red.
Firing Rules and Reachability
A transition fires by consuming tokens from its input places and producing tokens in its output places. But it can only fire when it has enough tokens to consume. The enabling condition is:
Every input place must have at least as many tokens as the arc weight demands. If any input place is short, the transition is blocked.
When an enabled transition fires, the new marking is:
For every place : subtract the tokens consumed (arc from to ) and add the tokens produced (arc from to ). If isn’t connected to , both weights are zero and — unconnected places are unaffected.
A Worked Example
Consider a simple three-place chain:
[p1] -> t1 -> [p2] -> t2 -> [p3]
With initial marking (one token in ).
Step 1: Is enabled? Its only input is , and . Yes. Fire :
Step 2: Is enabled? Its only input is , and . Yes. Fire :
The token has moved from through to . The reachability set is . Three reachable markings, matching intuition — the token can be in exactly one of three places.
Firing Sequences
A firing sequence is an ordered list of transitions: . The sequence is valid from marking if each transition is enabled when it’s supposed to fire — is enabled at , is enabled at the marking after fires, and so on.
We write to mean “firing sequence is valid from and leads to .” The reachability set is then:
Nondeterminism
When multiple transitions are enabled simultaneously, either one could fire. The Petri net doesn’t prescribe which. This nondeterminism is deliberate: it models concurrency, where the order of independent events is unspecified.
In the traffic light, only one transition is ever enabled at a time, so there’s no nondeterminism. But in the intersection model from Chapter 1, when the shared token is available, both lights could claim it. The net structure constrains what’s possible; it doesn’t dictate the schedule.
The Incidence Matrix
Computing markings by hand gets tedious. The incidence matrix makes it mechanical.
The incidence matrix has one row per place and one column per transition. Each entry is the net effect of firing that transition on that place:
Positive means the transition produces tokens in that place. Negative means it consumes. Zero means no net effect, which includes a self-loop that consumes and produces the same number. Inhibitor and read arcs, which test a place without moving tokens, have no entry in at all; Appendix E explains what that costs.
go-pflow builds this matrix in IncidenceMatrix (reachability/invariants.go) with the same orientation, rows for places and columns for transitions, sorted by name, and it skips inhibitor arcs for the same reason.
Building the Matrix
For the three-place chain:
Reading column : firing removes one token from and adds one to . Reading column : firing removes one from and adds one to . Each column is a change vector — the delta applied to the marking when that transition fires.
The State Equation
With the incidence matrix, the firing rule becomes matrix multiplication:
Where is the firing count vector — how many times each transition fires. For a single firing of , :
Fire both transitions once () to go directly from to :
The state equation is linear: given any firing count vector, one matrix multiplication gives the resulting marking. The caveat is that it doesn’t check enabling. A firing count vector might describe a sequence that isn’t valid — some transition might need tokens that aren’t there yet. The state equation gives you a necessary condition for reachability, not a sufficient one.
A Richer Example
Consider a net where a transition has two inputs — the synchronization pattern:
[p1] --> t1 --> [p3]
[p2] --/
Transition needs a token from both and to fire. The incidence matrix:
With , firing gives . With , is not enabled — has no token. The synchronization is enforced by the structure.
P-Invariants and Conservation Laws
The incidence matrix also shows what cannot change, whatever sequence of transitions fires.
A P-invariant (place invariant) is a non-zero vector such that:
The vector assigns a weight to each place such that the weighted sum of tokens is preserved by every transition. If is a P-invariant, then for any reachable marking :
The proof is one line of the state equation. If , then , so
This is a conservation law: whatever fires, in whatever order, the weighted token count stays constant. The argument needs only the state equation, which holds for every valid firing sequence, so the caveat about enabling does not weaken it.
Finding P-Invariants
For the three-place chain, try :
It works. The invariant says:
The total number of tokens is always 1. go-pflow’s TestPInvariantThreePlaces (reachability/farkas_test.go) builds the same chain with five tokens in the first place, asserts that the only minimal invariant found is a + b + c == 5, and checks it on every reachable marking (not re-run here).
Chapter 1 argued informally that the traffic light keeps exactly one token. The same check makes that argument formal. With places Green, Yellow, Red as rows and transitions go_yellow, go_red, go_green as columns, the light’s incidence matrix and the all-ones vector give
so in every reachable marking. Each column sums to zero because each transition moves one token from one place to the next.
What Conservation Laws Tell You
P-invariants answer practical questions:
“Can tokens leak?” If is an invariant, the total token count is constant. The net is closed — nothing is created or destroyed. This is the Petri net equivalent of conservation of mass.
“Is this resource pool managed correctly?” If two places (available) and (busy) satisfy for some constant , then resources are always either available or busy, never duplicated or lost.
“Is the net bounded?” If every place appears in at least one P-invariant with a positive coefficient, then no place can accumulate unbounded tokens: for any invariant covering . The net is structurally bounded, bounded from every initial marking, with the bound depending on . The test is sufficient, not necessary; a net can be bounded without a covering invariant. go-pflow implements this test as StructuralBoundedness in reachability/invariants.go.
Partial Invariants
Not every net has a P-invariant covering all places. A net with a “source” transition (one that produces tokens from nothing) or a “sink” transition (one that consumes tokens into nothing) breaks total conservation. But subsets of places may still be conserved.
For example, in an open producer-consumer system, has no input place and has no output place:
t_produce -> [buffer] -> t_consume
The buffer’s row of is , and no non-zero makes , so this net has no P-invariant at all. go-pflow’s TestPInvariantNoneForUnbounded (reachability/farkas_test.go) checks the producer half of this net and expects an empty result.
Now add a capacity limit by looping a token back to a pool of empty slots, and let also record each delivery:
[empty_slots: 5] -> t_produce -> [buffer] -> t_consume -> [empty_slots]
\-> [delivered]
The incidence matrix, with rows empty_slots, buffer, delivered:
| empty_slots | ||
| buffer | ||
| delivered |
Solving by hand: the first column forces , and the second then forces . So , and in every reachable marking. The buffer can never exceed 5. The delivered place is in no invariant, and it grows by one on every consumption without limit: the conservation law covers part of the net and not the rest.
In Code
The go-pflow library computes incidence matrices and checks invariants directly. The net below is this chapter’s three-place chain with five tokens in the first place, built the way TestPInvariantThreePlaces builds it; the calls after it are the analyzer’s public methods:
net := petri.Build().
Place("a", 5).Place("b", 0).Place("c", 0).
Transition("t1").Transition("t2").
Arc("a", "t1", 1).Arc("t1", "b", 1).
Arc("b", "t2", 1).Arc("t2", "c", 1).
Done()
initial := reachability.Marking{"a": 5, "b": 0, "c": 0}
analyzer := reachability.NewInvariantAnalyzer(net)
matrix, places, transitions := analyzer.IncidenceMatrix()
fmt.Println(places, transitions, matrix)
for _, inv := range analyzer.FindPInvariants(initial) {
fmt.Println(inv.String()) // the test expects exactly one: "a + b + c == 5"
}
fmt.Println(analyzer.CheckConservation(initial)) // is the all-ones vector an invariant?
IncidenceMatrix builds from the net’s arcs and sorts places and transitions by name, so for this net it returns rows a, b, c and columns t1, t2: the table printed earlier in this chapter (read from the code, not re-run). FindPInvariants solves for semi-positive with the Farkas algorithm and returns the minimal-support invariants, each with its constant evaluated at the given marking; every semi-positive invariant is a non-negative combination of these, so an empty result means the net has no conservation law (provided the search did not hit its row limit, which PInvariantBasis reports). CheckConservation tests only whether the all-ones vector is an invariant, that is, whether the total token count is preserved. All three are in reachability/invariants.go; the tests in reachability/farkas_test.go cover weighted invariants, invariants over three places, and the mutual-exclusion net with its three separate laws.
Putting It Together
The mathematics of this chapter — the 5-tuple, the state equation, the incidence matrix, P-invariants — is the toolkit for structural analysis. Given a Petri net, you can:
- Write the incidence matrix from the arc structure
- Rule out markings with the state equation : a marking with no non-negative integer solution is unreachable, though a solution does not prove reachability
- Find conservation laws by solving
- Prove boundedness when P-invariants cover every place (sufficient, not necessary)
- Check for deadlocks by finding reachable markings where no transition is enabled
Items 1 to 4 are static analysis: you reason about the structure without running the net, and the results hold for every firing sequence. Item 5 is different. Deadlock depends on which markings are reachable, so it is found by building the reachability graph. go-pflow’s Analyzer.BuildGraph (reachability/analyzer.go) collects every explored marking with no enabled transition in Result.DeadMarkings, which is the definition used here. By that definition the chain’s final marking is dead. The separate Result.Deadlocks list is a heuristic for “stuck, not finished” that leaves out a marking drained to empty; TestEmptyDeadMarkingCounts in reachability/liveness_test.go pins the case where the two disagree, and TestGraphDeadlock in reachability/reachability_test.go checks the heuristic on a net that stalls for want of a second resource token.
That exploration is where discrete nets run into their limit. They track individual tokens and individual firings, and for large systems — thousands of tokens, complex topologies — the reachability set can be enormous. The next chapter trades exactness for scale by letting tokens be real numbers and transitions fire continuously, turning the state equation into a differential equation.
From Discrete to Continuous
Learning objective: Convert a Petri net into an ODE system and understand why this is powerful.
The previous chapter gave you a toolkit for analyzing Petri nets: incidence matrices, state equations, P-invariants. All of that works by tracking integer tokens through discrete firing events. This chapter shows what happens when you let go of the integers — when tokens become real-valued concentrations and transitions fire continuously at rates determined by the net’s structure. The state equation becomes a differential equation, and the entire apparatus of calculus becomes available.
Why Discrete Event Simulation Hits Walls
Discrete Petri net simulation is straightforward. Pick an enabled transition. Fire it. Update the marking. Repeat.
For small nets this works fine. But as systems grow, three problems compound:
Event volume scales with population. A hospital ER with 10 patients might generate 50 events (arrivals, triages, consultations, discharges). The same ER with 10,000 patients generates 500,000 events. Each event must be processed sequentially — check which transitions are enabled, choose one, fire it, update the marking, record the event. The cost scales linearly with the number of tokens moving through the system.
State space explodes. The reachability set grows combinatorially with the number of tokens and places. If a net’s transitions can spread 100 tokens over 10 places in every possible way, there are reachable markings (a stars-and-bars count, derived by hand rather than enumerated). Enumerating them becomes infeasible long before the model is “large” by real-world standards.
Individual identity is usually irrelevant. Discrete simulation tracks which specific token moved where. But for capacity planning, bottleneck analysis, or throughput estimation, you don’t care about Patient 47. You care about how many patients are waiting, on average, and how fast the queue drains. Tracking individuals is expensive bookkeeping for information you don’t need.
The continuous approach addresses all three. Tokens become real numbers — concentrations, not counts. Transitions fire continuously at rates determined by the current state. The evolution of the system is described by a set of ordinary differential equations (ODEs), one per place, and the cost of solving them does not grow with the number of tokens the way event-by-event simulation does.
Mass-Action Kinetics
The bridge from discrete to continuous comes from chemistry, where it’s called mass-action kinetics: the rate of a reaction is proportional to the product of the concentrations of its reactants.
Consider a transition with rate constant and two input places and :
[p1] --> t[k] --> [p3]
[p2] --/
In the discrete world, fires when both and have at least one token. In the continuous world, fires at a rate that depends on how many tokens are in its inputs:
More tokens in the input places means a higher firing rate. Zero tokens in any input place means zero rate — the transition stalls. This is the continuous analog of the enabling condition: instead of a binary enabled/disabled, you get a smooth rate that goes to zero as inputs deplete.
The General Rate Law
For a transition with rate constant and input places , go-pflow’s solver uses:
Each input place enters the rate once, to the first power, whatever its arc weight. The weight appears only in the stoichiometry: while flows at rate , it drains at and fills each output place at that arc’s weight times . A transition that consumes two tokens of per firing empties twice as fast as one that consumes one, but its rate is still linear in . This is the law in go-pflow’s solver/ode.go (buildVecODEFunction), which also sets a transition’s flux to zero whenever any of its input places is at or below zero.
Textbook chemical mass action differs on this point: it raises each concentration to its stoichiometric coefficient, , so a reaction is quadratic in . go-pflow does not. The two agree when every input arc has weight 1 and diverge otherwise; “When the Relaxation Doesn’t Apply” below returns to what that means when two engines are compared.
Why This Works
Mass action is the natural rate law when transitions fire at random with probability proportional to the availability of inputs. If a transition needs one token from and one from , and tokens are selected at random, the probability of a successful firing scales as .
Chemistry discovered this in the 19th century. The same logic applies to any system where events happen stochastically and depend on resource availability: customers joining queues, orders consuming inventory, players taking turns.
The Continuous Relaxation
With mass-action rates defined, we can write the ODE system for any Petri net. Recall the incidence matrix from Chapter 2, where is the net change in place when transition fires. Collect all transition rates into a vector:
The continuous state equation is:
This says: the rate of change of the marking is the incidence matrix times the rate vector. Each place’s token count changes by the weighted sum of all transition rates affecting it; the weights are the entries of , which is where arc weights enter the continuous model. Tokens flow in from transitions that produce, and flow out to transitions that consume.
Example: Three-Place Chain
The simplest non-trivial example:
[p1] -> t1[k1] -> [p2] -> t2[k2] -> [p3]
Incidence matrix and rate vector:
The ODE system:
Starting from with and :
Because the system is linear, it has a closed form, which we derived by hand rather than from a solver run:
and . Tokens drain from exponentially; fills, peaks at with exactly 5 tokens, then drains into , which approaches 10. The figure plots these formulas. go-pflow checks its own solver against the same kind of closed form: TestConsistencyLinearChain in stochastic/consistency_test.go runs a three-place chain (100 tokens, rates 1 and 0.5) and requires a tight-tolerance ODE solve (AccurateOptions with Dtmax lowered to 0.01) to stay within 0.1 token of , and their complement, and the discrete engine’s mean over 400 runs to stay within 1 token.
The conservation law still holds — for all time — because . Tokens aren’t created or destroyed, just redistributed continuously.
What Changes, What Stays
The continuous relaxation changes the execution model (real-valued tokens, rate-based firing) but preserves the structural properties:
- Conservation laws still hold. If in the discrete case, the same identity holds in the continuous case, and the weighted token sum is constant for all time.
- The incidence matrix is identical. The structure of the net doesn’t change.
- Boundedness from P-invariants still applies.
What you gain is speed at scale. The cost of a solve depends on the number of places and transitions and on how quickly the rates make the marking change, not on how many tokens there are to move one at a time; for a linear net like the chain, multiplying the initial marking by 1,000 multiplies the solution by 1,000 without changing its time scales. And the solution gives you a smooth trajectory — the entire evolution of the system, not just a sequence of discrete snapshots.
What you lose is individual identity. Token 47 no longer exists. You have 4.3 tokens in — a concentration, an average, a continuous quantity. For capacity and throughput questions that is usually the trade-off you want; “When the Relaxation Doesn’t Apply” below covers the cases where it is not.
Numerical Integration
Most ODE systems can’t be solved analytically. Even the three-place chain above has a closed-form solution only because it’s linear. Add a synchronization transition (two inputs) and the system becomes nonlinear — the rate depends on the product of two state variables, and closed forms are generally no longer available.
Instead, we solve numerically: start at the initial marking, compute the derivatives, step forward in time, repeat.
Euler’s Method (and Why It’s Not Enough)
The simplest numerical method is Euler’s method:
Where is the timestep and is the derivative function. Compute the slope, take a step in that direction.
Euler’s method works but is inaccurate. Its global error is — to halve the error, you must halve the timestep and double the work. For Petri net simulations with rates spanning several orders of magnitude, tiny timesteps are needed, making Euler impractically slow.
Runge-Kutta Methods
The standard remedy is to evaluate the derivative at multiple points within each step and combine them for a better approximation. These are Runge-Kutta methods, and they’re classified by their order — the power of in the error term.
A 4th-order method (RK4) has local error per step and global error ; a 5th-order method has local error . Higher order means fewer steps for the same accuracy.
Tsit5: What go-pflow Uses
The default solver in go-pflow is Tsit5 — a 5th-order Runge-Kutta method published by Charalampos Tsitouras in 2011 (solver/tsit5.go carries the reference and the coefficients). go-pflow evaluates its seven stages every step to compute both a 5th-order solution and an embedded 4th-order one. The difference between them estimates the error.
This error estimate enables adaptive timestep control. In go-pflow’s Solve (solver/ode.go) each step goes like this:
- Compute both the 5th-order and 4th-order solutions
- Scale each place’s error estimate by , the larger of its values before and after the step, and take the largest:
- If : accept the step and grow the next one by , at most fivefold and never past
Dtmax(0.1 underDefaultOptions) - If : reject the step and retry with a smaller one (a step already at
Dtminis accepted regardless)
The solver takes large steps where the solution is smooth and small steps where it changes rapidly. You specify the error tolerance, not the timestep, so one solver covers both a slow-draining reservoir and fast kinetics without hand-tuning the step, provided the system is not stiff. Tsit5 is an explicit method, so time scales that differ by orders of magnitude force it into very small steps; for that case solver/implicit.go provides the implicit methods ImplicitEuler and TRBDF2, which default to StiffOptions.
In code, the three-place chain above:
net, rates := petri.Build().
Place("p1", 10).Place("p2", 0).Place("p3", 0).
Transition("t1").Transition("t2").
Arc("p1", "t1", 1).Arc("t1", "p2", 1).
Arc("p2", "t2", 1).Arc("t2", "p3", 1).
WithCustomRates(map[string]float64{"t1": 0.2, "t2": 0.1})
prob := solver.NewProblem(net, net.SetState(nil), [2]float64{0, 50}, rates)
sol := solver.Solve(prob, solver.Tsit5(), solver.DefaultOptions())
final := sol.GetFinalState()
// closed form at t = 50: p1 ≈ 0.0005, p2 ≈ 0.13, p3 ≈ 9.87
The builder calls are those in go-pflow’s petri/builder.go, and NewProblem builds the mass-action derivative from the net’s arcs. We have not re-run this snippet for the book; the comment gives the closed-form values at , which DefaultOptions() (relative tolerance ) should reproduce to about that precision. The caller specifies the net, the rates and the time span; the solver chooses the steps.
Other Solvers
go-pflow provides several Runge-Kutta methods for different use cases:
| Solver | Order | Use Case |
|---|---|---|
Tsit5() | 5(4) | Default — Tsitouras’s 5(4) pair |
RK45() | 5(4) | Dormand-Prince — the classic MATLAB ode45 |
BS32() | 3(2) | Bogacki-Shampine — faster per step, less accurate |
RK4() | 4 | Classic fixed-step — no adaptive control |
Euler() | 1 | Forward Euler — teaching and debugging |
For most Petri net simulations, Tsit5 is the right choice. On a simple decay, go-pflow’s TestSolverMethodsProduceSimilarResults (solver/solver_test.go) requires Tsit5, RK45 and BS32 to agree within 5%. RK4() and Euler() carry no error estimator, so under adaptive options they run at a fixed step of Dt. The lower-order methods exist for comparison and for systems where function evaluations are extremely expensive.
Solver Presets
Rather than manually tuning tolerances, go-pflow provides presets for common scenarios:
solver.DefaultOptions() // General purpose (Dt=0.01, Reltol=1e-3)
solver.FastOptions() // Game AI, interactive (Dt=0.1, Reltol=1e-2)
solver.AccurateOptions() // Research, publishing (Dt=0.001, Reltol=1e-6)
solver.JSParityOptions() // As Default, but Dtmax=1.0; mirrored in pflow.xyz's petri-learn.js
DefaultOptions() has the same values as the defaults of pflow.xyz’s browser solver (public/petri-solver.js), so it is the preset that reproduces an editor plot. JSParityOptions() differs from it only in a larger Dtmax and matches jsParityOptions() in public/petri-learn.js; Appendix A: Solver Parameter Reference tabulates every preset.
The FastOptions preset trades precision for speed, for game AI where you need many evaluations per second; its doc comment in solver/ode.go estimates a tenfold speedup, and TestFastOptionsSpeed checks only that it takes fewer steps than AccurateOptions on an SIR net. AccurateOptions tightens tolerances for publication-quality results. ode.go defines further presets (StiffOptions, EpidemicOptions, WorkflowOptions and others).
Equilibrium Detection
Many systems settle into a steady state where nothing changes anymore. The ODE solver can detect this automatically.
Equilibrium means:
All derivatives are zero. Tokens still exist, but the flow in equals the flow out at every place. The system has reached a balance.
For the three-place chain, equilibrium is , all tokens in . The trajectory approaches it as without reaching it: under the product rate law neither input place empties exactly, but both rates decay toward zero. This is a terminal equilibrium — the system winds down to a stop.
Other nets reach dynamic equilibrium where transitions still fire but the marking doesn’t change. A net with a cycle:
[p1] -> t1[k1] -> [p2] -> t2[k2] -> [p1]
reaches equilibrium when — the flow from to equals the flow back. The tokens are still moving, but the concentrations are stable.
Why Equilibrium Matters
Equilibrium tells you the long-run behavior of the system:
Capacity planning. A hospital ER at equilibrium has stable queue lengths. Those lengths tell you whether you have enough doctors, whether patients wait too long, whether the system is overloaded.
Bottleneck identification. At equilibrium, tokens accumulate before the slowest transition. A place with a high equilibrium concentration is a bottleneck — work piles up there because the downstream transition can’t keep up.
Optimization. The equilibrium value of an objective function (profit, throughput, win probability) tells you how good a configuration is. Change a rate constant, re-solve to equilibrium, compare.
In Code
go-pflow can solve until equilibrium is detected, stopping early instead of integrating to an arbitrary end time:
prob := solver.NewProblem(net, initialState, [2]float64{0, 1000}, rates)
sol, result := solver.SolveUntilEquilibrium(
prob,
solver.Tsit5(),
solver.DefaultOptions(),
solver.DefaultEquilibriumOptions(),
)
if result.Reached {
fmt.Printf("Equilibrium at t=%.2f\n", result.Time)
fmt.Printf("Final state: %v\n", result.State)
fmt.Printf("Max rate of change: %e\n", result.MaxChange)
}
The equilibrium detector in solver/equilibrium.go checks the maximum absolute derivative across all places at regular intervals of accepted steps, once a minimum time has passed. When that maximum is below a tolerance (default ) at several consecutive checks, the solver declares equilibrium and stops. Presets control the sensitivity:
solver.DefaultEquilibriumOptions() // Tolerance 1e-6, 5 consecutive checks, every 10 steps
solver.FastEquilibriumOptions() // Tolerance 1e-4, 3 checks, every 5 steps
solver.StrictEquilibriumOptions() // Tolerance 1e-9, 10 checks, every step
TestSolveUntilEquilibrium in solver/solver_test.go exercises this on a single decaying place, with its own looser settings (tolerance , 3 checks every 5 steps), and requires equilibrium to be declared before the end of the time span.
When the Relaxation Doesn’t Apply
Everything above rests on one assumption: that a transition’s firing rate is a smooth function of the current marking. That assumption is false for four common modeling constructs.
Read arcs, inhibitor arcs, reachable capacities, and guards all depend on a firing instant — a specific moment where the marking is checked against a threshold. Mass action has no such moment. It treats every input as a continuous flow, all the time, so there is no point at which it can ask “is this inhibitor’s threshold exceeded right now?” or “did this firing just hit the capacity bound?” go-pflow’s stochastic.Forecast, the continuous engine in its stochastic package, calls Model.Gating() (metamodel/firing.go) first. Gating() names these four, plus three rarer constructs (non-kinetic input arcs, fixed delays, and multi-stage durations that have not been expanded into a chain), and a capacity counts only if some transition can raise its place. When the list is not empty, Forecast refuses rather than guess; it refuses a model with rate schedules the same way (stochastic/stochastic.go):
result, err := stochastic.Forecast(model, marking, stochastic.Options{})
// Diverged: true
// Reason: this model constrains firing in ways a continuous solution cannot
// express... Use the discrete engine (Simulate).
The refusal is deliberate: the ODE has no instant at which to ask the question. A model with a capacity that the net’s own transitions can actually reach needs the discrete engine, stochastic.Simulate, which fires one event at a time and can check the bound at the instant it matters. Chapter 5 shows both sides of this line. The go-pflow coffee shop net built there declares no capacities and no guards, so the relaxation applies to it; the café model in sim.pflow.xyz’s catalog, which declares pantry capacities that its restock transitions can reach, is the kind Forecast refuses (Chapter 18 shows the refusal). Chapter 5’s “A Caveat About the ODE” works through the difference.
Below the gating constructs, a second and separate question is population size. On an ungated net whose input arcs all have weight 1, the discrete engine’s average over many runs follows the ODE: exactly when every transition has a single input (the chain), and approximately when a transition multiplies two inputs together, with the gap shrinking as the population grows. go-pflow’s stochastic/consistency_test.go checks both: the linear chain against its closed form, and an SIR epidemic at 1,000 and 10,000 individuals, where the gap between the discrete mean and the ODE must stay within 5% of the population at 1,000, within 2% at 10,000, and be smaller at the larger size. A thousand customers served one at a time behave like a smooth curve; the discreteness averages out. Three baristas and a milk supply that runs dry five orders into a rush are a different regime. There, the variance is the answer you’re after — how often does the shop actually run dry, not what it does on average — and the ODE has no ran-dry event to count. The rule of thumb: large populations and you want the average, use the ODE; small counts and you want the distribution of outcomes, or “how often does X happen,” run the discrete engine and look at the spread across realizations.
An arc weight above 1 gives the two engines different rate laws, not one law computed with different precision. The ODE’s mass-action rate multiplies the input place’s concentration into the flux once per input arc, no matter the weight — a transition that consumes 20g of beans per firing still contributes to the rate, not or any combinatorial term in 20. The discrete engine’s propensity, by contrast, uses the full combinatorial count, — the number of distinct ways to draw 20 indistinguishable tokens from however many are on hand, which is the stochastic (Gillespie) form of chemical mass action (the package comment at the top of stochastic/stochastic.go states both laws). The two conventions coincide exactly at weight 1, where there’s only one way to draw one token, and diverge for any recipe that consumes more than a single unit of an ingredient per firing. Neither is wrong — “what does the concentration do on average” and “how many indistinguishable tokens can I draw” are different questions once more than one token is consumed per firing — but don’t expect a weight-20 arc to produce quantitatively matching numbers from both engines, even on a net the ODE doesn’t refuse. go-pflow pins this disagreement in a test: on the dimerisation with 200 tokens of , TestConsistencyPreconditionIsHonest requires the discrete mean and the ODE to differ by more than one token.
A third engine sits between the two. The chemical Langevin equation — a stochastic differential equation built from the same propensities the discrete engine uses, but with continuous state — gives intrinsic firing noise: a variance band, cheap enough to sweep like the ODE because its cost does not grow with the population. go-pflow implements it as stochastic.SimulateSDE (stochastic/sde.go), and like Forecast it refuses a gated net. That is a different thing from layering exogenous volatility, such as geometric Brownian motion, onto chosen “volatile” places on top of the ODE — the right tool for a DeFi price feed or an external demand shock, but noise imposed from outside the model rather than noise the net’s own structure produces. Use the SDE path when the population is too large for the discrete engine’s per-firing cost to be worth paying, but small enough that the ODE’s zero-variance answer would be misleading, and the model has no gating for the ODE to refuse over in the first place.
Choosing an Engine
| Your model has… | Use |
|---|---|
| a read arc, inhibitor, reached capacity, or guard | the discrete engine (or the ODE, and read the refusal) |
| large populations, no gating, you want the average | the ODE |
| small counts, you want the distribution or “how often does X happen” | the discrete engine |
| any input arc with weight > 1 | expect the two engines to disagree quantitatively — decide which rate law your model actually means |
| exogenous continuous uncertainty (price, demand) on top of the ODE | the volatility layer, not the relaxation itself |
| intrinsic firing noise, cheap enough to sweep | the chemical Langevin SDE |
The Full Picture
The continuous relaxation transforms the Petri net from a discrete-event system into a dynamical system. The incidence matrix becomes the stoichiometry matrix. The firing rule becomes mass-action kinetics. The state equation becomes a differential equation.
The incidence matrix and every P-invariant carry over unchanged. Read arcs, inhibitors, reachable capacities and guards do not, which is why the engines above refuse nets that use them. Where it applies, the continuous form is much cheaper to simulate at large populations and opens the door to equilibrium analysis, sensitivity analysis, and gradient-based optimization.
The pattern for using continuous Petri nets is:
- Build the net — places, transitions, arcs (same as discrete)
- Assign rates — a rate constant for each transition
- Solve the ODE — from initial marking to final time or equilibrium
- Read the results — token trajectories, equilibrium values, conservation checks
The remaining chapters in this book use this pattern extensively. The coffee shop in Chapter 5 uses equilibrium analysis for capacity planning. The knapsack problem in Chapter 8 uses continuous relaxation to approximate discrete optimization. The enzyme kinetics in Chapter 9 recover classical biochemistry equations directly from the net’s structure.
In each case the mathematics is ; what changes from chapter to chapter is the net and its rates.
The Token Language
Learning objective: Use the pflow DSL to define nets with guards, roles, and typed arcs.
The first three chapters built Petri nets from mathematical primitives — places, transitions, arcs, tokens, rate constants. That’s sufficient for analysis but awkward for specification. You wouldn’t write a web application by specifying its state machine as a 5-tuple. You’d want a language.
This chapter introduces the token language — a small, interpreted DSL for defining Petri net models with rich data semantics. It extends the mathematical foundation with guards, typed state, invariants, and categorical net types, while keeping the vocabulary to four terms. The implementation is go-pflow’s tokenmodel/dsl package, and Appendix B: Token Language Grammar is the full grammar reference. The behaviour described below was read from that code and the tests named alongside it; the tests were not re-run for this chapter.
The Four-Term Primitive
The token language distills to four primitives:
| Term | Maps To | Purpose |
|---|---|---|
cell | State / Place | Containers for tokens or data |
func | Action / Transition | Operations that transform state |
arrow | Arc | Flow connections with optional bindings |
guard | Predicate | Boolean conditions gating actions |
The four terms are the book’s vocabulary, not the DSL’s keywords. In the DSL a cell is written state, a func action and an arrow arc; a guard is attached to an action as :guard {...}; and a fifth form, constraint, declares an invariant. We make no claim that four is a minimum. They are the four things every model in this book needs, and the rest of the language is annotation on them.
S-Expression Syntax
The DSL uses an S-expression syntax. This ERC-20 token is the erc020DSL schema from go-pflow’s tokenmodel/dsl/dsl_test.go, copied with only the indentation changed:
; ERC-020 Fungible Token Standard
(schema ERC-020
(version v1.0.0)
(states
(state totalSupply :type uint256)
(state balances :type map[address]uint256 :exported)
(state allowances :type map[address]map[address]uint256 :exported))
(actions
(action transfer :guard {balances[from] >= amount && to != address(0)})
(action approve)
(action transferFrom :guard {balances[from] >= amount && allowances[from][caller] >= amount})
(action mint :guard {to != address(0)})
(action burn :guard {balances[from] >= amount}))
(arcs
(arc balances -> transfer :keys (from))
(arc transfer -> balances :keys (to))
(arc approve -> allowances :keys (owner spender))
(arc balances -> transferFrom :keys (from))
(arc allowances -> transferFrom :keys (from caller))
(arc transferFrom -> balances :keys (to))
(arc mint -> balances :keys (to))
(arc mint -> totalSupply)
(arc balances -> burn :keys (from))
(arc totalSupply -> burn))
(constraints
(constraint supply_conservation {sum(balances) == totalSupply})))
TestInterpret_ERC020 parses and interprets this text and checks that the result has 3 states, 5 actions, 10 arcs and 1 constraint; TestRoundTrip_ParseAndValidate passes it through schema validation.
Each kind of declaration lives in its own group — states, actions, arcs, constraints — and the parser rejects a bare (state ...) placed directly under schema. Within the groups:
statedeclares a cell with a name and type. The:exportedkeyword marks states that are visible across schema boundaries.actiondeclares a func, optionally with a guard expression in braces.arcdeclares an arrow;->separates source from target. The parser accepts any two names; validation then requires one end to be a state and the other an action.:keysnames the bindings that select an entry in a map-valued state.constraintdeclares an invariant, checked after each action the runtime executes (see Guard vs. Invariant).
The DSL has no variable declarations, control flow or modules, so the structure of the model is visible in the shape of the text.
In Go
The same model can be constructed with a fluent builder. This is TestBuilder_ERC020 from tokenmodel/dsl/builder_test.go:
schema := Build("ERC-020").
Version("1.0.0").
Data("totalSupply", "uint256").
Data("balances", "map[address]uint256").Exported().
Data("allowances", "map[address]map[address]uint256").Exported().
Action("transfer").Guard("balances[from] >= amount && to != address(0)").
Action("approve").
Action("transferFrom").Guard("balances[from] >= amount && allowances[from][caller] >= amount").
Action("mint").Guard("to != address(0)").
Action("burn").Guard("balances[from] >= amount").
Flow("balances", "transfer").Keys("from").
Flow("transfer", "balances").Keys("to").
Flow("approve", "allowances").Keys("owner", "spender").
Flow("balances", "transferFrom").Keys("from").
Flow("allowances", "transferFrom").Keys("from", "caller").
Flow("transferFrom", "balances").Keys("to").
Flow("mint", "balances").Keys("to").
Flow("mint", "totalSupply").
Flow("balances", "burn").Keys("from").
Flow("totalSupply", "burn").
Constraint("supply_conservation", "sum(balances) == totalSupply").
MustSchema()
The test checks the same counts — 3 states, 5 actions, 10 arcs, 1 constraint — and that validation passes. Both front ends build the same kind of syntax tree and hand it to the same interpreter, but the trees are not always identical: the builder gives token states the type int and defaults the version to v1.0.0, where the parser leaves both empty unless the source sets them (Appendix B). The builder’s String() method prints the S-expression form, so a schema built in code can be read and shared as text.
As Struct Tags
A third front end declares the schema as a Go struct (tokenmodel/dsl/tags.go). Fields of the marker types DataState, TokenState and Action become states and actions, their meta tags carry the type, initial value, exported flag or guard, and a Flows() method lists the arcs. This is the ERC20 struct from tokenmodel/dsl/tags_test.go, with its Flows() method cut after the first two entries:
type ERC20 struct {
_ struct{} `meta:"name:ERC-020,version:ERC-020:1.0.0"`
TotalSupply DataState `meta:"type:uint256"`
Balances DataState `meta:"type:map[address]uint256,exported"`
Allowances DataState `meta:"type:map[address]map[address]uint256,exported"`
Transfer Action `meta:"guard:balances[from] >= amount && to != address(0)"`
Approve Action `meta:""`
TransferFrom Action `meta:"guard:balances[from] >= amount && allowances[from][caller] >= amount"`
Mint Action `meta:"guard:to != address(0)"`
Burn Action `meta:"guard:balances[from] >= amount"`
}
func (ERC20) Flows() []Flow {
return []Flow{
{From: "Balances", To: "Transfer", Keys: []string{"from"}},
{From: "Transfer", To: "Balances", Keys: []string{"to"}},
// ... the other eight arcs of the S-expression version
}
}
SchemaFromStruct reads the struct by reflection and lowercases the first letter of each name, so the field Balances becomes the state balances. TestTagsERC20 checks the result: 3 states, 5 actions, 10 arcs, the transfer guard, and balances exported with type map[address]uint256. The test’s struct also has a Constraints() method declaring two invariants, so it expects 2 constraints where the S-expression version has 1.
Guards and Conditional Firing
In a basic Petri net, a transition fires whenever its input places have enough tokens. Guards add a second condition: even if tokens are available, the transition fires only when its guard expression evaluates to true.
Expression Syntax
Guards support a familiar expression language:
Comparison: balances[from] >= amount
to != address(0)
Logical: condition1 && condition2
condition1 || condition2
!condition
Indexing: balances[key]
allowances[owner][spender]
Field access: schedule.revocable
data.timestamp
Functions: address(0)
tokens("count")
sum("balances_")
go-pflow’s evaluator (tokenmodel/guard/eval.go) short-circuits: && stops on the first false and || on the first true, so the right operand is not evaluated when the left one decides the result. Every evaluation gets the built-in functions that addBuiltins in guard.go installs: address, len, two-number min and max, abs, the string tests contains, startsWith and endsWith, includes for arrays, and hasRole, which looks for a role name in the roles list of a user binding. A function the caller supplies under the same name replaces the built-in. The marking aggregates sum, count, tokens, minOf and maxOf (with min and max as aliases) are defined in aggregate.go and take a place ID or ID prefix as a string. They are supplied when an expression is evaluated as an invariant; a guard has them only if the caller passes them in.
Guard vs. Invariant
Both guards and invariants are boolean expressions, but they serve different purposes and fire at different times:
| Aspect | Guard | Invariant |
|---|---|---|
| When checked | Before action fires | After state update |
| On failure | Action is blocked, nothing changes | Error returned; the update is not undone |
| Purpose | Precondition | System property |
| Scope | Single action | Entire schema |
A guard asks: “Is this action allowed right now?” An invariant asks: “Did this action break anything?”
The “on failure” row is go-pflow’s tokenmodel.Runtime (runtime.go). It applies the arcs first and checks constraints afterwards, and a violated constraint makes Execute return ErrConstraintViolated with the new state already in place. A caller that wants all-or-nothing behaviour runs the action on Runtime.Clone() and keeps the clone only if no error comes back. Both checks also need an evaluator: Runtime.GuardEvaluator is an interface that go-pflow declares but does not implement, and with it left nil the runtime skips guards and constraints alike.
For the ERC-20 transfer, the guard balances[from] >= amount prevents overdrafts. The invariant sum(balances) == totalSupply states that no action creates or destroys tokens. Evaluating it needs the map: go-pflow’s EvaluateInvariantWithData (guard/invariant.go) binds each data state by name, and its sum totals the values of a map. tokenmodel.Runtime does not call it. Its constraint check receives only the token counts, so the runtime cannot check a constraint over the balances map (Appendix B gives the detail). Either way, a constraint is a runtime assertion about the states a run actually visits; it does not prove the property for every reachable state.
Evaluation Context
go-pflow’s guard evaluator works from a context with two parts (guard/eval.go):
- Bindings — every name the expression mentions, mapped to a value
- Functions — the built-ins listed above, plus whatever the caller supplies
There is no separate state component. When the guard balances[from] >= amount runs, from and amount come from the action’s parameters, and balances resolves only if the caller has put the current map into the bindings too; a name with no binding is an error (“unknown identifier”). When an expression is checked as an invariant (guard/invariant.go), the bindings are built from the marking, one per place, so pending + confirmed + shipped == 1 reads token counts by place name. Missing map keys default to zero: indexing a map with a key it lacks returns 0 rather than an error.
Weighted Arcs and Inhibitor Arcs
Basic arcs have an implicit weight of 1 — one token consumed, one token produced. Weighted arcs generalize this.
Weighted Arcs
An arc with weight from a place to a transition means “this transition consumes tokens from this place when it fires.” An arc with weight from a transition to a place means “this transition produces tokens in this place when it fires.”
The DSL has no syntax for arc weights. Its :value keyword names the binding whose value a data arc moves (Appendix B); it is not a weight, and the parser rejects a number in that position. Every arc written in the DSL has weight 1. A weighted arc is written in the JSON model format of Appendix C, or in Go. This fragment, a sketch rather than a file in any repository, is a coffee recipe that takes 2 units of water and 1 unit of grounds:
"places": [
{"id": "water", "initial": 10},
{"id": "grounds", "initial": 5},
{"id": "coffee", "initial": 0}
],
"transitions": [{"id": "brew"}],
"arcs": [
{"from": "water", "to": "brew", "weight": 2},
{"from": "grounds", "to": "brew", "weight": 1},
{"from": "brew", "to": "coffee", "weight": 1}
]
The brew action consumes 2 water and 1 grounds, producing 1 coffee. The enabling condition requires and . From the initial marking, water allows firings and grounds allows 5, so brew fires exactly five times and stops at water 0, grounds 0, coffee 5. That follows from the arcs by hand; it was not run. In the continuous simulation of Chapter 3 the weight scales how much water each firing consumes, not the rate law: go-pflow’s solver (solver/ode.go) computes a transition’s flux as its rate times the product of its input places’ markings, each to the first power, whatever the weights.
Inhibitor Arcs
An inhibitor arc is the opposite of a normal arc: it prevents a transition from firing when the source place has tokens, rather than when it doesn’t. Drawn as an arc with a small circle instead of an arrowhead, an inhibitor arc from place to transition means “ can only fire when is empty.”
Inhibitor arcs add expressiveness beyond standard Petri nets. They can test for zero, which basic Petri nets cannot do; that is enough to simulate a counter machine, so nets with inhibitor arcs are Turing-complete and reachability for them is undecidable. An inhibitor arc moves no tokens, so it has no entry in the incidence matrix: it is one of the contextual arcs of Appendix E, which sit outside the free structure the matrix describes. go-pflow’s runtime generalizes the test with the arc’s weight : the transition is blocked while the place holds at least tokens, so weight 1 means “fire only when empty”. Like weights, inhibitor arcs have no DSL syntax; in JSON they are "type": "inhibitor" on the arc (Appendix C).
Capacity limits are a common use. A buffer with maximum capacity 5 can also be built without one:
(schema Buffer
(states
(state buffer :kind token :initial 0)
(state empty_slots :kind token :initial 5))
(actions
(action produce)
(action consume))
(arcs
(arc empty_slots -> produce)
(arc produce -> buffer)
(arc buffer -> consume)
(arc consume -> empty_slots)))
This uses a complementary place (empty_slots) rather than an inhibitor arc, a common pattern that achieves the same effect while staying within the standard Petri net formalism. produce moves one token from empty_slots to buffer and consume moves it back, so with weight vector over (buffer, empty_slots) we have , and the P-invariant holds in every reachable marking. That is derived from the four arcs by hand.
Tokens vs. Data
The token language distinguishes two kinds of state, for two different ways that places hold information.
TokenState
Integer counters representing discrete quantities. This is classic Petri net semantics:
- Firing consumes and produces tokens
- The enabling condition checks token counts
- Tokens are fungible — we track counts, not identities
A place declared :kind token behaves like a place in the mathematical Petri nets of Chapter 2: its marking is an integer, its arcs consume and produce whole tokens, and the incidence-matrix results of that chapter apply to it. In the DSL a state is a data state unless it says :kind token; the JSON format of Appendix C has the opposite default.
DataState
Typed containers holding structured data — maps, records, scalar values. This extends Petri nets to handle real-world state:
- Arc keys select an entry (
balances[from]) - Data arcs move a value between entries; the container itself is never consumed
- Types are declared (
map[address]uint256,bool,string) but stored as written; neither the parser nor validation checks them
A data state holds a value, not a count. The balances place in the ERC-20 schema holds a map from addresses to amounts. When the runtime executes an action with bindings (runtime.go, applyDataArc), an input data arc subtracts the bound value — amount, unless :value names another binding — from the entry its :keys select, and an output data arc adds it. So transfer subtracts amount from balances[from] and adds it to balances[to]. A data input never blocks enablement: whether there is enough to move is the guard’s job, which is why transfer carries balances[from] >= amount.
The combination of TokenState and DataState lets you model systems where both control flow (tokens tracking “where we are”) and data transformations (balances, permissions, configuration) matter. A workflow token tracks the order through pending → confirmed → shipped. Data states track the order’s contents, the customer’s address, the payment amount.
Categorical Net Types
Not all Petri nets are alike. An order-processing workflow and an epidemiological simulation both use places, transitions, and arcs, but their tokens mean fundamentally different things. Net types classify Petri nets by how their tokens behave, what invariants hold, and how they compose.
The Five Types
The five types are declared in go-pflow’s metamodel/compose.go as the NetType of a subnet in a composed bundle.
| Type | Token Semantics | Intended invariant |
|---|---|---|
| WorkflowNet | Single control-flow token (cursor) | Mutual exclusion — cursor in exactly one state |
| ResourceNet | Countable inventory tokens | Conservation — total tokens constant |
| GameNet | Turn-based tokens with player roles | Both mutual exclusion and conservation |
| ComputationNet | Continuous quantities via ODE rates | Flux balance at steady state |
| ClassificationNet | Signal tokens with threshold activation | Threshold firing conditions |
The last column is what each type is for, not what go-pflow checks. Bundle validation checks one of these properties itself: it warns when a WorkflowNet does not start with exactly one token. The rest are the modeller’s to declare as constraints and to verify, as the composition example below does for Orders and Inventory.
WorkflowNet. A single token traces a path through states. An order moves through pending → confirmed → shipped → delivered. The token is a cursor — it marks where you are in a sequential process. With one token, a WorkflowNet is a finite state machine drawn as a net.
ResourceNet. Tokens represent countable, fungible things: inventory items, currency, capacity slots. A warehouse has 100 tokens in available, consumed by reserve and produced into reserved. The total is conserved — the P-invariant guarantees that nothing is created or destroyed.
GameNet. Tokens encode both game state and turn structure. In tic-tac-toe, empty cells hold tokens consumed when a player moves. A turn-control token alternates between players. GameNets combine WorkflowNet sequencing (turns) with ResourceNet accounting (board positions).
ComputationNet. Tokens are continuous, not discrete. Transitions fire at rates — mass-action kinetics from Chapter 3. An SIR epidemic model is a ComputationNet: the infection rate depends on the product of susceptible and infected populations.
ClassificationNet. Tokens accumulate as evidence. Transitions fire when enough tokens accrue — a threshold. A spam filter, for instance, could accumulate signal tokens from heuristics (suspicious sender, keyword matches, link density) and fire classify_spam when the threshold is met; this book does not build that model.
Why Types Matter
At the structural level, all five types are Petri nets. The type annotations matter because they constrain composition. When you connect two nets, the types determine what connections are valid:
- An EventLink connects transitions to transitions across schemas — when one fires, the other fires too
- A DataLink connects places to places — read-only observation across schema boundaries
- A TokenLink transfers tokens between schemas — resource coupling with cross-boundary conservation
- A GuardLink gates a transition in one schema on a place in another — constraint coupling
TokenLinks and DataLinks fuse places, EventLinks fuse transitions, and a GuardLink is lowered to an inhibitor arc or a guard conjunct. The legality rules are a small table in metamodel/compose_matrix.go. A TokenLink may join only nets whose places count fungible things, ResourceNets and GameNets, so a workflow cursor cannot be fused with an inventory counter. An EventLink is refused if either side is a ComputationNet, whose transitions have no discrete firing instant to synchronise on. DataLinks and GuardLinks are legal between any two types. A subnet with no declared type is legal with every link, so the check protects only the nets that declare a type.
Composition
Real systems are compositions of multiple nets. An order system combines a WorkflowNet (order lifecycle) with a ResourceNet (inventory), linked by EventLinks:
Orders (WorkflowNet): pending -> confirm -> confirmed -> ship -> shipped
Inventory (ResourceNet): available -> reserve -> reserved -> ship_out -> consumed
EventLinks:
orders.confirm → inventory.reserve— confirming reserves stockorders.ship → inventory.ship_out— shipping consumes reserved stock
This bundle exists as code: ordersInventoryBundle in go-pflow’s metamodel/compose_test.go, with one token in pending and 10 in available. Each schema declares its own property. The Orders WorkflowNet declares mutual exclusion, tokens("pending") + tokens("confirmed") + tokens("shipped") == 1; the Inventory ResourceNet declares conservation, tokens("available") + tokens("reserved") + tokens("consumed") == 10.
This is assume-guarantee reasoning: each component is verified in isolation, and composition only needs to check the boundaries. TestComponentInvariantsSurviveComposition in metamodel/compose_verify_test.go flattens the bundle, recomputes the P-invariants from the incidence matrix of the whole, and checks that for each component some composite invariant covers all three of its places. It checks the support of the invariants, not their weights.
The flattened net does not depend on the order in which subnets and links are declared. TestFlattenAssociativity checks this on a chain of three subnets, swapping the order of the links and of the subnets and comparing the results.
Composition is not monotonic. Adding an unlinked schema is the monoidal product — the two nets share nothing, so each behaves exactly as it did alone. But adding a link restricts. An EventLink is a rendezvous: the fused transition fires only when every participant is enabled, so inventory.reserve can no longer fire whenever stock exists — it must wait for an order to confirm. A GuardLink gates by construction. A TokenLink introduces a shared place that constrains its consumers. Each of these removes behavior rather than adding it. In the example above the restriction can be counted by hand. Inventory alone can reach every marking whose three counts are non-negative and sum to 10, and there are of them. Composed with Orders, reserve fires only with confirm and ship_out only with ship, each at most once, so the composite reaches 3 markings. TestEventLinkRestrictsBehavior checks that the composed count is smaller and logs both; the 66 and 3 above are derived, not read from a run.
What survives an EventLink is refinement: every firing sequence of the composite, projected onto a component’s transitions, is a firing sequence of that component alone. TestProjectionRefinement checks the marking form of this on the Orders + Inventory bundle: every reachable composite marking, projected onto Orders, is reachable in Orders alone. Refinement is what assume-guarantee needs, and it is what preserves safety — invariants, mutual exclusion, conservation. It does not preserve liveness: a component that could always eventually fire may, once linked, wait forever on a partner. Links that fuse places (TokenLinks, DataLinks) give a weaker guarantee, because the other side can add or remove tokens in the shared place; there a component’s conservation law carries over only when the other side has an invariant that agrees with it on the shared places. Appendix E, Composition Preserves Safety, Not Liveness, states both cases with their evidence.
The Execution Pipeline
From source text to running model, the token language follows a classic interpreter pipeline:
- Lexer (
lexer.go) — tokenizes source intoLParen,RParen,Arrow,Keyword,Symbol,String,NumberandGuardtokens - Parser (
parser.go) — builds an AST withSchemaNode,StateNode,ActionNode,ArcNode,ConstraintNode - Interpreter (
interpret.go) — converts the AST to atokenmodel.Schemaand validates it: IDs unique and non-empty, every arc joining a declared state to a declared action - Runtime (
runtime.go) — executes actions against a snapshot of the state
Runtime.ExecuteWithBindings runs an action in this order:
- Guard check: evaluate the guard with the caller’s bindings, if a guard evaluator is set
- Enablement: every token input holds at least its arc’s weight (an inhibitor input, fewer)
- Input processing: consume tokens on token arcs; subtract the bound value on data arcs
- Output processing: produce tokens on token arcs; add the bound value on data arcs
- Sequence: increment
Runtime.Sequence - Invariant check: evaluate every constraint against the token counts, if checking is on and an evaluator is set
If the guard fails or the action is not enabled, the call returns an error and nothing changes. If a constraint fails, the call returns an error but the update stays, as described under Guard vs. Invariant. Sequence counts executed actions; a caller can compare it to detect a stale snapshot, but the runtime itself does no concurrency control.
schema, err := dsl.ParseSchema(`
(schema Counter
(states
(state count :kind token :initial 10)
(state done :kind token :initial 0))
(actions
(action decrement))
(arcs
(arc count -> decrement)
(arc decrement -> done)))
`)
The ParseSchema function runs the full pipeline — lexing, parsing, interpretation, and validation — returning an executable schema or an error. decrement needs no guard: its input arc already requires a token in count, so starting from 10 it is enabled exactly ten times, after which count is 0, done is 10 and Execute("decrement") returns ErrActionNotEnabled. Every firing moves one token from count to done, so count + done == 10 throughout. This counter is a sketch for this chapter, not a test in go-pflow, and the behaviour above is derived from the arcs, not run.
Putting It Together
The token language adds three layers on top of the mathematical Petri net:
- Guards and invariants — conditional firing and conservation enforcement
- Typed state — TokenState for discrete counts, DataState for structured values
- Net types and composition — categorical classification with typed links
These layers organize the mathematics rather than replace it. For the token places, the incidence matrix, state equation and P-invariants of Chapters 2 and 3 still apply; guards add preconditions, constraints add runtime checks after each step, and types add composition rules. Guards and inhibitor arcs are the part that falls outside the incidence matrix, which is where Appendix E draws the contextual boundary.
The four-term vocabulary — cell, func, arrow, guard — is how the rest of the book describes models. Chapter 6 uses this package directly, writing tic-tac-toe in its Go struct-tag form. The other application chapters, from coffee shops to poker tables, present their models in other notations, but each of them comes down to the places, transitions, arcs and guards defined here.
Resource Modeling — The Coffee Shop
Learning objective: Model inventory, throughput, and bottlenecks as token flow.
The first four chapters built the machinery: bipartite graphs, incidence matrices, ODEs, a DSL. Now we use it. This chapter models a coffee shop — ingredients, recipes, orders, capacity limits — as a Petri net. The model answers operational questions: When do we run out of beans? Which drink creates the worst bottleneck? How should we staff during peak hours?
The coffee shop is a ResourceNet in the categorical vocabulary from Chapter 4. Tokens represent fungible quantities — grams of beans, milliliters of milk, cups. Conservation laws guarantee that nothing is created or destroyed without an explicit transition. The continuous relaxation from Chapter 3 turns the model into a capacity planning tool.
The Problem
A coffee shop has limited inventory. Different drinks consume ingredients at different rates:
| Drink | Beans | Water | Milk | Syrup | Cups |
|---|---|---|---|---|---|
| Espresso | 18g | 30ml | — | — | 1 |
| Americano | 18g | 200ml | — | — | 1 |
| Latte | 18g | 30ml | 180ml | — | 1 |
| Cappuccino | 18g | 30ml | 120ml | — | 1 |
| Mocha | 18g | 30ml | 150ml | 2 pumps | 1 |
Starting inventory: 1,000g beans, 5,000ml milk, 10,000ml water, 500 pumps of syrup, 100 cups.
The questions are straightforward. Which ingredient runs out first? How many drinks can we serve before something depletes? If we increase latte production, what’s the knock-on effect on bean consumption?
A spreadsheet answers them with static arithmetic, multiplying rates by time, and the linear estimates later in this chapter are exactly that arithmetic. The net adds dynamics: rates that change as resources deplete, and several transitions competing for the same inputs.
Defining the Net
The coffee shop net has three categories of places:
Ingredient places hold the current stock. Each starts with an initial token count representing the inventory on hand:
coffee_beans: 1000 (grams)
milk: 5000 (milliliters)
water: 10000 (milliliters)
cups: 100
syrup: 500 (pumps)
Consumption tracking places count what’s been used. They start at zero and accumulate as drinks are made:
beans_used: 0
milk_used: 0
water_used: 0
cups_used: 0
syrup_used: 0
Transitions represent drink preparation — one per drink type:
make_espresso
make_americano
make_latte
make_cappuccino
make_mocha
The structure is bipartite: ingredient places connect to transitions (input arcs), and transitions connect to tracking places (output arcs). No place connects to another place. No transition connects to another transition. The Petri net enforces this separation by construction.
In Code
The code in this chapter is adapted from NewInventoryNet in go-pflow’s examples/coffeeshop/inventory.go. That net is larger than the one built here: it adds an iced latte (200ml milk), a sugar-packet condiment and a refill transition for every ingredient. The chapter keeps the five drinks in the table above, so its numbers are for the five-drink net.
net := petri.NewPetriNet()
// Ingredient places
net.AddPlace("coffee_beans", 1000, nil, 100, 100, nil)
net.AddPlace("milk", 5000, nil, 100, 200, nil)
net.AddPlace("water", 10000, nil, 100, 300, nil)
net.AddPlace("cups", 100, nil, 100, 400, nil)
net.AddPlace("syrup", 500, nil, 100, 600, nil)
// Tracking places
net.AddPlace("beans_used", 0, nil, 300, 100, nil)
net.AddPlace("milk_used", 0, nil, 300, 200, nil)
net.AddPlace("water_used", 0, nil, 300, 300, nil)
net.AddPlace("cups_used", 0, nil, 300, 400, nil)
net.AddPlace("syrup_used", 0, nil, 300, 600, nil)
Each place gets an initial token count. The tracking places start at zero — they’re sinks that accumulate evidence of consumption. Together with the ingredient places, they form a conservation system: every bean consumed from coffee_beans appears in beans_used.
Weighted Arcs as Recipes
Each drink requires specific quantities of ingredients. The arc weights encode these recipes directly in the net’s structure.
For espresso — 18g beans, 30ml water, 1 cup:
net.AddTransition("make_espresso", "consume", 200, 150, nil)
// Input arcs (consumption)
net.AddArc("coffee_beans", "make_espresso", 18, false)
net.AddArc("water", "make_espresso", 30, false)
net.AddArc("cups", "make_espresso", 1, false)
// Output arcs (tracking)
net.AddArc("make_espresso", "beans_used", 18, false)
net.AddArc("make_espresso", "water_used", 30, false)
net.AddArc("make_espresso", "cups_used", 1, false)
For a latte — 18g beans, 30ml water, 180ml milk, 1 cup:
net.AddTransition("make_latte", "consume", 200, 350, nil)
net.AddArc("coffee_beans", "make_latte", 18, false)
net.AddArc("water", "make_latte", 30, false)
net.AddArc("milk", "make_latte", 180, false)
net.AddArc("cups", "make_latte", 1, false)
net.AddArc("make_latte", "beans_used", 18, false)
net.AddArc("make_latte", "water_used", 30, false)
net.AddArc("make_latte", "milk_used", 180, false)
net.AddArc("make_latte", "cups_used", 1, false)
The arc weight from milk to make_latte is 180. This means make_latte is enabled only when . Each firing consumes 180 tokens from milk and produces 180 tokens in milk_used. Inside the net, the recipe is the arc structure. The example also keeps a separate Recipes map in inventory.go, which CanMakeDrink reads instead of the arcs, so the same numbers exist twice there and have to be kept in step by hand.
The Incidence Matrix
The incidence matrix for the full model captures every recipe in a single data structure. Each column is a drink type. Each row is an ingredient (or tracking place). Reading column make_latte:
Negative entries are consumption. Positive entries in the tracking rows mirror them:
Conservation Laws
The paired structure — every token consumed from an ingredient place appears in the corresponding tracking place — creates P-invariants. For coffee beans:
For milk:
These hold for all time, under any firing sequence. The conservation law is structural — it follows from the arc weights summing to zero across each ingredient/tracking pair. No beans are created or destroyed. They’re consumed from stock into the “used” counter.
This is the Petri net equivalent of double-entry bookkeeping. Every debit (consumption) has a matching credit (tracking). The invariant is the balance equation.
ODE Simulation for Capacity Planning
With the net defined, the continuous relaxation from Chapter 3 turns it into a dynamical system. Each transition gets a rate constant; InventoryRates() in inventory.go labels them drinks per minute at peak:
rates := map[string]float64{
"make_espresso": 0.5, // 30/hr
"make_americano": 0.3, // 18/hr
"make_latte": 0.8, // 48/hr — most popular
"make_cappuccino": 0.4, // 24/hr
"make_mocha": 0.2, // 12/hr
}
go-pflow’s solver (solver/ode.go) computes each transition’s flux as its rate constant times the first power of every input place, and the arc weight scales only how much each firing consumes:
The weight 18 on the bean arc does not become an 18th power. Chemistry’s mass-action law would raise each input to its stoichiometric coefficient; go-pflow’s solver, which its own comments call simplified mass action, puts the weight in the stoichiometry only.
Scaling for Stability
Even with first powers, the product of four or five large stocks is enormous: 1,000 × 10,000 × 5,000 × 100 for a latte. Mass-action kinetics was designed for chemical concentrations, which are small numbers; coffee shop inventory has large integer token counts. The example’s simulation.go multiplies every rate constant by the same small factor:
scaledRates := make(map[string]float64)
for k, v := range rates {
scaledRates[k] = v * 0.0001
}
prob := solver.NewProblem(net, initialState, [2]float64{0, duration}, scaledRates)
opts := solver.DefaultOptions()
opts.Dt = 0.001
sol, eqResult := solver.SolveUntilEquilibrium(
prob, solver.Tsit5(), opts, nil,
)
Multiplying every rate constant by the same factor stretches the time axis and changes nothing else: the trajectory passes through the same markings in the same order, only on a different clock. The example’s comment gives numerical stability as the reason for the scaling; mathematically, it is a choice of time units.
What scaling cannot undo is the reweighting the product causes. Because the stocks multiply into the flux, a drink’s ODE flux depends on how many ingredients it uses, not just on its . At the initial marking (derived by hand from the rate law, not re-run):
- , from latte’s extra milk factor
- , from mocha’s extra syrup factor
So in the ODE the rate constants are not drinks per minute, and the drink mix is not 0.8 lattes to every 0.5 espressos. The drinks-per-minute reading belongs to the linear estimate in the next section.
What the Model Predicts
Which stock goes first follows from how much of each stock a single drink takes. A milk drink takes 120–180ml of 5,000ml milk (2.4–3.6%), 18g of 1,000g beans (1.8%), one of 100 cups (1%) and 30ml of 10,000ml water (0.3%). The ordering is:
- Milk goes first. Three of the five drinks draw on it, about 222ml per minute at the baseline rates, so 5,000ml lasts roughly 23 minutes on the linear estimate. As milk runs low, all three milk drinks stall, because milk is a factor in each of their fluxes.
- Coffee beans go next. Every drink uses 18g, 1,000g supports about 55 drinks, and once the milk drinks stall only espresso and americano still draw on them.
- Cups never come close. 100 cups at 2.2 drinks per minute would last 45 minutes if nothing else ran out, but milk and then beans run out first.
- Water lasts longest: 10,000ml, with every drink except the americano using 30ml.
Cups are the smallest number, so intuition says they go first. They do not, because the weights decide it: a latte takes 180 tokens of milk and one token of cups.
Under product kinetics no place reaches exactly zero. Each stock decays toward zero and every transition that reads it slows down with it, so “goes first” here means “falls fastest”. The minute figures above are linear estimates. A committed ODE run that gives the same order, with its own clock, is not yet part of the example: TestSimulateInventoryDynamics in coffeeshop_test.go runs the ODE but checks only that some beans were used.
The conservation laws hold at every point of an ODE trajectory, because the solver adds to beans_used for every it takes from coffee_beans:
Checking this sum in the solver output is a quick test that the arcs were wired correctly.
Predicting Runout
Rather than running the full ODE, we can estimate depletion times from the rates and arc weights, reading each rate constant as drinks per minute. This is a condensed version of PredictRunout in simulation.go, which also covers the iced latte and sugar packets:
consumptionRates := map[string]float64{
"coffee_beans": 18 * (rates["make_espresso"] +
rates["make_americano"] +
rates["make_latte"] +
rates["make_cappuccino"] +
rates["make_mocha"]),
"milk": 180*rates["make_latte"] +
120*rates["make_cappuccino"] +
150*rates["make_mocha"],
"water": 30*(rates["make_espresso"] +
rates["make_latte"] +
rates["make_cappuccino"] +
rates["make_mocha"]) +
200*rates["make_americano"],
"cups": rates["make_espresso"] +
rates["make_americano"] +
rates["make_latte"] +
rates["make_cappuccino"] +
rates["make_mocha"],
"syrup": 2 * rates["make_mocha"],
}
for ingredient, rate := range consumptionRates {
runoutTime := currentStock[ingredient] / rate
fmt.Printf("%s depletes in %.0f minutes\n", ingredient, runoutTime)
}
With the baseline rates the arithmetic can be checked by hand. The table below was derived that way; the example’s TestPredictRunout checks only that every runout time is positive, so no test pins these values:
| Ingredient | Draw per minute | Stock | Linear runout |
|---|---|---|---|
| milk | 180(0.8) + 120(0.4) + 150(0.2) = 222 ml | 5,000 ml | ≈ 23 min |
| coffee_beans | 18 × 2.2 = 39.6 g | 1,000 g | ≈ 25 min |
| cups | 2.2 | 100 | ≈ 45 min |
| water | 30(0.5 + 0.8 + 0.4 + 0.2) + 200(0.3) = 117 ml | 10,000 ml | ≈ 85 min |
| syrup | 2 × 0.2 = 0.4 pumps | 500 | ≈ 1,250 min |
The linear estimate assumes every drink keeps its rate until a stock hits zero. The ODE instead slows each transition as its inputs decline. The two should agree on the order, which follows from the per-drink fractions above, but not on the timings. In this model they do not even share a clock, because the ODE’s rate constants are not drinks per minute (see “Scaling for Stability”).
Bottleneck Analysis from Equilibrium
When the ODE reaches steady state (), the marking shows where tokens are left over, and the path to that state shows the order in which the bottlenecks hit.
In the coffee shop, equilibrium means every drink transition has stalled because at least one of its inputs is near zero. Water, cups and syrup are still on hand at that point. The bottleneck sequence is:
- First bottleneck: Milk (three drinks, heavy weights — 222ml/min at baseline)
- Second bottleneck: Beans (every drink needs 18g, and after the milk drinks stall, espresso and americano keep drawing on them)
- Cups and water never become the bottleneck at these rates
Scenario Analysis
Change the rates to model different days. The minute figures below are linear estimates, computed from the table above:
Slow day — halve all rates:
rates["make_latte"] = 0.4 // 24/hr instead of 48; likewise for the others
Every runout time doubles: milk lasts about 45 minutes and beans about 50. Halving demand delays the bottleneck but keeps it in the same place, and 5,000ml of milk still does not last a shift.
Rush hour — double all rates:
rates["make_latte"] = 1.6 // 96/hr
Milk depletes in half the time — about 11 minutes on the linear estimate. Beans follow.
Latte promotion — triple latte rate, keep others constant:
rates["make_latte"] = 2.4 // 144/hr
Milk was already the first bottleneck; now it is a sharper one. Consumption rises to about 510ml per minute, so 5,000ml lasts roughly 10 minutes on the linear estimate. Beans deplete sooner too — every extra latte costs 18g, and the other drinks keep their own (unchanged) rates — down from about 25 minutes to about 15.
Each scenario is the same net with different rate constants; places, arcs and weights are unchanged.
Sensitivity Analysis
go-pflow includes sensitivity analysis that systematically evaluates which rate changes have the biggest impact:
scorer := sensitivity.FinalStateScorer(func(final map[string]float64) float64 {
return final["cups_used"] // maximize drinks served
})
analyzer := sensitivity.NewAnalyzer(net, state, rates, scorer).
WithTimeSpan(0, 60)
result := analyzer.AnalyzeRatesParallel()
This is the core of OptimalDrinkMix in simulation.go. The analyzer perturbs each rate individually, simulates the ODE, and ranks transitions by their impact on the scoring function. A shop owner would read the ranking as a list of where added capacity buys the most throughput.
The ranking itself is not reproduced here. No test in the example pins its output, and it has not been re-run for this chapter. The flux ratios in “Scaling for Stability” also mean the ODE’s ranking need not follow the rate constants’ order of popularity, because each extra input stock multiplies into a drink’s flux.
Restocking and Capacity Limits
A real coffee shop doesn’t run until depletion — it restocks. The Petri net models this with refill transitions that move tokens from supply places into ingredient places:
// Supply places (incoming inventory)
net.AddPlace("beans_supply", 0, nil, 500, 100, nil)
net.AddPlace("milk_supply", 0, nil, 500, 200, nil)
// Refill transitions
net.AddTransition("refill_beans", "refill", 400, 100, nil)
net.AddArc("beans_supply", "refill_beans", 500, false)
net.AddArc("refill_beans", "coffee_beans", 500, false)
net.AddTransition("refill_milk", "refill", 400, 200, nil)
net.AddArc("milk_supply", "refill_milk", 1000, false)
net.AddArc("refill_milk", "milk", 1000, false)
The supply places start at zero — no restocking scheduled. When external events add tokens to beans_supply (a delivery arrives), the refill_beans transition becomes enabled and transfers 500g into the active inventory.
With refills in the net, the two-place law no longer holds: refill_beans adds 500 to coffee_beans without touching beans_used. The invariant widens to three places. refill_beans moves 500 from supply to stock and every drink moves 18 from stock to used, so for the vector that is 1 on all three bean places, :
A delivery is not a transition. It is an external change to the marking that raises . Between deliveries, the law tells you whether beans leak; comparing successive values of with beans_used tells you whether deliveries keep up with consumption.
Low-Stock Alerts
The model can trigger alerts based on inventory thresholds (abridged from CheckLowStock in inventory.go, which also watches water, sugar and syrup):
func CheckLowStock(state map[string]float64) map[string]bool {
thresholds := map[string]float64{
"coffee_beans": 100, // 100g ~ 5 drinks
"milk": 500, // 500ml ~ 3 lattes
"cups": 10,
}
alerts := make(map[string]bool)
for ingredient, threshold := range thresholds {
if state[ingredient] < threshold {
alerts[ingredient] = true
}
}
return alerts
}
In a guard-based formulation (Chapter 4), these thresholds would be guards on the make transitions:
(action make_latte :guard {tokens(coffee_beans) >= 118 && tokens(milk) >= 680})
The guard checks not just whether there’s enough for this drink, but whether stock is above the alert threshold plus one recipe’s worth (100 + 18 and 500 + 180). This is precautionary guarding: production stops before the resource reaches critical levels. A guard is evaluated at a firing instant, though, and that has a consequence for which engine can run the model.
A Caveat About the ODE
The analysis so far assumes the continuous relaxation from Chapter 3 applies, and the net built here qualifies for it. Its places declare no capacities (the third argument to every AddPlace is nil), and it has no read arcs, inhibitors or guards, so none of the four constructs that Chapter 3’s “When the Relaxation Doesn’t Apply” lists is present.
Two small changes would remove it from that safe ground. Adding the precautionary guard above is one. Turning the Max… constants into real shelf capacities on the ingredient places is the other: refill_beans can then push coffee_beans against its bound, which is a reachable capacity rather than a bound that is declared and never approached. The café model in sim.pflow.xyz’s catalog (its JSON), which the live demo at the end of this chapter runs, has exactly this shape: its pantry places declare a capacity (4,000 g of beans, for example) and its restock transitions add to them. go-pflow’s stochastic.Forecast, the continuous engine in its stochastic package, checks Model.Gating() and refuses such a model, because mass action has no firing instant at which to ask “did this refill just hit the cap?” The discrete engine, stochastic.Simulate, fires one event at a time and can check the bound when it matters.
Population size matters too, even without gating. A thousand grams of beans drawn down 18 at a time is the large-population case the ODE is built for, and there the average is the useful number. A shop that stocks four shots’ worth of beans overnight and wants to know how often it runs dry before the morning delivery is asking a different question: how much a single night varies. That calls for stochastic.Simulate, run across enough realizations to see the spread, rather than one solver run. As Chapter 3 notes, the two engines also handle an arc weight above 1 differently. The ODE takes once into the flux of an 18g espresso, while the discrete engine’s propensity counts the ways to draw 18 tokens, so they will not agree quantitatively on this recipe.
Full Day Simulation
The last analysis simulates a whole business day with varying demand. This is a sketch of RunDaySimulation in simulation.go, with the hourly bookkeeping folded into helper functions:
func RunDaySimulation(peakHours []int, baseRate float64) {
currentState := initialState
for hour := 6; hour <= 20; hour++ {
multiplier := 1.0
for _, peak := range peakHours {
if hour == peak {
multiplier = 2.5 // Rush hour
break
}
if hour == peak-1 || hour == peak+1 {
multiplier = 1.5 // Shoulder hours
}
}
// each rate × baseRate × multiplier × 0.0001
rates := scaleRates(InventoryRates(), baseRate * multiplier)
prob := solver.NewProblem(net, currentState,
[2]float64{0, 60}, rates)
sol := solver.Solve(prob, solver.Tsit5(), solver.FastOptions())
currentState = sol.GetFinalState()
stats := computeHourlyStats(currentState)
fmt.Printf("%02d:00 %4s drinks: %d beans: %.0fg alerts: %v\n",
hour, rateLabel(multiplier), stats.drinks, stats.beans, stats.alerts)
}
}
The example’s command-line demo (examples/coffeeshop/cmd/main.go) calls it with peaks at 8am, noon and 5pm. Each peak hour runs at 2.5× the base rate and the hours on either side at 1.5×. Nothing adds tokens to the supply places, so the refill transitions never fire, and the day’s report shows how far the opening stock goes and in which hour the low-stock alerts start. That hourly table has not been re-run for this chapter. Given the depletion order above, the first alerts should come from milk.
The solver handles each hour independently: the final state of one hour becomes the initial state of the next. FastOptions() trades precision for speed, with looser tolerances (10⁻²) and an iteration cap of 1,000, which suits fifteen short solves in a row.
From Model to Application
The coffee shop model demonstrates a development pattern that recurs throughout this book:
- Define the net — places for resources, transitions for operations, weighted arcs for recipes
- Verify structure — check P-invariants (does the model conserve resources?), check for deadlocks (can the system get stuck?
AnalyzeInventoryReachabilityinsimulation.goruns a bounded search) - Simulate dynamics — run the ODE to see how resources flow over time, after checking that the model has nothing the ODE would have to refuse
- Analyze bottlenecks — read the depletion order and sensitivity rankings
- Build the application — use the verified model as the backend for operational decisions
The aim is for the net to be the system’s specification rather than an approximation of it: the arc weights are the recipes and the conservation laws are the accounting rules. The go-pflow example falls short of this in one place, the duplicate Recipes map noted under “Weighted Arcs as Recipes”, which a change to an arc weight would leave stale.
This is the ResourceNet pattern: tokens count fungible things, arc weights specify recipes, conservation laws check the accounting, and ODE simulation answers capacity questions for large, ungated stocks. The same pattern applies wherever a system counts things, such as inventory, budgets, resource schedules and supply chains.
Try it live: The Café model at sim.pflow.xyz is a coffee shop with three drinks, an order-to-serve workflow with walkouts, staff as a shared resource, and capped pantry stock with restock transitions. It is a different net from the five-drink one in this chapter, so its numbers will differ.
The next chapter applies a different pattern — the GameNet — to tic-tac-toe, where tokens encode board positions and turn order, and an ODE run from each candidate move scores it.
Game Mechanics — Tic-Tac-Toe
Learning objective: Encode board positions, turns, and win conditions as token flow; use ODE simulation for move evaluation without game-specific heuristics.
The coffee shop modeled resources — fungible tokens flowing through recipes. This chapter models a game — structured tokens encoding board state, turn order, move history, and win detection. The Petri net is the same formalism, but the pattern is fundamentally different: a GameNet instead of a ResourceNet.
The claim this chapter tests is that strategic value can be read from model topology. We don’t code “prefer the center.” The Petri net’s structure — which positions participate in more winning patterns — produces that preference through the ODE dynamics. Blocking is where the claim starts to fail, and the second half of the chapter is about that boundary and what closes it.
The Board as Places
A tic-tac-toe board has nine cells. Each cell is a place, initialized with one token meaning “available”:
P00: 1 P01: 1 P02: 1
P10: 1 P11: 1 P12: 1
P20: 1 P21: 1 P22: 1
The naming convention is P{row}{col}, zero-indexed. P00 is the top-left corner, P11 is the center, P22 is the bottom-right corner.
When a player claims a cell, the token is consumed from the position place. An empty place () means the cell is occupied. This is the enabling condition in action: a move transition for cell requires . Once the token is consumed, no other transition can claim that cell. The bipartite structure of the Petri net enforces the rule “you can’t play in an occupied cell” without any conditional logic.
Turn Control via Mutual Exclusion
Tic-tac-toe alternates between X and O. A single place Next controls whose turn it is:
Next = 0means X’s turnNext = 1means O’s turn
Each X move transition produces a token into Next:
P_ij --> PlayX_ij --> X_ij
--> Next
Each O move transition consumes a token from Next:
Next --> PlayO_ij --> O_ij
P_ij -->
X goes first (Next starts at 0, so O transitions are blocked). After X plays, Next becomes 1, enabling O. After O plays, Next returns to 0. The alternation is structural — no turn counter, no modular arithmetic, just a token bouncing between “available” and “consumed.”
This is the same mutual exclusion pattern from the traffic intersection in Chapter 1. The Next token is a shared resource that enforces sequential access, exactly like the shared token that prevents both lights from being green simultaneously.
History Places for Pattern Detection
The basic model tracks where tokens are (board state) but not where they came from (move history). Adding history places upgrades the model from “what’s on the board” to “who played where.”
For each cell, two history places record which player claimed it:
X00, X01, X02, ..., X22 (9 places — X's moves)
O00, O01, O02, ..., O22 (9 places — O's moves)
When X plays at position (1,1):
- Consume token from
P11(cell becomes occupied) - Produce token in
X11(record X played here) - Produce token in
Next(pass turn to O)
When O plays at position (0,2):
- Consume token from
Next(it’s O’s turn) - Consume token from
P02(cell becomes occupied) - Produce token in
O02(record O played here)
The history layer doesn’t change the game mechanics — it adds information without altering what moves are legal. But it enables win detection, which needs to know not just that a cell is occupied, but which player occupies it.
It also makes visible a split that every executing model in this book has, and that this net is small enough to show whole. The history places are write-once: no move transition takes a token back, and only the pattern collectors of the next section consume one. They are the model’s past — monotone, irreversible, accumulating facts that a pattern collector can AND together without ever replaying the moves. The board places and Next are the present: the marking the next step is about. The move transitions and their enabling conditions are the future: recomputed from the marking on every step, stored nowhere. The past is tropical, the future is predicate, and the marking is where they meet. Appendix E states this once, formally; here it is just three groups of places and transitions, all in the same document.
The Full Place Set
The complete model has 30 places:
| Category | Places | Count |
|---|---|---|
| Board positions | P00–P22 | 9 |
| X history | X00–X22 | 9 |
| O history | O00–O22 | 9 |
| Turn control | Next | 1 |
| Win detection | WinX, WinO | 2 |
And a conservation constraint ties them together:
Every cell is in exactly one state: available (), claimed by X (), or claimed by O (). The total is always 9 — the board size. This is a P-invariant of the move layer, and you can check it by hand from the incidence matrix: every move column takes one token from a place and puts one in an or place, so the weighted sum is unchanged. go-pflow’s example declares it as the board_size constraint in examples/tictactoe/metamodel/tictactoe.go, which is also where the struct and flows below come from. The pattern collectors of the next section deliberately break it, since a collector consumes history tokens without returning them. That breakage is the point made there.
In the DSL
Using the struct tag syntax from Chapter 4:
type TicTacToe struct {
_ struct{} `meta:"name:tic-tac-toe,version:v1.0.0"`
// Board positions (1 = available)
P00 dsl.TokenState `meta:"initial:1"`
P01 dsl.TokenState `meta:"initial:1"`
// ... P02 through P22
// X move history (0 = not played)
X00 dsl.TokenState `meta:"initial:0"`
X01 dsl.TokenState `meta:"initial:0"`
// ... X02 through X22
// O move history
O00 dsl.TokenState `meta:"initial:0"`
// ... O01 through O22
// Turn control and win detection
Next dsl.TokenState `meta:"initial:0"`
WinX dsl.TokenState `meta:"initial:0"`
WinO dsl.TokenState `meta:"initial:0"`
// Move actions (18 total: 9 for X, 9 for O)
PlayX00 dsl.Action `meta:""`
PlayO00 dsl.Action `meta:""`
// ...
// Win detection (16 total: 8 for X, 8 for O)
XRow0 dsl.Action `meta:""` // X00, X01, X02
XDg0 dsl.Action `meta:""` // X00, X11, X22
// ...
}
The flows define the arc structure:
func (TicTacToe) Flows() []dsl.Flow {
return []dsl.Flow{
// X moves: Position -> PlayX -> History + Next
{From: "P00", To: "PlayX00"},
{From: "PlayX00", To: "X00"},
{From: "PlayX00", To: "Next"},
// O moves: Next + Position -> PlayO -> History
{From: "Next", To: "PlayO00"},
{From: "P00", To: "PlayO00"},
{From: "PlayO00", To: "O00"},
// Win detection: 3-in-a-row -> WinX
{From: "X00", To: "XRow0"},
{From: "X01", To: "XRow0"},
{From: "X02", To: "XRow0"},
{From: "XRow0", To: "WinX"},
// ... all 8 patterns for each player
}
}
The total model: 30 places, 34 transitions, 118 arcs (27 for X’s moves, 27 for O’s, 64 for the sixteen collectors; the example’s README prints the same counts when it loads the net). Every rule of tic-tac-toe — valid moves, turn alternation, win conditions — encoded purely in arc structure.
Win Detection Without Search
Win detection is where the model becomes compositionally interesting. There are 8 winning patterns in tic-tac-toe: 3 rows, 3 columns, 2 diagonals. Each pattern is a transition that consumes three history tokens and produces a win token.
For the top row (X wins):
X00 --> XRow0 --> WinX
X01 -->
X02 -->
The transition XRow0 is enabled when AND AND — all three top-row cells claimed by X. When it fires, it produces a token in WinX.
This is a pattern collector: a transition that recognizes a specific configuration of history tokens. Each winning pattern gets its own collector. No conditional logic, no “check all rows and columns” procedure — just 8 independent transitions, each watching for its specific three-token combination.
The 16 pattern collectors (8 for X, 8 for O) are the complete game-over detection system. When any one fires, the game has been won. Multiple can potentially fire (if a player completes two lines simultaneously), but in practice the first one to fire determines the winner.
Why Composition Matters
Each pattern collector is independent. Adding a new win condition (say, for a variant game) means adding a new transition with three input arcs and one output arc. Removing a condition means removing a transition. The rest of the model is untouched.
The collectors are also the first place this book’s core–observer split shows up. Every collector consumes three history tokens (four, once the halting fix below adds the turn token) and produces one, so its compression ratio — tokens consumed over tokens produced — is at least 3. The move transitions sit near : in this chapter’s Next-as-a-bit encoding an X move consumes one token and produces two, an O move the reverse, and the pair of them is balanced; the symmetric two-turn-place encoding used on the blog makes each move exactly . That gap — balanced moves, compressing collectors — is what the tropical and zero-knowledge chapters detect as “observer”. The collectors break nothing categorical: they are ordinary transitions with ordinary arcs, and they compose exactly as this section says. What they break is the one-producer-one-consumer property that the throughput analysis of Chapter 13 needs, and the uniformity of the circuit in Chapter 12. Appendix E separates that boundary from the other one — guards — which is categorical and which tic-tac-toe does not have.
This is the compositional advantage of Petri nets over procedural game logic. In code, win detection is typically a function that iterates over patterns:
winPatterns := [][]string{
{"00", "01", "02"}, {"10", "11", "12"}, ...
}
for _, pattern := range winPatterns {
if allMarked(pattern) { return true }
}
The procedural version works, but it’s monolithic — changing the win conditions means changing the function. The Petri net version is modular — each pattern is an independent structural element that composes with the rest.
Position Value from Topology
Each board position participates in a different number of winning patterns:
| Position | Patterns | Type |
|---|---|---|
| Center (1,1) | 4 | Row + Column + 2 Diagonals |
| Corners (0,0), (0,2), (2,0), (2,2) | 3 | Row + Column + 1 Diagonal |
| Edges (0,1), (1,0), (1,2), (2,1) | 2 | Row + Column |
The center participates in 4 winning patterns. Corners participate in 3. Edges participate in 2. This structural fact — encoded in the arc connectivity — is the source of strategic value. More connections to pattern collectors means more paths to victory, which the ODE dynamics translate into higher scores.
No game theory is needed to derive this. It falls directly from the net’s topology.
ODE-Guided Strategy
With the model defined, we can use the continuous relaxation to evaluate moves. The algorithm is simple:
- For each available move, create a hypothetical state after making that move
- Run the ODE simulation forward from that state
- Read the final values of
WinXandWinO - Score = my_win - opponent_win
The move with the highest score is the best move.
The Scoring Function
Condensed from ODEAIMove in go-pflow’s examples/tictactoe/cmd/game.go, which runs it on the 30-place net with every rate set to 1.0:
targetPlace := "win_x"
oppPlace := "win_o"
if currentTurn == PlayerO {
targetPlace = "win_o"
oppPlace = "win_x"
}
for _, move := range availableMoves {
// Create hypothetical state
hypState := copyState(currentState)
hypState[position] -= 1
hypState[historyPlace] += 1
// Run ODE
prob := solver.NewProblem(net, hypState,
[2]float64{0, 3.0}, rates)
sol := solver.Solve(prob, solver.Tsit5(), opts)
final := sol.GetFinalState()
// Score
score := final[targetPlace] - final[oppPlace]
}
The mass-action ODE advances every enabled move at once instead of choosing one. When X has tokens in positions that participate in many patterns, the flow toward WinX is higher. When O can block a pattern, that flow is diverted. The final values of WinX and WinO aggregate that relaxed flow; they are not an average over discrete games, and how far apart the two are is what the tournament below measures.
What the ODE Discovers
Empty board evaluation. X evaluates all 9 positions. On the 30-place net above, go-pflow’s example prints these scores in the verbose output recorded in its README (not re-run for this edition):
- Center (1,1): score 0.487 — highest, because 4 pattern connections create the most flow toward WinX
- Corners: score 0.359 — second, 3 patterns each
- Edges: score 0.248 — lowest, 2 patterns each
The figure above and the tic-tac-toe blog post quote 1.27 / 0.95 / 0.63 for the same three cells. Those come from an earlier version of the net, and the ranking is the same.
The ODE has “discovered” the opening strategy: play the center. No minimax tree, no alpha-beta pruning, no opening book — just mass-action kinetics flowing through the net’s topology.
Responding to center. After X takes center, O evaluates defensive options. All scores are negative (X has the advantage), but corners (-1.04) minimize X’s lead better than edges (-1.38). The ODE discovers the defensive principle: play corners against center.
Finding winning threats. When X has center and a corner, the ODE identifies the opposite corner as the best move (score 1.39) because it creates a two-way threat — a fork that completes one diagonal while opening another. The pattern collectors naturally amplify fork positions because they have higher connectivity.
Blocking. When X has two in a row, O’s best move is the blocking position (score 0.80 vs. 0.74-0.77 for other moves). The ODE discovers blocking because the flow toward WinX is dramatically higher along the threatened pattern. Placing a token to block cuts off that flow. Note how thin the margin is: a forced block wins by hundredths where the opening preferences differ by tenths. Tactical necessities are second-order effects in the relaxed flow — a weakness the tournament results below make concrete.
These four sets of numbers do not come from one net. The center-response and fork scores come from the same earlier version as 1.27 / 0.95 / 0.63; their magnitudes exceed 1, which a net that halts on a win cannot produce. The blocking scores, positive for O, come from the halting, draw-detecting net of the next section, in a test in a private repository. None was re-run for this edition. The rankings within each example are what we expect to carry between versions, and that has not been checked.
Performance
Each move evaluation requires one ODE solve. With 9 possible moves on an empty board, that’s 9 solves. Using tuned solver options:
opts := &solver.Options{
Dt: 0.2,
Reltol: 1e-3,
}
The example’s README reports about 0.04 seconds per move evaluation and about 1.8 seconds for a full ODE-vs-ODE game, which is 45 evaluations (9 + 8 + … + 1). We have not re-timed it. That is fast enough for interactive play.
How well does this evaluator actually play? Measuring that fairly requires two refinements the model does not yet have — the game must stop when someone wins, and a draw must be worth something to the defender. Both come next; the tournament follows them.
Game Halting and Draw Detection
What happens when a player wins? In the basic model, tokens continue flowing after a win — the ODE doesn’t know the game should stop. This distorts strategic values because the simulation averages over impossible continuations.
The fix is game halting: win transitions consume the turn token without returning it.
X00 --> XRow0 --> WinX
X01 -->
X02 -->
Next --> (consume turn -- game stops)
When X wins, the XRow0 transition consumes Next (it was O’s turn). No turn token is returned. All further move transitions are blocked because they require either an empty position token or a turn token, and the turn token is gone. The win state becomes an absorbing state — once reached, no further flow is possible.
Draw Detection
Draw detection adds a move counter. Each play transition deposits a token into move_tokens. A draw transition fires when:
- 9 move tokens have accumulated (all squares filled)
game_activeis still marked (no winner)
The draw transition deposits into its own draw place, and the scoring objective counts it for the defender: win_x - win_o - draw, which X maximizes and O minimizes. This encodes the principle that “a draw is a win for the defender” — tic-tac-toe is asymmetric, O cannot force a win, so O’s goal is “X does not win” and a draw counts fully. (Keeping the draw in its own place, rather than crediting WinO directly, also keeps the outcome announceable: an application reading the marking can tell a draw from a win.)
That is the discrete reading. In the ODE the weight-9 arc does not make the draw a count to nine. go-pflow’s flux is the rate times each input place’s marking to the first power — here (solver/ode.go) — and the weight scales only how much is consumed. So the relaxed draw starts firing from the first fractional move, as a hazard linear in move_tokens. Even so, adding it changes the ODE dynamics:
Without draw detection: O’s scores are always negative. The model only sees win paths, so it favors positions with more winning lines even when blocking is essential.
With draw detection: O’s scores become positive because draws count as partial victories. Blocking a threat now has measurable value — it preserves the possibility of a draw, which has positive worth.
Tournament Results
With halting and draw detection in place, the complete model can play. The scoring function from earlier now reads the declared objective — score = win_x - win_o - draw, negated for O — and the tournament is reproducible: 100 games per matchup, the random player seeded, ODE ties broken by declared move order. The harness is examples/ch06-ttt-tournament/main.go, pinned to go-pflow v0.23.1, and prints this table plus an ODE-vs-ODE game trace. The figures below are from its last recorded run; we did not re-run it for this edition.
Its net is the halting, draw-detecting construction, with three differences from the diagrams above. Two turn places, x_turn and o_turn, replace Next. A game_active token is spent by every detector and by the draw. And each detector reads its three history places catalytically, consuming and returning them, so a detected line stays on the board and the board-size sum survives the detectors. A catalytic detector consumes five tokens and produces four, so its is rather than the 4 of the halting diagram: still above 1, still on the observer side.
| Matchup | X Wins | O Wins | Draws |
|---|---|---|---|
| ODE vs Random | ~97% | 0% | ~3% |
| Random vs ODE | ~3% | ~88% | ~9% |
| ODE vs ODE | 100% | 0% | 0% |
The ODE evaluator dominates random play from either side. As O — the seat that only exists to deny X — it converts ~88% of games into wins against a random X, which the draw-blind scorer could never do: without the draw term, blocking has no measurable value.
The third row looks wrong and is the most instructive number in the table. Two identical players, and X wins every game — where a naive reading expects all draws. But “same player both sides means a tie” is a property of perfect players only. Two copies of an imperfect evaluator lose in whichever seat their shared weakness is punished, and tic-tac-toe’s seats are not symmetric: X’s job is threat creation, a strategic property the aggregate flow measures well, while O’s job is threat denial — exact, discrete, forced. So the same evaluator that goes ~88% as O against random play fumbles reliably against the one opponent that punishes a single missed block every time: itself. (Measured on the draw-blind model — score = win_x - win_o, a tie worth zero to both sides instead of counting against X — and with unseeded tie-breaking, this matchup comes out mostly drawn. That is an artifact of the scorer, not a property of the evaluator. The move sequences still vary slightly between runs, because the solver’s floating-point summation order follows map iteration and flips near-ties; the harness’s own comment says the outcome does not.) A representative game:
ply 1: X takes center ply 2: O takes corner (2,0)
ply 3: X takes corner (0,0) ply 4: O blocks the diagonal at (2,2)
ply 5: X takes edge (2,1), threatening column 1
ply 6: O plays (0,2) — the losing move
ply 7: X completes column 1 at (0,1)
At ply 6 the block at (0,1) is forced: X holds (1,1) and (2,1), so every other reply lets X complete column 1. Exact minimax over the same net agrees — o_play_01 values at +1 for O (the draw) and every other move at -1 (X wins). The relaxation’s own numbers at that position show why it fails: the forced block scores 0.248 while two strategically-pretty but losing corner moves score 0.275. The harness prints the trace, not these per-move values, so they are recorded here from a probe of that position and cannot be regenerated from the harness as shipped. A block’s value is conditional on the opponent’s next discrete move; in the continuous flow that conditionality is a second-order effect, and 0.027 of aggregate connectivity outweighs it. The forced block is exactly the thin-margin tactical judgment flagged earlier, and the margin goes the wrong way.
That exhibit is configuration-dependent in a way the failure class itself is not. This harness runs its win detectors fast (rate 720 against the plays’ rate 1), so the referee dominates the relaxed flow; at uniform rates the same evaluator finds this particular block, and the margin flips back the right way. A tactic whose correctness depends on a solver rate choice was never being seen — it was balanced on an artifact, in whichever direction the rates happened to lean. What did not flip at any horizon, detector rate, or draw rate in a later sweep is the double-corner fork: X in opposite corners, O in the center, no threat on the board yet, where every corner reply loses and every edge draws. There the losing moves outscore the optimal ones on every final-state coordinate under every configuration tried (27, by the count at the time; the sweep code has since been pruned, so that count cannot be re-checked) — the fork is the relaxation’s true boundary, and the missed block above is its rate-sensitive shadow.
That is the boundary of the relaxation used alone. It is a strategic prior derived from topology — it finds the center opening, the corner defense, forks, and most blocks, with no game knowledge anywhere — but a tactical necessity is a second-order effect in the relaxed flow, and it will occasionally miss one. The right place for a prior is not the driver’s seat. Where its right seat is — and what it does there — closes this chapter, once the integer reduction has given the prior its closed form.
The Integer Reduction
The ODE scores from the empty board are suspiciously proportional. Divide each by the smallest — the public example’s and the earlier net’s:
Both are close to . The ODE is tracking three integers — not computing them exactly, since the ratios are off by a few percent, but recovering the ranking and grouping that the integers predict.
Incidence Degree to Terminals
The win transitions in this model are terminal — they are sinks in the net. The number of arcs from a position’s history place to downstream win transitions is its incidence degree. This is a graph property — count the arcs, get an integer. No simulation needed.
| Position | Win patterns | Incidence degree |
|---|---|---|
| Center (1,1) | Row + Column + 2 Diagonals | 4 |
| Corners (0,0), (0,2), (2,0), (2,2) | Row + Column + 1 Diagonal | 3 |
| Edges (0,1), (1,0), (1,2), (2,1) | Row + Column | 2 |
The full board heatmap is [3, 2, 3, 2, 4, 2, 3, 2, 3]. The strategic value of a position in a game with terminal win states is determined by its incidence degree to those terminals. The ODE recovers this ranking through dynamics; the graph gives it directly.
Generalizing to Any Board Size
The incidence degree formula works for any board. Each position at gets:
- 2 (its row + its column), always
- +1 if on the main diagonal ()
- +1 if on the anti-diagonal ()
So the only possible degrees are {4, 3, 2}, and degree 4 only occurs at the center of odd-sized boards. go-pflow’s TestIntegerReduction, in examples/tictactoe/cmd/nxn_bench_test.go, builds the N×N game net for N = 3 to 7, checks each history place’s arc count against that formula, and scores every opening move by the uniform-rate ODE from t = 0 to 9. It asserts two properties at every size:
- Positions with the same incidence degree score within 5% of each other
- A higher incidence degree scores higher
It prints, but does not assert, each degree’s score as a ratio to the degree-2 score. As recorded in the blog post The Incidence Reduction (not re-run here), the error against the integer ratio is −2.0% (degree 4) and −3.6% (degree 3) at 3×3, −19.2% and −14.7% at 5×5, and −13.3% and −9.7% at 7×7. Our explanation for the drift is that more positions compete for flow through shared win transitions, since each win transition consumes every history place on its line at once. The ranking — which is what move selection needs — held at every size tested, so on the empty board the ODE’s opening move is the arc-counting opening move.
Dynamic Evaluation: Injecting Current State
The empty board is the easy case. The real utility comes from injecting the current game state as the marking and recomputing.
When a position is occupied, its token has been consumed — it drops out of the calculation. The incidence degree is now computed only against still-reachable win transitions. A corner that participates in 3 win patterns on an empty board might participate in only 1 if the opponent has blocked the other two. The heatmap updates to reflect the live topology.
This is the general “next step” evaluator. Given any board state:
- Identify which win transitions are still reachable (not blocked by opponent pieces)
- For each empty position, count the number of reachable win transitions it connects to
- The highest count is the strategically strongest move — which, as the tournament showed, is not always the right move when a forced tactic is on the board
go-pflow’s example does not package this counting procedure; what it runs is the ODE version, re-scoring every legal move each turn. sim.pflow.xyz’s sim_evaluate tool has the closed form as its incidence method.
The Boundary Between Counting and Simulation
Tic-tac-toe reduces to {4, 3, 2} precisely because it is simple enough that topology is all you need. The win transitions are independent sinks. No position participates in resource competition with another. The incidence structure has no interesting dynamics — just a direct count.
For more complex games — poker with its multi-phase betting structure, or governance models with competing resource flows — the incidence structure is rich enough that positions do not reduce to small integers. Multiple paths interact, resource constraints create bottlenecks, and the dynamics through the net have real work to do. The ODE earns its keep in those cases.
But the mechanism is identical:
- Model the system as a Petri net with terminal (win/loss/goal) transitions
- Inject the current state as the marking
- Compute the evaluation from token flow to reachable terminals
For simple nets, step 3 is integer counting. For complex nets, step 3 is ODE simulation. The boundary between them is the boundary between systems where topology alone determines strategy and systems where dynamics matter.
What we have is a static evaluation function defined purely by net topology and current state. No heuristics, no training data, no game-specific knowledge beyond the Petri net model itself. For any game or system modeled as a Petri net with designated terminal states, the function is: for each position, how connected is it to winning? The Petri net is the domain knowledge — the topology encodes the rules, and the incidence structure encodes the strategic prior.
Oracle Play
The tournament showed where the static evaluator’s honesty runs out: it is a strategic prior, and a prior that drives loses to a forced block. This section puts it in its right seat. The result is perfect play, and — this is the point — perfect play derived from the net, with no more game knowledge than the evaluator itself used.
The Search Is Already in the Net
Exact minimax needs four things: the legal moves, whose turn it is, when the game is over, and what the outcome was. The net declares all four. Legal moves are enabled transitions — an occupied cell’s move is not pruned by game logic, it is simply not enabled, because the position token is gone. The turn is whichever turn place holds a token. The win detectors and the draw call are the referee: fired to quiescence between moves, they decide the game exactly as they did during simulation. And a missing turn token — absorbed by a detector — is the game-over test. The search over those semantics is a page of code with nothing about tic-tac-toe in it. Condensed from minimax in the tournament harness:
func minimax(mk Marking, alpha, beta int) int {
mk = fireHouse(mk) // detectors and the draw call referee
switch {
case mk["x_turn"] > 0:
// maximize over enabled x_play_* moves, prior-ordered
case mk["o_turn"] > 0:
// minimize over enabled o_play_* moves, prior-ordered
default: // turn token absorbed: game over
return mk["win_x"] - mk["win_o"] // win +1, loss -1, draw 0
}
}
Change the net — a 4x4 board, a misère rule where completing a line loses, an extra win pattern — and this player changes with it, because it was never written, only derived. The rules live in one artifact and everything else is a view of it.
The Prior Takes Its Seat
The static evaluator’s role changes from player to oracle: its ranking decides which move the search examines first, and never what any position is worth. That division of labor is exactly what alpha-beta wants — cutoffs come from trying strong moves early, so an ordering heuristic pays in pruned subtrees while remaining unable to corrupt the answer. And the integer reduction is what makes the oracle cheap: the ranking is the incidence degree, readable off the graph, with the ODE solve needed only where topology alone stops being enough.
The prior’s value is measurable, not rhetorical: from the empty board, the harness reports that the exact search expands 18,297 positions taking moves in declared order, and roughly 7,000 with the prior ordering them — the same proven answer at about 2.6x less work (the precise count varies by a few percent run to run, because near-tied prior scores resolve by floating-point summation order). Trying center before edge is most of what there is to know about tic-tac-toe move ordering, and the prior knows it from the arc structure alone.
Perfect Play, Measured
The same tournament harness, with the oracle seated:
| Matchup | X Wins | O Wins | Draws |
|---|---|---|---|
| Oracle vs Oracle | 0% | 0% | 100% |
| ODE vs Oracle | 0% | 0% | 100% |
| Oracle vs ODE | ~40% | 0% | ~60% |
Every game between two oracles is a draw — the “identical players tie” intuition holds the moment both players are actually perfect, and the search proves the game’s value from the empty board is the draw. The oracle never loses from either seat: as O it blocks every threat the bare relaxation missed, and as X it converts the heuristic’s missed blocks into wins about 40% of the time while conceding nothing. This construction — a topological prior ordering an exact search over the same net — is what a deployed bot should ship. sim.pflow.xyz’s sim_evaluate tool ships it as its search method: alpha-beta minimax over the declared game, with a transposition table and the incidence ranking from the integer reduction ordering the moves (Chapter 18: sim.pflow.xyz — From Description to Checked Model).
The Objective Is a Modelling Statement
One detail in the harness deserves its own paragraph, because it is a lesson about declaring objectives rather than about search. The oracle’s leaves score win +1, loss -1, draw 0 — the three outcomes must rank for perfect play to mean anything. The model’s declared objective, win_x - win_o - draw, instead folds the draw into the defender’s win. That is the right encoding for the asymmetric question it was written to ask — O cannot force a win, so O’s goal is “X does not win,” and a draw counts fully for O. But it makes X indifferent between drawing and losing. An earlier version of the harness, whose oracle X maximized the declared objective, lost 59% of its games against itself, every loss a position it valued identically to the draw it could have had; that version is not the one in the repository, which scores leaves win +1, loss −1, draw 0. Same net, same search, one term moved in the objective — and “perfect play” quietly meant something else. An objective is a modelling statement, and this is what getting one wrong looks like from the inside.
Declaring the Opponent
Oracle play answers the question this chapter set out with, through a division of labor: structure for the prior, search for the tactics. That division turns out not to be forced, and the reason is a lesson about modelling.
The starting point is the fork boundary above, sharpened into an impossibility: at the double-corner trap, the losing corner replies dominate the optimal edges on every coordinate of the relaxed final state — lower opponent-win mass, higher own-win mass, higher draw mass — at every rate configuration tried. So no monotone scoring function over that final state, one that never prefers less of O’s good outcomes or more of X’s, can pick the right move. Whatever fixes the fork must change the net being evaluated, not the number read off it.
That reframes what the evaluator was doing all along. Mass-action flow with uniform rates advances every legal continuation in proportion to availability alone, which reads as a mean-field version of both players moving at random. On that reading the ceiling the experiment measured for play-scoring — every game drawn as X against a minimax opponent, 93 of 100 drawn as O — is what to expect: the evaluator catches every tactic visible as a static threat and fails where the value lives in the opponent’s forced replies. (We have not compared it against a random-playout evaluator directly.) What the relaxation lacks is an opponent model, and an opponent model is declarable.
The declaration is direct. For each win line and each of its cells, add a copy of that cell’s play transition, catalyzed — read arcs, nothing moved — by the opponent holding the line’s other two cells. Forty-eight transitions, one shared rate. Inside the forward solve, wherever a threat exists, flow pours into the move that answers it: the simulated players stop being random and start playing threats-are-answered. The evaluation net is then derived from the declared one by mechanical transforms — delete the draw machinery (its counting semantics cannot survive the relaxation, and keeping it measurably poisons the objective), delete the places that become write-only, add the forced-reply copies — leaving two scalars, the reply bias and the defender’s win-versus-survive exchange rate, both of which fall out of a two-parameter fit against minimax labels from a naive start.
The verdict is stronger than any tournament: a referee walks every legal opponent line, both seats, and checks that the evaluator’s move never worsens the position’s exact game value. Over all distinct reachable decisions — 96 as X, 309 as O — it found zero value-losing moves and zero missed wins. One ODE solve per candidate, a linear read of the final state, no search — and it never loses a drawn position and converts every won one, against arbitrary opposition. The experiment, its fifteen findings, and the exhaustive referee live in experiments/ode-minimax in sim.pflow.xyz’s source, which is not public; the derivation transforms and the fitting ship as general tools in go-pflow’s derive and learn packages (v0.23.1). (The experiment runs on sim.pflow.xyz’s shipped tic-tac-toe model. It has the harness’s catalytic detectors and weight-9 draw counter, but its draw deposits into win_o instead of a place of its own, and the experiment measures against a minimax opponent rather than a random one, so its numbers are not this chapter’s tables. The structural conclusions carry.)
Two of those findings deserve restating here because they are about modelling, not tic-tac-toe. First, static evaluators degrade gracefully with initiative and sharply without it: a tempo ahead, every threat you must answer is already on the board — a fact the flow measures directly, which is why the bare relaxation was already perfect as X — while a tempo behind, the decisive danger is assembled from the opponent’s forced replies and lives only in move order. When testing an evaluator on any game, instrument the defending seats first. Second, a prior the structure already computes must not be written in again: the integer reduction earlier in this chapter showed the topology producing the 4:3:2 incidence ranking for free, and every attempt to also encode those counts — into deposit weights, into detector rates, in any direction — measurably degraded play. The topology applies its prior exactly once, and every duplicate is paid for.
Where does that leave oracle play? Intact, and honestly priced. The search is still the cheapest guarantee — a page of derived code whose answer is proven, with the prior pruning its tree. What the derived evaluator adds is the demonstration that the guarantee was never the relaxation’s ceiling: hand the flow a net that declares how opponents actually behave, and the flow alone reaches the same perfection. The declared model stays the single source of truth and the referee. The evaluation net is what it was all along — a compiled artifact, built from the declaration by transforms with stated semantics, and the compiler is where the modelling lives.
The GameNet Pattern
Tic-tac-toe demonstrates the GameNet pattern from Chapter 4:
- Board state as places — each cell is a place, tokens mark availability
- Move history as places — separate tracking of who played where
- Turn control as a shared token — mutual exclusion enforces alternation
- Pattern collectors as transitions — compositional win detection
- ODE scoring — strategic value emerges from topology
- Integer reduction — for simple games, the ODE collapses to incidence degree counting
- Oracle play — the prior orders an exact search over the same net; perfect play is derived, not programmed
- Derived evaluation nets — declare the opponent’s policy as structure (forced-reply transitions) and the relaxation alone reaches the same perfection, no search at all
The same pattern scales to more complex games. A Connect Four model would have 42 position places (7 columns × 6 rows) and more pattern collectors (horizontal, vertical, diagonal sequences of 4). A Go model would have 361 position places. The complexity is in the number of places and patterns, not in the logic. When the game is simple enough, the strategic prior is a set of integers you can read off the graph without running the solver at all; whether the prior is enough to play well is the question the tournament, oracle and derived-net sections answer for this game, and it has to be asked again for each new one.
The mathematical foundation is the coffee shop’s. The incidence matrix encodes all arcs, P-invariants say which weighted token sums are conserved (here, the board-size sum of the move layer), and the ODE gives the relaxed flow. The difference is interpretation: in the coffee shop, tokens are grams of beans; in tic-tac-toe, tokens are board positions and move records.
Try it live: The Tic-Tac-Toe model is in sim.pflow.xyz’s catalog, where the
sim_evaluateMCP tool scores a player’s legal moves from any position — by seeded rollouts by default, or with thesearchandincidencemethods described above (Chapter 18).
The next chapter applies Petri nets to constraint satisfaction — modeling Sudoku as a system where arc weights and conservation laws enforce the puzzle’s rules, and the ODE relaxation finds valid configurations. Chapter 13 returns to the integer reduction from a different angle: deriving rate constants automatically from graph connectivity, and feeding them directly into the ZK verification pipeline.
Constraint Satisfaction — Sudoku
Learning objective: Express a puzzle’s constraints as net structure, and test whether a continuous relaxation of that net can rank candidate moves.
Chapters 5 and 6 applied Petri nets to resource management and game mechanics. This chapter applies them to a different problem class: constraint satisfaction. Sudoku is a puzzle where you fill a grid such that every row, column, and block contains each digit exactly once; there is no optimization and no opponent, only the constraints.
The encoding follows the three-layer pattern of Chapter 6: Game Mechanics — Tic-Tac-Toe: cells as places, digit placements as transitions that leave a history token, and constraint collectors that feed a solved place. The method carried over from tic-tac-toe is to rank candidate moves by how much ODE flow each directs toward solved. The model is go-pflow’s Sudoku example: the generator is createODENet in examples/sudoku/cmd/model.go, and the nets it produced are committed beside it as sudoku-4x4-ode.jsonld and sudoku-9x9-ode.jsonld. Read against that code, the collectors as built can never fire, so the ranking is not yet demonstrated. This chapter describes what the code builds, shows why the ranking fails, and ends on what a collector would have to express for it to work.
The Puzzle
We’ll use a 4×4 mini-Sudoku to keep things comprehensible. It is the sample puzzle in getSamplePuzzle in examples/sudoku/cmd/main.go:
Initial: Solution:
+---+---+---+---+ +---+---+---+---+
| 1 | . | . | . | | 1 | 2 | 4 | 3 |
+---+---+---+---+ +---+---+---+---+
| . | . | 2 | . | | 3 | 4 | 2 | 1 |
+===+===+===+===+ -> +===+===+===+===+
| . | 3 | . | . | | 2 | 3 | 1 | 4 |
+---+---+---+---+ +---+---+---+---+
| . | . | . | 4 | | 4 | 1 | 3 | 2 |
+---+---+---+---+ +---+---+---+---+
Constraints: each row, column, and 2×2 block must contain digits 1–4 exactly once. The 9×9 version uses digits 1–9 with 3×3 blocks — same structure, just more of it.
Cell Places and Digit Transitions
Node names in this chapter are the ones in the committed sudoku-4x4-ode.jsonld (P01, D2_01, _D2_01, Block00_Complete). The current generator writes them with a separator between row and column (P0_1, D2_0_1, _D2_0_1, Block0_0_Complete); the structure is the same.
Layer 1: Cell Places
Each cell in the grid is a place. A token means “this cell is empty”:
P00: 0 P01: 1 P02: 1 P03: 1
P10: 1 P11: 1 P12: 0 P13: 1
P20: 1 P21: 0 P22: 1 P23: 1
P30: 1 P31: 1 P32: 1 P33: 0
Given cells (1 at position 00, 2 at position 12, 3 at position 21, 4 at position 33) have no token — they’re already filled. Instead, the history place for the clue starts marked: _D1_00 holds a token from the beginning because the puzzle gives a 1 at (0,0), while _D2_00, _D3_00 and _D4_00 start at 0.
Layer 2: Digit Transitions and History
For each empty cell × digit combination, a transition represents “write this digit in this cell”:
Transition D2_01: History place _D2_01:
"Write digit 2 at (0,1)" "Digit 2 is at (0,1)"
+------+
P01 --| D2 |---> _D2_01
(1) | _01 | (0 -> 1)
+------+
Firing consumes the cell token (cell is now filled) and produces a history token (recording which digit was placed). This is the tic-tac-toe pattern: P_ij → PlayX_ij → X_ij.
The generator makes digit transitions only for empty cells, so the 4×4 puzzle has 12 empty cells × 4 digits = 48 digit transitions, while history places exist for every cell, 16 × 4 = 64 history places. A digit transition has exactly one input arc, from its cell, and one output arc, to its history place. Nothing from the cell’s row, column or block touches it, so the net does not stop a second 1 being written into row 0: D1_01 is exactly as enabled as D2_01. Whatever constraint the model carries has to live in the collectors.
Layer 3: Constraint Collectors
There are 12 constraint collectors — 4 rows (Row0_Complete …), 4 columns (Col0_Complete …) and 4 blocks (Block00_Complete …) — each with one output arc into solved, whose capacity is 12. The intent is that Row0_Complete fires when row 0 contains 1, 2, 3 and 4. The generator wires it to every history place in the row, 4 digits × 4 cells = 16 input arcs:
_D1_00 _D2_00 _D3_00 _D4_00 -->
_D1_01 _D2_01 _D3_01 _D4_01 --> Row0_Complete --> solved
_D1_02 _D2_02 _D3_02 _D4_02 -->
_D1_03 _D2_03 _D3_03 _D4_03 -->
A transition is enabled only when every input place holds a token, so this collector asks for every cell of the row to hold every digit at once. A cell has one token to give, so on any legal fill exactly 4 of the 16 places are marked, and the collector stays disabled. As built, solved cannot leave 0.
The counts check against the committed net: 81 places (16 cells, 64 history places, solved), 60 transitions (48 digit moves, 12 collectors) and 300 arcs (2 per digit transition, 16 into and 1 out of each collector).
The tic-tac-toe collectors of Chapter 6 don’t have this problem because a win line is a plain conjunction — X at three named cells, three input arcs. “Row 0 is complete” is a conjunction over digits of a disjunction over cells: 1 is in some cell of the row, and 2 is, and so on. A single transition’s enabling rule is a conjunction over its inputs, and wiring every (digit, cell) pair as an input is how the generator ended up asking for all 16.
How the Model Works
Step-by-step for cell (0,1) — currently empty:
-
Initial:
P01 = 1(cell is empty, available for placement) -
Consider digit 2: Transition
D2_01is enabled becauseP01has a token — and so areD1_01,D3_01andD4_01, by the same arc -
Fire
D2_01:P01: 1 → 0 (cell now filled)_D2_01: 0 → 1 (history records “digit 2 at position (0,1)”)
-
Constraint progress:
Row0_Completeis still disabled. It also needs_D1_01,_D3_01and_D4_01, which can no longer be marked becauseP01’s token is spent, and_D2_00,_D3_00and_D4_00, which no transition writes, because (0,0) is a given
The net encodes what a digit placement is. It does not yet encode what a valid solution is.
ODE Prediction for Move Ordering
The tic-tac-toe method scores each candidate by simulating the net from the marking the move would leave. As a procedure (a sketch; nothing in the repository implements it for Sudoku):
For each candidate move:
1. Create hypothetical state (after placing this digit)
2. Run ODE simulation (t=0 to t=3.0)
3. Measure token flow to 'solved' place
4. Higher flow = move more likely leads to solution
What the Net Computes
On the committed net this procedure gives every candidate the same score, zero. go-pflow’s rate law sets a transition’s flux to its rate times the product of its input places’ token counts, and to 0 outright if any input is at or below 0 (solver/ode.go). Every row, column and block of the sample puzzle contains one given cell. A given cell has no digit transitions, so three of its four history places are 0 for all , and every collector over that row, column or block has those places among its inputs. Every collector’s flux is therefore 0 from the first step, whichever move was tried.
The history layer cannot separate the candidates either. The four digit transitions out of an empty cell share one input and one rate (SetRates gives every transition 1.0 unless overridden, petri/net.go), so the ODE splits the cell’s token evenly among its four history places. With the collectors inert, nothing connects one cell to another, and placing a 2 or a 4 at (0,1) leaves the rest of the trajectory unchanged.
We derived this by reading the generator and the solver against the committed net; the simulation was not re-run.
Move Ranking Example
For cell (0,1), reasoning from the puzzle rules out two digits and leaves two:
| Digit | The rules | The net | Score on the committed net |
|---|---|---|---|
| 1 | excluded: row 0 has the 1 at (0,0) | D1_01 enabled | 0 |
| 2 | candidate (the solution’s digit) | D2_01 enabled | 0 |
| 3 | excluded: column 1 has the 3 at (2,1) | D3_01 enabled | 0 |
| 4 | candidate | D4_01 enabled | 0 |
The scores are derived from the argument above, not from a run. The exclusions in the second column are the reader’s reasoning; neither shows up in the net, where all four transitions are enabled by the same token. For the method to work, the ODE would have to score 2 above 4 and give 1 and 3 zero flow. No run in the repository demonstrates either.
Tuning for Speed
A full-precision solve of the 9×9 net is slow, so the benchmark in sudoku_bench_test.go runs the Tsit5 solver with looser settings than solver.DefaultOptions():
| Parameter | DefaultOptions() | Benchmark | Why |
|---|---|---|---|
| Time horizon | passed with the problem (tic-tac-toe used t=10.0) | t=3.0 | Only relative rankings are needed |
| Abstol | 1e-6 | 1e-4 | Looser tolerance, faster solve |
| Reltol | 1e-3 | 1e-3 | Unchanged |
| Initial step (dt) | 0.01 | 0.2 | Larger first step; the solver is adaptive and Dtmax stays 0.1 |
| Max iterations | 100000 | 100000 | Left at the default |
Cutting the horizon assumes that ranking needs candidates in the right order rather than converged token counts, and that a move ahead at t=3.0 is still ahead at t=10.0. Nothing in the repository tests that assumption for Sudoku, and with every score at 0 there is nothing yet to order. The same cut was made first in the tic-tac-toe example, whose README reports a 21× speedup and about 0.04 s per move evaluation.
benchmark_results.txt records one run on an Apple M4 Max:
| Benchmark | Time per evaluation |
|---|---|
| 4×4, benchmark settings | 0.067 s |
| 4×4, tighter tolerance | 14.8 s |
| 9×9, benchmark settings | 4.58 s |
That file names benchmarks (…SingleEvaluation, …WithTighterTolerance) that the current test file no longer has; it now has BenchmarkSudoku4x4ODE, BenchmarkSudoku9x9ODE and BenchmarkSudoku16x16ODE. The settings behind the 14.8 s row are therefore not in the repository, and the roughly 220× gap between the two 4×4 rows is against settings we cannot name. At the recorded speeds, scoring the four candidates for a 4×4 cell takes about a quarter of a second, and the nine for a 9×9 cell about forty seconds. From the go-pflow root, go test -run '^$' -bench Sudoku4x4ODE ./examples/sudoku/cmd re-times the 4×4 solve; it discards the result, so nothing in the repository yet reads solved from a solution or ranks a move. (The analyzer’s --analyze flag does not call the solver either: runODESimulationOnNet in main.go prints a description of the method and returns.) Not re-run for this chapter.
Scaling from 4×4 to 9×9
The same generator builds the 9×9 net:
| Component | 4×4 | 9×9 |
|---|---|---|
| Cell places | 16 | 81 |
| Digits | 4 | 9 |
| History places | 64 | 729 |
| Digit transitions (sample puzzle) | 48 | 459 |
| Digit transitions (empty grid) | 64 | 729 |
| Row / column / block collectors | 4 / 4 / 4 | 9 / 9 / 9 |
| Inputs per collector | 16 | 81 |
solved capacity | 12 | 27 |
The 9×9 sample is the 30-clue puzzle in getSamplePuzzle, so 51 empty cells and 459 digit transitions; the committed sudoku-9x9-ode.jsonld has 486 transitions, which is 459 plus the 27 collectors. Every row, column and block of that puzzle also contains a given, so the 9×9 collectors are starved the same way the 4×4 ones are.
The intended use was for the ranking to order the choices of a discrete solver (backtracking, constraint propagation) rather than to solve the puzzle itself. No such solver is wired to it in the repository.
Constraint Satisfaction as Token Flow
The Sudoku model suggests a layering for constraint satisfaction problems:
- Variables become places (cells that can be filled)
- Domain values become transitions (digits that can be placed), each leaving a history token
- Constraints become collector transitions (patterns that must be completed)
- Solution is a state where all collectors have fired
Steps 1, 2 and 4 carry over from tic-tac-toe directly. Step 3 is where the Sudoku net goes wrong. A collector’s enabling rule is a conjunction over its inputs, so a constraint with a disjunction inside it — “some cell of row 0 holds a 1” — needs structure in between. One shape would give each (digit, row) pair its own place, fed from that row’s four history places, and give the row collector one input per digit. It has not been built, and it raises a question of its own: the column and block collectors need the same history tokens, so the new layer would have to test them without consuming them — with read arcs, which fall outside the free structure (Appendix E: Categorical Foundations, “Where the Free Structure Stops”) — or put them back. Even with working collectors, the digit layer has no arcs that make a conflicting placement cost anything, so whether the ODE would separate 2 from 4 at (0,1), or show 1 and 3 as zero flow, is open.
The same layering can be sketched for other problems. An N-queens net would have N² square places, queen-placement transitions, and collectors for rows, columns and diagonals; a graph-coloring net would have vertex places, color transitions, and a collector for each edge. Neither is built in the repository, and neither has been checked against the collector problem above.
In constraint programming, the order in which variables are assigned and values tried has a large effect on search time. Flow toward solved was meant as a value-ordering heuristic of that kind: try the assignment that sends the most flow toward the solution. On the net as built, every assignment sends none, so whether it can serve as one depends on a collector design that has not been tried.
Optimization — The Knapsack Problem
Learning objective: Solve NP-hard problems approximately via mass-action kinetics.
The previous chapter tested whether an ODE relaxation could rank moves in a constraint problem, and found that on the Sudoku net as built it cannot yet. This chapter applies the same continuous relaxation to a combinatorial optimization problem small enough that the dynamics can be solved by hand, so we can say exactly what the relaxation sees and what it misses.
The 0/1 knapsack problem asks: given items with weights and values, select a subset that maximizes total value within a weight budget. It’s NP-hard. Traditional approaches use branch-and-bound — systematic enumeration with pruning. The Petri net approach uses mass-action kinetics — items compete for capacity through continuous dynamics. Repeating the simulation with one item removed at a time shows which removal raises the value the dynamics settle at.
The 0/1 Knapsack as a Petri Net
Problem Definition
Four items with different weights and values, capacity budget of 15:
| Item | Weight | Value | Efficiency (v/w) |
|---|---|---|---|
| item0 | 2 | 10 | 5.0 |
| item1 | 4 | 10 | 2.5 |
| item2 | 6 | 12 | 2.0 |
| item3 | 9 | 18 | 2.0 |
These are the values in go-pflow’s examples/knapsack, which produced every simulation number in this chapter; the example’s README records its output. The numbers were not re-run for this chapter, and no test pins them (the example only prints them), but each one also follows from the closed form derived below.
The optimal solution takes items 0, 1, and 3 — total weight 15, total value 38. The example prints that as a constant rather than computing it; it is checked by enumeration under Comparison with Branch-and-Bound. Item2 and item3 tie on efficiency at 2.0, so the ratio can’t choose between them; capacity does. After items 0 and 1 take 6 units, item3 fills the remaining 9 exactly, while item2 would leave 3 idle (items 0, 1, 2 weigh 12 and are worth 32).
Net Structure
The Petri net encodes the knapsack as a dynamic system:
- Item places: Each holds 1 token (item available) or 0 (item taken). Under the discrete firing rule this enforces the 0/1 constraint: an item is taken once or not at all. The ODE relaxes it, so an item place can settle anywhere between 0 and 1.
- Capacity place: Holds tokens representing available weight budget. Initial marking = 15 (the weight limit).
- Take transitions: One per item. Consumes the item token plus capacity tokens equal to the item’s weight. Produces tokens into value and weight tracking places.
For item0 (weight 2, value 10), with arc weights in parentheses:
item0 ----(1)---> take_item0 ---(10)--> value
^ \
capacity ---(2)----+ `--(2)---> weight
createKnapsackNet in main.go builds these places and arcs, and the same net in the editor’s JSON format is checked into go-pflow as a parse golden, where the transitions are named txn0–txn3.
The arc from capacity to take_item0 has weight 2 — taking item0 costs 2 units of capacity. The enabling condition requires AND . If the remaining capacity is less than 2, this item can’t be taken.
The structural point is that all items compete for the same capacity pool. Taking item2 (weight 6) leaves less capacity for item3 (weight 9). This competition is encoded in the shared input place, not in any explicit exclusion logic.
Why Every Item Is Taken Equally
In the basic model, all transitions have rate 1.0. go-pflow’s mass-action kinetics are first-order in every input place (solver/ode.go):
The arc weight scales how much capacity each firing consumes, not the rate: it does not appear as an exponent. (Chemical mass action would raise to the power ; go-pflow does not.)
This makes the dynamics solvable by hand. Let . Each item place obeys , so
— the same curve for every item, whatever its weight or value. Values never enter the dynamics at all; they sit on output arcs into a place nothing reads. All active items are therefore taken in one common fraction , and the remaining capacity is , where is the total weight of the active items. If , capacity runs out at and the net settles at value , with the total value of the active items. If , and the net eventually collects all of . Every number in the rest of this chapter follows from that formula.
Continuous Relaxation and Rounding
Running the ODE simulation with uniform rates:
Final state (continuous approximation):
Value accumulated: 35.71
Weight used: 15.00
Capacity remaining: 0.00
Item consumption (fraction taken):
item0: 71.4% taken
item1: 71.4% taken
item2: 71.4% taken
item3: 71.4% taken
The continuous relaxation takes fractional amounts of each item — all at exactly , as the formula predicts (, , value ). The total value is 35.71, compared to the discrete optimum of 38.
The fractional solution looks like the LP (linear programming) relaxation of the knapsack, but it is not one: an LP relaxation is an upper bound on the integer optimum (here the LP value is 38 — items 0 and 1 whole, then 9 units at ratio 2.0), while the ODE settles at 35.71, below the integer optimum of 38. Mass-action kinetics spreads consumption across items proportionally; it is a smooth dynamics, not a maximiser. The gap between 35.71 and 38 tells us that simple rounding won’t find the optimum. We need more information about the solution structure.
Exclusion Analysis for Sensitivity
Exclusion analysis disables each item’s transition one at a time (main.go sets the item’s token and its rate to 0) and re-runs the ODE to :
| Excluded | Final Value | Relative to Baseline |
|---|---|---|
| none | 35.71 | 100.0% |
| item0 | 31.58 | 88.4% |
| item1 | 35.29 | 98.8% |
| item2 | 37.75 | 105.7% |
| item3 | 32.00 | 89.6% |
Three of the four items behave as expected — excluding them reduces the total value. But item2 is anomalous: excluding it increases the value from 35.71 to 37.75.
The formula explains the whole table. While the active items overweigh the capacity, the value is — capacity times the aggregate value density of the active set. Excluding item0 costs the most because it is the densest item: falls from to , giving 31.58. Excluding item3 leaves items weighing 12, which fit, so the net collects their full value of 32. Item2 is the only exclusion that raises the value, because without it the remaining weights sum to exactly 15 and the net can take all of items 0, 1 and 3.
So item2 is “hurting” the solution in a precise sense: its exclusion is the one that makes the rest fit. On this instance one sensitivity pass — five ODE runs — points at the optimum. Single exclusions only examine subsets of size , though, and on a larger instance the optimum can drop several items; that this heuristic finds the optimum in general is not shown here.
Convergence After Exclusion
With item2’s transition disabled, the ODE converges toward the discrete optimum:
| Time | Value | Gap to Optimal |
|---|---|---|
| t=10 | 37.75 | 0.2517 |
| t=100 | 37.97 | 0.0253 |
| t=1000 | 38.00 | 0.0025 |
Given enough simulation time, the continuous relaxation without item2 converges to the exact discrete optimum of 38. The remaining items (0, 1, 3) weigh exactly the capacity, so capacity and items drain together: integrates to , and the gap to 38 is (0.2517, 0.0253 and 0.0025 at the three times, matching the table) — algebraic rather than exponential, which is why it takes until to close.
The exclusion step removes the item whose presence keeps the rest from fitting; the ODE then fills the set that remains. It reaches the integer optimum here because , not because the dynamics select it.
Comparison with Branch-and-Bound
The two approaches work through different mechanisms, and only one of them solves the problem.
Branch-and-bound treats optimization as search. It builds a decision tree where each node represents a binary choice: take this item or skip it. The algorithm explores branches, computing upper bounds to prune paths that can’t improve on the best solution found so far. It’s systematic enumeration with smart pruning — still exponential in the worst case, but practical for moderate problem sizes.
The ODE treats optimization as simulation. Instead of explicit decisions, items compete for capacity through continuous dynamics. The mass-action kinetics means all enabled transitions fire simultaneously at rates proportional to available resources. There’s no decision tree — just differential equations evolving toward equilibrium.
| Aspect | Branch-and-Bound | ODE |
|---|---|---|
| Core operation | Decision-tree search with bounds | Continuous dynamics |
| Decisions | Explicit (take/skip) | None — every active item is taken in the same fraction |
| Solution type | Exact integer | Fractional approximation |
| Cost | Exponential worst case (pruned) | One ODE solve per run; does not solve the integer problem |
| Primary output | The optimal subset | A relaxed value, and its sensitivity to each item |
For the exact answer, search wins. No branch-and-bound was run on this instance, and go-pflow has no implementation, but on four items plain enumeration settles it: of the 16 subsets, three are over capacity ({0, 2, 3} at 17, {1, 2, 3} at 19, all four at 21), and of the thirteen that fit, {0, 1, 3} is the best at 38, then {0, 1, 2} at 32. Any exact method has to return that subset. The ODE reaches 35.71 by taking the same fraction of everything.
What the ODE adds is the sensitivity table. The exclusion pass singles out item2 as the one item whose removal raises the relaxed value; branch-and-bound reaches the same subset by pruning, without reporting why. The closed form says how much that table can carry: the dynamics never read the values, so on this instance the signal is the weight fit — without item2 the remaining items fill capacity exactly.
When to Use Each
The two can be chained: run the exclusion pass to find items whose removal helps, then give the reduced instance to branch-and-bound or dynamic programming for the exact answer. This chapter shows the first half on one four-item instance; no example in go-pflow runs the combined workflow.
Beyond Four Items
The 4-item example is intentionally small. For larger instances:
-
100 items: Each ODE run stays cheap — the number of transitions scales linearly — and single-item exclusion analysis is 101 runs. But single exclusions only look at 99-item subsets, and the optimum can drop many items, so this does not replace branch-and-bound’s exponential worst case; a benchmark on larger instances has not been done.
-
Items with equal efficiency: item2 and item3 tie at 2.0 here, and the exclusion pass separates them only by how their weights fit the capacity, since the dynamics never read values. Whether it tells interchangeable items apart on other instances has not been demonstrated.
-
Multiple constraints: A second constraint (volume, fragility) makes this the multidimensional knapsack problem, which is harder for any method. In the net it is a second capacity place with its own arc weights. Each take transition then has three input places, so every item still drains along one shared curve, now with the integral of , and the net stops at the fraction where the first capacity runs out. That follows from the same derivation;
examples/knapsackhas no such variant to run.
The Pattern
The knapsack model demonstrates a fourth application pattern, distinct from resources (Chapter 5), games (Chapter 6), and constraints (Chapter 7):
- Decision variables become places (items available or taken)
- Resource constraints become shared capacity places with weighted arcs
- Competition comes from the shared input place: under uniform rates every item is drawn down by the same fraction, and capacity in proportion to weight
- Exclusion analysis shows which single removal raises the relaxed value
- Continuous relaxation settles below the optimum here; the exclusion pass leads to the exact solution on this instance
The ODE does not find the optimum. It produces a relaxed value and a sensitivity table, and on this instance the table leads straight to the optimum. On larger instances it can at best guide a search, and that has not been benchmarked.
Try it live: This chapter’s net is small enough to write as model JSON (Appendix C). Store it with
POST https://sim.pflow.xyz/api/models, no account needed, and open the returned id in the what-if console at/whatif/?id={id}.
Biochemistry — Enzyme Kinetics
Learning objective: See how Petri nets naturally model chemical reactions, recovering classical equations.
The previous chapters applied the continuous semantics of Chapter 3: From Discrete to Continuous to domains that borrowed it — resource flows, games, puzzles, optimization. This chapter returns to the domain that rate law came from: chemistry. Enzyme kinetics is the study of how enzymes catalyze reactions, and the Michaelis-Menten equation is its central rate law.
Textbooks start from four rate equations, assume the enzyme-substrate complex sits at a quasi-steady state, and do the algebra. A 4-place Petri net with mass-action rates gives you those four rate equations without anyone typing them, and the solver integrates them as they stand, with no steady-state assumption. Michaelis-Menten is still an approximation of that system, and it still comes from the algebra; what the net changes is that the system being approximated is the model itself rather than a hand transcription of it.
Substrate, Enzyme, Product
An enzyme catalyzes the conversion of substrate to product in three steps:
- Binding: enzyme and substrate combine to form a complex (rate )
- Unbinding: the complex falls apart without producing product (rate )
- Catalysis: the complex converts substrate to product, releasing the enzyme (rate )
The enzyme is not consumed; it cycles between free and bound states, and that cycle maps directly onto token flow.
The Petri Net
Four places, three transitions:
| Place | Initial | Role |
|---|---|---|
substrate | 100 | Free substrate molecules |
enzyme | 10 | Free enzyme molecules |
complex | 0 | Enzyme-substrate complex |
product | 0 | Converted product |
| Transition | Rate | Arcs |
|---|---|---|
bind | substrate + enzyme → complex | |
unbind | complex → substrate + enzyme | |
catalyze | complex → product + enzyme |
The arc structure encodes the chemistry directly. bind consumes a free enzyme, and both unbind and catalyze give one back. The enzyme is not an input of catalyze; it is a catalyst because every path out of complex returns it.
The net is declared as services/enzyme-kinetics.json in the source of sim.pflow.xyz (a private repository; sim itself is retired): the four places and three rates above, and nine arcs, all of weight 1. The public net you can open is the Enzyme Kinetics example on pflow.xyz (source: examples/landing/enzyme-kinetics.jsonld). It has the same four places and the same nine weight-1 arcs, but it starts from 50 substrate and stores no rate constants, so its curves are not the ones quoted in this chapter.
In Code
The same net in go-pflow’s builder API (petri/builder.go). There is no enzyme example in go-pflow’s examples/, so this snippet is not a file in the repository and has not been run:
net, rates := petri.Build().
Place("substrate", 100).
Place("enzyme", 10).
Place("complex", 0).
Place("product", 0).
Transition("bind").
Transition("unbind").
Transition("catalyze").
Arc("substrate", "bind", 1).
Arc("enzyme", "bind", 1).
Arc("bind", "complex", 1).
Arc("complex", "unbind", 1).
Arc("unbind", "substrate", 1).
Arc("unbind", "enzyme", 1).
Arc("complex", "catalyze", 1).
Arc("catalyze", "product", 1).
Arc("catalyze", "enzyme", 1).
WithCustomRates(map[string]float64{
"bind": 0.01,
"unbind": 0.1,
"catalyze": 0.5,
})
WithCustomRates returns the net and the rate map together; WithRates takes a single default rate for every transition, which is not what this model needs.
Mass-Action Kinetics as Native Semantics
With mass-action kinetics, each transition fires at a rate proportional to the product of its input concentrations:
Every input arc here has weight 1, so go-pflow’s first-power rate law and textbook chemical mass action coincide for this net (Chapter 3 explains where they differ). The ODE system follows from the topology as , with the incidence matrix (rows are places, columns are transitions) and the vector of the three rates:
Nobody writes these equations into the simulation. go-pflow’s solver builds each derivative from the arcs (solver/ode.go: flux is the rate times the product of the input markings), as Chapter 3 describes. The service definition does carry the four equations as metadata, for people to read; the solver never sees them.
Michaelis-Menten as an Approximation
Set (the quasi-steady-state assumption):
Solving for the reaction rate and using :
where and .
This is the Michaelis-Menten equation, and it comes from the algebra, not from the solver. The solver integrates the full four-equation system; Michaelis-Menten approximates it well when is small against (at the defaults below, 10 against 160).
The saturation curve itself, rate against initial substrate, would come from a sweep: integrate the net across a range of initial substrate, take the initial rate at each, and plot it against . The expectation is a close match at and a drift as approaches . No code in the pflow repositories runs that sweep yet, so this is a prediction, not a result.
The Saturation Effect
Why does the rate saturate? The Petri net makes it visible through token flow.
At low substrate, most enzyme tokens are in the enzyme place (free). Increasing [S] means more bind events, so the rate climbs linearly. But at high substrate, almost all enzyme tokens are tied up in complex. Adding more substrate can’t speed things up — there’s no free enzyme to bind with.
is the substrate concentration at half-maximum rate. With the default parameters, . It is often read as binding affinity, but that reading holds only when . Here is five times , and the dissociation constant is 10, so most of is turnover rather than loose binding.
is the rate with all enzyme bound. With 10 enzyme molecules and , .
Both values are the two formulas above applied to the rate constants. Neither is fitted to a simulated curve.
Simulation Readouts
A browser demo built from the same net and default rates (now retired) integrated it with Tsit5 at a fixed step over a 30-second window and reported four readouts. Its source is frontends/enzyme-kinetics/main.js in petri-pilot (runODE and computePredictions). With the demo retired, no live page reproduces the table:
| Readout | Default Value | What It Is |
|---|---|---|
| Time to 50% conversion | ~17s | First time free substrate falls to half its initial value |
| Peak reaction rate | ~2.95 | Largest finite-difference d[P]/dt in the run |
| Final yield | ~70% | Product as a percentage of initial substrate at the end of the window |
| / | 60 / 5.0 | Computed from the rate constants, not measured from the run |
The first three come out of the integration. They are the demo’s readouts at the default settings and have not been re-run for this edition.
One of them can be checked by hand. Since and can never exceed the 10 enzyme molecules, the peak rate is bounded by . The Michaelis-Menten approximation gives a closer estimate: at it predicts , and free substrate only falls from there. A peak of about 2.95 sits just under that estimate, as expected when some substrate is already tied up in complex by the time the rate peaks. That is a derivation, not a run.
The concentration curves show the familiar pattern: substrate depletes as product accumulates, with the enzyme-substrate complex rising quickly and then falling as substrate runs out.
Conservation Laws from P-Invariants
The net’s structure carries two conservation laws.
Enzyme conservation:
Free enzyme plus bound enzyme always equals the initial enzyme count. Nothing in the model states this as a constraint; it follows from the arcs. The enzyme circulates through enzyme → complex → enzyme but never leaves the system.
Check via P-invariant: the weight vector (for places [substrate, enzyme, complex, product]) satisfies :
bindcolumn:unbindcolumn:catalyzecolumn:
Mass conservation:
Substrate is either free, bound in complex, or converted to product. The weight vector is :
bindcolumn:unbindcolumn:catalyzecolumn:
Both checks are by hand, against the nine arcs of the service definition. Because , the exact ODE gives , so both sums are constant along every trajectory. The demo did not check them during a run. They make a useful test: if drifts in a simulation, an arc is missing, a weight is wrong, or the solver has a bug. go-pflow’s solver tests make that check for small nets (TestSolveConservation in solver/solver_test.go), not for this one.
Parameter Exploration and Sensitivity
Changing the rate constants explores the model. The values below follow from the formulas; none of these scenarios has been re-run for this edition.
High enzyme, low substrate (): there is plenty of enzyme, so the reaction runs much faster. This is also where the Michaelis-Menten constants stop meaning much. With 50 enzyme against , the quasi-steady-state condition fails, and the formula’s is unreachable: by the second conservation law, the complex can hold at most the 20 substrate molecules there are, so never exceeds .
Low (): binding becomes the bottleneck. , six times the default initial substrate.
High (): the enzyme turns over faster and rises to 20, but also rises, to . Faster catalysis empties the complex faster, so more substrate is needed to keep it populated.
Equal and (): a complex is equally likely to unbind or to catalyze, so half the binding events are “wasted” on unbinding. , higher than the default.
Each scenario is a different set of rate constants on the same net; the structure does not change.
Beyond Chemistry
The shape — a limited resource cycling between free and occupied, with throughput capped by how much of it there is — resembles processes and cores, callers and agents, jobs and machines. None of those has been built as a net here, and the mapping is looser than swapping labels. A call center has no obvious unbind (a caller abandoning mid-service, perhaps), and a context switch is overhead on the core rather than a reversible binding. What should carry over is the enzyme invariant, free plus busy is constant, and the ceiling that comes with it: throughput cannot exceed rate × servers, for the same reason cannot exceed .
The enzyme net is a ComputationNet in the sense of Chapter 4: The Token Language: continuous quantities, rate-based firing, and conservation laws carried by the arcs. It is small enough to understand completely. What it establishes is that the net generates the mass-action ODE system without anyone writing it and carries two conservation laws in its structure; the Michaelis-Menten equation is the quasi-steady-state reduction of that system.
Complex State Machines — Texas Hold’em
Learning objective: Model multi-player, multi-phase systems with roles and guards.
The previous chapters built progressively: resources (coffee shop), two-player games (tic-tac-toe), constraint puzzles (Sudoku), optimization (knapsack), and chemistry (enzyme kinetics). Each used a focused subset of Petri net features. Texas Hold’em asks for several at once: sequential phases, multi-player turn control, role-based permissions, conditional betting, and event sourcing for audit trails.
The model in this chapter is a tutorial Hold’em net, services/texas-holdem.json: five seats, four streets, 18 places and 32 transitions in one JSON file, from which an application generator produced an event-sourced Go service (examples/texasholdem) and a browser demo. Neither the generated code nor the demo is public any longer; the file paths below name where each cited piece lived. The same primitives as the earlier chapters carry the phases, the turn order and the event log. Chips, bet sizing and the winner do not fit into this net, and the chapter marks where the structure stops.
The Challenge
Poker has intricate state:
- Phases: preflop → flop → turn → river → showdown — a sequential state machine
- Turn order: Players act in sequence, skipping folded players
- Actions: fold, check, call, raise — each with preconditions on chips, bets, and game state
- Roles: Only the dealer should deal cards, and only players still in the hand should bet
- Audit: Every action must be logged for replay and verification
Traditional implementations scatter this logic across conditionals, state variables, and validation functions. A Petri net makes the parts it can carry explicit: where a rule is in the structure, an illegal move is not enabled rather than checked for at runtime. The rest of this chapter shows how far that reaches in this model.
Phase Places
The core flow is a WorkflowNet — a sequential state machine where a single token traces a path through phases:
waiting -> preflop -> flop -> turn_round -> river -> showdown -> complete
Each phase is a place. Phase transitions move the game forward:
preflop --> deal_flop --> flop
^
betting_done +
The deal_flop transition requires two things: a token in preflop (we’re in that phase) and a token in betting_done (the betting round is over). Both must be present for the transition to fire, so cards are not dealt mid-betting. “Over” is narrower than in real poker: betting_done is produced by seat 4’s action, so each street is exactly one orbit of the table, p0 through p4, and a raise does not reopen the action to seats that already acted. Re-raise loops are not in this net.
The phase token is a cursor — exactly one phase place holds a token at any time. The P-invariant:
Reading the arcs, every one of the 32 transitions either moves one token along this chain or leaves it untouched; we checked that by hand against the JSON, not with an invariant solver. This is the WorkflowNet guarantee: mutual exclusion. The game is always in exactly one phase.
Turn Tokens and Role-Based Access
Each player has a turn place: p0_turn, p1_turn, …, p4_turn. When it’s Player 0’s turn, only p0_turn holds a token. Player actions consume their turn token and produce the next player’s. From the model file:
p0_check:
inputs: [p0_turn, p0_active]
outputs: [p0_active, p1_turn]
Player 0 can only check when two conditions hold: it’s their turn (p0_turn has a token) AND they’re still in the hand (p0_active has a token). Checking hands the active token back and moves the turn token to Player 1. Call and raise have the same arcs.
This is the turn control mechanism from tic-tac-toe (Chapter 6: Game Mechanics), generalized from one alternating Next place to a ring of five turn places. The turn order is a conservation law of the net. Reading the arcs, every transition preserves
so at most one seat holds the turn at any reachable marking. A player action moves the token from one seat to the next (seat 4 hands it to betting_done), each deal transition turns betting_done back into p0_turn, and the phase transitions at either end of the hand pass it through showdown, complete and waiting. As with the phase invariant, this was checked by hand, not run.
Folding and Skipping
When a player folds, their p_active token is consumed:
p2_fold:
inputs: [p2_turn, p2_active]
outputs: [p3_turn]
// Note: p2_active is NOT returned
A folded seat has no active token, so its fold, check, call and raise are all disabled. Only the skip transition, which needs nothing but the turn token, can pass the turn along:
p2_skip:
inputs: [p2_turn] // No p2_active required
outputs: [p3_turn]
The model declares no guard on the skip, and its description reads “Skip player 2 (all-in/eliminated)”. So p2_skip is also enabled for a seat that is still in the hand: nothing in the net forces an active player to act rather than pass. Restricting the skip to folded seats would take an inhibitor arc from p2_active — a contextual arc, outside the incidence matrix (Appendix E) — or a guard. The model has neither, so the structure guarantees that a folded seat can only pass, not that an active seat must play.
Betting Conditions as Guard Expressions
Some actions require conditions beyond token availability. Guards from Chapter 4: The Token Language handle this. This model declares none; the generated README’s transition table shows - in the Guard column for all 32 transitions. The guard a raise would need looks like this (a sketch in Chapter 4’s syntax, not from the model):
(action p0_raise
:guard {bets[0] >= current_bet && chips[0] >= raise_amount})
It would ensure:
- Player has matched the current bet (can’t raise without calling first)
- Player has enough chips to raise
In the demo, chip stacks, bets, blinds and the pot live in the browser’s JavaScript state (frontends/texas-holdem/main.js), not in the net.
Guards add business logic without changing the Petri net structure. The net handles what can happen (which transitions exist). Guards handle when it can happen (what conditions must hold). A guard can only disable a firing the structure allows, so every marking the guarded net reaches is also reachable without guards, and invariants and mutual exclusion proved from the net alone still hold. Deadlock freedom does not carry over the same way: a guard that is never true disables a transition the structural analysis counted on.
The Full Action Set
For each player, four actions. The net checks the token preconditions; the poker condition in the last column is left to code in this model:
| Action | Net precondition | Net effect | Poker condition (not in the net) |
|---|---|---|---|
fold | Turn token + active | Turn to next seat; active token consumed | — |
check | Turn token + active | Turn to next seat; active token returned | No outstanding bet |
call | Turn token + active | Turn to next seat; active token returned | Sufficient chips |
raise | Turn token + active | Turn to next seat; active token returned | Bet matched, sufficient chips |
Five players × four actions = 20 player transitions, plus 5 skip transitions, plus 7 phase transitions (start, deal flop/turn/river, showdown, determine winner, end hand). Total: 32 transitions.
The Model Structure
The full model:
Places (18):
waiting, preflop, flop, turn_round, -- Phase places
river, showdown, complete
p0_turn, p1_turn, p2_turn, -- Turn tokens
p3_turn, p4_turn
p0_active, p1_active, p2_active, -- Active markers (initial 1)
p3_active, p4_active
betting_done -- Sync signal
Transitions (32):
start_hand, deal_flop, deal_turn, -- Phase transitions
deal_river, go_showdown,
determine_winner, end_hand
p0_fold, p0_check, p0_call, p0_raise, -- Player 0 actions
p1_fold, p1_check, p1_call, p1_raise, -- Player 1 actions
... -- (5 players x 4 actions)
p0_skip, p1_skip, ... -- Pass the turn (needs only pN_turn)
A Defect in the Arcs
One defect is visible in the arcs. end_hand puts a fresh token into every pN_active without consuming the old one, and check, call and raise return the active token they take. So a seat that played a hand to the end starts the next hand with two active tokens; a single fold then leaves it with one, and on the next street that seat can check, call or raise again. The active places are not 1-bounded across hands. The fix is to restore only the seats that folded instead of refilling every seat; the model has not been patched.
Role-Based Access Control
The model’s access block restricts the phase transitions to a dealer role and declares admin as inheriting from dealer:
| Role | Transitions |
|---|---|
dealer | start_hand, deal_flop, deal_turn, deal_river, go_showdown, determine_winner, end_hand |
admin | inherits dealer (also listed on start_hand) |
There are no per-seat roles. Nothing in the model binds p0_raise to the person in seat 0, so any caller can fire any seat’s action while that seat holds the turn token. Enforcement is also thinner than the declaration. The generator could produce a permission middleware from the access block, but the generated example passes it an empty rule list (examples/texasholdem/service.go, accessRules := []*AccessControl{}), and its router (api.go) applies only an optional authentication middleware, not the permission check. In this model the roles are a declaration; the runtime does not yet enforce them.
Event Sourcing for Audit Trails
Every transition in the model names an event type (p0_raise → p0_raised, deal_flop → flop_dealt), and every firing in the generated service appends one event to an event store. A log looks roughly like this (a sketch: the amount and cards fields come from the model’s event schema, the times are made up):
[
{"action": "start_hand", "time": "10:00:00"},
{"action": "p0_raise", "amount": 50, "time": "10:00:15"},
{"action": "p1_call", "time": "10:00:23"},
{"action": "p2_fold", "time": "10:00:31"},
{"action": "deal_flop", "cards": "Ah Ks 7d", "time": "10:00:35"}
]
The Petri net’s discrete transitions map directly onto event sourcing, and the generated code implements three uses of it:
- Replay: Given the initial marking and the event sequence, reconstruct any game state by replaying transitions.
GET /api/texasholdem/{id}/at/{version}replays the stream up to a version. - Audit: A firing that was not enabled cannot appear in the log.
Executein the generatedaggregate.gorefuses any transition that cannot fire from the current marking before it appends an event. - Undo:
POST /api/texasholdem/{id}/truncatediscards every event after a target version. Truncation rewrites the stream, so the log is append-only only as long as nobody calls it.
This is the event sourcing pattern, revisited in Chapter 20: Dual Implementation and Verification: . Each event is a transition firing. Each state is a marking. The fold is the firing rule applied sequentially.
ODE Analysis of Hand Strength
The demo’s strategic analysis is not an ODE over the 18-place game net. For each decision, the frontend builds a separate eight-place net (buildHandStrengthPetriNet in main.js) whose initial marking and rates are set from card heuristics, solves it with the pflow.xyz Tsit5 solver, and reads values off the final state. From computeODEHandStrength:
const model = buildHandStrengthPetriNet(holeCards, communityCards)
const net = Solver.fromJSON(model)
const initialState = Solver.setState(net)
const rates = Solver.setRates(net)
const prob = new Solver.ODEProblem(net, initialState, [0, solverParams.tspan], rates)
const opts = { dt: solverParams.dt, adaptive: solverParams.adaptive }
const solution = Solver.solve(prob, Solver.Tsit5(), opts)
// ...
const strength = Math.min(1, Math.max(0,
preflopQuality * 0.5 + currentHandValue * 0.3 + baseStrength * 0.15 + improvement * 0.05
))
The small net has places for the current made hand, preflop quality, kicker, three draws (flush_draw, straight_draw, pair_draw), improvement potential and a hand_strength output. The draw places start at a completion probability from the rule of 2 and 4 (outs × 4% with two cards to come, outs × 2% with one), and their transitions feed hand_strength. The final value of hand_strength is then blended with three of the input places by the fixed weights above, and each action’s expected value comes from hand-written formulas: fold is 0; a call is strength × (pot + call) − call, halved when strength is below the pot odds; a raise is scaled up above a 0.6 strength threshold. The ODE is one aggregation step inside a heuristic, and the heuristic, not the net topology, decides the ranking.
That is the opposite of tic-tac-toe (Chapter 6), where the ODE runs on the game net itself. Poker also has hidden information (the opponents’ hole cards), which neither net models; the demo does no opponent range estimation. Poker hand ranking comes back in Chapter 13: Topology-Driven Verification and Chapter 15: Exponential Weights and Scoring Systems, as a question of what belongs inside a net and what belongs outside it.
Compositional Design
The Texas Hold’em model combines simpler patterns:
- WorkflowNet — Phase sequence (waiting → preflop → … → complete)
- GameNet — Turn control and player actions
- Roles — The
accessblock on the phase transitions
Two patterns a full poker engine needs are not in the net: a ResourceNet for chips (bet placement, pot management, conservation of total chips) and guards for conditional betting. In this model both live in frontend code.
The patterns that are present each carry a property you can check from the arcs: the phase sequence gives mutual exclusion (one phase at a time), and turn control gives at most one seat holding the turn. The betting_done place links them, connecting turn control to phase advancement, and both invariants above hold in the linked net, checked by hand on the whole model. This is the shape of the assume-guarantee reasoning from Chapter 4: verify components in isolation, check only the boundaries. Here the two components share a place, and Appendix E explains why gluing along a place needs that boundary check rather than getting the invariants for free.
Why Petri Nets for Complex Systems
Traditional game code mixes state, rules, and UI into monolithic logic. A Petri net separates concerns:
- Structure = What’s possible (places, transitions, arcs)
- State = What’s current (token marking)
- Rules = What’s allowed (guards, roles)
- History = What happened (events)
In this model the separation buys an invariant for the turn order and the phase sequence, a replayable log in which every entry was an enabled firing, and a structure in which defects such as the end_hand refill can be found by reading the arcs. Adding rules such as side pots or all-in needs the chip arithmetic in the net or in guards first; the model does not yet show that this can be done without the net growing out of proportion.
Texas Hold’em is at the complex end of the spectrum covered in Part II. It reuses the phase cursor, turn tokens and event log from the previous chapters in a single model, with the same vocabulary that described the coffee shop, the tic-tac-toe board, the Sudoku grid, the knapsack and the enzyme reaction. Where it stops — chips, bet sizing, the winner — is where the earlier chapters’ resource and guard patterns would have to be added.
Part III of this book shifts focus from building models to analyzing and verifying them — process mining, zero-knowledge proofs, topology-driven verification and on-chain verification.
Process Mining
Learning objective: Discover Petri net models from event logs and use them for prediction.
The previous chapters built Petri net models by hand — designing places, transitions, and arcs to capture known rules. But what about systems where the rules aren’t written down? Where the actual process diverges from the official procedure? Process mining reverses the direction: instead of building a model and running it, you collect data from a running system and discover the model automatically.
This chapter covers the complete pipeline: event logs as raw material, discovery algorithms that extract Petri net structure, timing analysis that learns transition rates, and predictive monitoring that uses the learned model to forecast outcomes before they happen.
Event Logs: The Raw Material
Most information systems already record events. Hospital admissions systems record when patients register, get triaged, see a doctor, and are discharged. ERP systems record when orders are placed, approved, shipped, and invoiced. The events are already there — process mining extracts structure from them.
An event log has three required fields:
| Field | Example | Purpose |
|---|---|---|
| Case ID | P101 | Which process instance |
| Activity | Registration | What happened |
| Timestamp | 2024-11-21 08:15:00 | When it happened |
Optional fields — resource (who did it), lifecycle (start/complete), cost, outcome — enrich the analysis but aren’t required for discovery.
A trace is the sequence of activities for a single case. Patient P101’s trace might be:
Registration -> Triage -> Doctor_Consultation -> Discharge
Patient P102, who needed lab work:
Registration -> Triage -> Doctor_Consultation -> Lab_Test -> Results_Review -> Discharge
These are process variants — different paths through the same system. How often each variant occurs is itself something the log records; discovery starts by counting variants, and the simplest algorithm keeps only the most frequent one.
Loading Event Logs
config := eventlog.DefaultCSVConfig()
log, _ := eventlog.ParseCSV("hospital.csv", config)
summary := log.Summarize()
// NumCases 4, NumEvents 26, NumActivities 11, NumVariants 4
The eventlog package handles CSV and JSONL formats with configurable column mappings (eventlog/csv.go, eventlog/jsonl.go). The log used throughout this chapter is go-pflow’s examples/mining_demo/hospital.csv: four patients, 26 events, eleven distinct activities, and four variants, because no two patients took the same path. The counts in the comment are read off the CSV, not from a re-run of the demo. Four cases are enough to show every step of the pipeline and far too few to trust any number it produces; the chapter uses them only for the first purpose.
Process Discovery
Given an event log, a discovery algorithm produces a Petri net that explains the observed behavior. Three algorithms illustrate the design space.
Common-Path Discovery
The simplest approach: find the most frequent trace variant and build a linear Petri net for it.
Most frequent variant: Reg -> Triage -> Doctor -> Discharge
Discovered model:
[start] -> Reg -> [p1] -> Triage -> [p2] -> Doctor -> [p3] -> Discharge -> [end]
Each activity becomes a transition. Places are inserted between transitions to carry the control flow token. A token in start means the case has arrived; a token in end means it’s complete; a token in p2 means the patient has been triaged and is waiting for the doctor.
Common-path discovery is fast and always produces a sequential net, but it ignores every other variant. It’s useful as a starting point or when the process is genuinely linear.
discovery, _ := mining.Discover(log, "common-path")
net := discovery.Net
// discovery.CoveragePercent: share of cases that follow the chosen variant exactly
On the hospital log every variant occurs exactly once, so “most frequent” is a four-way tie. DiscoverCommonPath breaks it by iterating over a Go map, whose order is randomized, so repeated runs can return different nets; each covers 25% of cases. The net committed as discovered_hospital_net.json is patient P003’s path, Registration → Triage → Doctor_Consultation → Prescription → Discharge: six places and five transitions.
The Alpha Algorithm
The Alpha algorithm, introduced by van der Aalst in 2004, discovers concurrent structure — not just sequences. It works by analyzing ordering relations between activities.
The algorithm builds a footprint matrix from the event log. For every pair of activities (A, B), it classifies their relationship:
| Relation | Symbol | Meaning |
|---|---|---|
| Causality | A → B | B directly follows A somewhere, never the reverse |
| Parallel | A ‖ B | Each directly follows the other somewhere |
| Choice | A # B | Neither directly follows the other |
Given traces:
Case 1: A -> B -> D -> E
Case 2: A -> C -> D -> E
The footprint matrix reveals: A → B (causal), A → C (causal), B # C (choice — neither directly follows the other), B → D and C → D (both causal), D → E (causal).
From these relations, the Alpha algorithm constructs a Petri net:
-> [B] ->
[A] -> [D] -> [E]
-> [C] ->
B and C are alternative paths after A, both converging at D. The algorithm discovers this branching structure automatically — no human specified that B and C are alternatives.
The implementation, mining/alpha.go, enumerates candidate places (X, Y), where every activity in X is causally followed by every activity in Y and the activities within X, and within Y, are pairwise in choice. It then keeps only the maximal candidates. The footprint is built in mining/footprint.go, and mining/mining_test.go exercises the miner on sequential and parallel logs. The A–E example above is worked by hand; it is not one of those tests.
miner := mining.NewAlphaMiner(log)
net := miner.Mine()
The Alpha algorithm has known limitations, listed in the source: it can’t handle loops of length 1 or 2, and it’s sensitive to noise in the log. For real-world data, the heuristic miner is more robust.
Heuristic Miner
The heuristic miner tolerates noise by scoring each ordered pair of activities from directly-follows counts, instead of treating a single observation as a relation. mining/heuristic.go uses the dependency measure
where counts how often directly follows . An edge is kept when its score reaches DependencyThreshold, which defaults to 0.5:
Observations Score
A -> B: 100, B -> A: 0 100/101 ≈ 0.99
A -> B: 100, B -> A: 3 97/104 ≈ 0.93
C -> X: 2, X -> C: 0 2/3 ≈ 0.67
C -> X: 1, X -> C: 0 1/2 = 0.50
A few reversed observations barely dent a strong relation, and that is where the noise tolerance comes from. A rare edge seen in only one direction is another matter: at the default threshold even a single observation scores exactly 0.5 and survives. Filtering the two-observation C → X edge takes a stricter threshold:
opts := mining.DefaultHeuristicOptions()
opts.DependencyThreshold = 0.8 // drops one-way edges seen fewer than four times
res, _ := mining.DiscoverHeuristicWithOptions(log, opts)
The scores are computed by hand from the formula, not from a run. A higher threshold gives a cleaner model at the cost of ignoring rare behavior, which may be exactly the behavior you wanted to find.
Timing Analysis and Rate Learning
Discovery tells us the process structure — which activities exist and how they connect. Timing analysis tells us the dynamics — how long each activity takes and how fast cases flow through the system.
Extracting Timing Statistics
stats := mining.ExtractTiming(log)
// Per-activity statistics, hospital.csv
meanTriage := stats.GetMeanDuration("Triage") // 1650 seconds (27.5 min)
stdTriage := stats.GetStdDuration("Triage") // 300 seconds
rateTriage := stats.EstimateRate("Triage") // 0.000606 /sec
ExtractTiming collects, for each activity, its durations and occurrence count; the methods above turn those into a mean, a sample standard deviation and a rate. It also records inter-arrival times (how frequently new cases appear) and total case durations (end-to-end cycle time). The log has one timestamp per event and no start/complete lifecycle, so an activity’s “duration” is the time from its event to the next event in the same case, which includes any wait before the next step. The last event of a case has no successor and contributes no duration. Triage’s four observations are 30, 30, 20 and 30 minutes, which give the values in the comments (worked by hand from the CSV).
From Durations to Rates
The key conversion: . If triage takes an average of 10 minutes, the triage rate is per second. This assumes exponentially distributed service times — the same memoryless property that mass-action kinetics uses.
For the hospital log (worked by hand from the CSV; the first five rates match the learned rates printed in go-pflow’s mining/README.md):
| Activity | Observations | Mean Duration | Estimated Rate |
|---|---|---|---|
| Registration | 4 | 12.5 min | 0.00133 /sec |
| Triage | 4 | 27.5 min | 0.000606 /sec |
| Doctor_Consultation | 4 | 31.2 min | 0.000533 /sec |
| Lab_Test | 2 | 97.5 min | 0.000171 /sec |
| Results_Review | 3 | 50.0 min | 0.000333 /sec |
| Discharge | 0 | — | 0.1 /sec (default) |
Discharge is the last event of every case, so it has no duration at all, and EstimateRate falls back to a default of 0.1 per second: a ten-second mean that comes from the code, not the data. The five activities seen once each (X-Ray, Surgery, Recovery, Prescription, Specialist_Referral) are left out of the table.
Lab_Test has the lowest rate among the activities observed more than once, which makes it the first candidate for the bottleneck. With two observations it is a candidate, not a finding, and Surgery’s single 180-minute observation is longer still.
Learning Rates for Simulation
The learned rates plug directly into the ODE solver (from examples/mining_demo/main.go):
rates := mining.LearnRatesFromLog(log, net)
initialState := net.SetState(nil)
prob := solver.NewProblem(net, initialState, [2]float64{0, 10000}, rates)
sol := solver.Solve(prob, solver.Tsit5(), solver.DefaultOptions())
The simulation now uses rates derived from the log rather than guesses. What it does with them follows from go-pflow’s rate law (Appendix A: Solver Parameter Reference): a transition’s flux is its rate times the product of its input places’ tokens, each to the first power. Every transition in a common-path net has a single input place, so the net is a cascade of first-order decays. The token’s mass lingers longest in the place whose outgoing rate is smallest, and the mass in end at time is the probability that a case with these exponentially distributed step times has finished by . Its mean completion time is therefore the sum of the step means. For the committed Prescription-path net that is 12.5 + 27.5 + 31.2 + 15 minutes plus Discharge’s ten seconds, about 86 minutes; for P001’s path through Lab_Test and Results_Review it is about 219 minutes. Both figures are derived from the rate law, not re-run.
This closes the loop: event log → discovered model → learned rates → simulation → prediction. The same Petri net formalism works for hand-crafted models (Parts I and II) and data-driven models (this chapter).
Predictive Monitoring
With a learned model, we can predict the future. A patient who has completed registration and triage but not yet seen a doctor — what’s their expected remaining time? Will they violate the 4-hour SLA?
State Estimation
The first step is mapping the patient’s event history to a Petri net marking. Each observed activity corresponds to firing a transition:
currentState := monitoring.EstimateCurrentState(activeCase, net)
The function replays the event history through the net: start with a token in the start place, fire each observed transition in sequence, and the resulting marking represents the patient’s current position in the process. If the patient has completed Registration and Triage, the token sits in the place between Triage and Doctor_Consultation.
monitoring/predictor.go assumes the net has places named start and end, which the common-path and Alpha miners both produce. The replay is best-effort: an activity the net does not contain is skipped, and a transition that is not enabled is fired anyway, with its input places clamped at zero. A case that has left the model’s path therefore shows up as a marking that makes no sense, not as an error.
Simulation-Based Prediction
From the current state, the ODE solver simulates forward to predict completion:
predictor := monitoring.NewPredictor(net, rates)
pred := predictor.PredictFromState(currentState, currentTime)
remainingTime := pred.PredictedEndTime - pred.CurrentTime
confidence := pred.Confidence
The predictor simulates up to 24 hours ahead and reports the first time the token mass in end reaches 0.5 as the predicted completion time. On a chain like the one above, that is the median of the remaining-time distribution, not its mean. The confidence is the mass in end at the 24-hour horizon: how much of the case the model expects to have finished by then, not a calibrated probability that the prediction is right.
SLA Violation Detection
Suppose a patient who arrived at 8:00 AM is still in the system at 9:30, 90 minutes in, and the model predicts 180 more minutes because the next step is the lab. The predicted total of 270 minutes exceeds a 4-hour (240-minute) SLA, so the alert fires two and a half hours before the breach would happen. That leaves time to expedite the lab order, assign additional staff, or tell the patient about the wait.
Those figures are illustrative arithmetic, not model output. examples/monitoring_demo/main.go runs the real loop: it learns from three synthetic historical cases, streams three patients against a 4-hour SLA, and raises alerts through monitoring.Monitor. Its README shows sample output, which was not re-run for this chapter.
Next Activity Prediction
Beyond completion time, the model predicts which activity happens next and how likely each option is:
predictions := monitoring.PredictNextActivity(activeCase, predictor)
// []NextActivity{Activity, Probability, ExpectedTime}, one per enabled transition
Each enabled transition gets an effective rate, its rate constant times the product of its input places’ tokens, and its probability of firing first is its share of the total: the race between exponential clocks. Two consequences follow from the code. On a common-path net only one transition is ever enabled, so the prediction is a single activity with probability 1; branch probabilities need a model with choices, such as the Alpha miner’s. And because the rate constants are learned from durations, at a choice the faster activity is predicted to be the likelier one. How often each branch was taken in the log does not enter the calculation.
The Hospital ER Case Study
Putting it all together, condensed from examples/mining_demo/main.go, with the values worked by hand from hospital.csv in the comments:
// 1. Parse event log
log, _ := eventlog.ParseCSV("hospital.csv", config)
// 4 cases, 26 events, 11 activities, 4 variants
// 2. Extract timing
stats := mining.ExtractTiming(log)
// Registration 12.5 min, Triage 27.5, Doctor_Consultation 31.2,
// Lab_Test 97.5, Results_Review 50.0; Discharge has no duration
// 3. Discover model
discovery, _ := mining.Discover(log, "common-path")
net := discovery.Net
// four-way tie between variants; the chosen one covers 25% of cases
// 4. Learn rates
rates := mining.LearnRatesFromLog(log, net)
// 5. Simulate
prob := solver.NewProblem(net, net.SetState(nil), [2]float64{0, 10000}, rates)
sol := solver.Solve(prob, solver.Tsit5(), solver.DefaultOptions())
// 6. Use for prediction
predictor := monitoring.NewPredictor(net, rates)
The four cases in the log took 210, 510, 60 and 240 minutes, a mean of 255. A single common-path net cannot reproduce that spread: it models one path, and its mean completion time is about 86 or 219 minutes, depending on which variant won the tie (derived above). The demo also integrates for only 10,000 seconds, about 167 minutes, which stops before the Lab_Test path’s mean completion time. With four cases, the case study shows the pipeline running end to end; it does not validate the numbers.
What-If Analysis
The learned model enables scenario planning. “What if we add another lab technician?” — double the Lab_Test rate and re-simulate. “What if we add a fast-track for simple cases?” — add a bypass transition from Doctor to Discharge with a guard on case complexity.
Each scenario is a parameter change or a structural change to the same Petri net. A rate change needs no new data. A structural change does: the bypass transition needs a rate, and the log cannot supply one until the bypass exists.
Conformance Checking
Discovery produces a model. Conformance checking asks: how well does the model match reality?
Fitness measures how well the log replays on the model. If the model says A must precede B, but a trace shows B before A, that trace doesn’t fit. CheckConformance uses token-based replay: it fires each trace’s activities in order and counts tokens produced (), consumed (), missing (: needed but absent, plus one for each activity the model lacks) and remaining (: left outside a final place at the end). It reports
A trace fits when it has no missing and no remaining tokens, and FittingTraces counts those separately. A fitness of 1.0 means every trace replays cleanly.
Precision measures how much of the model’s allowed behavior actually occurs. CheckPrecision counts escaping edges, transitions enabled in a replayed state but never taken there, and reports 1 − escaping/enabled. A model that allows everything fits every trace but has low precision, because it is too general to be useful. A model that captures only the observed paths has high precision.
Good models balance both: high fitness (captures real behavior) with high precision (doesn’t over-generalize). Adding paths to a model usually raises the first and lowers the second.
conf := mining.CheckConformance(log, net)
// committed Prescription-path net vs hospital.csv:
// Fitness ≈ 0.58, FittingTraces 1 of 4
Those values are worked by hand from the replay rules in conformance.go, not re-run. P003, the variant the net was built from, replays cleanly. The other three are charged one missing token for each activity the net does not contain, find Discharge’s input place empty when they rejoin the path, and leave a token stranded mid-net. Summed over the log, , , and . The non-fitting traces are the variants common-path discarded. A miner that keeps them, Alpha or heuristic, should fit better at some cost in precision; that comparison has not been run on this log.
Generator and Recognizer: Closing the Loop
Process mining infers structure from observations. The complementary move is executing a declared structure to produce observations. Both end at the same artifact — a Petri net — but they travel in opposite directions.
Take a streaming pipeline of the kind Apache Beam popularised: a chain of
windowed aggregations over a keyed event stream. The tokenmodel/dataflow
package lowers such a pipeline to a bundle of Petri net subnets — one per
key, one per (key, window) accumulator, one for the watermark. Feed the
pipeline an event stream and every order becomes a token in the net. The
pipeline is the generator.
Mining is the recognizer. Give it the execution trace and ask it to recover the structure that produced it:
log := pipeline.ToEventLog()
res, _ := mining.DiscoverPipeline(log, mining.PipelineDiscoveryOptions{
IdealEventsPerWindow: 7,
})
// Truth: kind=fixed, size=60, 6 keys. Recovered: kind=fixed, size=50, 6 keys.
loop_closure_test.go
runs the coffee shop’s sample order stream (58 orders over eight hours)
through a pipeline with fixed 60-minute windows, exports the input
history, and hands it to
DiscoverPipeline.
The test asserts that the recovered window kind and key count match the
spec, and that the window size is within a factor of two of 60. The size
is where the heuristic shows. It aims for about IdealEventsPerWindow
events per window, which gives a raw size of 470 × 7 / 58 ≈ 57, then snaps
to the nearest entry in a list of round sizes (…, 20, 50, 100, …) that does
not include 60. The recovered size is therefore 50, derived from the code
rather than re-run, and the same value go-pflow’s mining README prints. The
stream’s timing cannot reveal that 60 was chosen because it is an hour. Nor
is the trigger recovered: DiscoverPipeline returns after-watermark, its
default, unless the caller supplies an EarlyFireRate.
The two directions differ in kind. The generator is total and deterministic: a spec fully determines the net. The recognizer is partial and statistical: a log under-determines the net, which is why there are algorithms like Alpha and the heuristic miner to choose between candidates. Both end at a Petri net, and whether it was declared or induced, it is analysed with the same incidence matrix and simulated with the same solver.
From Data to Model to Prediction
Parts I and II showed how to build models from domain knowledge, encoding rules as structure. This chapter shows how to extract models from data, discovering rules from behavior.
The pipeline:
- Collect event logs from existing systems
- Discover process structure using mining algorithms
- Learn transition rates from timestamps
- Validate via conformance checking and simulation
- Predict using ODE simulation with learned parameters
- Intervene based on early warnings
The same Petri net formalism handles both directions. A coffee shop model built by hand (Chapter 5: Resource Modeling — The Coffee Shop) and a hospital process discovered from logs produce the same kind of object: places, transitions, arcs, rates. The solver and the incidence-matrix analysis do not know which one was hand-crafted and which was mined.
Any system that writes timestamped events per case can be fed to this pipeline. How far its predictions can be trusted depends on the log: the hospital log here has four cases, enough to show every step and too few to support any of the numbers.
Zero-Knowledge Proofs
Learning objective: Prove a state transition is valid without revealing the state.
Every Petri net model in this book has been transparent — all token counts visible to all participants. The coffee shop owner sees inventory levels. Both tic-tac-toe players see the board. The hospital monitor sees patient states. But some applications require privacy. A voter should prove they cast a valid ballot without revealing their choice. A financial institution should verify a transfer is valid without exposing account balances. A player should prove their move is legal without revealing their strategy.
Zero-knowledge proofs make this possible, and a Petri net is a natural input to them: it is already a formal specification of valid state transitions, and a ZK circuit turns that specification into a cryptographic proof system. The prover demonstrates they followed the rules; the verifier confirms it without seeing the state.
The Statement Being Proven
Every ZK proof in this system proves one statement:
“I know a valid marking that, when transition T fires, produces the claimed next state.”
More precisely:
- The pre-state root (a hash) matches a specific private marking
- The post-state root matches a specific private marking
- The chosen transition was enabled — all input places had sufficient tokens
- The marking change is correct — post = pre + delta, where delta comes from the net topology
The verifier sees only the two state roots and the transition ID. The token counts are not inputs to verification; whether they stay hidden depends on what else is public, which What ZK Doesn’t Hide takes up.
Public vs. Private
| What | Who Sees It | |
|---|---|---|
| Public | Pre-state root (hash) | Everyone |
| Public | Post-state root (hash) | Everyone |
| Public | Transition ID | Everyone |
| Private | Pre-marking (all token counts) | Prover only |
| Private | Post-marking (all token counts) | Prover only |
The state roots are commitments. They bind the prover to a specific marking without revealing it.
State Commitment via MiMC Hashing
The hash function matters. Inside a ZK circuit, every operation becomes arithmetic constraints on a finite field. SHA-256 is built from bitwise operations, each of which must be decomposed into bits, and is commonly quoted at roughly 25,000 constraints per compression (a literature figure, not measured here). MiMC (Minimal Multiplicative Complexity) is designed for arithmetic circuits: it operates over the same finite field the circuit uses. gnark’s BN254 MiMC absorbs one field element at a time, running 110 rounds of on each, and each round costs three multiplications (encryptPow5 in gnark v0.14.0, the version the circuit code below pins; 110 rounds is mimcNbRounds in gnark-crypto’s bn254/fr/mimc). That is 330 constraints per element, so hashing a marking of places costs (derived from the code, not measured).
The hash used throughout this chapter is from the ZK tic-tac-toe circuit code, zk-tictactoe/petri_circuits.go (not public):
func petriMimcHash(api frontend.API, values []frontend.Variable) frontend.Variable {
h, _ := mimc.NewMiMC(api)
for _, v := range values {
h.Write(v)
}
return h.Sum()
}
The state root is:
Inverting MiMC is believed to be infeasible, so the root binds the prover to one marking. It hides that marking only conditionally: the root carries no random salt, so anyone who can list the candidate markings can hash each one and compare. A net with a small reachable set, like tic-tac-toe’s, offers no protection by the hash alone.
The Circuit in Five Steps
The gnark circuit for a Petri net transition proof has five steps. Each adds constraints that the prover must satisfy. The excerpts below are from PetriTransitionCircuit in the same file; go-pflow’s petrigen emits the same Define from a template (zkcompile/petrigen/templates.go), adding a guard block when the model has guards.
Step 1: Hash the Pre-Marking
Compute the MiMC hash of every place’s token count and assert it equals the public pre-state root:
preRoot := petriMimcHash(api, c.PreMarking[:])
api.AssertIsEqual(preRoot, c.PreStateRoot)
This binds the private marking to the public commitment. The prover can’t lie about what state they started from.
Step 2: Hash the Post-Marking
Same check for the post-state:
postRoot := petriMimcHash(api, c.PostMarking[:])
api.AssertIsEqual(postRoot, c.PostStateRoot)
Now both states are committed.
Step 3: Compute the Delta from Topology
From the transition ID, look up the Petri net topology to build a delta vector. The topology is baked into the circuit as constants — the incidence matrix encoded as input/output lists:
for t := 0; t < NumTransitions; t++ {
isThis := api.IsZero(api.Sub(c.Transition, t))
for _, p := range Topology[t].Inputs {
deltas[p] = api.Sub(deltas[p], isThis)
}
for _, p := range Topology[t].Outputs {
deltas[p] = api.Add(deltas[p], isThis)
}
}
The isThis variable is 1 for the selected transition and 0 for all others. This multiplexes over all transitions without branching — arithmetic circuits can’t branch, so we compute all possibilities and select. Only the chosen transition’s delta contributes to the result.
Step 4: Assert Marking Change
For every place, check that the post-marking equals the pre-marking plus the delta:
for p := 0; p < NumPlaces; p++ {
expected := api.Add(c.PreMarking[p], deltas[p])
api.AssertIsEqual(c.PostMarking[p], expected)
}
This ensures the marking changed exactly as the topology dictates, with no token appearing or vanishing anywhere else. Each listed place moves by exactly one token, so every arc has weight 1 (the ArcDef comment in petri_state.go says as much for tic-tac-toe). The ERC-20 circuit later in the chapter replaces the 1 with an amount.
Step 5: Assert Enabledness
Every input place of the selected transition must hold at least one token (excerpt, comments trimmed):
for p := 0; p < NumPlaces; p++ {
isInput := frontend.Variable(0)
for t := 0; t < NumTransitions; t++ {
isThis := api.IsZero(api.Sub(c.Transition, t))
for _, inp := range Topology[t].Inputs {
if inp == p {
isInput = api.Add(isInput, isThis)
}
}
}
diff := api.Sub(c.PreMarking[p], isInput)
api.ToBinary(diff, 8) // 8 bits is enough for small token counts
}
isInput is 1 when place p is an input of the selected transition and 0 otherwise. ToBinary decomposes pre[p] - isInput into 8 bits. If an input place were empty, the difference would wrap to a huge field element, the decomposition would fail, and no proof could be generated. This is the standard gnark pattern for range checks: decompose into bits to prove non-negativity. Because the check runs on every place, it also bounds every pre-marking count below 256, matching the uint8 marking type in zk-tictactoe/petri_state.go.
Topology as Circuit Constants
The central property of this approach is that the Petri net topology is baked into the circuit as constants. For the tic-tac-toe net below, an excerpt of petri_state.go:
var Topology = [NumTransitions]ArcDef{
// X plays: consume cell + x_turn, produce x_piece + o_turn
TXPlay00: {[]int{P00, PlaceXTurn}, []int{X00, PlaceOTurn}},
// ...
// X wins: consume 3 x_pieces + game_active, produce win_x + return pieces
TXWinRow0: {[]int{X00, X01, X02, PlaceGameActive}, []int{PlaceWinX, X00, X01, X02}},
// ...
}
This means:
- The circuit contains no application-specific logic. The same
Define()method works for any net whose arcs have weight 1 and which has no guards. - Topology changes require recompilation. Adding a place or transition means a new trusted setup.
- The circuit is auditable. Anyone can inspect the topology to check that it matches the claimed rules.
Groth16 Proofs
The proving system is Groth16, implemented by gnark. It needs a trusted setup for each circuit, and in return its proofs are three curve points (two in G1, one in G2) and its verification time does not grow with the size of the circuit. For BN254, gnark can also write the verifier as a Solidity contract (VerifyingKey.ExportSolidity in backend/groth16/bn254).
| Property | Groth16 | PLONK | STARKs |
|---|---|---|---|
| Proof size | ~128 B | ~400 B | ~50 KB |
| Verification | ~2ms | ~5ms | ~50ms |
| Trusted setup | Per-circuit | Universal | None |
| Quantum-safe | No | No | Yes |
The figures are typical orders of magnitude for each system, not measurements of the circuits in this chapter. The Groth16 proof size follows from its shape: on BN254 a compressed G1 point is 32 bytes and a G2 point 64, so .
For applications with small, fixed circuits and many proofs, such as games or token transfers, those two properties usually outweigh the cost of a per-circuit setup.
ZK Tic-Tac-Toe: A Complete Example
The ZK build of tic-tac-toe uses a variant of the Chapter 6 model with 33 places and 35 transitions (Chapter 6’s model has 30 and 34; the ZK variant uses separate x_turn/o_turn places and a game_active flag). It uses two circuits, both encoding the full Petri net:
PetriTransitionCircuit proves a move is legal. It’s the general circuit described above — works for any transition in the net. Used for every move.
PetriWinCircuit proves a player has won. The win condition is already in the Petri net topology (win-detection transitions from Chapter 6 fire when three cells align). The circuit checks that the win_x or win_o place has a token (comments trimmed):
func (c *PetriWinCircuit) Define(api frontend.API) error {
root := petriMimcHash(api, c.Marking[:])
api.AssertIsEqual(root, c.StateRoot)
winTokens := frontend.Variable(0)
for p := 0; p < NumPlaces; p++ {
isWinnerPlace := api.IsZero(api.Sub(c.Winner, p))
winTokens = api.Add(winTokens, api.Mul(c.Marking[p], isWinnerPlace))
}
api.ToBinary(api.Sub(winTokens, 1), 8)
isXWin := api.IsZero(api.Sub(c.Winner, PlaceWinX))
isOWin := api.IsZero(api.Sub(c.Winner, PlaceWinO))
validWinner := api.Add(isXWin, isOWin)
api.AssertIsEqual(validWinner, 1)
return nil
}
The last four lines restrict Winner to win_x (place 29) or win_o (place 30). Without them a prover could name any marked place, an occupied cell for instance, as the winner.
Because the game logic lives in the net topology, the transition circuit knows nothing about tic-tac-toe, and the win circuit knows only the indices of the two win places. Change the topology constants (and those indices) and you get ZK proofs for a different game.
The tests in zk-tictactoe/petri_circuits_test.go check both circuits against gnark’s test prover. TestPetriTransitionCircuit_FullGameXWins plays X to a left-column win (cells 0, 1, 3, 4, 6, alternating X and O) and asserts that a proof succeeds for every move and for the x_win_col0 firing; TestPetriWinCircuit_XWins and TestPetriWinCircuit_OWins assert that the win proof succeeds for each player. Two tests assert failure: TestPetriTransitionCircuit_WrongTurn builds a witness that fires an X move on O’s turn, and TestPetriWinCircuit_NoWinnerFails claims a win for X after two moves. Neither circuit has been re-run for this chapter.
Constraint Counts
No test logs the constraint count of this circuit (the compile tests call frontend.Compile but do not print GetNbConstraints), so the 33-place, 35-transition net has no measured total. What can be read off the code:
| Component | Constraints | Source |
|---|---|---|
| MiMC hash (pre) | 33 elements at 330 each (derived above) | |
| MiMC hash (post) | same | |
| Delta accumulation | none of its own | additions are linear and fold into the constraints that use them |
| Transition selectors | 35 IsZero calls in step 3, a further in step 5 | per-call cost not measured |
| Marking assertion | 33 | one AssertIsEqual per place |
| Enabledness | 33 eight-bit decompositions | one ToBinary(·, 8) per place |
The two hashes dominate, so the total exceeds 21,780. Proving and verification times have not been benchmarked for this chapter. The circuit compiles once, and proofs are generated per move.
The Game Protocol
A ZK tic-tac-toe game runs roughly as follows (a sketch of the protocol, not code):
Initial: state_hash = hash(empty_board)
Round n:
1. Current player fires transition locally (computes new marking)
2. Computes new_state_hash = MiMC(new_marking)
3. Generates Groth16 proof: (old_hash, new_hash, transition_id, proof)
4. Opponent verifies proof
5. If valid: state_hash = new_hash, continue
6. If invalid: cheating detected, game forfeited
The opponent knows which transition fired, because the move is public. Win detection is a separate proof demonstrating that a win place has a token. What the opponent can and cannot learn about the board is taken up in What ZK Doesn’t Hide below.
Beyond Games: Token Transfers
The same circuit structure handles token transfers. An ERC-20 transfer is a Petri net transition:
balances[from]is an input place (tokens consumed)balances[to]is an output place (tokens produced)- The guard
balances[from] >= amountis the enabledness check
The companion zk-erc20/petri_circuits.go applies the circuit to a two-account ERC-20 net with 5 places (totalSupply, two balances, two allowances) and 10 transitions (transfer, approve, transferFrom, mint and burn, one of each per account; zk-erc20/petri_state.go). Two things change. Amount becomes a public input and weights every arc, so a transfer of 100 debits 100 and credits 100:
for _, p := range arc.Inputs {
delta := api.Mul(isThis, c.Amount)
expectedPost[p] = api.Sub(expectedPost[p], delta)
}
for _, p := range arc.Outputs {
delta := api.Mul(isThis, c.Amount)
expectedPost[p] = api.Add(expectedPost[p], delta)
}
And the enabledness check subtracts the amount consumed rather than 1, decomposed into 64 bits instead of 8:
diff := api.Sub(c.PreMarking[p], consumed)
api.ToBinary(diff, 64) // 64 bits for token amounts up to ~1.8 * 10^19
Approve transitions are the exception: they set an allowance to Amount rather than adding to it, and skip the enabledness check. The same file adds an ERC20InvariantCircuit that proves balance_0 + balance_1 = totalSupply against a state root.
A note on what that guard is. In a model that states it explicitly, as the DSL of Chapter 4 does, it is a read of balances[from] — a contextual arc, not a column of the incidence matrix — and contextual arcs are exactly the thing that stops a net from generating the free symmetric monoidal category of Appendix E. Inside the circuit that distinction disappears: a proof certifies one firing, one firing has only interleaving semantics, and under interleaving semantics a read arc and a consume-then-restore self-loop are the same thing. So encoding the guard as a range check on a witnessed balance, as zk-erc20 does, is exact rather than an approximation. The boundary the circuit cannot erase is the other one — a transition with more inputs than outputs still costs a non-uniform constraint block, because that is a fact about and the circuit is compiled from .
A flat hash over every balance does not scale to many accounts, because every proof would hash the whole marking. Chapter 14 replaces it with a Merkle tree, so that a proof touches only the accounts involved and only the root is published on-chain.
| Application | Places | Transition | Enabledness |
|---|---|---|---|
| Tic-Tac-Toe | 33 board+game states | Player move | Cell empty, correct turn |
| ERC-20 Transfer | Account balances | Transfer | Sufficient balance |
| Workflow | Process stages | State change | Required approvals |
| Voting | Ballot states | Cast vote | Eligible, hasn’t voted |
Only the first two rows are built on this circuit in code. The workflow row is the same mapping on paper. bitwrap-io’s vote circuit (prover/vote_gen.go) is a different construction: it proves membership in a Merkle registry of voters, binds a nullifier so that nobody votes twice, and commits to the choice, rather than proving a marking change.
What ZK Doesn’t Hide
A common misconception is that ZK hides the transition ID. It doesn’t: the verifier sees which transition fired. What can be hidden is the state, the full marking of every place, but only to the extent the verifier cannot reconstruct it from public data.
In tic-tac-toe it can. The initial marking is a constant of the model (InitialMarking in petri_state.go), and every move’s transition ID is public, so the opponent can replay the moves and recover all 33 places. This is the event-sourcing fold of Chapter 20 applied to public events. The tic-tac-toe proofs show that every move was legal; they hide nothing about the board. In the ERC-20 circuit, Amount is public as well, so balances stay hidden only if the verifier does not know the starting balances. Even then, as noted under MiMC above, an unsalted root gives away any marking drawn from a set small enough to enumerate.
An application that must hide the transition as well needs a proof that some valid transition fired without saying which. For the circuit in this chapter that step is small, because it already multiplexes over every transition: make Transition a private input instead of a public one. One constraint would have to be added, that exactly one selector isThis equals 1, since an out-of-range ID selects no transition and would let a prover pass off an unchanged marking as a move. This is read off the code; no such circuit has been built.
The Proof Pipeline
A complete proof cycle for any Petri net application:
- Client fires transition locally (computes new marking)
- Client computes MiMC state roots for pre and post markings
- Prover receives witness (pre/post markings + transition ID) and generates Groth16 proof
- Proof returned as 128 bytes (compressed) with public inputs
- Anyone can verify the proof, in time independent of the circuit’s size
- On-chain verification through the exported Solidity verifier (Chapter 14)
The circuit doesn’t encode tic-tac-toe, or token transfers, or workflow rules. It encodes Petri net semantics: hash the marking, compute the delta from topology, assert the change, check enabledness. The application logic is in the net, and the proof certifies that one firing followed it.
Topology-Driven Verification
Learning objective: Generate ZK proof circuits automatically from Petri net topology, and verify execution on-chain.
Chapter 12 built ZK circuits by hand — defining the PetriTransitionCircuit step by step, wiring up MiMC hashes and delta computations manually. That was instructive, but it is not something to repeat for every new model. This chapter closes the loop: given a Petri net JSON model, go-pflow’s petrigen package generates the gnark circuits, the witness generator and their tests, and the compiled circuit can then be exported as a Solidity verifier. The topology becomes constant arrays in the circuit, so changing the model and regenerating gives a new proof system.
Along the way, graph connectivity turns out to carry strategic value as well as circuit structure. Once the modeler says which transitions are moves and which are goals, rate constants for the ODE can be read off the bipartite graph, with no training data and no manual tuning, and counting win-line connections reproduces the classic tic-tac-toe heuristic (center > corner > edge). The derived rates are the constants of the ZK ODE circuit built for this game.
The Compilation Pipeline
The full path from model to verifiable computation:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ JSON Model │────▶│ petrigen │────▶│ gnark Circuit │
│ (Petri net) │ │ (generator) │ │ (Go code) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ Groth16/PLONK │
│ Prover │
└─────────────────┘
│
▼
┌─────────────────┐
│ Solidity │
│ Verifier │
└─────────────────┘
The petrigen package in go-pflow reads a Petri net model and generates four files:
| File | Purpose |
|---|---|
petri_state.go | Place/transition constants, topology arrays, marking operations |
petri_circuits.go | PetriTransitionCircuit and PetriReadCircuit definitions |
petri_game.go | Game state tracking and witness generation |
petri_circuits_test.go | Compilation and proof verification tests |
The topology encoding — which places each transition consumes from and produces to — becomes compile-time constant arrays in the generated code, and the selector trick from Chapter 12 (evaluating all transitions and using IsZero to select one) is wired up automatically. The Solidity verifier is a separate step: SolidityExporter in zkcompile/solidity.go compiles a circuit, runs a Groth16 setup on BN254 and calls gnark’s ExportSolidity.
Two limits of the generator follow from that encoding (context.go). Each arc moves exactly one token: the arc’s weight is not read, so petrigen is only faithful on nets whose arcs all have weight 1. And a read or inhibitor arc moves no tokens, which two lists of decremented and incremented places cannot express, so petrigen refuses such a model with an error rather than prove a net that consumes from the tested place. Contextual arcs sit outside the incidence matrix; Appendix E gives the boundary they mark.
A Complete Example: Order Workflow
Consider a simple order processing workflow:
[pending] --approve--> [approved] --ship--> [shipped]
|
+----cancel----> [cancelled]
Define it as JSON:
{
"name": "order-workflow",
"places": [
{"id": "pending", "initial": 1},
{"id": "approved"},
{"id": "shipped"},
{"id": "cancelled"}
],
"transitions": [
{"id": "approve"},
{"id": "ship"},
{"id": "cancel"}
],
"arcs": [
{"from": "pending", "to": "approve"},
{"from": "approve", "to": "approved"},
{"from": "approved", "to": "ship"},
{"from": "ship", "to": "shipped"},
{"from": "pending", "to": "cancel"},
{"from": "cancel", "to": "cancelled"}
]
}
Generate the circuits:
gen, _ := petrigen.New(petrigen.Options{
PackageName: "main",
OutputDir: ".",
IncludeTests: true,
})
files, _ := gen.Generate(&model)
for _, f := range files {
fmt.Println("Generated:", f.Name)
}
Output:
Generated: petri_state.go
Generated: petri_circuits.go
Generated: petri_game.go
Generated: petri_circuits_test.go
The generated petri_state.go encodes the topology as constants (an excerpt, laid out from the template in templates.go; the file also holds the place and transition names, the initial marking, IsEnabled, Fire and the MiMC marking root):
const NumPlaces = 4
const NumTransitions = 3
const (
Pending = 0
Approved = 1
Shipped = 2
Cancelled = 3
)
const (
Approve = 0
Ship = 1
Cancel = 2
)
var Topology = [NumTransitions]ArcDef{
Approve: {Inputs: []int{0}, Outputs: []int{1}},
Ship: {Inputs: []int{1}, Outputs: []int{2}},
Cancel: {Inputs: []int{0}, Outputs: []int{3}},
}
This is the same pattern from Chapter 12, but generated automatically. The circuit’s Define() method iterates over Topology, computing deltas and enforcing the firing rule, and the developer does not edit circuit code.
go-pflow’s integration_test.go runs this pipeline end to end on the same workflow with a deliver step added (5 places, 4 transitions): it generates the four files, builds them, and runs the generated tests, which compile both circuits and check with gnark’s test harness that a proof succeeds for the first enabled transition. A second test does the same for a model with guards.
Proving a Transition
With the generated code, proving a valid state transition takes five steps. The listing below is a sketch against the generated API and gnark’s Groth16 backend, with errors ignored for brevity; the generated test performs the equivalent check through gnark’s test harness:
// 1. Compile the circuit
ccs, _ := frontend.Compile(ecc.BN254.ScalarField(),
r1cs.NewBuilder, &PetriTransitionCircuit{})
fmt.Printf("Circuit has %d constraints\n", ccs.GetNbConstraints())
// 2. Trusted setup (one-time per circuit)
pk, vk, _ := groth16.Setup(ccs)
// 3. Fire a transition locally
game := NewPetriGame()
witness, _ := game.FireTransition(Approve)
// 4. Generate proof
assignment := witness.ToPetriTransitionAssignment()
w, _ := frontend.NewWitness(assignment, ecc.BN254.ScalarField())
proof, _ := groth16.Prove(ccs, pk, w)
// 5. Verify
publicWitness, _ := w.Public()
err := groth16.Verify(proof, vk, publicWitness)
// err == nil: proof valid
The verifier sees three public inputs — PreStateRoot, PostStateRoot, and Transition — and confirms the state changed correctly. The actual marking (which places have tokens) stays private.
We do not quote a constraint count or timings for this circuit: none of petrigen’s tests prints them, and the pipeline was not re-run for this chapter. Step 1 prints the count, which is dominated by the two MiMC hashes of the marking and so grows with the number of places. What does not depend on the run is the proof’s size: a Groth16 proof over BN254 is two G1 points and one G2 point, 128 bytes compressed, whatever the circuit, and verifying it costs a fixed number of pairings plus work proportional to the public inputs (three here).
Invalid Transitions Are Unprovable
What happens if someone tries to ship an order that hasn’t been approved?
game := NewPetriGame() // Initial: pending=1
_, err := game.FireTransition(Ship)
// err: "transition ship failed: transition ship is not enabled"
The FireTransition function checks enabledness before generating a witness. But even if someone bypasses this check and constructs a malicious witness, the circuit’s bit decomposition will fail — PreMarking[Approved] is 0, and 0 - 1 wraps to a huge field element that can’t be decomposed into 8 bits, so no proof can be generated. Soundness comes from the circuit, not from the application code. Note what is tested: the generated TestPetriTransitionCircuit_InvalidTransition exercises only the application-level check, and the circuit-level claim follows from the enabledness constraint (api.ToBinary(diff, 8) in the template) rather than from a test that feeds the circuit a bad witness.
From Graph Connectivity to Rate Constants
Chapter 3 introduced mass-action kinetics with hand-tuned rate constants, and Chapter 6 ran the tic-tac-toe heatmaps with uniform rates. But where do rate constants come from?
For chemical reactions, rates encode physical properties — activation energies, temperature dependence, catalytic effects. You measure them in a lab. For games and workflows, there’s no lab. The rate constants encode strategic value, and once the modeler has said which transitions are moves and which are goals, that value can be read off the graph.
The Algorithm
The rate auto-derivation algorithm operates on the bipartite directed graph of the Petri net:
- Identify candidate transitions (the moves a player can make) and target transitions (the goals — win conditions, completion states)
- For each candidate, find its unique output places — places it produces that no other candidate produces
- Count how many target transitions take those unique places as inputs
- That count is the rate constant
The implementation is deriveRatesFromTopology in the ZK ODE circuit generator, zk-ode/codegen/context.go in the petri-pilot repository (not public). Candidates and targets are given as globs over transition names (x_play_*, x_win_*), so the move/goal split is the modeler’s input, not something the graph decides. Two details of the code: a count of 0 or 1 leaves the default rate of 1, and a rate other than the default 1 written in the model is kept rather than derived.
Tic-Tac-Toe: Strategy from Topology
The ZK variant of the TTT Petri net from Chapter 6 (the one Chapter 12 compiles; 33 places and 35 transitions, against Chapter 6’s 30 and 34) is the model used here, services/tic-tac-toe.json. petri-pilot and sim.pflow.xyz’s source (neither public) each hold a copy with the same places, transitions and arcs, and the test cited below loads petri-pilot’s. Each play transition (like x_play_11) produces a piece at a position (like x11). Each win transition (like x_win_diag) requires three specific pieces as inputs.
Apply the algorithm to the center position:
x_play_11 outputs → {x11, o_turn, move_tokens}
Unique outputs (only x_play_11 produces x11):
x11
Win transitions with x11 as input:
x_win_row1 (middle row) ✓
x_win_col1 (center column) ✓
x_win_diag (main diagonal) ✓
x_win_anti (anti-diagonal) ✓
Rate for x_play_11 = 4 (center: 4 win lines)
Compare with a corner:
x_play_00 outputs → {x00, o_turn, move_tokens}
Unique outputs: x00
Win transitions with x00 as input:
x_win_row0 ✓
x_win_col0 ✓
x_win_diag ✓
Rate for x_play_00 = 3 (corner: 3 win lines)
And an edge:
x_play_01 outputs → {x01, o_turn, move_tokens}
Unique outputs: x01
Win transitions with x01 as input:
x_win_row0 ✓
x_win_col1 ✓
Rate for x_play_01 = 2 (edge: 2 win lines)
Counting connections ranks center above corner above edge, the classic opening heuristic, without game-tree search or training data. The generator’s cross-validation test, TestCrossValidate_TTTTopology in petri-pilot’s zk-ode/codegen/crossvalidate_test.go, loads the JSON model with play transitions of both players as candidates and win transitions of both as targets, and checks that every derived rate equals the hand-coded table in zk-ode/ttt_topology.go (center 4, corners 3, edges 2, all win transitions 1); it was not re-run for this chapter.
Filtering Shared Places
The algorithm has one non-obvious step: filtering shared output places. Without it, every candidate gets the same rate.
Every x_play_* transition produces three output places: the piece (e.g., x00), the opponent’s turn token (o_turn), and a move counter (move_tokens). The piece place is unique to that candidate — only x_play_00 produces x00. But o_turn and move_tokens are produced by all 9 x-play transitions identically.
The problem: o_turn is an input to every x_win_* transition (win detection happens on the opponent’s turn). If you include o_turn in the connectivity count, every candidate connects to all 8 win targets through it, giving every position rate=8. The heatmap collapses to a flat field — center, corner, and edge become indistinguishable.
The fix: exclude any output place produced by more than one candidate. A shared place connects every candidate that produces it to the same targets, and because each target is counted once, it saturates the count at the same value for all of them. Only places unique to a single candidate can distinguish one candidate from another.
Graph Theory First
The rate auto-derivation is pure graph theory. It operates on a bipartite directed graph — nodes are candidates and targets, edges pass through output places — and computes degree centrality of candidates with respect to targets through unique edges. Nothing about the algorithm requires Petri net firing semantics, token counts, or conservation laws.
The algorithm is structurally similar to a single message-passing step in a graph neural network:
- GNN:
node_embedding = aggregate(neighbor_features) - Petri net:
rate[candidate] = count(reachable_targets through unique_outputs)
The resemblance is one of shape: a GNN learns its aggregation function from data, while the rate derivation uses a fixed one, a count of target connections, so there is nothing to train.
What the Petri net formalism adds sits above the rate derivation. Firing semantics make transitions consume and produce tokens atomically, which gives state machines that graph connectivity alone cannot express. The mass-action rate law, (first power in every input place, as in go-pflow’s solver), couples the topology-derived constants to the current marking. P-invariants constrain the state space in ways centrality cannot. And the pre- and post-place lists of each transition define the gnark circuit’s constraints: their difference, the incidence matrix with unit weights, gives the marking change, and the pre-places alone give the enabledness check. The rate derivation says how much each candidate matters; the net’s semantics say what happens when one fires.
Poker Hand Ranking: Integer Reduction
The tic-tac-toe example derives strategic value from outgoing connectivity — more connections to win transitions means higher value. But the same mechanism works in reverse. In poker, we want to rank hand categories by rarity. Rare hands should have high value; common hands, low.
The construction encodes combinatorial frequency as structural outflow. The analysis net is build_hand_analysis_net in pflow-rs’s zk_holdem.rs example; each hand category gets:
- A source place
src_H(1 token) — constant inflow via catalytic arc - A value place
val_H(0 tokens) — accumulation target - A play transition
play_H— moves tokens from source to value, returning the source token - N drain transitions — consume tokens from
val_Hat a rate proportional to hand frequency
The drain counts are chosen by hand to rise with the 5-card combination counts. The source comment calls them log-scaled, but they are not a fixed log or power transform of the counts: one pair to two pair is a factor of 8.9 in combinations and 1.5 in drains.
| Hand | 5-Card Combos | Drains |
|---|---|---|
| Straight Flush | 40 | 1 |
| Four of a Kind | 624 | 2 |
| Full House | 3,744 | 4 |
| Flush | 5,108 | 5 |
| Straight | 10,200 | 8 |
| Three of a Kind | 54,912 | 12 |
| Two Pair | 123,552 | 16 |
| One Pair | 1,098,240 | 24 |
| High Card | 1,302,540 | 32 |
The full net has 18 places and 113 transitions (9 play + 104 drain).
At equilibrium under mass-action kinetics, inflow equals outflow for each value place:
Since src_H is catalytic (always 1) and rates are uniform:
Rare hands have fewer drains, accumulate more tokens, and produce higher equilibrium values. Common hands drain fast, accumulate little, and score low. Each accumulator is its own decoupled linear ODE, so this equilibrium is exact and needs no solver. The example runs Tsit5 to equilibrium anyway (hand_integer_reduction) and divides every value by the smallest, High Card’s , which gives . The values below are that closed form, derived rather than re-run:
Straight Flush: 32.0 (1 drain)
Four of a Kind: 16.0 (2 drains)
Full House: 8.0 (4 drains)
Flush: 6.4 (5 drains)
Straight: 4.0 (8 drains)
Three of a Kind: 2.7 (12 drains)
Two Pair: 2.0 (16 drains)
One Pair: 1.3 (24 drains)
High Card: 1.0 (32 drains)
The poker ordering comes out of the ODE because it went in with the drain counts. The frequency table is the poker knowledge, and what the net adds is a mechanical, inspectable path from that table to the values. Nothing in the net counts poker hands, which is the difference from tic-tac-toe, where the win-line counts are read off the game’s own transitions.
TTT vs. Poker: Same Mechanism, Inverted Reading
In tic-tac-toe, more connections to win transitions means higher strategic value: in Chapter 6’s ODE heatmap the center scores highest because it feeds the most win lines.
In poker, fewer drain connections means higher hand value. The raw concentration of val_H rises as the drain count falls, so the straight flush, with one sink, holds the most.
Both cases read a ranking back from token flow, exactly as for poker and approximately (within a few percent, per Chapter 6) as 4 : 3 : 2 for tic-tac-toe. The routes differ: a tic-tac-toe move that feeds more win collectors sends more flow toward the win place, while a poker value place with fewer drains keeps more of its inflow.
This bears on the modeling-scope boundary of Chapter 15, where 52 detection transitions produced a score that nothing in the net read. Here the drain transitions take part in the dynamics: they are what makes each value place settle where it does. The scoring is still a design choice, moved from the multipliers into the drain counts, but it is now in a form the net computes with rather than one it merely stores.
The next chapter completes the pipeline: compiling guards and state invariants into ZK circuits, committing state with Merkle trees, and verifying proofs on-chain via smart contracts.
On-Chain ZK Verification
Learning objective: Compile guards and state invariants into ZK circuits, commit state with Merkle trees, and verify Petri net execution on-chain.
Chapter 13 showed how petrigen compiles Petri net topology into gnark circuits and how graph connectivity determines strategic value. This chapter covers the rest of the pipeline: guards become arithmetic constraints, state is committed via Merkle trees, invariants become circuit constraints, and proofs are verified on-chain by smart contracts. The compiler stages are go-pflow’s zkcompile package; the contracts are petri-pilot’s ZkOde and the ZKHoldem contract generated by pflow-rs. Nothing in this chapter was re-run for it; where a number is derived rather than read from the code, the text says so.
Guard Compilation
Chapter 4 introduced guards — boolean expressions that add conditions beyond simple token availability. A guard like balances[from] >= amount on a transfer transition means: even if the input places have tokens, the transition only fires when the guard is satisfied.
In a ZK circuit, guards become arithmetic constraints. The GuardCompiler in go-pflow (zkcompile/guard.go) transforms guard expressions into the constraint IR that the gnark code generator consumes.
Boolean Logic as Field Arithmetic
ZK circuits operate over a finite field. There are no if statements, no booleans, no branches. Everything is multiplication and addition over integers mod a prime. The compiler transforms each logical operation:
AND: A && B becomes A * B. Both must be 1 for the product to be 1.
OR: A || B becomes A + B - A * B. At least one must be 1.
NOT: !A becomes 1 - A. The operand must be boolean (0 or 1).
These formulas compute a value; they do not by themselves constrain it. In the current compiler the constraints come from comparisons, each of which is asserted unconditionally and then returns the constant 1, and the value of the guard as a whole is never asserted to equal 1 (Compile discards it). A conjunction of comparisons, like the ERC-20 guard balances[from] >= amount && to != address(0) that guard_test.go compiles, is therefore enforced exactly. A comparison under || is enforced as though it stood alone, and !revoked adds only the check that revoked is 0 or 1, so disjunction and negation are not yet enforced.
Comparisons as Range Checks
The more subtle transformations handle comparisons:
Greater-or-equal: left >= right becomes:
- Compute
diff = left - right - Assert
diffis non-negative with a range check
Non-negativity in a finite field is tricky — every field element is technically positive. The trick from Chapter 12 applies: require diff to fit in a fixed number of bits. The generated code asserts diff <= 2^64 - 1 (api.AssertIsLessOrEqual in zkcompile/gnark.go), which gnark implements by bit decomposition. If the original value was negative, it wraps to a huge field element that won’t fit in 64 bits, and the check fails.
Strict greater-than: left > right reduces to left - right - 1 >= 0.
Equality: left == right is a direct AssertIsEqual constraint.
Inequality: left != right requires proving the inverse exists. The compiler introduces a witness inv and constrains (left - right) * inv = 1. This is satisfiable only when left - right is non-zero — zero has no multiplicative inverse in a field.
State Access and Merkle Proofs
Guards often reference state: balances[alice] >= amount. The compileIndexExpr function handles map lookups by registering a state read. Each state read becomes a Merkle proof obligation — the prover must demonstrate that the claimed value actually exists in the committed state tree.
For nested maps like allowances[owner][spender], the compiler generates composite key hashing: key = Poseidon(owner, spender). The resulting key looks up a single leaf in the Merkle tree. The excerpt below has its error checks trimmed:
func (c *GuardCompiler) compileIndexExpr(idx *guard.IndexExpr) *Expr {
// Check for nested index (e.g., allowances[owner][spender])
if innerIdx, ok := idx.Object.(*guard.IndexExpr); ok {
return c.compileNestedIndex(innerIdx, idx.Index)
}
// Simple index: place[key]
placeIdent, _ := idx.Object.(*guard.Identifier)
keyIdent, _ := idx.Index.(*guard.Identifier)
// Register state read — triggers Merkle proof generation
witness := c.witnesses.AddStateRead(placeIdent.Name, []string{keyIdent.Name})
return VarExpr(witness.Name)
}
The guard compiler doesn’t verify Merkle proofs itself. It registers what state needs to be proven, and the pipeline (zkcompile/pipeline.go) hands those reads to the Merkle proof compiler, which generates the verification constraints.
Merkle State Commitment
Chapter 12 committed state with a flat MiMC hash: feed all place values into a single hash and publish the result. That chapter derives 330 constraints per element absorbed, so the 33-place ZK tic-tac-toe marking costs about constraints per hash. That is affordable for a small net.
But real applications have thousands or millions of state entries. An ERC-20 token has one balance per address. A workflow system has one case state per process instance. Flat hashing doesn’t scale.
From Flat Hash to Merkle Tree
A Merkle tree organizes state as leaves and hashes pairs up to a single root:
root
/ \
h01 h23
/ \ / \
h0 h1 h2 h3
| | | |
leaf0 leaf1 leaf2 leaf3
To prove a single value, the prover provides the leaf and the sibling hashes along the path to the root — hashes instead of . The compiler fixes the depth at 20 (MerkleProofDepth in zkcompile/merkle.go), which supports (~1 million) leaves with 20 hashes up the path plus one for the leaf.
Poseidon or MiMC
The Merkle compiler’s constraint IR names its hash Poseidon, a ZK-friendly hash usually cheaper in circuits than MiMC. The IR constraint is marked as a placeholder in merkle.go, though, and the gnark code generator currently lowers every Poseidon constraint to a two-input MiMC call (mimcHash in gnark.go). As generated today, then, each hash in a Merkle proof is a MiMC hash of two elements, constraints by Chapter 12’s derivation. go-pflow’s research outline estimates about 182 constraints for a Poseidon call; that is an estimate, not a count taken from a compiled circuit.
Verification in the Circuit
The Merkle proof verification algorithm in the circuit (CompileProof in merkle.go):
- Compute the leaf hash:
leaf = Poseidon(key, value) - Walk up the tree: at each level, select left/right based on the path index, then hash the pair
- Assert the computed root equals the committed state root
The path selection uses the same no-branching pattern as transition selection — arithmetic multiplexing:
left = pathIndex * sibling + (1 - pathIndex) * current
right = pathIndex * current + (1 - pathIndex) * sibling
hash = Poseidon(left, right)
Each level adds one hash, a boolean check on the path index and the two selections; the leaf adds one more hash and the root one equality. A proof is therefore 21 two-input hashes plus 61 small constraints. With the MiMC the generator emits, that is about constraints per state access; with Poseidon at the outline’s estimate it would be about . Both figures are derived, not measured. Every state access costs one proof, but the circuit does not grow with the number of entries in the tree.
The pipeline proves reads against the pre-state root only. It declares a public post-state root but generates no constraints for writing the new values into the tree, so proving the updated root is not yet part of the generated circuit.
Nested Maps
For data structures like allowances[owner][spender], the compiler hashes the key pair into a single composite key:
compositeKey = Poseidon(owner, spender)
leaf = Poseidon(compositeKey, value)
This flattens nested maps into a single Merkle tree. The prover includes the raw keys and the composite key hash in the witness, and the circuit verifies the key composition.
State Invariants in Circuits
Chapter 2 introduced P-invariants — weighted sums of places that remain constant across all firings. In its three-place chain, never changes: tokens are neither created nor destroyed, only moved.
Offline, an invariant is something you check. Compiled into a proof circuit as a constraint, it becomes something the prover cannot get around: no valid proof exists for a step that breaks it. go-pflow’s InvariantCompiler (zkcompile/invariant.go) generates these constraints. It is exercised on its own by invariant_test.go (mint, transfer and burn against sum(balances) == totalSupply, and an NFT supply bound), but Pipeline.Compile does not yet call it: the pipeline passes no invariant constraints to the code generator.
Conservation Laws
Consider an ERC-20 token with the invariant sum(balances) == totalSupply. In a ZK circuit, we can’t iterate over all balances — the circuit doesn’t know how many accounts exist. Instead, we verify the invariant differentially:
Untouched balances don’t change, so their deltas are zero. The circuit only needs to verify that the changes to touched balances sum to the change in total supply. Condensed from CompileConservation:
func (c *InvariantCompiler) CompileConservation(
sumPlace string,
totalPlace string,
transitions []StateTransition,
) []*Constraint {
// Sum deltas for the summed place (e.g., balances)
var sumDeltaExpr *Expr
for _, t := range transitions {
if t.Place == sumPlace {
delta := SubExpr(VarExpr(t.PostVar), VarExpr(t.PreVar))
if sumDeltaExpr == nil {
sumDeltaExpr = delta
} else {
sumDeltaExpr = AddExpr(sumDeltaExpr, delta)
}
}
}
// Find delta for total place (e.g., totalSupply); 0 if untouched.
// ...
// Conservation: delta(total) == sum(deltas)
return []*Constraint{{
Type: Equal,
Left: totalDeltaExpr,
Right: sumDeltaExpr,
Tag: fmt.Sprintf("conservation: delta(%s) == sum(delta(%s))", totalPlace, sumPlace),
}}
}
This is Chapter 2’s P-invariant argument applied to differences: if is the same before and after a step, then , and only the places the step touched contribute non-zero terms.
Non-Negativity
Token counts can’t go negative. The CompileNonNegative function adds range checks on every touched place’s post-transition value:
func (c *InvariantCompiler) CompileNonNegative(
place string,
transitions []StateTransition,
) []*Constraint {
var constraints []*Constraint
for _, t := range transitions {
if t.Place == place {
constraints = append(constraints,
RangeConstraint(VarExpr(t.PostVar),
fmt.Sprintf("%s[%v] >= 0", place, t.Keys)))
}
}
return constraints
}
In the generated circuit this is the same 64-bit range check the guard compiler uses, the trick Chapter 12 used for enabledness checks. If a balance would go negative, the field element wraps to a huge value that fails the range check.
Boundedness
Some places have capacity limits; an NFT’s supply of each token ID, for instance, is at most 1, which is the case TestInvariantCompiler_Bounded compiles. The CompileBounded function constrains post-values to not exceed a maximum, again by a range check on the difference:
// max - post >= 0
diff := c.witnesses.AddComputed(fmt.Sprintf("bound_%s", t.PostVar))
constraints = append(constraints,
EqualConstraint(
VarExpr(diff.Name),
SubExpr(ConstExpr(maxValue), VarExpr(t.PostVar)),
fmt.Sprintf("%s[%v] <= %s", place, t.Keys, maxValue),
),
RangeConstraint(VarExpr(diff.Name), "bounded check"),
)
From Schema to Constraints
CompileFromSchema reads invariants from the model schema, but its parser (parseSchemaConstraint) recognises only two shapes:
sum(balances) == totalSupply → Conservation constraint
balances >= 0 → Non-negative constraint
Any other expression, an upper bound such as votes <= maxVotes included, is skipped; a bound has to be compiled by calling CompileBounded directly.
Each invariant adds one to three constraints to the IR: one equality for conservation, one range check for non-negativity, an equality and a range check for a bound. In R1CS the equalities are cheap and each 64-bit range check costs on the order of the bit width; no compiled count is recorded. Once such a constraint is in a circuit, a step that violates it has no valid proof.
On-Chain Verification
Generating proofs locally is useful for peer-to-peer verification — one player proves to another that a move is valid. But for applications with shared state — token transfers, governance, auctions — the proof needs to be verified where the state lives: on a blockchain.
State Root Chaining
petri-pilot’s ZkOde contract (solidity/src/ZkOde.sol) maintains a chain of state roots. The genesis root, the MiMC hash of the initial marking, is a constructor argument. Each submitted proof’s pre-state root (public input 0) must equal the stored root, and after the proof verifies the contract advances to the next root:
Genesis: stateRoot₀ = MiMC(initial_marking)
Step 1: proof₁ has preRoot = stateRoot₀; contract stores stateRoot₁
Step 2: proof₂ has preRoot = stateRoot₁; contract stores stateRoot₂
...
Step n: proofₙ has preRoot = stateRootₙ₋₁; contract stores stateRootₙ
The contract rejects any proof whose pre-state root doesn’t match:
if (preRoot != currentStateRoot) {
revert InvalidStateChain(currentStateRoot, preRoot);
}
A proof made against an old root reverts, so steps cannot be replayed or reordered. Which root comes next is a separate question. The contract advances to nextStateRoot, an argument the prover passes alongside the proof; in the tic-tac-toe deployment it is the board after the chosen move, while the proof’s own post-state (public input 1) is the state after one ODE step. The verifier never sees nextStateRoot, so that link of the chain rests on the contract’s onlyProver restriction, not on the proof.
The ZkOde Contract
The contract’s state:
contract ZkOde {
IVerifier public verifier;
address public prover;
uint256 public currentStateRoot;
uint256 public stepCount;
uint256 public immutable numTransitions;
bool public enforceOptimal;
struct Step {
uint256 preRoot;
uint256 postRoot;
uint256 nextRoot;
uint256 stepSize;
uint256 chosenTransition;
uint256 timestamp;
}
mapping(uint256 => Step) public steps;
}
The verifier is a gnark-generated Groth16 verifier, reached through a small adapter contract that converts the call into gnark’s flat argument format (solidity/DEPLOY.md). submitStep passes its arguments to _verifyAndRecord, which checks the chain, verifies the proof, records the step and advances the root. An excerpt, with the optimal-play check and the event omitted:
function _verifyAndRecord(
uint256[8] calldata proof,
uint256[] calldata publicInputs,
uint256 chosenTransition,
uint256 nextStateRoot
) internal {
require(publicInputs.length >= 3 + numTransitions, "insufficient public inputs");
uint256 preRoot = publicInputs[0];
uint256 postRoot = publicInputs[1];
uint256 stepSize = publicInputs[2];
// Verify state chain: preRoot must match current state
if (preRoot != currentStateRoot) {
revert InvalidStateChain(currentStateRoot, preRoot);
}
// ... chosen-transition bounds check and optimal-play check ...
// Verify the ZK proof
uint256[2] memory a = [proof[0], proof[1]];
uint256[2][2] memory b = [[proof[2], proof[3]], [proof[4], proof[5]]];
uint256[2] memory c = [proof[6], proof[7]];
bool valid = verifier.verifyProof(a, b, c, publicInputs);
if (!valid) revert InvalidProof();
// Record step
steps[stepCount] = Step({
preRoot: preRoot,
postRoot: postRoot,
nextRoot: nextStateRoot,
stepSize: stepSize,
chosenTransition: chosenTransition,
timestamp: block.timestamp
});
// Chain on the discrete post-move board, not the ODE post-state
currentStateRoot = nextStateRoot;
stepCount++;
}
petri-pilot’s solidity/test/ZkOde.t.sol covers this contract with a stub verifier, the optimal-play rule, and the real Groth16 verifier behind the adapter (17 tests in three suites, per DEPLOY.md; not re-run here).
Optimal Play Enforcement
For game applications, the contract can enforce that the chosen transition has the highest value among all transitions. Public inputs 3 onward carry one value per transition, which the proof binds: the rate constants in the cascade circuit, and the nine heatmap scores in the tic-tac-toe circuit (DeployHeatmap.s.sol configures 12 public inputs: pre-root, post-root, step size and nine scores). The contract checks that no other transition has a higher value:
if (enforceOptimal) {
uint256 chosenRate = publicInputs[3 + chosenTransition];
for (uint256 t = 0; t < numTransitions; t++) {
uint256 rate = publicInputs[3 + t];
if (rate > chosenRate) {
revert NotOptimalPlay(
chosenTransition, chosenRate, t, rate);
}
}
}
The contract holds no game rules and no board; it compares numbers that the proof binds to the circuit. Ties pass, since only a strictly higher value reverts. Whether the highest value is the best move is a property of the scoring, which Chapter 13 derives from topology; the contract does not check that.
Batch Submission
For applications with many steps per session (a full game, a sequence of workflow transitions), submitting proofs one at a time pays the fixed cost of a transaction for every step. The submitBatchSteps function accepts arrays of proofs and processes them in order:
function submitBatchSteps(
uint256[8][] calldata proofs,
uint256[][] calldata publicInputsBatch,
uint256[] calldata chosenTransitions,
uint256[] calldata nextStateRoots
) external onlyProver {
require(proofs.length == publicInputsBatch.length, "length mismatch");
require(proofs.length == chosenTransitions.length, "transitions length mismatch");
require(proofs.length == nextStateRoots.length, "nextStateRoots length mismatch");
for (uint256 i = 0; i < proofs.length; i++) {
_verifyAndRecord(proofs[i], publicInputsBatch[i], chosenTransitions[i], nextStateRoots[i]);
}
}
Gas Costs
No gas measurement of submitStep is checked into the repository. An estimate can be derived from the EVM’s prices for the BN254 precompiles (EIP-1108) and for storage (EIP-2929):
| Operation | Gas (derived) |
|---|---|
| Groth16 pairing check, 4 pairings: | 181,000 |
| Public-input combination: one scalar multiplication (6,000) and one addition (150) per input | 30,750 for 5 inputs; 73,800 for 12 |
Step record: six fields in a fresh storage slot each, at 22,100 for a zero-to-non-zero write | up to 132,600 |
currentStateRoot and stepCount updates | about 10,000 |
That puts a step at roughly 350,000 gas for the five-input cascade and 400,000 for the twelve-input tic-tac-toe circuit, before the 21,000 base cost of a transaction and its calldata. What that costs in money depends on the chain’s gas price at the time.
Deployed Contracts
Foundry’s broadcast logs in petri-pilot’s solidity/broadcast/ record two deployments on Base Sepolia (testnet, chain 84532):
| Deployment | Verifier | ZkOde | Transitions | Optimal |
|---|---|---|---|---|
| Cascade (3-place) | 0xA675... | 0x2084... | 2 | Yes |
| TTT Heatmap (33-place) | 0x97a6... | 0xF5d9... | 9 | Yes |
Both were deployed with enforceOptimal set, so the TTT contract rejects a move whose score is lower than another transition’s. That falls short of a trustless game in two ways already described: only the deployer’s prover address can submit steps, and the board root the contract advances to is not bound by the proof.
ZK Hold’em: Topology-Derived Payouts
The poker hand analysis net from Chapter 13 produces hand strength values from its topology, in which the drain counts encode how common each hand is. pflow-rs’s zk_holdem.rs example carries those values into a game contract as payout multipliers. Run with --export-solidity, it renders a ZKHoldem contract from the template render_holdem_contract in pflow-zk-arkworks/src/solidity_export.rs. Its proofs come from a different stack from ZkOde’s: arkworks Groth16 over BN254 with Poseidon state roots. The contract adds three poker-specific mechanisms.
Commit-reveal shuffle. The example shuffles the deck with Fisher-Yates driven by a seeded linear congruential generator (shuffle_deck) and publishes a Poseidon commitment to the seed; the contract stores it through commitShuffle. At showdown the house reveals the seed, so anyone can recompute the commitment and the cards off-chain. The generated revealAndSettle does not yet do either check itself: its body says the Poseidon check and the card derivation are left for production, and it takes both hand ranks as arguments. A claimTimeout function is meant to close a game the house abandons; as generated, its 100-block timeout counts from block 0 rather than from showdown, so it does not yet enforce a reveal window.
State root chaining per action. Each game action — deal, check, bet, call, fold — fires a transition on a reduced heads-up game net (build_game_net: 18 places, 16 transitions — not the Chapter 10 model) and produces a Groth16 proof. playerAction and houseAction require the proof’s pre-state root to equal the stored root and then store its post-state root, so here, unlike in ZkOde, every link of the chain is bound by a proof.
Topology-derived bonus payouts. The winner takes the pot plus a bonus proportional to the integer reduction value of their hand. The example rounds Chapter 13’s values, , to integers and writes them into the contract:
uint256[9] private HAND_STRENGTH = [
uint256(1), 1, 2, 3, 4, 6, 8, 16, 32
];
// Index: 0=HC, 1=Pair, 2=2P, 3=3K, 4=Str, 5=Flush, 6=FH, 7=4K, 8=SF
uint256 bonus = HAND_STRENGTH[playerRank] * SMALL_BLIND;
The array values are that rounding of the closed form (32, 16, 8, 6.4, 4, 2.7, 2, 1.3, 1), derived rather than re-run. A straight flush win pays 32 times the small blind as bonus, a pair 1 time. As Chapter 13 notes, the ordering went into the net with the drain counts, which were chosen by hand from the combination counts. The net does not discover the payout schedule; it gives a mechanical, inspectable path from the frequency table to the multipliers, which is what makes the schedule auditable.
The example’s house plays a deterministic strategy based on hand strength and pot odds, so it could in principle be checked on-chain. The generated contract does not check it: houseAction accepts any action that comes with a valid transition proof.
Combinatorial vs. Continuous
The circuits in this chapter and the last fall into two modes, and the choice affects both the circuit design and how the results should be read.
Combinatorial Mode
Games, workflows, governance, token standards.
The state space is finite and discrete. Tic-tac-toe has at most 5,478 reachable board states. A workflow has a bounded number of case states. An ERC-20 has integer balances.
In these systems, the topology and discrete scoring are sufficient. The ODE provides a continuous picture of token flow, useful for intuition and as a heatmap, but when it comes time to decide, you discretize. The heatmap scoring that drives move selection in tic-tac-toe is discrete: count win lines, evaluate threats, pick the best move. There is no continuous quantity being modeled.
The “mass-action kinetics” framing is a useful metaphor that lets you apply ODE machinery, but the strategic information is graph-theoretic.
What the ZK circuit proves: the discrete state transition was valid — correct inputs consumed, correct outputs produced, guard conditions met. The ODE step is optional — it enriches the public output with heatmap scores but isn’t necessary for correctness.
Rate derivation: auto-derive from topology, by Chapter 13’s count of win transitions reachable through each move’s unique outputs.
Continuous Mode
Chemical kinetics, population ecology, epidemiology, economic models.
The state genuinely evolves in continuous time. Concentrations rise and fall. Populations oscillate. Epidemics peak and decay. The trajectory carries information — you care about when concentrations peak, in what order, and how fast.
In these systems, the topology tells you what can happen, but the ODE tells you what happens first. A chemical cascade where reaction A peaks before reaction B produces a different product mix than one where B peaks first, even if the topology is identical.
What the ZK circuit proves: the ODE integration was computed correctly. petri-pilot’s zk-ode circuit recomputes the seven stages of a Tsit5 step, the mass-action rates and the stoichiometry-weighted derivatives in fixed point and constrains the result. The circuit is compiled against fixed topology constants: the three-place cascade A → B → C in zk-ode/topology.go, and a separate 33-place tic-tac-toe topology for the heatmap circuit. Another net needs new constants, a recompile and a new verifier (DEPLOY.md).
Rate derivation: bring domain-specific rates. They encode physical properties (activation energies, birth/death rates, transmission coefficients) that topology cannot capture.
Fixed-Point Arithmetic for Continuous Mode
ZK circuits operate over finite fields — integers mod a prime. There are no floating-point numbers. zk-ode/fixedpoint.go uses fixed-point arithmetic with a scale factor over the BN254 scalar field:
This gives 18 decimal digits after the point, using only integer operations that ZK circuits handle natively. In the circuit, FixMul takes the quotient and remainder from a prover hint and constrains , so every product is truncated, and a long integration can drift from a floating-point run by the accumulated truncation.
The Pipeline Supports Both
| Combinatorial | Continuous | |
|---|---|---|
| Rates | Auto-derived from topology | Specified in model |
| ODE step | Optional (enriches output) | Essential (proves trajectory) |
| Scoring | Discrete win/block detection | Rate-weighted heatmap |
| Circuit focus | State transition validity | Integration correctness |
| Examples | TTT, Hold’em, workflows, ERC-20 | The A → B → C cascade |
Epidemic and population models fit the continuous column on paper; none has been compiled to a ZK ODE circuit. petri-pilot’s zkgen command (cmd/petri-pilot/zkgen.go) generates a ZK ODE circuit package from a model file, with an optional scoring configuration for the tic-tac-toe heatmap.
Putting It Together
The compilation pipeline from this chapter and Chapter 13, combined with the circuit fundamentals from Chapter 12, creates a complete system for verifiable Petri net execution:
- Define the model in JSON — places, transitions, arcs, guards, invariants
- Generate circuits —
petrigenturns topology into constants and guards into constraints;zkcompile’s guard and Merkle stages handle map-valued state, and its invariant compiler is not yet wired into that pipeline - Derive rates from graph connectivity — or specify domain-specific rates
- Prove transitions locally — the prover generates a Groth16 proof that the state changed correctly
- Verify — off-chain in milliseconds (Chapter 12’s typical figure, not benchmarked here), or on-chain for a few hundred thousand gas (derived above)
The model is the specification, and each proof attests that one step followed it.
Two games now carry topology-derived values into a proof system:
| Game | What is recovered | How | Net |
|---|---|---|---|
| Tic-Tac-Toe | Position value: center=4, corner=3, edge=2 | Count of win transitions reachable from each move | 33 places, 35 transitions (ZK variant) |
| Hold’em | Hand ranking: SF=32, 4K=16, …, HC=1 | Equilibrium of an analysis net, normalised and rounded | 18 places, 113 transitions (analysis net) |
The two differ in where the game knowledge enters. Tic-tac-toe’s values are counted from the game’s own win transitions; Hold’em’s come from a separate analysis net whose drain counts encode the hand-frequency table, so the poker knowledge enters as data. They also use different proof stacks: the tic-tac-toe circuits are gnark Groth16 over BN254 with MiMC state roots (Chapter 12), the Hold’em example arkworks Groth16 over BN254 with Poseidon roots. In both, the circuit is compiled from the net’s topology and contains no game-specific code.
Exponential Weights and Scoring Systems
Learning objective: Design scoring systems using power-of-2 encoding in net structure.
Chapters 5 through 10 modeled diverse systems with Petri nets, and Chapters 11 through 14 extracted models from data, derived strategy from topology, and compiled nets into proofs. This chapter examines a technique that sits at the edge of what a Petri net should model internally and what should be delegated to external systems: encoding priority rankings as exponential arc weights.
Power-of-2 weights encode a lexicographic order as a single integer. Applying that encoding to poker hand scoring inside the net, and then removing it, is the case study here; the removal suggests a rule for deciding what belongs in a net at all.
Binary Dominance
The core idea: assign power-of-2 weights so that any single higher-priority item outweighs all lower-priority items combined. This is the same principle behind bitmasks, Unix file permissions (read=4, write=2, execute=1), and binary-encoded feature flags.
For poker card ranking, each rank gets a power of 2:
| Rank | Rank Power |
|---|---|
| A | 4096 () |
| K | 2048 () |
| Q | 1024 () |
| J | 512 () |
| T | 256 () |
| 9 | 128 () |
| … | … |
| 2 | 1 () |
The key property is binary dominance, and on rank powers alone it is exact: , so one King (2048) outweighs Queen through Two together (2047). For two hands with no repeated rank, comparing the sums of their rank powers gives the same answer as comparing their ranks highest first. No sorting is needed.
The poker experiment described below also broke ties by suit (spade=3, heart=2, diamond=1, club=0), with the per-card formula:
Every card maps to a unique integer: A-spade = 16387, A-heart = 16386, down to 2-club = 4. But the factor of 4 leaves room for one card’s suit value, not for the suit values of a whole hand, so summed card weights can misorder two hands that differ only in a low card:
| Hand | Card weights | Sum |
|---|---|---|
| A♣ K♣ Q♣ 4♦ 2♣ | 16384 + 8192 + 4096 + 17 + 4 | 28693 |
| A♠ K♠ Q♥ 3♠ 2♠ | 16387 + 8195 + 4098 + 11 + 7 | 28698 |
Neither hand is a flush or a straight, so both are compared card by card, and the first wins on its fourth card (4 over 3). The sums say the second. The fix is a larger factor: when the factor exceeds three times the number of cards, the summed suit values can never outweigh a one-step difference in the rank sum, so rank_power × 32 + suit_value orders any hands of up to ten distinct-rank cards by rank first and by total suit value only on a tie. This bound and the table are derived by hand from the formula, not taken from a test.
Why Linear Weights Fail
Naive linear weights (A=13, K=12, Q=11, down to 2=1) break dominance. A hand with {A, K, 5, 4, 3} scores . A hand with {A, Q, J, T, 9} scores . Linear scoring says the second hand wins; poker says the King beats the Queen, so the first hand wins.
Rank powers give against . The King’s 2048 exceeds the 2047 that every lower rank together can contribute, so the first hand outscores any hand whose second-highest card is a Queen.
The Score Is the State
When each item gets weight , the sum of any subset is unique: that is binary representation. Consider what this means for Petri nets.
A hand with {K, T, 5, 2}, using rank powers:
K = 2^11 = 2048
T = 2^8 = 256
5 = 2^3 = 8
2 = 2^0 = 1
---------------
Sum = 2313
Now write 2313 in binary, padded to thirteen digits: 0100100001001. Each bit position maps to a rank, Ace in the leading position and Two in the last: the bits are the places of a thirteen-place rank vector and the 1s are its tokens. The binary representation of the score is that marking.
A Petri net marking is a vector of token counts across places. When every place holds 0 or 1 tokens, that vector is a bit string, and a bit string is a binary number, so the accumulated score, the bit string and the marking carry exactly the same information.
The constraint: this works for set membership, where each place holds at most one token. If a place could hold 2 or more tokens, a single bit cannot represent it. It also needs one power of two per place. The suited card weights above are not one bit per card, and their sums collide: {A♠, K♣} and {A♣, K♠} both total 24579. Recovering the exact cards would take a distinct power of two for each of the 52 card places, a 52-bit integer. With that encoding, the number does not just rank the hand; it identifies it.
What We Built (And Removed)
We encoded this in the poker hand Petri net:
- A
kicker_scoreplace that accumulated the total weight (initial = 0) - 52 detection transitions (
hc_A-heart,hc_K-spade, …), one per card - Consuming input arcs from each card place to its detection transition
- Weighted output arcs from each detection transition to
kicker_score
When a card was in the hand, its place had a token, enabling the corresponding transition. It fired once — consuming the card token — and deposited the card’s universal weight into kicker_score. Cards not in the hand never fired. The consuming arcs made each transition self-limiting.
Mechanically, it worked: the transitions fired and tokens accumulated, and two hands’ kicker scores could be compared to pick a winner. That comparison was only as good as the formula, and the pair of high-card hands in the table above is one it orders wrongly.
Then we removed it. The revert takes out the 52 hc_* transitions, the kicker_score place and a card_counter guard from the model builder.
Why It Was Wrong
The poker hand model that remains, buildPokerHandModel in pkg/serve/serve.go (in sim.pflow.xyz’s source, which is not public; the model is no longer served live), encodes hand patterns as structure. Each of its 78 pair transitions (6 suit pairs × 13 ranks) has input arcs from two cards of one rank, so it is enabled exactly when both cards hold tokens; three-of-a-kind and straight-flush transitions work the same way with three and five cards. Flushes and straights are covered only for a representative subset of patterns, ten five-card flush patterns per suit and one suit combination per straight, as the builder’s own comments note. Where a pattern has a transition, the net’s structure is the classifier.
What has not been demonstrated is the net doing that classification end to end. The builder also computes the hand’s name directly in Go for the model’s description, and its tests (pkg/serve/poker_hand_test.go) check that name against a standard evaluator and check the net’s structure (52 deal transitions, 78 pair transitions). The web page that served the model compared hands with a conventional JavaScript evaluator. No test fires the detection transitions and reads the result.
Kicker scoring has no such structure. The kicker_score place just accumulates a number. Nothing in the net reads that number. No transition is enabled or disabled by it. No arc weight depends on it. The model needs a separate interpreter to extract meaning from the token count: you have to decompose the sum back into powers of 2 to recover which cards contributed, and with the suited weights even that decomposition is ambiguous.
That is bookkeeping bolted onto the side of the model, not modeling.
A Petri net model should be self-describing: the structure of places, transitions, and arcs encodes the rules. If you need a decoder ring to read meaning out of a token count, the net has become a storage medium for an external computation. The 52 extra transitions and their arcs added complexity without adding behavior.
The model that remains carries a smaller instance of the same pattern. Eight score_* transitions deposit weights 2 through 9 into a hand_strength place, and no arc leads out of it. By the test at the end of this chapter, hand_strength is bookkeeping too.
The Boundary Between Net and External Logic
The lesson is about where the model ends and the world begins. This is a boundary of modeling scope, not either of the two core–observer boundaries of Appendix E.
Petri nets are good at modeling concurrent, discrete behavior through structure. Places represent state, transitions represent events, and arcs define preconditions and effects, so the topology carries the logic. When you need to add behavior, the right instinct is to add structure: new places, transitions and arcs that encode the rules.
Assigning weights to arcs adds no behavior. It makes the net store something for someone else to read, which is fine as long as you are clear about the boundary.
When Exponential Weights Belong
The encoding is valuable when the consumer is external and the Petri net is generating output for it. The book does not yet give a worked model for any of the three settings below; they are the shapes the argument predicts, not results.
Event-sourced state. In an event-sourced system built on a Petri net, transitions emit events and external projections interpret them. If a projection needs to rank items by priority, the net can deposit exponentially-weighted tokens into an output place, and the projection reads the accumulated value and sorts by it directly.
Multi-criteria scoring. When criteria have strict priority order (safety > performance > cost), exponential weights encode the hierarchy. A workflow net could accumulate scores as items pass through evaluation stages, leaving the full priority ranking as a single integer in an output place that an external dashboard reads without replaying the evaluation logic. The factor between levels has to exceed the largest total a lower level can reach, the same condition the suit tiebreaker above failed.
Compact set representation. With one power of two per place, the score in binary is the place vector. That makes power-of-2 sums useful whenever a Petri net needs to tell an external consumer which subset of items was selected: one place holds one integer, and the consumer reads its bits to reconstruct the set without replaying any transitions.
When They Don’t Belong
The encoding fails when the net itself needs to read the result. If no transition depends on the accumulated score, no guard references it, and its meaning has to be decoded outside the net, then the encoding adds structural complexity (more transitions, more arcs) without adding behavioral capability.
The General Principle
The poker experiment suggests a design heuristic for Petri net modeling:
Ask: does any transition use this information?
If the answer is yes, because a place’s token count enables, disables or influences a transition, then encode it in the net.
If the answer is no, because the information is only consumed by external systems, then the net is the wrong place for the computation. Let the net generate the raw events and the external system do the interpretation, rather than adding 52 transitions and their arcs to encode something that a simple function could compute from the event stream.
This boundary applies beyond exponential weights. Any time you’re tempted to add net structure that doesn’t participate in the net’s behavior, such as logging places, summary counters or encoding tricks, ask whether the information is being modeled or merely stored.
The exponential encoding itself is useful: with one power of two per item it maps sets to integers, and with rank powers on distinct items it orders them lexicographically, so two results compare with one integer comparison. The mistake was embedding it in the net instead of applying it at the boundary where the net’s output meets the world.
There is, however, a way to put the poker hand ranking into the net’s dynamics rather than bolting it on. The integer reduction technique in Chapter 13: Topology-Driven Verification builds a hand analysis net in which each hand category gets a number of drain transitions, chosen by hand to rise with its combinatorial frequency (from 1 drain for straight flush to 32 for high card). At ODE equilibrium each value place settles at , so rare hands hold more tokens; scaled so that high card = 1, straight flush = 32, four of a kind = 16, and so on down. That equilibrium is a closed-form consequence of the rate law. The ranking goes in with the drain counts rather than being discovered, but the drain transitions are the mechanism that produces the values rather than bookkeeping beside them. The construction orders hand categories only: two high-card hands settle on the same value, so kicker comparison stays outside the net. See “Poker Hand Ranking: Integer Reduction” in Chapter 13 for the construction.
Declarative Infrastructure
Learning objective: Use JSON-LD and semantic vocabularies to make nets self-describing and composable.
The previous chapters built models, analyzed them, and even proved their transitions in zero knowledge. But how do those models travel between systems? How does a Petri net created in the browser editor reach the Go solver? How does a model saved before the schema grew remain valid after it?
The answer is JSON-LD — a serialization format that is purely declarative and monotonically expansive. This chapter argues that these two properties are what let independent tools share one file, using the three vocabularies the pflow ecosystem uses.
Three Contexts, One Discipline
The pflow ecosystem uses three JSON-LD vocabularies. Each serves a different purpose. All share the same envelope.
Petri net model (pflow.xyz editor; trimmed — a saved file also carries @version, token, layout coordinates and authorship, as in the fixtures under parity/fixtures/):
{
"@context": "https://pflow.xyz/schema",
"@type": "PetriNet",
"places": {
"Idle": { "@type": "Place", "initial": [1], "capacity": [1] }
},
"transitions": {
"Brew": { "@type": "Transition" }
},
"arcs": [
{ "@type": "Arrow", "source": "Idle", "target": "Brew", "weight": [1] }
]
}
Blog metadata (schema.org):
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "JSON-LD as Declarative Infrastructure",
"author": { "@type": "Person", "name": "stackdump" },
"datePublished": "2026-02-15T00:00:00Z"
}
ActivityPub actor (federation; served by blog.stackdump.com from tens-city’s pkg/activitypub/actor.go):
{
"@context": [
"https://www.w3.org/ns/activitystreams",
"https://w3id.org/security/v1"
],
"type": "Person",
"preferredUsername": "myork",
"inbox": "https://blog.stackdump.com/users/myork/inbox",
"publicKey": { "id": "...#main-key", "publicKeyPem": "..." }
}
Each snippet names, in its @context, the vocabulary that defines its terms, and none of them contains instructions: they are assertions.
Purely Declarative
A JSON-LD document is a serialized RDF graph: a set of subject-predicate-object triples. It makes statements about the world but never tells you what to do with them. There are no callbacks, no event handlers, no conditionally-included fields.
This matters for interoperability. The same .jsonld Petri net file is read by two tools:
- JavaScript — the pflow.xyz browser editor (
public/petri-view.js) loads it, renders the net, and runs simulations - Go parser — go-pflow’s
FromJSON(parser/json.go) reads it for ODE-based analysis and validation
They are independent readers. They do not coordinate at runtime; the file is assertions, not a protocol. What keeps the readers in agreement is a shared contract rather than a conversation: go-pflow pins its reading of the editor format to the goldens in parser/testdata/editor-shape/ (editor_shape_test.go), and other readers replay the same inputs. Neither runs a JSON-LD processor on the file. Each reads the fields it understands and ignores the rest: the Go simulator doesn’t care about x/y layout coordinates or parents lineage. The RDF reading of the file matters at one point, sealing, described below.
Declarative data lets a reader skip what it does not use. In a format where the order of fields implies a processing sequence, or where consumers must execute embedded logic to reconstruct the data, skipping a step changes the result. Here the @context fixes what each term means, and each consumer decides what to do with it.
Monotonic Expansion
The pflow.xyz context, served at https://pflow.xyz/schema from public/schema in the pflow-xyz repository, has this history there:
| Commit date | Terms added |
|---|---|
| 2025-10-24 (first version in the repository) | PetriNet, Place, Transition, Arrow; marking and layout terms (initial, capacity, weight, inhibitTransition, x, y); the seal vocabulary (PetriNetSeal, InvariantClaim, Signature, PetriRuntime, TransitionFireEvent) |
| 2026-02-06 | net types (WorkflowNet, ResourceNet, GameNet, ComputationNet, ClassificationNet) and composition (CompositeNet, links, DataLink, EventLink, TokenLink, GuardLink); then claim and bound for invariant claims |
| 2026-06-12 | parents, the ordered list of CIDs a net derives from |
Each change added terms. The file’s git history shows no term removed or redefined; the only deleted lines, on 2026-02-14, were comments that had made the file invalid JSON. A model that uses only the October 2025 terms is still valid under the current context, and the reason is structural: the context only grows.
This is monotonic expansion: new facts can be added, but existing facts are never retracted. It’s the same discipline that makes append-only logs reliable and RDF graphs composable — and the same property the history places of Chapter 6 have. A schema that only grows is a past-tense object, like an event log or a write-once place: once absorbed, a fact never changes.
Practically, adding terms cannot break an old model. A net saved before CompositeNet existed still loads in an editor that understands composition; the editor sees a net that composes with nothing — a valid state. The additions needed no migration scripts, no version negotiation, no “this file was created with an older version” warnings. What can break an old model is a change to a reader, and that is what the editor-shape goldens above guard against. The schema’s structure keeps old models meaningful; the goldens keep the readers reading them the same way.
Content Addressing via Canonicalization
If JSON-LD is declarative, its identity should derive from what it says, not from how it was serialized. Two documents that make the same assertions — regardless of key order, whitespace, or field arrangement — should hash to the same value.
The URDNA2015 algorithm (RDF Dataset Normalization) makes this possible. It converts any JSON-LD document into a canonical set of N-Quads — sorted, deterministic, order-independent. From there, a standard hash produces a content identifier. The pflow-xyz sealer, SealJSONLD in internal/seal/seal.go, does exactly this (excerpt; error handling and the type assertion around m elided):
delete(m, "@id") // m is the parsed document; its own @id is not part of the preimage
proc := ld.NewJsonLdProcessor()
opts := ld.NewJsonLdOptions("")
opts.Format = "application/n-quads"
opts.Algorithm = "URDNA2015"
opts.DocumentLoader = cachedLoader // serves a fixed pflow.xyz context, no network fetch
normalized, _ := proc.Normalize(doc, opts) // canonical N-Quads
multihash, _ := mh.Sum([]byte(normalized.(string)), mh.SHA2_256, -1)
c := cid.NewCidV1(cid.DagJSON, multihash) // CIDv1, dag-json codec
cidStr, _ := c.StringOfBase(multibase.Base58BTC) // base58btc, "z" prefix
The resulting CID becomes the model’s @id — a self-certifying identifier. The sealer removes any existing top-level @id before hashing; otherwise the identifier would be part of its own preimage and re-sealing a stored file would give a different answer. It also resolves https://pflow.xyz/schema against a context compiled into it rather than fetched, so a CID cannot change because the served schema grew. If the model changes, the CID changes. If two independently created documents make the same assertions, they get the same CID. Identity follows from content, not from a registry or a counter.
What counts as content is decided by the context. x, y and parents are terms in the sealing context, so layout and lineage are assertions too: moving a place on the canvas changes the CID, and so does adding a parent or reversing the order of two. Reordering keys or whitespace does not.
These properties are tested in pflow-xyz, not just argued. cid_consistency_test.go seals one net with its keys in two different orders, and again after re-marshaling through Go’s encoding/json, and requires a single CID. In parity_test.go, TestSealIgnoresTopLevelID requires that adding or changing @id leaves the CID alone, and TestParentsLineageContract requires that parents, and their order, change it. The layout half of the previous paragraph follows from x and y being in the context; no test pins it. Finally, the browser’s sealer (public/seal-cid.mjs) and the Go sealer must both reproduce the CIDs recorded for six fixtures in parity/golden.json; the coffee-shop fixture, for instance, seals to z4EBG9jDsuUdvVN4bUXRHxoDG3p274FfhcJd8BiruRcE1jLCHi8 in both languages. make test-parity runs both sides. We have not re-run these tests for this chapter.
This is what makes a seal checkable: a seal is a commitment to a specific graph, and any party can verify it by re-canonicalizing and re-hashing.
The Pipeline
JSON-LD document
v strip the top-level @id
v expand (resolve @context against the fixed copy)
v normalize (URDNA2015 -> canonical N-Quads)
v hash (SHA-256 multihash)
v encode (CIDv1, dag-json codec, base58btc)
Content-addressed identifier
Every step is deterministic. Two parties processing the same assertions — even serialized differently — arrive at the same CID, which is what the JS/Go golden check above demonstrates on six fixtures.
The Categorical View
There is a categorical reading of what @context does, and it should be stated at the strength it has been checked, which is not much. A JSON-LD context maps local terms (short names like Place, Transition) to global IRIs (like https://pflow.xyz/schema#Place):
Read as a functor between discrete categories, this is a function and nothing more. Extending a context — adding mappings while keeping the old ones — makes the old map the restriction of the new one to the old terms. The source blog post calls this a natural transformation; making that precise needs more structure on LocalTerms than a set of names, and nobody has written it down, so treat it as an analogy.
Combining vocabularies needs the most care. The IRIs of pflow.xyz, schema.org and ActivityStreams are namespace-disjoint, so on the global side the three behave like a coproduct. The local names are not disjoint: schema.org’s context defines Place and Person, and ActivityStreams also defines Person. When a document lists several contexts, JSON-LD processes them in order and a term defined more than once takes its last definition. Combining contexts is ordered override, not a disjoint sum. Cross-Vocabulary References, below, shows where that bites.
Canonicalization supplies identity. URDNA2015 gives isomorphic RDF graphs the same canonical N-Quads, so — under the same context, and up to hash collision — two documents share a CID exactly when they assert the same graph.
Connecting to Petri Nets
The declarative and monotonic properties of JSON-LD mirror properties of Petri nets themselves:
Declarative. A Petri net model is a declaration of structure — places, transitions, arcs. It doesn’t prescribe an execution order or processing sequence. The firing rule determines what happens at runtime, but the model itself is static assertions about what’s possible. JSON-LD serializes these assertions without adding procedural content.
Monotonic — at the level of the document. Adding a place or transition to a Petri net doesn’t invalidate existing structure. New arcs can reference existing elements. A model that gains a field stays readable by tools that ignore it. This mirrors monotonic schema expansion: new terms never break existing ones.
The mirror stops at behavior. A document can only grow, but a composed net can shrink: linking two subnets (Chapter 4) restricts what each can do, because a link is a rendezvous or a gate rather than an addition (see “Composition Preserves Safety, Not Liveness” in Appendix E: Categorical Foundations). Monotonic serialization and monotonic semantics are different claims, and only the first one holds here.
Content-addressable. The canonicalized form of a Petri net model — sorted N-Quads — produces its identifier. Two documents with the same assertions, however they were authored or serialized, get the same CID; two nets with the same places and arcs but different layout or lineage do not, because layout and lineage are assertions too. Given a CID, you can verify that a model hasn’t changed.
Practical Implications
Model Interchange
A model created in the pflow.xyz visual editor (JavaScript) can be:
- Saved as JSON-LD with
@context: "https://pflow.xyz/schema" - Loaded by go-pflow for ODE simulation and analysis
- Converted by go-pflow’s
parser.ModelFromJSONinto themetamodel.Modelthat sim.pflow.xyz stores and runs (Chapter 18) - Sealed with a content-addressed CID for immutable reference
- Shared via URL, embedded in a page as a
<petri-view>element, or stored under its CID (the three example nets in pflow-xyz’sexamples/directory are stored under file names that are their CIDs, the same valuesparity/golden.jsonrecords for the coffee-shop, net-a and net-b fixtures)
Nobody converts the file between steps. Each tool converts it into its own internal form on read, but the file that travels is the same file, with the same assertions, consumed by different tools for different purposes.
Schema Evolution
When the net-type and composition terms arrived in February 2026, existing models remained valid — they are nets that don’t compose with anything. go-pflow’s composition code makes the same guarantee from the other side: a bundle holding one subnet and no links flattens back to exactly that net (TestFlattenIdentity in metamodel/compose_test.go). The readers handle the absence of new terms because a missing field is unknown, not invalid — JSON-LD’s open-world reading, which the readers implement by ignoring keys they do not use.
Cross-Vocabulary References
A pflow.xyz file can use schema.org terms without listing a second context. The served pflow.xyz context sets @vocab to https://schema.org/, so any key it does not define resolves there. Saved editor files use this for authorship (trimmed from parity/fixtures/net-a.jsonld):
{
"@context": "https://pflow.xyz/schema",
"@type": "PetriNet",
"author": {
"@type": "Person",
"identifier": "https://github.com/stackdump",
"name": "stackdump"
},
"places": { ... }
}
PetriNet is defined by the pflow.xyz context; author, Person and name are not, and fall through @vocab to schema.org. (The context compiled into the two sealers sets @vocab to https://pflow.xyz/schema# instead, so inside a CID’s preimage these terms land in the pflow namespace. Identity is unaffected, since every sealer uses the same fixed context, but the served and sealing contexts do not agree on these terms. Nor do they agree on transitions, arcs, source and target: the sealing context defines them in the pflow namespace, while the served context leaves them to @vocab as well.)
Listing both contexts explicitly, as ["https://pflow.xyz/schema", "https://schema.org"], would be a mistake. schema.org’s context defines Place; as the later definition it would win, and every place in the net would expand to schema.org’s geographic Place. Order matters when contexts are combined, which is the ordered override described in the categorical section above.
Infrastructure, Not a Feature
JSON-LD works as infrastructure for the pflow ecosystem because its job is narrow. The file states assertions and the context fixes what its terms mean; what to do with them is left to each consumer.
That division is what lets independent tools share one file. The model format does not know about editors, solvers or code generators; it describes a Petri net, and each consumer reads the places, transitions and arcs it needs.
The book’s argument about Petri nets — a small set of primitives that combine to model a wide range of systems — applies to their serialization as well. Three JSON-LD keywords (@context, @type, @id) carry the self-description, the typing and the content address of a pflow model; the complexity lives in the applications.
The Visual Editor — pflow.xyz
Learning objective: Design nets visually, export to JSON, and iterate on models interactively.
Parts I through III approached Petri nets through code and mathematics: builder APIs, incidence matrices, ODE solvers. A Petri net also has a standard drawing, with circles for places, rectangles for transitions and arrows for arcs, and the pflow.xyz editor makes that drawing the primary interface. You draw a net, and the editor keeps the JSON-LD document behind it (topology, initial marking, layout) in step with the canvas.
This chapter walks through the editor: how to build nets interactively, how the visual representation maps to the mathematical formalism, and how models travel between the editor and the rest of the ecosystem.
The Editor Interface
The pflow.xyz editor is a custom HTML element, <petri-view>, defined in public/petri-view.js together with a few sibling ES modules: the firing rules in petri-sim.js, the ODE solver in petri-solver.js, CID computation in seal-cid.mjs. It is plain JavaScript with no framework and no build step; its one third-party library, jsonld, is vendored as a pre-built bundle. It provides:
- Toolbar — six editing modes (select, place, transition, arc, token, delete; keys 1–6), a label-edit toggle (7), and a play button that runs the discrete simulation (8 or X)
- Canvas — the drawing area, with pan, zoom, multi-select and undo/redo
- JSON editor — an optional panel showing the model as JSON-LD, editable in place
- Analysis workbench — continuous-time (ODE) simulation, rate scans, sweeps and phase plots, opened from the menu or with key 9
Models are JSON-LD documents with "@context": "https://pflow.xyz/schema" and "@type": "PetriNet". If a loaded document lacks them, the editor fills them in, along with @version and a default token list.
The Web Component
The entire editor is a custom HTML element. A page loads the module and its stylesheet, and gives the element its model as a child JSON-LD script:
<link rel="stylesheet" href="https://pflow.xyz/petri-view.css"/>
<script type="module" src="https://pflow.xyz/petri-view.js"></script>
<petri-view data-json-editor>
<script type="application/ld+json">
{"@context": "https://pflow.xyz/schema", "@type": "PetriNet", ...}
</script>
</petri-view>
The component reads that script when it connects to the page and writes every edit back into it, so the page always holds the current document; it also autosaves to the browser’s local storage. Scripts can call getModel(), setModel() and importJSON(), and listen for transition-fired-success and marking-changed events (see the pflow-xyz README). Because it is an ordinary element, the editor can be embedded in any web page: documentation, tutorials, other applications.
Drawing Nets: Click-to-Place Workflow
Building a Petri net in the editor follows a direct manipulation pattern:
Adding Elements
-
Place: Choose place mode (key 2) and click the canvas. A circle appears with a generated id,
pfollowed by a base-36 timestamp. Label mode (key 7) gives it a readablelabel. -
Transition: Choose transition mode (key 3) and click the canvas. A rectangle appears, with an id beginning
t. Label it with the action it represents. -
Arc: Choose arc mode (key 4), click a source, then click a target. The editor asks for a weight (default 1) and adds the arc. Right-clicking the target, or long-pressing it on a touch screen, makes an inhibitor arc instead: one that disables its transition while the place holds at least the arc’s weight in tokens. Inhibitor arcs are contextual arcs; Appendix E: Categorical Foundations explains why they sit outside the algebra the rest of the net obeys.
-
Tokens: In token mode (key 5), click a place to add or remove tokens; right-clicking a place does the same. A place shows a single dot when it holds one token and a numeral when it holds two or more.
The Bipartite Constraint
The editor enforces the bipartite structure that defines a Petri net: an arc connects a place to a transition or a transition to a place, never two nodes of the same kind. The firing rule, the conservation laws and reachability analysis all assume it.
If, in arc mode, you click a place and then another place, the editor flashes both and discards the draft (_arcNodeClicked in petri-view.js). The check runs when you draw. The file format does not encode the restriction: an arc in the JSON is a source id and a target id, and a hand-edited document could name two places.
Weighted Arcs
Arc weights default to 1. Resource models like the coffee shop (Chapter 5) need higher weights: there, an espresso consumes 18 g of beans and 30 ml of water. Set the weight when the editor prompts for it, or right-click an existing arc to change it. The weight appears as a badge on the arc; by default the badges are hidden while every arc in the net has weight 1.
From Visual to Formal
Each editing action writes a corresponding change into the JSON-LD model:
| Visual Action | Formal Effect |
|---|---|
| Click the canvas in place mode | A new entry in places: {"@type": "Place", "initial": [0], "x": …, "y": …}, with an unbounded capacity |
| Click the canvas in transition mode | A new entry in transitions: {"@type": "Transition", "x": …, "y": …} |
| Draw an arc from beans to brew, weight 18 | {"@type": "Arrow", "source": "beans", "target": "brew", "weight": [18], "inhibitTransition": false} |
Counts and weights are arrays because a net can carry several token colours, one array entry per colour in the token list; a single-colour net uses one-element arrays.
The editor stores x/y coordinates for layout. They do not affect firing or the ODE, so two models with identical topology but different layouts behave identically. They are still different documents, and they get different CIDs (see Content-Addressed Storage below).
The JSON-LD Model
A small model in the editor’s format, with readable ids and the espresso weights from Chapter 5. It is trimmed by hand: a file saved by the editor also carries capacity and offset on every place. For a file exactly as saved, see parity/fixtures/coffee-shop.jsonld, a different, three-colour coffee-shop net.
{
"@context": "https://pflow.xyz/schema",
"@type": "PetriNet",
"@version": "1.1",
"token": ["https://pflow.xyz/tokens/black"],
"places": {
"beans": { "@type": "Place", "initial": [1000], "x": 100, "y": 200 },
"water": { "@type": "Place", "initial": [10000], "x": 100, "y": 300 },
"espresso": { "@type": "Place", "initial": [0], "x": 300, "y": 250 }
},
"transitions": {
"brew": { "@type": "Transition", "x": 200, "y": 250 }
},
"arcs": [
{ "@type": "Arrow", "source": "beans", "target": "brew", "weight": [18], "inhibitTransition": false },
{ "@type": "Arrow", "source": "water", "target": "brew", "weight": [30], "inhibitTransition": false },
{ "@type": "Arrow", "source": "brew", "target": "espresso", "weight": [1], "inhibitTransition": false }
]
}
This file can be:
- Loaded back into the editor (visual round-trip)
- Parsed by go-pflow’s
parserfor ODE simulation (Chapter 3) - Converted by go-pflow’s
parser.ModelFromJSONinto themetamodel.Modelformat that sim.pflow.xyz stores and runs (Chapter 18) - Sealed with a content-addressed CID (Chapter 16)
- Shared via URL
In-Browser Simulation
The editor runs both simulations in the browser, so you can draw a net, press play, and watch the marking change.
Discrete-Event Mode
Step through the model one transition at a time. The editor fills enabled transitions (those with sufficient input tokens) green; click one to fire it, and the token counts update immediately. The play button fires enabled transitions automatically. Stepping by hand is the quickest way to learn the firing rule, to trace one execution path, or to find out why a transition you expected to fire is not enabled.
Continuous-Time Mode
The Analysis workbench integrates the ODE forward. Token counts become continuous values, so a place might hold 47.3 tokens. Its Simulate tab plots how each place’s count evolves over the time span, alongside a table of initial and final values; the other tabs scan one rate, overlay trajectories across rate values, and plot one place against another.
The workbench uses the same Tsit5 solver as go-pflow, with the same mass-action kinetics: each transition’s flux is its rate times the product of its input places’ token counts, and arc weights scale how much is consumed (Chapter 3). A model designed in the browser therefore has the same dynamics when loaded into the Go library. Chapter 20 covers this dual-implementation requirement in general.
Matching Go and JavaScript
The browser solver (public/petri-solver.js) uses the same defaults as go-pflow’s DefaultOptions (solver/ode.go):
- Adaptive stepping with Tsit5
- dt = 0.01, dtmax = 0.1, abstol = 1e-6, reltol = 1e-3
- Time span configurable via controls
A model that behaves differently in the browser and in Go is a bug, and two tests in the pflow-xyz repository exist to catch one. parity/ode/ode_parity_test.go integrates a fixed set of fixture models with both solvers and requires the final states to agree within a relative tolerance of 1e-6 per place; the file records the measured agreement as about 1e-15, because the two implementations take the same steps. parity/sim/sim_parity_test.go does the same for discrete firing: it walks 200 seeded random models through petri-sim.js and go-pflow’s reachability engine in lockstep and compares the enabled sets and markings at every step. Both run under make test-parity-behavior and need node; they were not re-run for this chapter.
Export Formats
The editor supports multiple export paths:
JSON-LD
The native format. The menu’s Download JSON item saves the model, including its x/y layout, as a file named after its CID. The other pflow tools read this format, either directly or through a converter such as parser.ModelFromJSON.
SVG
SVG comes from the Go backend rather than from the editor’s canvas. GET /img/{cid}.svg renders any stored model, and POST /api/svg renders a posted document; the renderer is internal/svg/svg.go. Without a layout parameter it draws the model at its stored coordinates. With one, it rearranges the net first, using the same algorithms the editor’s Layout Algorithms menu applies to the canvas: circular, sugiyama (layered), grid, bipartite and string-diagram. The editor’s own SVG download is the one inside its String Diagram view.
Content-Addressed Storage
When you save to the pflow.xyz server (the editor’s Save asks you to log in with GitHub first; the POST /api/save endpoint itself also accepts an anonymous document and stores it with no author), the server canonicalizes the model with URDNA2015 and hashes the result into a CIDv1: dag-json codec, SHA-256, base58btc, so every CID begins with z (Chapter 16):
POST /api/save -> { "cid": "z4EBG9j..." }
GET /o/{cid} -> { "@context": "https://pflow.xyz/schema", ... }
The editor computes the same CID in the browser with seal-cid.mjs; that is how Download JSON names its file. The Go and JavaScript sides are held to byte-identical CIDs by parity/golden.json, six fixtures with their expected CIDs, which make test-parity checks from both languages.
The CID is derived from the model’s content, not from a counter or timestamp, so two people who produce the same document get the same CID. “The same document” is strict. The coordinates and labels are part of the sealed content, so moving a node changes the CID even though it changes nothing about how the net behaves. Within that limit, the CID supports deduplication and verifiable references.
Sharing and Embedding Models
URL Sharing
A saved model opens in the editor at https://pflow.xyz/?cid={cid}; GET /o/{cid} returns the stored JSON-LD itself. Because the identifier is content-addressed, the document behind a CID cannot change. It can disappear: the author of a saved model can delete it (DELETE /o/{cid}). Without logging in, Save Permalink writes the model into the page URL instead of storing it on the server.
Embedding in Web Pages
The <petri-view> element shown earlier can be embedded in any HTML page. An embedded element is the same component as the full editor, with the same simulation; server saving and GitHub login appear only when the element carries the data-backend attribute.
Blog posts at blog.stackdump.com link to models instead of embedding the component. The editor’s Share dialog produces the snippet they use: the server-rendered SVG wrapped in a link to the editor.
[](https://pflow.xyz/?cid={cid})
SVG Generation via API
The rendering endpoint takes the stored model’s CID and an optional layout:
GET /img/{cid}.svg
GET /img/{cid}.svg?layout=circular
GET /img/{cid}.svg?layout=sugiyama
An unrecognized layout name is logged and the model is drawn at its stored positions. The server marks each response cacheable for a year, which suits generated documentation and CI pipelines: the model behind a CID does not change.
The Editor as a Design Tool
A model often begins in the visual editor. A domain expert sketches places and transitions — “there’s a waiting room, a triage station, a doctor’s office” — and connects them with arcs. The initial model is rough but captures the essential structure.
Then iteration: add initial tokens, set arc weights, run a simulation, observe the dynamics. “The tokens pile up before the doctor — that’s the bottleneck.” Adjust rates, add a second doctor transition, simulate again. Because the model is on screen while it runs, this loop can be quicker than editing code.
Once the model stabilizes, it travels through the ecosystem:
- Editor — design and iterate visually
- go-pflow — run formal analysis (reachability, P-invariants, sensitivity)
- sim.pflow.xyz — run seeded what-ifs and check verdicts against the stored model
- ZK circuit — derive a circuit from the same net when its firings need to be proved (Chapter 12)
The circles and rectangles on screen are the same places and transitions that appear in incidence matrices, ODE systems and ZK circuits. The drawing is one view of a document that the other tools also read.
Try it live: Design your own Petri net at pflow.xyz, then see stored models run as seeded what-ifs at sim.pflow.xyz.
sim.pflow.xyz — From Description to Checked Model
Learning objective: Store a Petri net model in a hosted service, run it as a seeded what-if, and get verdicts about it that someone else can re-check.
The visual editor (Chapter 17) produces a model. The Go library (Chapter 19) analyzes it. Between the two sits a practical question: once a model exists, where does it run, and how does someone who did not build it decide whether to believe what it says? sim.pflow.xyz is a hosted answer. You give it a model, written by hand or derived from a plain-language description or from source code, and it stores the model under a content address. You can then run seeded scenarios against it, compare them on a shared seed, rank its knobs by measured influence, and verify structural properties, with every verdict saying how far it reaches.
This chapter describes that service: its surfaces, the path a model takes through it, and the line it draws between what an engine can read and what it refuses to guess. The engines underneath are go-pflow’s, at v0.34.0, the version sim’s go.mod pins: the discrete and continuous simulators in stochastic, the model type in metamodel, the property checker in verify. sim’s own source is not public, so the chapter cites its tools and HTTP routes, which anyone can call, and links go-pflow where go-pflow does the work. Tool behaviour is quoted from the tool descriptions the MCP server publishes; the example outputs below are real calls against the live service, rounded for the page.
The Surfaces
sim.pflow.xyz is one service with three ways in:
| Surface | Where | What it is for |
|---|---|---|
| MCP server | https://sim.pflow.xyz/mcp | sim_* tools for an LLM client: store, run, diagnose, verify, prove, publish |
| HTTP API | https://sim.pflow.xyz/api/... | The same reads per model (/api/models/{id}/scenario, /diagnose, /verify, …), CORS-open |
| Consoles | /whatif/?id={id}, /build/ | A generic what-if console for any stored model, and a guided builder |
Connecting an MCP client is one line:
claude mcp add --transport http sim https://sim.pflow.xyz/mcp
Read tools (listing and fetching models, scenarios, comparisons, diagnosis, verification, invariants, reachability, witness checks) work without signing in, and the ones that run an engine are rate-limited per client. Storing a model also works without signing in, but the model is then stored unowned. Every other tool asks for OAuth the first time it is used: those that store something under your name, call an LLM or publish to Google Sheets, and also sim_receipt, sim_canonical and sim_prove. The service’s llms.txt lists every tool and route; this chapter covers the ones that make up the main path.
The Pipeline
description / source code / hand-written JSON
|
| sim_generate, sim_code_to_flow, /build/, POST /api/models
v
model (JSON, content-addressed, immutable)
|
+--> sim_scenario, sim_compare seeded runs, shared-seed comparison
+--> sim_diagnose knobs ranked against a noise floor
+--> sim_verify, sim_invariants proved / refuted / unknown
+--> sim_crosscheck independent readings, agreement or divergence
+--> sim_receipt a signed run anyone can replay
+--> sim_publish_app, sim_publish a single-file app, a Google Sheet
Every arrow out of the model is a read. Running a scenario cannot change the model, and a changed model is a different model.
Step 1: The Model
A model is a go-pflow metamodel.Model in JSON: places, transitions and arcs, plus optional blocks that sim’s engines read, such as capacities on places, rates, stages and a schedule on transitions, declared parameters, and a simulation.objective. Appendix C documents the format.
{
"name": "toggle",
"places": [{"id": "off", "initial": 1}, {"id": "on"}],
"transitions": [{"id": "switch", "rate": 1.0}],
"arcs": [{"from": "off", "to": "switch"}, {"from": "switch", "to": "on"}]
}
It is stored with sim_create_model or POST /api/models. Signed in, sim_create_model stores it as yours; without sign-in, either route stores it unowned for good: reachable by anyone holding its id, listed for nobody, and deletable by nobody. The id is a content address: the first 24 hex characters (96 bits) of the sha256 of the model’s canonical JSON. Two uploads of the same model are the same model, an id can be cached forever, and nothing is mutated. Editing a model means storing a new one; sim_extend records the edit with lineage, and sim_supersede_model points the listing at the successor without moving anything else.
Storing refuses rather than guesses. The decoder reads the legal keys from go-pflow’s Go type by reflection and refuses any key the model schema does not define, naming each with its path and the key it most likely meant: places[0].intial comes back with a suggestion of initial. The reason is written into the decoder: Go’s JSON decoder silently drops an unknown key, so a misspelt initial would have stored a net with an empty place, and every run of it would have reported zeros with full confidence. Structural validation then reports every defect at once instead of the first one: a model with no name, places or transitions, a duplicated id, an arc whose endpoint does not exist, and go-pflow’s own checks on arcs, parameters and schedules. It gates structure, not quality. A well-formed net is storable whether or not it is a good model of anything.
Step 2: Getting a Model Without Writing JSON
Three routes produce a model from something less formal. All three end in the same store, under the same validation.
From a description. sim_generate asks the deployment’s LLM to write a net from plain-language requirements (“a lunch counter with two cooks and a ten-seat queue”). Each answer is checked as it arrives: it must decode, pass the validator, and then pass behavioural checks for disconnected parts, transitions that never fire, places nothing fills, and any place ids the caller required. Whatever is wrong is shown back to the LLM, and it answers again, up to retries times (0–4, default 2). best_of (1–5) starts again from scratch when a sample still has problems and stops at the first clean one. selfcheck asks the LLM to play its own net forward and replays that play against the net, which catches inconsistency, though not a wrong idea. A net that decodes and validates is stored even when behavioural problems remain. The response says whether it is clean and lists the problems, so a stored model is not a passed model.
From source code. sim_code_to_flow takes a code snippet, a language hint and a focus (control-flow, the default, or state-machine, resources or concurrency) and derives a net from it with the same LLM. The answer goes through the same decoder as a hand-written model, then a stricter validator that also explores the net’s reachable states with go-pflow’s reachability package. When the answer validates, it is stored as a new model; when it does not, the raw JSON and the validation errors come back so the caller can fix it and store it by hand.
Interactively. The builder is a guided conversation that edits a draft. After each turn it explores the draft’s reachable markings through go-pflow’s own firing rule (Model.Enabled and Fire in metamodel/firing.go), so its findings about dead transitions, unreachable places, deadlocks and unbounded growth are the engine’s answer and not a second reading of the arcs. The exploration is bounded by a state count, a time budget and the request. When a bound is hit, claims that need the whole space (“this never fires”) are withheld rather than guessed.
Both LLM routes are only as good as the model they call, and both need a deployment with an LLM provider configured. The checks bound what a wrong net can get away with structurally. They cannot tell whether the net describes the process the caller had in mind. That is what the instruments in the next steps are for.
Step 3: Run It
sim_scenario runs a seeded what-if: marking overrides (“three staff instead of two”), rate overrides, piecewise rate schedules, and values for the model’s declared structural parameters. Unset fields default to 8 hours, 16 realizations and seed 20260809. The service refuses, and does not clamp, more than 200 realizations, 10,000 hours or 5,000 samples. The result carries the trajectory (mean and standard deviation per place on a sample grid), final marking, time-weighted metrics, the places that ran out, contention, and the caveats and assumptions the engine wants the reader to see.
The default engine is go-pflow’s discrete stochastic simulator (stochastic.Simulate, Gillespie’s algorithm), which fires one event at a time. "engine": "ode" asks for the continuous mass-action reading (stochastic.Forecast) instead, and this is where the rule from Chapter 3 becomes an API: Forecast checks the model’s gating (Model.Gating() in metamodel/firing.go) and refuses a net with, among other things, a read arc, an inhibitor, a reachable capacity, a guard or a non-kinetic arc, because the ODE has no firing instant at which to test any of them. Asking for the ODE on the café in sim’s catalog returns a refusal, not a curve:
diverged: true
reason: this model constrains firing in ways a continuous solution cannot
express, so the ODE would silently model an unconstrained system. Use the
discrete engine (Simulate). Specifically: 17 non-kinetic input arc(s) gate
and consume without scaling the rate; ... capacity is declared on
[pantry/coffee_beans pantry/milk pantry/cups] but is a post-firing bound,
which has no continuous analogue
sim_compare runs up to 20 scenarios against one model on one seed. The server enforces the shared seed, so a difference between two results comes from the scenarios and not from the random numbers. On the same café, which stores two tokens on staff/available, the scenarios [{"name":"two staff"},{"name":"three staff","marking":{"staff/available":3}}] with the default eight hours and 16 realizations give:
| Scenario | Orders complete | Walked out | Staff utilization |
|---|---|---|---|
| two staff (as stored) | 169 ± 6 | 89 ± 13 | 0.80 |
| three staff | 217 ± 12 | 43 ± 14 | 0.68 |
The ± figures are the spread across realizations at the horizon, which the result reports beside each mean. The run also says what it assumed: every step takes an exponentially distributed time, the most erratic a shop can be for a given average, so the result labels its queues and walkouts as the bad case rather than the typical one.
Step 4: Diagnose It
A comparison answers a question the modeler thought to ask. sim_diagnose asks every such question at once: what one more of each resource, and a change in each rate, is worth to the outcome, each ranked against a measured noise floor. The ranking is derived from the net, so a new model gets its fitness checks by existing, with no test written first. The report also covers generic gates (mass balance, dormant sources, a staffing knee, whether any knob binds at all) and structural readings that need no run: T-invariants, siphons and traps with deadlock witnesses, and lumpability.
The sample size adapts. Leave realizations unset, and the diagnosis starts with 24, doubling while the baseline outcome sits inside its own noise floor, up to 200. The report records where it settled and why. An explicit count is used exactly. The service’s documentation reports that this pass has found capacity that does nothing (a café’s pantry stock, a hospital’s emergency bays) and, in a software-team model, capacity past which more engineers make the objective worse. Those are claims about specific catalog models, not general laws, but they are the kind of finding the tool exists to produce: “add more” gets measured instead of assumed. How a knob’s influence is scored depends on what the model counts as success, which sim_diagnose infers from place tags or reads from a declared simulation.objective.
Step 5: Verify It
Simulation samples behaviour. Verification makes claims about all of it, and sim keeps the two apart.
sim_verify checks declared properties: deadlock-free, bounded, live, terminating, conserves, mutual exclusion, a linear invariant over place counts, and reachable or unreachable target markings. It runs through go-pflow’s metamodel/metapetri bridge, which converts the model into an analysable net and records what the conversion could not express, and go-pflow’s verify package. Each verdict is proved, refuted or unknown. Unknown is never a pass, and the report’s ok is true only when every property is proved. Each verdict also carries a method, which says how far it reaches:
| Method | Meaning |
|---|---|
structural | From the incidence matrix with no state search; a structural bounded holds for every initial marking |
exhaustive | Every state reachable from this initial marking |
witness | A firing sequence found by targeted search, decisive for this marking |
partial | The search was truncated, so only a refutation is sound |
Run with the defaults (bounded and deadlock-free) on the same café, it returns one of each kind you would rather not see:
bounded refuted witness counter/pending_espresso grows without bound
trace: [counter/order_espresso]
deadlock-free unknown partial no deadlock in the states explored, but the
state space was truncated
Both verdicts are correct. Customer arrivals are a transition with no input place, so the net is open and its queue has no structural bound. The model relies on abandonment rates, not on structure, to keep the queue short, and the verifier says so with a one-step counterexample. The unbounded queue also means the state space cannot be exhausted, so deadlock freedom stays unknown and is not reported as a pass. The caveats list the three pantry capacities, carried into the analysis as post-firing bounds.
sim_invariants returns the algebra on its own: the P-invariants (conservation laws, from Farkas’ algorithm), the T-invariants (firing cycles), and the minimal siphons and traps, including any siphon empty at the initial marking, which proves every transition that needs it permanently disabled. The P-invariants are the conservation laws of Chapter 2, computed for whatever model you stored.
sim_crosscheck runs every applicable reading of a model against the others: discrete means against the mean-field solve, derived conservation laws against simulated means and, for game models, the closed-form incidence ranking against rollouts and exact search. A divergence is a finding, not an error, and the tool names its likely cause, such as a small-count mean-field gap or a heavy arc weight, which gets a different rate law under each engine. Gated nets have no ODE reading to compare against at all.
Step 6: Results Someone Else Can Check
Three mechanisms let someone other than the modeler check a result.
Determinism. Models are immutable and scenarios are pure, seeded reads, so the same scenario body against the same model id on the same surface returns the same answer, byte for byte. The HTTP and MCP surfaces fill unset fields differently (an HTTP scenario defaults to one hour, one realization and seed 0, and an HTTP comparison to seed 1), so a comparison across surfaces must set them explicitly.
Receipts. sim_receipt (signed in) or POST /api/models/{id}/receipt (anonymous) runs a scenario and returns, with the result, an Ed25519 signature over the model id, the scenario as run (defaults filled in), a hash of the result, and the service revision. The signature can be checked offline against the public key at /api/receipts/key, which shows the service reported this result. POST /api/receipts/verify with "replay": true replays the run and confirms that the result hash reproduces, which shows the result was not invented. Neither check needs an account.
Witnesses. The structural tools record their claims as edges with evidence that can be re-checked. sim_canonical computes an isomorphism-invariant id from a model’s exact automorphism orbits, so two differently labelled copies of one net can be recognised. sim_prove decides isomorphicTo, subnetOf, preservesInvariant or refines between two stored models. A proof is stored with a witness: a map, a map with an invariant cover, or a simulation relation. A refutation carries a counterexample, and a search that runs out of budget answers unknown and records nothing. sim_reach asks whether one marking can be reached from another in a stored net. It answers no with a separating P-invariant or an exhaustive search, yes with a replayable firing trace, or unknown, listing which budget stopped it. sim_check_witness re-checks any of these against the stored models, without searching again.
From Model to Application
A model in go-pflow’s format can carry a view: prose, addressed to whoever builds an application on the model, that says what the application should be (“let two players play on the board; a click fires that cell’s move transition”). Nothing executes it. It is part of the model’s content hash because the same net presented as a game and as a dashboard is two different artifacts, and the id should say which one you have.
sim_publish_app publishes the single-file HTML application written from that view, by a person or an LLM, and serves it at https://sim.pflow.xyz/app/{id}. The intended starting point is the runtime, not a blank page: /lib/app-template.html is a working console composed of the same web components the generic console runs, so an application built from them inherits the console’s role derivation, influence ranking and caveats instead of reimplementing them. The app is served in a sandboxed origin with no cookies and no session, under a Content-Security-Policy that confines scripts, styles and fetches to sim’s own origin, so it can reach only the public API. The upload checks refuse an empty or oversized document, one that never mentions its model id, and one that loads scripts or styles from elsewhere. Whether the app does what the view says is not checked; that responsibility stays with whoever wrote it.
For readers who would rather have a spreadsheet than an app, sim_publish and sim_publish_compare write a scenario or a shared-seed comparison into the caller’s own Google Sheet, with charts.
The Complete Workflow
A typical session with sim.pflow.xyz:
- Describe — write the model as JSON, or derive it with
sim_generate,sim_code_to_flowor the builder - Store —
sim_create_modelorPOST /api/models; read every reason the validator gives at once - Verify —
sim_verifyandsim_invariants; read the method on each verdict, and treat unknown as unknown - Run —
sim_scenarioon the discrete engine; ask for the ODE and read the refusal if the net is gated - Compare and diagnose —
sim_compareon a shared seed,sim_diagnosefor the knobs you did not think to ask about - Hand it over — a
sim_receiptfor the run that matters, a published app or sheet for the people who will use the answer
The model is the contract here too. Every run, verdict and receipt names the model’s content id, so a reader can always ask which net an answer came from, and get the same net back.
Try it live: The catalog lists every model in the commons, each with a what-if console. The Café used in this chapter, the Vet Clinic and Tic-Tac-Toe are good starting points.
The go-pflow Library
Learning objective: Use the core Go library for simulation, analysis, and integration.
The previous chapters used go-pflow implicitly — building nets, running simulations, analyzing results. This chapter makes the library itself the subject. It covers the package structure, the fluent builder API, solver configuration, and the higher-level abstractions (state machines, workflows, actors) that compile to, or describe themselves as, Petri nets.
The snippets below follow the go-pflow source but are not compiled as part of this book; where a test in the repository exercises the same calls, the section links it.
Package Overview
go-pflow is organized into packages that map to different concerns:
| Package | Purpose |
|---|---|
petri | Core types, fluent Builder API |
solver | ODE solvers (Tsit5, RK45, implicit), equilibrium detection |
stateutil | State map utilities (Copy, Apply, Merge, Sum, Diff) |
reachability | Discrete state space, deadlock and liveness analysis |
hypothesis | Move evaluation for game AI |
sensitivity | Parameter sensitivity analysis |
cache | Memoization for repeated simulations |
eventlog | Parse CSV/JSONL event logs |
mining | Process discovery (Alpha, Heuristic), rate learning |
monitoring | Real-time case tracking, SLA alerts |
statemachine | Hierarchical states compiled to Petri nets |
workflow | Task dependencies, resources, SLA tracking |
actor | Actor model with message passing |
visualization | SVG rendering |
tokenmodel | Token model schemas with DSL |
The table lists the packages this chapter uses. The library has more — stochastic simulation, declarative property checking (verify), parameter fitting (learn), the metamodel engine schema, the ZK prover — and the README’s package table lists them all with the chapter that covers each.
Decision Tree
| Problem | Package |
|---|---|
| Business workflows | workflow |
| Event-driven state machines | statemachine |
| Message-passing systems | actor |
| Game AI and move evaluation | hypothesis, cache |
| Parameter optimization | sensitivity |
| Process discovery from logs | mining, eventlog |
| Deadlock and liveness checking | reachability |
| Population dynamics (epidemics, ecology) | petri + solver |
| General state and resource flow | petri |
Building Nets
The fluent builder API (petri/builder.go) constructs Petri nets in a single expression:
net := petri.Build().
Place("A", 10).Place("B", 0).
Transition("t1").
Arc("A", "t1", 1).Arc("t1", "B", 1).
Done()
Each method returns the builder, allowing chaining. Place takes a name and initial token count. Transition takes a name. Arc takes source, target, and weight. Done returns the *petri.PetriNet. The builder also assigns each place and transition a screen position, left to right in the order they are added, which the SVG renderer uses later.
Chain Helper
For linear sequences — common in workflows — the Chain helper eliminates repetitive arc declarations:
net := petri.Build().
Chain(10, "start", "t1", "middle", "t2", "end").
Done()
This creates places start (10 tokens), middle, and end, transitions t1 and t2, and all connecting arcs, each of weight 1. The first argument is the initial token count for the first place. The element list must alternate place, transition, place and so end on a place; a list of the wrong length is ignored and the builder is returned unchanged.
Rates
Transition rates are separate from the net structure. The WithRates method assigns a default rate to all transitions:
net, rates := petri.Build().
Place("S", 100).Place("I", 1).Place("R", 0).
Transition("infect").Transition("recover").
Arc("S", "infect", 1).Arc("I", "infect", 1).Arc("infect", "I", 2).
Arc("I", "recover", 1).Arc("recover", "R", 1).
WithRates(1.0)
WithCustomRates(map[string]float64{"infect": 0.3, "recover": 0.1}) returns the net with a rate map you supply instead. The separation of structure and rates is deliberate — the same net can be simulated with different rate constants for sensitivity analysis or parameter fitting.
Shortcut Builders
Common model patterns have dedicated builders:
// SIR epidemic model
net, rates := petri.Build().SIR(999, 1, 0).WithRates(1.0)
This creates the susceptible-infected-recovered net from the previous snippet — places S, I, R, transitions infect and recover, the same five arcs — with the specified initial populations and a default rate of 1.0 for both transitions. TestBuilderSIR in petri/builder_test.go checks the places, transitions and arcs it produces.
Running Simulations
The solver package implements numerical ODE integration:
prob := solver.NewProblem(net, net.SetState(nil), [2]float64{0, 100}, rates)
sol := solver.Solve(prob, solver.Tsit5(), solver.DefaultOptions())
final := sol.GetFinalState()
NewProblem takes the net, initial state, time span, and rates. net.SetState(nil) returns the net’s initial marking as a map; passing a map instead overrides the places it names. Solve runs the integration. The result contains the full trajectory — token counts at each time step for every place. The rate law is the one from Chapter 3: From Discrete to Continuous: a transition’s flux is its rate times the product of its input places’ token counts, and arc weights scale how much each firing consumes and produces, not the kinetics (solver/ode.go).
Solver Methods
| Method | Description |
|---|---|
Tsit5() | Tsitouras 5(4) Runge-Kutta. Default choice. Adaptive stepping, high accuracy. |
RK45() | Dormand-Prince 5(4), the method behind MATLAB’s ode45. Similar to Tsit5, slightly different error estimation. |
ImplicitEuler(prob, opts), TRBDF2(prob, opts) | For stiff systems where explicit methods require impractically small steps. These are functions that return a solution directly, not a method passed to Solve. |
SolveImplicit(prob, opts) | Detects stiffness and chooses between explicit and implicit integration. |
RK4, Euler, Heun, Midpoint and BS32 are also available; Appendix A: Solver Parameter Reference describes each.
Tsit5 is the library’s default: Solve and SolveUntilEquilibrium fall back to it when passed a nil method, and the hypothesis and sensitivity packages call it internally. The adaptive step size shrinks where dynamics are fast (early transients) and grows where they are smooth (approaching equilibrium).
Solver Presets
| Preset | Use Case |
|---|---|
DefaultOptions() | General purpose — balanced accuracy and speed |
FastOptions() | Game AI, interactive use — looser tolerances, fewer steps |
AccurateOptions() | Research, publishing — high precision |
GameAIOptions() | Move evaluation — optimized for hypothesis testing |
EpidemicOptions() | SIR/SEIR models — tuned for population dynamics |
Each preset sets the Options fields: initial, minimum and maximum step size (Dt, Dtmin, Dtmax), tolerances (Abstol, Reltol), the iteration cap (Maxiters) and whether stepping is Adaptive. solver/ode.go defines further presets — StiffOptions, WorkflowOptions, LongRunOptions, and JSParityOptions for matching the pflow.xyz browser solver — and Appendix A tabulates every preset’s values. For most applications, DefaultOptions() works. For interactive use where latency matters more than precision, FastOptions() trades accuracy for speed; its doc comment estimates a tenfold speedup, which is not benchmarked — TestFastOptionsSpeed in solver/solver_test.go checks only that it takes fewer steps than AccurateOptions on an SIR net.
Equilibrium Detection
Many models converge to a steady state where token counts stop changing:
finalState, reached := solver.FindEquilibrium(prob)
FindEquilibrium integrates with Tsit5 and watches the largest absolute derivative across all places. With the default settings it checks every ten accepted steps, starting 0.1 time units into the run, and stops once that maximum has stayed below 10⁻⁶ on five consecutive checks (solver/equilibrium.go). reached reports whether that happened before the time span ran out; if it did not, finalState is the state at the end of the span. Stopping early saves the steps a fixed horizon would spend after the system has settled. TestFindEquilibrium in solver/solver_test.go runs a single transition moving tokens from A to B, starting from 50 each, and checks that A ends below 5 and that A + B stays within 1 of 100. It logs, but does not fail, when reached is false, so it tests the final state rather than the stopping rule.
Reading Results
The solution object provides the full trajectory. Continuing the SIR example:
sol := solver.Solve(prob, solver.Tsit5(), solver.DefaultOptions())
// Final state
final := sol.GetFinalState()
fmt.Println(final["R"])
// Full trajectory
for i, t := range sol.T {
fmt.Printf("t=%.1f: I=%.1f\n", t, sol.U[i]["I"])
}
sol.T is the time points. sol.U[i] is the state at time sol.T[i] — a map from place names to token counts. The time points are not evenly spaced — the adaptive solver places more points where dynamics are fast. Check sol.Truncated when comparing many solves: it is set when the solver hit Maxiters before the end of the time span, and a truncated solution otherwise looks like a complete one.
State Manipulation
The stateutil package provides utilities for working with state maps:
import "github.com/pflow-xyz/go-pflow/stateutil"
// Apply a delta to a state
newState := stateutil.Apply(state, map[string]float64{"pos": 0, "mark": 1})
// Sum all token counts
total := stateutil.Sum(state)
// Keys whose values differ, with the values from after
changes := stateutil.Diff(before, after)
// Deep copy
snapshot := stateutil.Copy(state)
They handle the common pattern of manipulating map[string]float64 state representations. Inside the library, hypothesis uses Apply to build each candidate state; the reachability analyzer works on its own integer Marking type instead.
Reachability Analysis
For discrete analysis — where tokens are integers and transitions fire one at a time — the reachability package explores the state space breadth-first (reachability/analyzer.go):
analyzer := reachability.NewAnalyzer(net).WithMaxStates(10000)
result := analyzer.Analyze()
The result reports, among other fields:
Bounded— false if some place exceeded the token limit (WithMaxTokens, default 1,000) during exploration. This is a cut-off, not a proof: a bounded net whose places legitimately hold more than 1,000 tokens also reads as unbounded.HasCycle— whether the explored state space contains a cycle (the system can return to a previous state);Cycleslists the transition sequences.Live— liveness in the Glossary’s sense: from every reachable marking, every transition can eventually fire again. It is reported true only when exploration finished.QuasiLiveis the weaker property that every transition fires somewhere in the graph; a quasi-live net can still deadlock.Livenessholds both as three-valued verdicts (true, false, unknown) and, when one is refuted, aWitness: a replayable firing sequence to the dead marking or to the closed region the net cannot leave (reachability/liveness.go).TestPhilosophersDeadlockIsNotLiveandTestLivelockIsDeadlockFreeButNotLiveinreachability/liveness_test.gocheck one refutation of each kind.Deadlocks— terminal states, where no transition is enabled, whose marking is not empty. A terminal state with no tokens left counts as a normal end. This is a heuristic for “stuck, not finished”;DeadMarkingslists every terminal state under the standard definition, empty ones included.
This is the discrete counterpart to ODE simulation. Where ODE simulation tracks continuous dynamics (Chapter 3), reachability analysis enumerates discrete states. It is exact when the exploration completes, but the state space can grow exponentially with the size of the net. WithMaxStates (10,000 is also the default) caps the exploration; a capped run sets Truncated, lists unfired transitions as PotentiallyDead rather than dead, and reports Live and QuasiLive as false. Its Liveness verdicts are never true; they read false only when the explored part already refutes them, with a dead marking that was reached or a closed region whose markings were all expanded, and unknown otherwise.
Hypothesis Evaluation
The hypothesis package evaluates candidate moves in game models (Chapter 6: Game Mechanics):
eval := hypothesis.NewEvaluator(net, rates, func(final map[string]float64) float64 {
return final["wins"] - final["losses"]
})
// Find best move among candidates (each a map of place updates)
bestIdx, _ := eval.FindBestParallel(state, []map[string]float64{move1, move2, move3})
// Sensitivity analysis — which transitions matter most?
impact := eval.SensitivityImpact(state)
Each candidate is a map of place updates. The evaluator applies it to the base state with stateutil.Apply, simulates forward with Tsit5 and FastOptions over a fixed span of t = 0 to 5, and scores the final state (hypothesis/hypothesis.go). It does not run to equilibrium; WithTimeSpan and WithOptions change the span and the solver settings. FindBestParallel evaluates the candidates in one goroutine each and returns the index and score of the best. SensitivityImpact sets each transition’s rate to zero in turn and returns the change in score from the baseline. The scoring function is user-defined — for tic-tac-toe it might maximize win tokens; for a resource model it might maximize throughput.
The cache package memoizes simulation results, so repeated evaluations of the same state (common in game tree search) are served from cache rather than re-simulated. The evaluator does not cache on its own: cache.NewCachedEvaluator(net, rates, size) is a separate evaluator with a cache in front. Entries are keyed by a hash of the state alone (cache/cache.go), so one cache is valid for one set of rates.
Higher-Level Abstractions
The core petri package provides the mathematical foundation. Three packages build domain-specific abstractions on top.
State Machines
The statemachine package implements hierarchical statecharts that compile to Petri nets:
chart := statemachine.NewChart("traffic_light").
Region("light").
State("red").Initial().
State("green").
State("yellow").
EndRegion().
When("timer").In("light:red").GoTo("light:green").
When("timer").In("light:green").GoTo("light:yellow").
When("timer").In("light:yellow").GoTo("light:red").
Build()
m := statemachine.NewMachine(chart)
m.SendEvent("timer")
m.State("light") // "green"
This is the chart from TestSimpleStateMachine in statemachine/statemachine_test.go, which asserts that three timer events take the light from red to green to yellow and back to red.
The statechart API is familiar to anyone who has used UML state diagrams. Chart.ToPetriNet (statemachine/builder.go) compiles it: each state becomes a place named region_state, and each chart transition becomes a net transition with one arc in from its source state and one arc out to its target; an Increment action adds an output arc to a counter place outside the region. For a flat region like this one, every transition therefore moves exactly one token within the region, so the region’s token count — one, placed on the initial state — is a P-invariant. That follows from the arcs; it is derived here, not computed by a test. NewMachine runs on the compiled net’s marking but routes events itself: SendEvent takes the first transition for the event whose source place is marked and whose guard holds, then clears the source and marks the target. Nested substates use the same one-token pattern, with extra arcs for the parent states.
Workflows
The workflow package models task dependencies with resources and SLA tracking:
wf := workflow.New("order").
ManualTask("receive", "Receive", 2*time.Minute).
AutoTask("validate", "Validate", 30*time.Second).
ManualTask("ship", "Ship", 5*time.Minute).
From("receive").Then("validate").To("ship").
Start("receive").End("ship").
WithSLA(4 * time.Hour).
Build()
engine := workflow.NewEngine(wf)
engine.StartCase("case-1", nil, workflow.PriorityMedium)
Tasks are labelled manual (human-performed) or automatic (system-performed). The engine does not treat the two differently; your code moves each task along with StartTask and CompleteTask either way. WithSLA sets a deadline per case with warning and critical thresholds at 80% and 95% of it (workflow/sugar.go), and Engine.CheckSLAs returns alerts for cases past those thresholds. NewEngine compiles the workflow with Workflow.ToPetriNet, but it tracks cases and resource pools in its own Go structures (workflow/engine.go). Formal properties are therefore something you check rather than something the engine guarantees: passing wf.ToPetriNet() to the reachability analyzer is how you would establish that every started case can complete. TestInventoryAndWorkflowIntegration in examples/coffeeshop/coffeeshop_test.go does pass a compiled order workflow to the analyzer, capped at 100 states, but it checks only that the net is bounded. No test yet checks the completion property.
Actors
The actor package implements the actor model — concurrent entities that communicate via message passing:
system := actor.NewSystem("sys").DefaultBus().
Actor("worker").
Handle("task", func(ctx *actor.ActorContext, s *actor.Signal) error {
ctx.Emit("done", map[string]any{"result": "ok"})
return nil
}).
Done().
Start()
At runtime the actors are goroutines exchanging signals over a bus, and a handler like the one above is an ordinary Go function, not a Petri transition. The Petri-net view is structural. ActorSystem.ToBundle (actor/subnet.go) emits one subnet per actor, with an in-port place for each signal type it subscribes to, an out-port for each type its behaviours emit, and a transition per behaviour trigger; links join every emitter of a signal type to every subscriber, which is the bus’s fan-out. The bundle is meant for visualization, deployment specs and event-log conformance checking. An actor’s behaviour can also carry its own net (WithNet), which SimulateBehavior integrates with the ODE solver. Analysing the bundle for deadlock does not prove the running system free of it, since the handlers sit outside the net.
Sensitivity Analysis
The sensitivity package measures how changes in parameters affect simulation outcomes (sensitivity/sensitivity.go):
sa := sensitivity.NewAnalyzer(net, baseState, rates, sensitivity.PlaceScorer("R"))
result := sa.AnalyzeRates()
for _, r := range result.Ranking {
fmt.Printf("%s: impact=%.4f\n", r.Name, r.Impact)
}
AnalyzeRates sets each transition’s rate to zero in turn, re-simulates (Tsit5, DefaultOptions, t = 0 to 10 unless WithTimeSpan changes it), and records the change in score from the baseline; Ranking sorts the transitions by the size of that change. For small perturbations rather than removal, Gradient and AllGradients take central differences in each rate, and SweepRate scans one rate over a list of values. A transition whose rate moves the score most is a candidate bottleneck. This connects to the bottleneck analysis in Chapter 5: Resource Modeling and the what-if scenarios in Chapter 11: Process Mining.
Process Mining Integration
The mining and monitoring packages (covered in depth in Chapter 11) connect external data to Petri net models:
// Parse event logs
log, _ := eventlog.ParseCSV("events.csv", eventlog.DefaultCSVConfig())
// Discover process model
result, _ := mining.Discover(log, "heuristic")
net := result.Net
// Learn rates from timing data
rates := mining.LearnRatesFromLog(log, net)
// Check how well the model fits the data
conf := mining.CheckConformance(log, net)
Discover accepts "sequential", "common-path", "alpha" and "heuristic". The same *petri.PetriNet type produced by the builder API or the mining algorithms feeds into the solver, the reachability analyzer, and the renderer. The library doesn’t distinguish between hand-crafted and data-discovered models.
SVG Rendering
The visualization package generates SVG diagrams from nets (visualization/svg.go):
svg, err := visualization.RenderSVG(net)
There is no layout step. RenderSVG converts the net to pflow.xyz’s JSON-LD format and draws each place and transition at its stored coordinates — for a builder-made net, the left-to-right positions the builder assigned. Places are drawn as circles with their tokens, transitions as rectangles, and arcs as lines with arrowheads; the renderer is adapted from pflow.xyz’s, so the output resembles the editor’s view (Chapter 17: The Visual Editor). SaveSVG writes the result to a file, and RenderWorkflowSVG and RenderStateMachineSVG draw workflows and statecharts in their own notations.
Putting It Together
The library’s packages compose. A typical application might:
- Build a net with the fluent API (
petri) - Simulate with the ODE solver (
solver) - Analyze reachability for correctness (
reachability) - Evaluate moves for game AI (
hypothesis) - Tune parameters via sensitivity analysis (
sensitivity) - Mine rates from production logs (
mining) - Monitor running instances for SLA compliance (
monitoring) - Visualize the net and simulation results (
visualization)
The shared *petri.PetriNet type is what lets them compose: the builder, the miners, the statechart and workflow compilers produce it, and the solver, the reachability analyzer, the evaluators and the renderer consume it. The token-model and metamodel packages carry a second representation for the declarative schemas of Chapter 4: The Token Language, with a bridge between the two, so “one type everywhere” holds for the simulation and analysis packages described here rather than for the whole library.
Dual Implementation and Verification
Learning objective: Achieve specification parity between Go and JavaScript implementations.
Every tool in the pflow ecosystem processes the same JSON-LD models. The Go library runs ODE simulations on the server. The JavaScript solver runs them in the browser. If they produce different results from the same input, either one of them has a bug or the specification is ambiguous, and any downstream analysis, proof, or decision based on those results is suspect.
This chapter covers the dual-implementation discipline: why both Go and JavaScript implementations exist, how parity is checked, and how event sourcing ties them together.
Why Two Implementations?
A specification written in prose is ambiguous. A specification implemented in one language might contain bugs that look like features. A specification implemented twice, in two languages, and checked to produce the same output gives a reader more to trust: wherever the two disagree, at least one is wrong, and the comparison says where.
The pflow ecosystem maintains two implementations:
| Go (go-pflow) | JavaScript (pflow-xyz) | |
|---|---|---|
| Role | Authoritative backend | Browser verification |
| ODE solver | solver/tsit5.go (tableau), solver/ode.go (Solve) | public/petri-solver.js (Tsit5, solve) |
| Discrete firing | reachability/ engine over the petri/ net | public/petri-sim.js |
| Runs in | Server, CLI | Browser |
| Used by | Go programs built on go-pflow, sim.pflow.xyz | pflow.xyz editor |
Both implementations parse the same JSON-LD format. Both implement the same Tsit5 ODE solver. Both use the same mass-action rate law: a transition’s flux is its rate times the product of its input places’ token counts, and arc weights scale how much is consumed, not the rate (Chapter 3). The claim: given identical input (model, initial state, rates, time span), they produce the same output within a stated numerical tolerance.
What the Parity Tests Compare
Three tests in the pflow-xyz repository check the claim, and they compare different things because the outputs differ in kind.
The model’s identity is compared exactly. A model’s CID is a hash of its canonical form (Chapter 16), and make test-parity computes it with both the Go sealer (internal/seal) and the browser’s seal-cid.mjs, against the shared fixtures in parity/golden.json. Any divergence fails the build. A hash comparison works here because canonicalization is exact: either both sides produce the same bytes or they do not.
ODE trajectories are compared within a tolerance. Floating-point output does not hash reliably, so parity/ode/ode_parity_test.go integrates the ten fixture models in parity/ode/fixtures.json (among them an SIR model, a closed cycle, a weighted chain, competing transitions and several multi-color nets) with both solvers under the shared default options, and requires every place’s final value to agree within . For the two closed fixtures, sir and cycle, it also checks that each solver’s final total is within 0.1% of the initial total. The file’s comment records the measured agreement as about : the two solvers share a tableau, a step-size controller and defaults, so they take the same steps, and the bound leaves nine orders of magnitude of headroom.
A second pair of tests pins both sides to a recorded trajectory, parity/ode/expected.json, generated by go-pflow. TestODEGoMatchesExpected in the same Go file requires the same number of accepted steps and the same value at every step, bit for bit where the generator found the fixture bit-stable and within otherwise (Go’s randomized map iteration can change the order in which a place’s flux terms are summed). parity/ode/ode_expected_test.ts replays the browser solver against the same record, with exact step counts and a relative bound of ; its comment attributes the residual to Go’s math.Pow and V8’s Math.pow differing by one or two units in the last place.
Discrete firing is compared step by step. parity/sim/sim_parity_test.go generates 200 seeded random models, covering arc weights above 1, inhibitor arcs, place capacities and two-color tokens, and walks each one for up to 40 steps through petri-sim.js and go-pflow’s reachability engine in lockstep. At every step both engines must report the same enabled set and the same marking. The walk always fires the lexicographically smallest enabled transition, so no randomness crosses the language boundary and any divergence is a semantic difference between the engines.
The ODE and discrete tests run under make test-parity-behavior and need node; none of these tests was re-run for this chapter.
The Tsit5 Algorithm — Twice
Both implementations use the Tsitouras 5th-order Runge-Kutta method (Tsit5). The coefficients are published constants, and the two files carry the same digits: seven stages, the same c, a and b arrays, and the same error-weight vector. The integration loop is where an implementation can quietly differ, so here is the error estimate and step-size control from each, copied from the source.
Go Implementation
// go-pflow solver/ode.go, inside Solve (excerpt)
for i := 0; i < n; i++ {
errest := 0.0
for j := 0; j < len(solver.Bhat); j++ {
errest += dtcur * solver.Bhat[j] * k[j][i]
}
uc := ucur[i]
un := unext[i]
scale := abstol + reltol*math.Max(math.Abs(uc), math.Abs(un))
if scale == 0 {
scale = abstol
}
val := math.Abs(errest) / scale
if val > err {
err = val
}
}
// ... on an accepted step:
factor := 0.9 * math.Pow(1.0/err, 1.0/float64(solver.Order+1))
factor = math.Min(factor, 5.0)
dtcur = math.Min(dtmax, math.Max(dtmin, dtcur*factor))
JavaScript Implementation
// pflow-xyz public/petri-solver.js, inside solve (excerpt)
for (const key of stateLabels) {
let errest = 0;
for (let j = 0; j < solver.bhat.length; j++) {
errest += dtcur * solver.bhat[j] * k[j][key];
}
const scale = abstol + reltol * Math.max(Math.abs(ucur[key]), Math.abs(unext[key]));
err = Math.max(err, Math.abs(errest) / scale);
}
// ... on an accepted step:
const factor = 0.9 * Math.pow(1.0 / err, 1.0 / (solver.order + 1));
dtcur = Math.min(dtmax, Math.max(dtmin, dtcur * Math.min(factor, 5.0)));
The error is the largest scaled per-place estimate, and the next step grows by at most a factor of 5. A rejected step shrinks by at most a factor of 10 in both files. The differences are representational: Go holds the state as a dense vector indexed by place and skips zero tableau entries, JavaScript holds it as an object keyed by place name, and Go’s scale == 0 fallback only matters when abstol is zero.
Parity has a limit that this pair illustrates. Both files’ comments record that the last entry of the error-weight vector once had the wrong sign, instead of , which made the error estimate first order: go-pflow’s comment says the step count grew about tenfold per decade of reltol instead of about -fold. A bug both implementations share is one that agreement between them cannot reveal. What pins it now are invariants checked on each side separately: TestTsit5BhatSumsToZero and TestTsit5StepControlIsFifthOrder in solver/tsit5_test.go, and the matching assertion in pflow-xyz’s public/petri-solver_test.ts.
Parameters Must Match
Agreement also depends on the options. go-pflow’s DefaultOptions() and the defaults of the browser’s solve are the same values:
- Adaptive stepping with Tsit5
dt = 0.01,dtmin = 1e-6,dtmax = 0.1abstol = 1e-6,reltol = 1e-3,maxiters = 100000- The time span from the model
These are the options the ODE parity test uses on both sides. go-pflow’s JSParityOptions() differs from them only in Dtmax = 1.0, matching petri-learn.js rather than the editor’s plots (Appendix A: Solver Parameter Reference tabulates every preset).
Event Sourcing
The dual-implementation discipline extends beyond ODE simulation to state management. The pflow ecosystem uses event sourcing as its state management pattern:
State is not stored directly. Instead, the system stores an immutable log of events (transition firings), and the current state is reconstructed by replaying the events from the beginning.
Events as Transition Firings
In Petri net terms, an event is a transition firing. go-pflow’s eventsource package (eventsource/event.go) defines the record; serialized, an event has this shape (the values are illustrative):
{
"id": "evt-0042",
"stream_id": "coffeeshop-1",
"type": "brew",
"version": 42,
"timestamp": "2024-01-19T10:30:00Z",
"data": { "beans_used": 2, "water_used": 3 }
}
The event records which transition fired, on which stream, at which position in that stream, and with what data. The state change (tokens removed from input places, tokens added to output places) is determined by the event and the net.
In eventsource/aggregate.go, the firing rule is split across two methods. StateMachine.Fire checks enablement (input tokens, inhibitor and read thresholds, and an optional guard), refuses a transition the net does not declare, and returns an event without changing the marking. StateMachine.Apply is the apply of the fold: it subtracts the transition’s inputs and adds its outputs, and it does not re-check enablement. Replay therefore trusts the log; the check happened once, when the event was created. Read arcs are deliberately absent from Apply, because applying a read on every replayed event would decrement a place that a read never consumes.
Replay Equivalence
If both Go and JavaScript replay the same firing sequence against the same model, they must arrive at the same marking. This is a separate guarantee from ODE parity, because it covers discrete-event execution rather than continuous simulation.
Firing sequence: [brew, brew, restock, brew]
Go replay: fold(apply, initial, events) -> State A
JS replay: fold(apply, initial, events) -> State B
State A == State B (must hold)
The check that exists today is the lockstep walk described above: sim_parity_test.go drives petri-sim.js and go-pflow’s reachability engine through the same firing sequences and compares markings after every firing. No test yet replays a stored eventsource log through a JavaScript fold; that would extend the check from the firing rule to the event format.
Why Event Sourcing Fits
Event sourcing and Petri nets fit together because each concept of one has a counterpart in the other. Every transition firing is an event, so the event log is the net’s execution trace. The current marking is the state, computed by applying the firing rule once per event, and replaying the log from the initial marking reconstructs the state at any earlier point, which is what auditing, debugging and time-travel queries need. The net’s topology plays the part of a schema: it says which events are valid, and Fire refuses a brew if the net has no brew transition or if brew is not enabled.
The Verification Loop
The parity tests compare the two implementations offline, in CI. The same comparison can be run live, with the browser acting as a verifier of the server:
- The client (JavaScript) fires a transition, computes the new marking locally, and sends the firing to the server.
- The server (Go) computes the new marking independently, stores the event and returns the marking.
- The client compares the two. A match means the implementations agree on that step; a mismatch is a discrepancy to investigate.
This is a design sketch, not a description of a running service: the pflow.xyz server stores and renders models but has no endpoint that fires transitions, and the editor fires them locally. The pattern is the one the ZK tic-tac-toe protocol of Chapter 12 uses with cryptographic proofs, where the opponent checks each move rather than trusting the party that made it.
Trust Model
In such a loop the server is authoritative, and its state is the canonical one; the client checks the server’s work rather than replacing it. A discrepancy shows a bug in one or both implementations, and agreement raises confidence that the specification has one reading. Neither implementation is trusted on its own account; the confidence comes from their agreement, with the limit already noted: a shared bug agrees with itself.
Token Model Equivalence
The tokenmodel package in go-pflow carries the same idea to the schema level. A token model can be written as JSON (the interchange format), as Go struct tags, or in the S-expression DSL of Chapter 4.
What the tests check is a round trip between notations. TestTagsRoundTrip in tokenmodel/dsl/tags_test.go converts a tagged struct to the DSL’s syntax tree, prints it as an S-expression, parses it back, and compares the name and the number of states and actions. TestBuilder_RoundTrip in tokenmodel/dsl/builder_test.go does the same for the fluent builder, comparing name, version and the counts of states, actions and arcs. Those checks would catch a notation that drops an element; they compare counts, not structure, so they do not show that the three notations produce the same net. A test that builds one model in all three notations and compares the resulting nets element by element is not yet written.
What Parity Proves
Dual implementation does not prove the specification correct. It shows that two implementations, written separately in different languages from the same specification, arrive at the same behavior on the inputs tested, which is evidence that the specification has one reading.
For Petri nets, the tests above cover four parts of that reading. Both engines agree on when a transition is enabled and on the marking after it fires, at every step of 200 random walks. Both solvers produce the same trajectories within on ten fixtures, with a measured agreement near . Both sealers compute the same CID for the shared fixtures. Event replay is covered at the level of the firing rule, not yet at the level of a stored log.
These are the properties a formal modeling system needs if its mathematics is to describe what its code does, and a second implementation is one way to check them. It is not the only check needed, as the error-weight bug showed.
From Two to Twenty
Two implementations show a specification can be read one way. They do not show it is portable, that a stranger in a third language could read the document and arrive at the same behavior. The history of this project includes what happens when there is no document to arrive at.
Five ports of an early version of this work (Rust, Python, Lua, TypeScript and Solidity) were each an internal DSL: you wrote code, in that language, that built a net. All five claimed to encode the same thing. None could show it, because the specification lived only in five separate programs that agreed by intention. They went quiet independently over about two years, and nothing noticed, because nothing was checking (the account is from the blog post A Tiling for Computation).
pflow-polyglot is the structural fix. One model.json, a ten-place coffee machine, is implemented thirty-nine times across ten languages, in five forms: an interpreter that reads the net as data, pure state-to-state functions, source generated from model.json, a contract API, and a proof form that checks every reachable marking before it runs. Every program must print the six-line trace in parity/trace.golden. make parity builds the twenty Go, Rust, Python and JavaScript programs under hermetic toolchains and diffs each one’s output against the golden byte for byte; any drift fails the build. make parity-native holds the Ruby, Julia, Haskell, Bash and Lean programs to the same golden, skipping a language whose toolchain is missing and saying so. The two Solidity programs are in neither gate. A second golden, parity/reachability.golden, records the full reachable state space (16 markings, 26 edges, one terminal marking) and is checked against the trace golden.
The proof form is kernel-checked only in Lean. There, lean/proof.lean is generated from model.json and the theorems (1-safety, the structural P-invariants, a unique terminal marking) are decided inside the kernel, so an unsafe net fails to compile (PROOF-ROADMAP, item P1). In Go, Rust, Python, JavaScript and Bash the proof form is an exhaustive model check that runs at startup.
Here the discipline stops being about Go and JavaScript. Parity between two runtimes is the smallest case of a general point: when the model is a value, agreement between implementations can be checked by comparing outputs, and a disagreement shows up as a diff.
The Ecosystem View
Each tool in the ecosystem reads the same model format, which is what makes cross-checking between tools possible:
JSON-LD Model (source of truth)
|
+-- pflow.xyz (JavaScript) -- ODE simulation, visual editing
|
+-- go-pflow (Go) -- ODE simulation, reachability, analysis
|
+-- sim.pflow.xyz (Go) -- Hosted what-if simulation, verification
|
+-- pflow-polyglot -- 39 implementations, one golden trace
|
+-- Lean / gnark -- Kernel-checked theorems, ZK circuits
The JSON-LD model is the shared contract, and each tool processes it independently. Where a parity test exists, as between pflow.xyz and go-pflow or across pflow-polyglot’s implementations, agreement is checked by machine; between other pairs it is possible in principle but not yet tested. The model format is declarative (Chapter 16), so what remains open is how each tool computes from it, and that is what a parity test checks.
This is what treating the model as data pays for in practice: the two runtimes read the JSON-LD model, thirty-nine programs and a kernel-checked proof are held to pflow-polyglot’s one model.json, and whether they agree is checked by machine. The preface applies the same discipline to composition: the composition and plan commands that pflow-native’s ten composition views draw from are held to go-pflow’s receipt for a model bundle and to pflow-rs’s receipt for search plans (each difference named and counted), the views themselves are held to goldens of what each one draws, and those are replayed against fixed files in tests that run, though the tools that made the receipts are not published. Here the agreement is a test that runs, and it complements the mathematics without replacing it: agreement shows the implementations read the specification the same way, and only checks against the mathematics show that reading is the right one.
Epilogue: What the Abstraction Sits On
Learning objective: Name the layered architecture this book actually built, see the six applications through the lens of net types, and identify the open problems worth pursuing.
The preface limited this book’s claim to composition: among notations for systems built from parts, the open Petri net is one structure that all of them can carry without loss. Chapter 13 placed that structure in a larger architecture, where the Petri net is one layer of a stack rather than its foundation. The result there that reaches furthest — that tic-tac-toe’s opening ranking can be read off graph connectivity, with no training data and no use of firing semantics, once the modeler has said which transitions are moves and which are goals — sits underneath the formalism the book is named for. This chapter starts from that result.
The Four-Layer Stack
The book built a stack, one layer at a time, without naming it as such until now:
Layer 4: Derived Artifacts (Chapters 12, 14, 17-20)
Editor, generated app, Go and JS runtimes, Lean
theorems, ZK circuit — each computed from the model
or reading it, none restating it by hand.
Layer 3: ODE Dynamics (Chapters 3, 5-10)
Mass-action kinetics couples topology to state.
Rate formula: v[t] = k[t] × ∏ M[inputs[t]]
Layer 2: Petri Net Semantics (Chapters 1-2, 4)
Firing rules, conservation laws, P-invariants.
Tokens consumed and produced atomically.
Layer 1: Graph Theory (Chapter 13)
Bipartite directed graph. Degree centrality.
Connectivity determines what matters.
Each layer adds something the layer below cannot express:
- Graph theory tells you what connects to what. It cannot tell you what happens when you act — there are no tokens, no state, no dynamics.
- Petri net semantics add state and atomicity. Transitions consume and produce. Conservation laws constrain the state space. But the formalism alone doesn’t tell you what happens first, or how fast.
- ODE dynamics add time. Mass-action kinetics couple topology-derived rates to the current marking. You get trajectories, equilibria, predictions. But the trajectories are only as trustworthy as the implementation that computed them.
- Derived artifacts add everything a user actually touches, and none of it restates the model by hand. The generated application, the kernel-checked theorems and the circuit’s per-net inputs are computed from the model document; the editor and the two runtimes read it. The ZK circuit illustrates the point without being the point: the circuit construction is fixed, and the topology arrays it reads are generated from each transition’s pre- and post-places (Chapters 12 and 13), so once the model is data the circuit follows. It is one derived artifact among several, and the book treats it that way.
Parts I–III introduced the bottom three layers out of order. Petri net semantics and ODE dynamics came first; graph theory came last, in Chapter 13, when the rate auto-derivation showed that pure connectivity carries more information than expected. The classic tic-tac-toe heuristic (center > corner > edge) falls out of counting connections, with no game theory and no training.
The Petri net is therefore the modeling layer, the place where graph structure acquires semantics, rather than the whole story.
Six Applications, Four Types
Chapter 4 introduced the five-type net taxonomy before the reader had examples to anchor it. After six worked applications in Part II, it can be checked against them:
| Chapter | Application | Net Type | Defining Property |
|---|---|---|---|
| 5 | Coffee Shop | ResourceNet | Conservation — ingredients are neither created nor destroyed |
| 6 | Tic-Tac-Toe | GameNet | Turn control + conservation — the move layer’s board-size sum |
| 7 | Sudoku | ClassificationNet | Constraint collectors into solved — as built, they can never fire |
| 8 | Knapsack | ComputationNet | Continuous relaxation — a relaxed value and per-item sensitivity, not the optimum |
| 9 | Enzyme Kinetics | ComputationNet | Native domain — mass-action kinetics is the chemistry |
| 10 | Texas Hold’em | GameNet | Phase workflow + seat turn control; dealer role declared, not enforced |
In each row the defining property is a property of the wiring. The coffee shop conserves ingredients because every gram a recipe takes from a stock place is deposited in a matching used place (Chapter 5). A GameNet alternates turns because a turn-control place gates player transitions through mutual exclusion. The Sudoku row shows the same thing from the failing side: each collector is wired as one conjunction over sixteen history places, so the wiring alone guarantees it never fires (Chapter 7). Read this way, the taxonomy describes structural invariants that the topology either has or lacks, which is Chapter 13’s observation seen from another angle.
What the Book Argued
Alongside the composition claim set out in the preface, three claims run from Chapter 1 to Chapter 20. They are argued from the worked examples rather than proved in general:
Small models beat black boxes. Every application in this book is inspectable. You can look at the tic-tac-toe topology and count win lines, read the stoichiometry matrix and see the differential equations, and read the generated code and the constraint system it compiles to. A trained model keeps its knowledge in weights that cannot be read this way. The cost is that a Petri net model needs a human to design the topology; the benefit is that the topology is the explanation.
One format, multiple tools. The JSON-LD model format (Chapter 16) is read by the visual editor (Chapter 17), the Go library (Chapter 19) and the ZK compiler (Chapter 12); sim.pflow.xyz runs models in go-pflow’s metamodel JSON (Chapter 18). Dual implementation (Chapter 20) checks that independent implementations agree, and pflow-polyglot extends the check to one coffee-machine net written thirty-nine times in ten languages against one golden trace, parity/trace.golden. make parity fails the build when any of its twenty Go, Rust, Python and JavaScript programs diverges, and make parity-native holds the Ruby, Julia, Haskell, Bash and Lean programs to the same file, skipping any language whose toolchain is missing. The two Solidity programs are in neither gate. For the other thirty-seven, the agreement is a test that runs.
Topology is primary, rates are secondary. Change the rate constants and the system’s quantitative behavior shifts; change the topology and it becomes a different system. The book observed this across its six applications rather than proving it, and Chapters 6 and 13 give it its sharpest form: a ranking read from incidence counts that the ODE reproduces. Chapter 6 also marks its limit. A forced block whose margin is thin can flip with the detector rates, so “secondary” means secondary for the ranking, not irrelevant.
What the Book Didn’t Solve
Chapter 13’s rate auto-derivation, and the composition machinery of Chapter 4, leave several questions open.
Multi-hop connectivity. The rate auto-derivation counts direct connections: candidate → unique output → target input. For tic-tac-toe, where every win is one hop from a placed piece, that is sufficient. The book has not applied it to games whose value lies several moves deep, such as chess or Go; a one-hop count is expected to miss most of what matters there, but that expectation is untested. The question is whether multi-hop reachability analysis — T-invariants, unfoldings, or iterative message-passing over the bipartite graph — can extend the one-hop algorithm to deeper games. It is a graph theory question rather than a Petri net question.
Weighted targets. The algorithm treats every target connection as weight 1. A checkmate path and a pawn capture score the same. The fix seems straightforward — assign importance weights to targets — but the principled question is where those weights come from. Can topology derive them recursively? Or does heterogeneous objective weighting require domain knowledge that the graph alone cannot supply?
Dynamic rates. Chapter 13’s topology-derived rates are computed once, from the full graph, yet a corner’s strategic value changes mid-game when it completes a fork threat. Chapter 6 handles this for tic-tac-toe in two ways: its dynamic evaluation recomputes the incidence degree against only the win transitions still reachable from the current board, and its derived evaluation net, which declares the opponent’s forced replies as transitions, makes no value-losing move against any opponent line in an exhaustive referee check (experiments/ode-minimax, in sim.pflow.xyz’s source, which is not public). Both are specific to one game. Whether the general rate derivation can be made state-dependent in the same way, recomputing connectivity over the reachable subgraph of any net, is open.
Composition is structurally solved; proof composition mostly is not. Composition is implemented, and for Chapter 4’s Orders/Inventory bundle, flattening the composite and recomputing its P-invariants recovers both component laws. That does not hold in general. Gluing a three-into-one netting transition onto a settlement cycle leaves the cycle’s all-ones invariant invalid in the composite (pflow-jl netting experiment): a component’s invariant extended by zeros need not be an invariant of the whole, although every invariant of the whole restricts to one of each part. What does lift is kernel-checked. If each component’s invariant agrees with the other’s on the shared places, together they define an invariant of the composite — the Lean theorem invariant_lift. Liveness need not lift: composition refines rather than extends, which preserves safety and not liveness (Appendix E). Beyond that one theorem, a composed system is still proved — in Lean or in circuit — as one flattened net rather than as a composition of component proofs. Assume-guarantee reasoning suggests the rest is tractable, since composition need only check the boundaries, though for shared places that check has real work to do (Appendix E). It is a derived-artifact problem rather than a modeling one.
What the ODE Was Actually Computing
Chapter 13’s rate auto-derivation counts, for each candidate move, how many target transitions consume the places that move alone produces: 4 for the center, 3 for a corner, 2 for an edge. On Chapter 6’s version of the tic-tac-toe net (30 places and 34 transitions, against the 33 and 35 of the variant Chapter 13 counts), go-pflow’s example records empty-board ODE scores of 0.487, 0.359 and 0.248 (not re-run); an earlier version of the net gave 1.27, 0.95 and 0.63. Both sets are within a few percent of 4 : 3 : 2, and in the same order. Chapter 13’s poker net reads the count the other way round. Each hand category’s value place fills at rate from a catalytic source and empties through drain transitions, so its equation is and its equilibrium is exactly : one drain for a straight flush, thirty-two for high card. That value is derived in closed form. The test test_integer_reduction_holdem in pflow-rs’s crates/pflow/src/lib.rs builds the same nine-category net, runs it to equilibrium with Tsit5, and asserts the strict ordering from high card to straight flush, with the straight flush within 0.5 of 32 times high card; it was not re-run for this edition. Counting and simulating agree because both read the same arcs — exactly where the equation can be solved by hand, and approximately but order-preserving on the tic-tac-toe boards Chapter 6 tested, where it cannot.
Where the Alphabet Has Travelled
Games are where the book validated its techniques. A stronger test of portability than a list of domains the techniques could apply to is the list where the same four primitives already run, sharing no code at the domain level. On sim.pflow.xyz, a help desk is built from three components — arrivals, service and a hazard — attached to one shared queue place, and the result is validated and simulated as one model (a test in sim’s private source composes it this way; not re-run here). Chapter 4’s ERC-20 schema declares its conservation law, sum(balances) == totalSupply, as part of the model rather than leaving it to an audit. In beats.bitwrap.io, drum patterns are token rings and song structure is a linear net that mutes and unmutes tracks; the sequencer plays a note when a transition fires on a hit. The deployment tooling for this ecosystem (private) declares each app as a manifest of a handful of fields and a marking, and derives the services entry, vhost, certificate and uptime check from it. And pflow-polyglot writes one model.json thirty-nine times against one golden trace.
The recipe is the same in each case: declare the structure, derive the rest.
The Structure Underneath
The four-layer stack describes the book’s architecture. Underneath it is one structure that explains why firing composes — why transitions chain and run side by side without interfering — and, read one level up, why two models glued at a shared place need no glue code and which properties of the parts survive into the whole.
That structure is the symmetric monoidal category (SMC).
Transitions as Morphisms
A Petri net transition consumes tokens from input places and produces tokens into output places. In categorical terms, this is a morphism — a map from domain to codomain. A transition with inputs and outputs is:
The is the monoidal product — it means “these things exist side by side.” Two tokens in separate places aren’t combined or merged; they coexist independently. This is how Petri nets express concurrency: means both places are marked, and both tokens are available simultaneously.
The objects are multisets of places — markings, elements of the free commutative monoid generated by the places — and the transitions are the generating morphisms. Every morphism is built from them by sequential and parallel composition.
Two Kinds of Composition
Every category has composition of morphisms. A monoidal category adds a second operation: the monoidal product. Inside a single net these are the two ways transitions combine, and that is the level this section works at: the objects are markings and the morphisms are firings. Whole nets compose one level up, in the category of open nets, where a net is itself a morphism between boundary multisets of places (Appendix E). There is still how two unlinked nets sit side by side. Nets that share something are glued instead. Gluing along a shared place is the subject of the preface’s claim; fusing transitions with an EventLink is the second kind of composition the preface names. Both return under Typed composition refines below.
Sequential composition (): the output places of transition become the input places of transition . Tokens flow through. This is ordinary morphism composition — the Texas Hold’em phase sequence (Chapter 10), the workflow cursor in a WorkflowNet (Chapter 4).
Parallel composition (): two transitions sit side by side with no shared places. They fire independently. This is the monoidal product — the nine hand categories of Chapter 13’s poker analysis net, each with its own source, value and drain places, sharing none with the others.
The symmetry is the swap map . It says we can reorder the components of a parallel composition without changing the behavior. In Petri net terms: the order in which we list the places carries no meaning. That is why pflow-polyglot’s golden trace prints each marking as place names sorted lexicographically: a listing order means nothing, so it has to be fixed before a Go map, a Rust set and a Python set can be compared at all.
Why This Explains the Book
The formal result, due to Sassone (1995) and Meseguer-Montanari (1990), is that a Petri net generates a free symmetric monoidal category whose objects are multisets of places and whose morphisms are equivalence classes of transition firings. “Free” means nothing extra is imposed — the only equations are the ones forced by the SMC axioms.
Three results from earlier chapters can be read through it:
-
Event sourcing works (Chapter 10) because sequential composition is associative: . The fold over events doesn’t depend on how you chunk the replay.
-
The poker ODE decouples (Chapter 13) because the analysis net is a parallel composition. Each hand category’s equation involves only its own value place, since the categories share no place for information to pass through.
-
Typed composition refines (Chapter 4). Adding an unlinked schema to a CompositeNet adds a new tensor factor at the level of open nets, and the monoidal product guarantees it can’t affect existing schemas — that much is monotonic. Adding a link is not: it identifies transitions or places, which is a quotient rather than a product, and quotients remove behavior. What the structure buys is refinement — every composite trace projects to a valid component trace — which preserves safety properties and not liveness.
What the Category Doesn’t See
The SMC encoding captures process structure — which compositions are valid, which transitions are independent. It has no privileged present: every marking is just another object. But every engine in this book reads one particular marking on every step, and that marking has a tense structure the category does not see.
Chapter 6 showed it on a net small enough to see whole. History places are past — write-once, monotone, the boolean case of tropical accumulation. The board and turn places are present — the marking the step is about. The move transitions and their guards are future — recomputed from the marking on every step, never stored. Appendix E states the split formally.
That is a scope boundary of the SMC framework rather than a deficiency: the category tells you what can compose, and the tenses tell you where you are in the composition. What matters for this book is that all three are data in the same document — the event log, the marking, the guards — so the question “do two implementations agree about where we are?” is answered by a trace diff, not an argument.
Where Declare-Then-Derive Already Runs
Step back and look at what is running. In every row the left column is a document in the four-primitive vocabulary, and everything in the right column is computed from it:
| Domain | Declared artifact | Derived from it |
|---|---|---|
| Business simulation | sim.pflow.xyz model (JSON-LD) | Analysis suite and the running application |
| Ecosystem devops (private) | App manifest (YAML) | Services entry, nginx vhost, certificate, uptime synthetic |
| Agent workflows (private) | Journey frontmatter (a Petri net) | The prompts themselves — the document is the runtime |
| Multi-language parity | pflow-polyglot/model.json | Five generated programs and the reachable-state golden, parity/reachability.golden |
| Formal proof | The same model.json | Kernel-checked Lean theorems (lean/proof.lean, generated) |
| Content addressing | index.md frontmatter | Searchable facets and a CID-addressed URL |
These rows were not designed together; each answered a specific problem, as the chapters did. They cohere because they share the alphabet: a place is a place in a help desk, a drum machine and a fleet of web services, and composing by shared place works the same way in each. Appendix E gives the categorical account of why that composition is well behaved, and of where it stops.
The Premise, Revisited
Chapter 1 opened with a complaint: informal models fail because they don’t capture the structure of the systems they represent. Concurrency is an afterthought. Resources are invisible. State is implicit.
Petri nets fix this by making structure explicit. Places hold state. Transitions change it. Arcs constrain what can flow where. Conservation laws fall out of the topology. The model is the specification.
The deeper lesson is that what made all of this possible is not specific to Petri nets: the model is a value, not a program. A net is a document: four primitives — place, transition, arc, guard — and a marking. It can be hashed, diffed, composed by matching edges, and handed to a stranger in another language who can check it without trusting us. The derived artifacts of Part IV, the invariants of Part I and the domains above all depend on that. In the systems this book modeled, topology determined more about behavior than parameter tuning did, and it could be read only because it was written down as data.
The preface called the practice built on that lesson Metamodel. Its alphabet is small and fixed, and local composition rules build specific systems from it whose structure can be checked. The palette is small on purpose, and its smallness is what lets it travel.
Appendix A: Solver Parameter Reference
This appendix documents the ODE solver methods, configuration options, and presets available in go-pflow’s solver package. Every value below is read from the package source (solver/); the tests named alongside are the checks the repository runs, and none were re-run for this appendix.
All the methods integrate the same right-hand side, built in solver/ode.go: a transition’s flux is its rate times the product of its input places’ token counts, each to the first power, and is zero if any input place is at or below zero. Arc weights multiply what each unit of flux consumes and produces; they do not enter the flux itself.
Solver Methods
Tsit5 (Default)
Tsitouras 5th-order Runge-Kutta with embedded 4th-order error estimator. Solve and SolveUntilEquilibrium use it when passed a nil method.
- Order: 5 (local truncation error )
- Stages: 7
- Adaptive: Yes (embedded error estimation)
- Reference: Ch. Tsitouras, “Runge-Kutta pairs of order 5(4) satisfying only the first column simplifying assumption”, Computers & Mathematics with Applications, 62 (2011) 770-775
sol := solver.Solve(prob, solver.Tsit5(), solver.DefaultOptions())
solver/tsit5_test.go pins the error estimator: the error weights sum to zero, the embedded weights satisfy the 4th-order quadrature conditions and not the 5th, and on the accepted-step count grows by less than 3× per decade of Reltol (a 5th-order controller gives about ).
RK45 (Dormand-Prince)
Classic Dormand-Prince 5(4) method, the algorithm behind MATLAB’s ode45. Same order and stage count as Tsit5, with a different tableau and error weights.
- Order: 5
- Stages: 7
- Adaptive: Yes
- Reference: J.R. Dormand & P.J. Prince, “A family of embedded Runge-Kutta formulae”, Journal of Computational and Applied Mathematics, 6 (1980) 19-26
sol := solver.Solve(prob, solver.RK45(), solver.DefaultOptions())
BS32 (Bogacki-Shampine)
3rd-order method with embedded 2nd-order error estimator, for problems with less stringent accuracy requirements where a 5th-order method does more work per step than it needs to.
- Order: 3
- Stages: 4
- Adaptive: Yes
- Reference: P. Bogacki & L.F. Shampine, “A 3(2) pair of Runge-Kutta formulas”, Appl. Math. Lett., 2 (1989) 321-325
TestSolverMethodsProduceSimilarResults in solver/solver_test.go runs Tsit5, RK45 and BS32 on a one-transition decay and requires their final values to agree within 5%.
Fixed-Step Methods: RK4, Heun, Midpoint, Euler
These four have no embedded error estimator: their error weights are all zero (solver/methods.go). The error estimate is therefore always zero, so even with Adaptive: true every step is accepted and Dt never changes. Pass Adaptive: false to make that explicit.
| Method | Order | Stages | Notes |
|---|---|---|---|
RK4() | 4 | 4 | Classic Runge-Kutta; teaching, debugging, or when a fixed step size is wanted |
Heun() | 2 | 2 | Improved Euler: an Euler predictor followed by a trapezoidal corrector |
Midpoint() | 2 | 2 | Evaluates the derivative at the half step |
Euler() | 1 | 1 | Forward Euler; needs very small step sizes for accuracy |
Implicit Euler
Backward Euler, for stiff systems where explicit methods need impractically small steps. ImplicitEuler is a function that returns a solution, not a method passed to Solve; with nil options it uses StiffOptions().
sol := solver.ImplicitEuler(prob, solver.StiffOptions())
It steps at the fixed size Dt and ignores Dtmin, Dtmax, Reltol and Adaptive (solver/implicit.go). The implicit equation is solved by fixed-point iteration, not Newton’s method: at most 50 iterations, stopping when successive iterates differ by less than Abstol, with no signal if the limit is hit first. That limits what the method buys on a stiff problem. For a linear decay the iteration is , which converges only when , so the step must still be small relative to the fastest time scale (derived from the iteration, not re-run). TestImplicitEuler checks only that a decay from 100 ends within 20% of , and TestImplicitVsExplicit that it lands within 20% of Tsit5 on a non-stiff net.
TRBDF2
Second-order implicit method: a trapezoidal stage to with , then a BDF2 stage to . Implicit Euler is first order. It shares Implicit Euler’s fixed step, StiffOptions() default and fixed-point iteration, with the same caveat. TestTRBDF2 checks the same decay to within 10%.
sol := solver.TRBDF2(prob, solver.StiffOptions())
SolveImplicit (Stiffness Heuristic)
Chooses once, at the initial state, between Tsit5 and Implicit Euler.
sol := solver.SolveImplicit(prob, solver.DefaultOptions())
The test is a heuristic on derivative magnitudes, not an eigenvalue estimate: it evaluates at and calls the problem stiff when the largest nonzero across places exceeds the smallest by more than a factor of 1000. If so it runs ImplicitEuler with the given options and Adaptive: false (so at fixed step Dt, 0.01 with DefaultOptions()); otherwise it runs Solve with Tsit5. It does not switch methods mid-run, and it never selects TRBDF2.
Configuration Parameters
The Options struct controls solver behavior:
| Parameter | Type | Description |
|---|---|---|
Dt | float64 | Initial time step (the fixed step for non-adaptive and implicit methods) |
Dtmin | float64 | Minimum allowed time step |
Dtmax | float64 | Maximum allowed time step |
Abstol | float64 | Absolute error tolerance |
Reltol | float64 | Relative error tolerance |
Maxiters | int | Maximum number of accepted steps; rejected steps do not count |
Adaptive | bool | Enable adaptive step size control |
If Maxiters runs out before Tspan[1], the solve stops early and sets Solution.Truncated; the final state is then at the last time reached, not at the end of the span. TestSolveReportsTruncation in solver/truncation_test.go covers it.
How Adaptive Stepping Works
When Adaptive is true, Solve does the following at each step (solver/ode.go):
- Evaluates the stages and forms the higher-order solution
u_new. - Estimates each place’s local error as
dt * Σ Bhat[j] * k[j]over the stagesk, where the method’sBhatfield stores the difference between the higher- and lower-order weights, so the lower-order solution is never formed separately. - Scales it and takes the maximum over places:
err = max |error| / (Abstol + Reltol * max(|u|, |u_new|)). - Accepts the step if
err <= 1, and also accepts it regardless of error onceDtis already atDtmin. - Computes
factor = 0.9 * (1/err)^(1/(order+1)), whereorderis the method’sOrder(5 for Tsit5 and RK45, 3 for BS32). After an accepted step,Dtis multiplied byfactorcapped at 5, then clamped to[Dtmin, Dtmax]. After a rejected step, it is multiplied byfactorfloored at 0.1, and never goes belowDtmin.
Because of step 4, a problem that drives Dt down to Dtmin keeps advancing with steps that exceed the tolerance, and nothing reports it. A run that is slow and spends many steps at Dtmin is the usual sign of stiffness. The browser solver in pflow-xyz (public/petri-solver.js) uses the same scaled error and the same cap of 5 on step growth.
Option Presets
General Purpose
| Preset | Dt | Dtmin | Dtmax | Abstol | Reltol | Maxiters | Use Case |
|---|---|---|---|---|---|---|---|
DefaultOptions() | 0.01 | 1e-6 | 0.1 | 1e-6 | 1e-3 | 100,000 | Most problems |
JSParityOptions() | 0.01 | 1e-6 | 1.0 | 1e-6 | 1e-3 | 100,000 | Mirror of jsParityOptions() in pflow-xyz’s petri-learn.js |
FastOptions() | 0.1 | 1e-4 | 1.0 | 1e-2 | 1e-2 | 1,000 | Interactive use, looser tolerances |
AccurateOptions() | 0.001 | 1e-8 | 0.1 | 1e-9 | 1e-6 | 1,000,000 | Research, publishing |
StiffOptions() | 0.001 | 1e-10 | 0.01 | 1e-8 | 1e-5 | 500,000 | Stiff systems |
All presets set Adaptive: true. TestOptionsPresets checks the Dt, Adaptive flag and Maxiters range of these five.
JSParityOptions() differs from DefaultOptions() only in Dtmax. The pflow.xyz editor’s own simulation (_odeSolve in public/petri-view.js) passes only dt, abstol, reltol and adaptive to the browser solver, whose defaults are DefaultOptions()’s values, so the editor’s plots run at Dtmax 0.1. To reproduce an editor plot in Go, use DefaultOptions(); JSParityOptions() matches the options petri-learn.js uses.
FastOptions()’s doc comment estimates a tenfold speedup. That figure is not benchmarked; TestFastOptionsSpeed checks only that it takes fewer steps than AccurateOptions() on an SIR net and stays within 10 tokens of conservation.
Domain-Specific
| Preset | Dt | Dtmin | Dtmax | Abstol | Reltol | Maxiters | Use Case |
|---|---|---|---|---|---|---|---|
GameAIOptions() | 0.1 | 1e-3 | 1.0 | 1e-2 | 1e-2 | 500 | Move evaluation |
EpidemicOptions() | 0.01 | 1e-6 | 0.5 | 1e-6 | 1e-4 | 200,000 | SIR/SEIR models |
WorkflowOptions() | 0.1 | 1e-4 | 10.0 | 1e-4 | 1e-3 | 50,000 | Process simulation |
LongRunOptions() | 0.1 | 1e-4 | 10.0 | 1e-5 | 1e-3 | 500,000 | Extended simulations |
The use cases in both tables are the doc comments’ intent, not measured comparisons.
Equilibrium Detection
SolveUntilEquilibrium integrates like Solve and stops early when the system reaches steady state (solver/equilibrium.go). It returns the solution and an EquilibriumResult whose Reason is equilibrium_reached, time_exhausted or max_iterations.
Equilibrium Parameters
| Parameter | Type | Description |
|---|---|---|
Tolerance | float64 | Largest over all places, at the start of the step, still counted as at rest |
ConsecutiveSteps | int | Number of consecutive checks below tolerance required |
MinTime | float64 | Time after before checking starts |
CheckInterval | int | Check every N accepted steps (0 or 1 = every step) |
ConsecutiveSteps counts checks, not steps: with the defaults, the derivative must stay below on five checks ten accepted steps apart.
Equilibrium Presets
| Preset | Tolerance | Consecutive | MinTime | Interval |
|---|---|---|---|---|
DefaultEquilibriumOptions() | 1e-6 | 5 | 0.1 | 10 |
FastEquilibriumOptions() | 1e-4 | 3 | 0.01 | 5 |
StrictEquilibriumOptions() | 1e-9 | 10 | 1.0 | 1 |
Convenience Functions
// Find equilibrium with default settings
state, reached := solver.FindEquilibrium(prob)
// Fast equilibrium (aggressive settings)
state, reached := solver.FindEquilibriumFast(prob)
// Accurate equilibrium (strict settings)
state, reached := solver.FindEquilibriumAccurate(prob)
FindEquilibrium uses Tsit5 with DefaultOptions() and DefaultEquilibriumOptions(); the Fast variant pairs FastOptions() with FastEquilibriumOptions(), and the Accurate variant AccurateOptions() with StrictEquilibriumOptions(). When reached is false, state is the state at the end of the run. TestFindEquilibrium runs a single transition from A to B and checks that A is nearly empty and A + B is conserved.
Combined Option Pairs
OptionPair bundles solver and equilibrium options:
pair := solver.GameAIOptionPair()
sol, eq := solver.SolveUntilEquilibrium(prob, solver.Tsit5(), pair.Solver, pair.Equilibrium)
| Pair | Solver options | Tolerance | Consecutive | MinTime | Interval |
|---|---|---|---|---|---|
GameAIOptionPair() | GameAIOptions() | 1e-3 | 2 | 0.01 | 3 |
EpidemicOptionPair() | EpidemicOptions() | 1e-6 | 5 | 0.1 | 10 (default) |
WorkflowOptionPair() | WorkflowOptions() | 1e-4 | 3 | 0.5 | 5 |
LongRunOptionPair() | LongRunOptions() | 1e-9 | 10 | 1.0 | 1 (strict) |
When to Use Which Solver
| Situation | Solver | Options |
|---|---|---|
| First attempt / don’t know | Tsit5() | DefaultOptions() |
| Reproduce a pflow.xyz editor plot | Tsit5() | DefaultOptions() |
Match petri-learn.js | Tsit5() | JSParityOptions() |
| Game AI move evaluation | Tsit5() | GameAIOptions() |
| Interactive / real-time | Tsit5() | FastOptions() |
| Publishing results | Tsit5() | AccurateOptions() |
| SIR/SEIR epidemics | Tsit5() | EpidemicOptions() |
| Process mining validation | Tsit5() | WorkflowOptions() |
Steps pinned at Dtmin (stiff) | ImplicitEuler() or TRBDF2() | StiffOptions() |
| Let the library guess stiffness | SolveImplicit() | DefaultOptions() |
| Fixed step (teaching) | RK4() | Adaptive: false |
If Tsit5() with DefaultOptions() doesn’t work for your problem, the usual adjustments are:
- Too slow: Use
FastOptions()(trades accuracy for speed) - Inaccurate: Use
AccurateOptions()(tighter tolerances) - Unstable/NaN: Use
StiffOptions(), withTsit5()or with an implicit method; the implicit methods help only as far as their fixed-point iteration converges at the chosenDt - Stops short or never settles: Check
sol.Truncatedand raiseMaxiters, extendTspan, or check for conservation violations
Appendix B: Token Language Grammar
This appendix documents the S-expression DSL for defining token model schemas, the syntax introduced in Chapter 4: The Token Language. The implementation is go-pflow’s tokenmodel/dsl package: lexer.go, parser.go, ast.go and interpret.go, with tests in dsl_test.go. The rules below were read from that code; the tests were not re-run for this appendix. The DSL is easier to read than JSON, but it expresses less: the JSON model format of Appendix C has fields the DSL has no syntax for (see Equivalence with JSON).
Lexical Elements
The lexer recognizes these token types:
| Token | Pattern | Examples |
|---|---|---|
LParen | ( | ( |
RParen | ) | ) |
Arrow | -> | -> |
Keyword | : followed by symbol | :type, :guard, :keys, :value, :initial, :exported, :kind |
Symbol | letter or _ (or a - not followed by > or a digit), then letters/digits/_/-/[/]/. | balances, map[string]int64, v1.0.0, ERC-020 |
Number | integer digits, optionally prefixed with -; no decimal point | 42, -1, 0 |
String | "..." with backslash escapes | "hello", "line\n" |
Guard | {...} with nested brace support | {amount > 0}, {balances[from] >= amount} |
Comment | ; to end of line | ; this is ignored |
Whitespace (spaces, tabs, newlines) separates tokens but is otherwise ignored.
Top-Level Structure
A schema definition has the form:
(schema <name>
(version <version>)
(states ...)
(actions ...)
(arcs ...)
(constraints ...))
The <name> and <version> are symbols, so v1.0.0 is written without quotes; a quoted string in either position is a parse error. The parser requires none of the clauses: (schema Test (version v1.0.0)) is a complete schema in TestParser_MinimalSchema. Clauses may appear in any order, and a repeated clause replaces the earlier one. The conventional order is version, states, actions, arcs, constraints.
Two lenient cases follow from parser.go and lexer.go; no test covers them. The lexer returns a character it does not recognize, such as @ or #, as an end-of-input token. Inside a clause the result is a parse error, but between clauses it ends the schema without an error and every later clause is silently dropped. The parser also returns as soon as it reaches the ) that closes (schema ...), or the end of the input, so neither a missing final ) nor trailing text after it is reported.
States
The states clause defines places in the Petri net:
(states
(state <id> :type <type> :kind <kind> :initial <value> :exported))
State Keywords
| Keyword | Value | Default | Description |
|---|---|---|---|
:type | symbol | (none) | Data type, stored as written and not checked by the parser or by validation. go-pflow’s tests use uint256, map[address]uint256 and map[address]map[address]uint256 |
:kind | token or data | data | Whether the place holds a token count or structured data. The parser accepts any symbol here, and Interpret treats anything other than token as data |
:initial | integer, string, nil, (map) or (list) | (none) | Initial value; (map) and (list) are an empty map and an empty list |
:exported | (no value) | false | Flag; an exported state can be bound across schemas |
All keywords are optional. A minimal state definition is just (state <id>), which is a data state. The default kind differs from the JSON model format, where a place with no kind is a token place; a token-counting place in the DSL needs :kind token.
Examples
; Token-counting place with initial tokens
(state pending :kind token :initial 1)
; Data place holding a map
(state balances :type map[string]int64 :exported)
; Simple data place with initial value
(state total_supply :type int64 :initial 0 :exported)
Actions
The actions clause defines transitions:
(actions
(action <id> :guard {<expression>}))
Action Keywords
| Keyword | Value | Description |
|---|---|---|
:guard | guard expression in {...} | Boolean precondition for firing |
Examples
; Action with no guard (always enabled when inputs are available)
(action ship)
; Action with guard expression
(action transfer :guard {balances[from] >= amount && amount > 0})
; Action with simple guard
(action mint :guard {amount > 0})
Arcs
The arcs clause defines connections between states and actions:
(arcs
(arc <source> -> <target> :keys (<key1> <key2> ...) :value <binding>))
The -> arrow separates source from target. The parser accepts any two symbols here; the check that an arc joins a state to an action (input arc) or an action to a state (output arc) comes afterwards, when Interpret calls Schema.Validate (tokenmodel/validate.go), which also rejects an end that names no declared state or action.
Arc Keywords
| Keyword | Value | Description |
|---|---|---|
:keys | parenthesized list of symbols | Map access keys for data places |
:value | symbol | Value binding name; when absent, the runtime uses amount |
The DSL has no syntax for arc weight or for inhibitor and read arcs. go-pflow’s tokenmodel.Arc has Weight and Type fields, but the DSL parser, the builder and the struct-tag dialect never set them, so every arc written in the DSL is a normal arc of weight 1. The contextual arcs of Appendix E have to be written in JSON or Go.
Examples
; Simple token arc (no keywords needed)
(arc pending -> ship)
(arc ship -> shipped)
; Data arc with keys and value
(arc balances -> transfer :keys (from) :value amount)
(arc transfer -> balances :keys (to) :value amount)
; Arc with multiple keys
(arc ledger -> settle :keys (from to) :value amount)
Constraints
The constraints clause defines invariants:
(constraints
(constraint <id> {<expression>}))
The expression is enclosed in {...} braces, like guard expressions. Schema.Validate does not look at constraints. go-pflow’s tokenmodel.Runtime (runtime.go) evaluates them against the token counts after each action it executes, provided CheckConstraints is true (the default) and a guard evaluator has been supplied; with no evaluator, constraints are skipped. A constraint is a runtime assertion about the markings a run actually visits. It does not prove the property over every reachable marking.
Examples
; Conservation law
(constraint conservation {sum(balances) == total_supply})
; Mutual exclusion
(constraint mutex {pending + shipped + delivered == 1})
Guard Expression Syntax
Guard expressions (used in both :guard and constraint) support:
| Category | Operators | Examples |
|---|---|---|
| Comparison | ==, !=, <, >, <=, >= | amount > 0 |
| Boolean | &&, ||, ! | a > 0 && b > 0 |
| Arithmetic | +, -, *, /, % | balances[from] - amount >= 0 |
| Map access | name[key] | balances[from] |
| Aggregates | see below | sum("balances_") == totalSupply |
The DSL parser does not read guard expressions. The lexer captures everything between { and the matching } as a single token, and the parser stores it as a string. Evaluation happens later, in go-pflow’s tokenmodel/guard package, which sim.pflow.xyz also uses.
The aggregates are defined in aggregate.go: sum, count, tokens, minOf and maxOf, with min and max accepted as aliases for the last two. Called with two arguments whose first is not a string, min(a, b) and max(a, b) are the ordinary two-number minimum and maximum instead. Each aggregate takes a place ID or ID prefix as a string and reads the token marking: sum("balances_") adds the token counts of every place whose ID starts with balances_, and TestAggregatesWithStringLiterals in guard_test.go checks that it equals 600 on a marking of 100, 200 and 300. TestMinMaxBothForms in numbers_test.go checks both forms of min and max.
To evaluate an invariant over data states, go-pflow provides EvaluateInvariantWithData in invariant.go. It binds each data state by name, so points[member] reads the map, and the aggregates then total a map passed directly or named by a string: TestEvaluateInvariantWithDataAndObjective checks sum(points) == 7.5 for the map {ann: 3, bob: 4.5}. The constraint sum(balances) == total_supply used in this appendix needs that entry point. tokenmodel.Runtime does not use it: its GuardEvaluator.EvaluateConstraint receives only the token counts, so the runtime’s after-each-action check cannot see the balances map.
Complete Examples
Neither example below is in go-pflow’s test suite, and neither was run for this appendix. The nearest tested schema is erc020DSL in dsl_test.go, a fuller ERC-20 with allowances and burn: TestInterpret_ERC020 parses and interprets it and checks for 3 states, 5 actions, 10 arcs and 1 constraint, and TestRoundTrip_ParseAndValidate passes it through Schema.Validate.
ERC-20 Token
(schema erc20-token
(version v1.0.0)
(states
(state balances :type map[string]int64 :exported)
(state total_supply :type int64 :initial 0 :exported))
(actions
(action transfer :guard {balances[from] >= amount && amount > 0})
(action mint :guard {amount > 0}))
(arcs
(arc balances -> transfer :keys (from) :value amount)
(arc transfer -> balances :keys (to) :value amount)
(arc mint -> balances :keys (to) :value amount)
(arc mint -> total_supply :value amount))
(constraints
(constraint conservation {sum(balances) == total_supply})))
Order Workflow
(schema order-processing
(version v1.0.0)
(states
(state received :kind token :initial 1)
(state validated :kind token)
(state shipped :kind token)
(state completed :kind token))
(actions
(action validate)
(action ship)
(action deliver))
(arcs
(arc received -> validate)
(arc validate -> validated)
(arc validated -> ship)
(arc ship -> shipped)
(arc shipped -> deliver)
(arc deliver -> completed))
(constraints
(constraint conservation {received + validated + shipped + completed == 1})))
The conservation constraint holds by construction. Each action has one input arc and one output arc of weight 1, so every firing moves the single token one place along the chain and the four counts always sum to the initial 1. That follows from the arcs by hand; it was not checked by a run.
AST Representation
The parser produces an abstract syntax tree with these node types:
| Node | Fields | Description |
|---|---|---|
SchemaNode | Name, Version, States, Actions, Arcs, Constraints | Root node |
StateNode | ID, Type, Kind, Initial, Exported | A place definition |
ActionNode | ID, Guard | A transition definition |
ArcNode | Source, Target, Keys, Value | A connection |
ConstraintNode | ID, Expr | An invariant |
The S-expression DSL is one of three front ends that build a SchemaNode. The others are the fluent builder (builder.go, dsl.Build(...)) and the Go struct-tag dialect (tags.go in the same package, dsl.ASTFromStruct). Interpret turns any SchemaNode into a tokenmodel.Schema and validates it. The three front ends do not produce identical trees for the same model: the builder and struct-tag paths default the version to v1.0.0 and give token states the type int, where the parser leaves both empty unless the source sets them.
Equivalence with JSON
A parsed DSL schema has two JSON forms. The first is tokenmodel.Schema itself, whose JSON field names come from the struct tags in tokenmodel/schema.go; its top-level keys are states, actions, arcs and constraints. The second is the model format of Appendix C: JSON Schema Reference, which calls the same things places, transitions, arcs and constraints. go-pflow’s metamodel.FromTokenModel (metamodel/convert.go) converts the first into the second:
| DSL | tokenmodel.Schema JSON | Appendix C model JSON |
|---|---|---|
(state id :kind token :initial 1) | {"id": "id", "kind": "token", "initial": 1} | {"id": "id", "kind": "token", "initial": 1} |
(action id :guard {expr}) | {"id": "id", "guard": "expr"} | {"id": "id", "guard": "expr"} |
(arc src -> tgt :keys (k) :value v) | {"source": "src", "target": "tgt", "keys": ["k"], "value": "v"} | {"from": "src", "to": "tgt", "weight": 1, "keys": ["k"], "value": "v"} |
(constraint id {expr}) | {"id": "id", "expr": "expr"} | {"id": "id", "expr": "expr"} |
go-pflow provides both halves of this route: ParseSchema in tokenmodel/dsl and then FromTokenModel in metamodel/convert.go. FromTokenModel drops each data state’s :initial, so a tool that accepts DSL input this way has to copy it into the place’s initial_value itself.
The two formats are not equally expressive. Arc weights and types, transition rates, views, parameters and the other sections of Appendix C have no DSL syntax, so every DSL schema has a JSON model but a JSON model cannot in general be written as DSL without losing fields.
Appendix C: JSON Schema Reference
This appendix documents the JSON model format of go-pflow’s metamodel.Model (metamodel/schema.go, at v0.33.0). It is the format sim.pflow.xyz stores and runs (Chapter 18), and the one go-pflow’s simulators and verifier read. The format defines what a valid Petri net model looks like: places, transitions and arcs, plus optional blocks for constraints, presentation intent (view, views), declared parameters and simulation.
A JSON Schema file for the format, petri-model.schema.json, exists, but it was written when the format’s main reader was an application generator, and it is not published. The Go types decide what is accepted, and where the schema file and the types disagree, this appendix follows the types and says so. The schema file lacks transition rate, arc type and kinetic, place capacity, and the top-level view and parameters; it gives transition bindings a different shape and a player’s maximizes a different default; and it still carries application-generator blocks and a form-style views, which go-pflow’s types no longer have (see the end of Top-Level Structure). These differences were found by reading the Go types against the schema file.
The types are also strict where it matters: sim.pflow.xyz refuses a model that carries a key metamodel.Model does not define, naming each unknown key with its path and the key it most likely meant, rather than letting Go’s decoder drop it silently.
Top-Level Structure
A model is a JSON object with four required fields and several optional ones:
{
"name": "order-processing",
"version": "1.0.0",
"description": "Order fulfillment workflow",
"places": [...],
"transitions": [...],
"arcs": [...],
"constraints": [...],
"view": "...",
"views": [...],
"parameters": [...],
"simulation": {...}
}
| Field | Required | Type | Description |
|---|---|---|---|
name | Yes | string | Unique identifier, kebab-case (^[a-z][a-z0-9-]*$) |
version | No | string | Semantic version (e.g., "1.0.0") |
description | No | string | Human-readable description |
places | Yes | array | States in the Petri net (min 1) |
transitions | Yes | array | Actions/events (min 1) |
arcs | Yes | array | Connections between places and transitions (min 1) |
constraints | No | array | Invariants that must hold |
view | No | string | Presentation intent: prose saying what an application built on the model should be |
views | No | array | Screens of that application, each a checked projection of the model |
parameters | No | array | Arc weights or capacities exposed as named structural knobs |
simulation | No | object | Objective, players and ODE solver configuration |
metamodel.Model has a few more optional fields, among them events (the data contract for transitions), decimals and unit (token display), assertedClasses and presentation (machine-readable console hints); schema.go documents them. Earlier versions of this format also carried application-generator blocks: roles, access, navigation, admin and eventSourcing, and a form-style views. go-pflow’s Model has no fields for the first five, so sim.pflow.xyz refuses a model that carries them, and views now has the shape described under Views below.
Places
A place holds state — either token counts (classic Petri net) or structured data.
{
"id": "order_received",
"description": "Order has been received but not yet validated",
"initial": 1,
"kind": "token",
"type": "string",
"initial_value": null,
"exported": false,
"persisted": false
}
| Field | Required | Type | Default | Description |
|---|---|---|---|---|
id | Yes | string | — | Unique identifier, snake_case (^[a-z][a-z0-9_]*$) |
description | No | string | — | Human-readable description |
initial | No | integer | 0 | Initial token count (min 0) |
kind | No | "token" or "data" | "token" | Whether this place holds token counts or structured data |
type | No | string | — | Data type for data kind places |
initial_value | No | any | — | Initial value for data places |
exported | No | boolean | false | Whether externally visible |
persisted | No | boolean | false | Whether persisted in event store |
capacity | No | integer | 0 | Upper bound on the token count: the discrete firing rule disables a transition whose firing would leave the place above it. 0 means unbounded (in the Go type, not in the schema file) |
Data Types
For kind: "data" places, the type field specifies the data type:
| Type | Description |
|---|---|
string | Text value |
int64 | 64-bit integer |
float64 | 64-bit floating point |
bool | Boolean |
time.Time | Timestamp (listed in schema.go, not in the schema file) |
map[string]int64 | Map from string keys to integer values |
map[string]string | Map from string keys to string values |
map[string]map[string]int64 | Nested map (e.g., per-user balances by asset) |
Transitions
A transition is an action that fires when enabled.
{
"id": "validate_order",
"description": "Validate the order details",
"guard": "amount > 0",
"event_type": "OrderValidated",
"http_method": "POST",
"http_path": "/api/validate",
"bindings": [
{"name": "amount", "type": "number", "value": true}
]
}
| Field | Required | Type | Default | Description |
|---|---|---|---|---|
id | Yes | string | — | Unique identifier, snake_case |
description | No | string | — | Human-readable description |
guard | No | string | — | Boolean precondition (guard DSL) |
event_type | No | string | PascalCase of id | Custom event type name (go-pflow marks it deprecated) |
http_method | No | string | "POST" | HTTP binding hint: GET, POST, PUT, DELETE, PATCH |
http_path | No | string | /api/{id} | HTTP binding hint; sim’s simulators ignore both |
bindings | No | array of objects | — | Operational data the transition reads or writes |
rate | No | number | — | Firing rate for simulation (in the Go type, not in the schema file) |
The schema file is stale on bindings: it describes the field as an object mapping names to strings. go-pflow’s Transition.Bindings is an array of Binding objects with fields name, type, keys (map access path), value (true for the transferred amount) and place. Go’s JSON decoder does not turn an object into an array, so by the types an object-form bindings fails to parse. The old map form survives as the separate field legacy_bindings. The binding in the example above is copied from pflow-xyz’s extend-operations.json fixture.
Guard Syntax
Guards are boolean expressions evaluated against the current state. The table describes go-pflow’s guard DSL, tokenmodel/guard at v0.34.0, which is the evaluator sim.pflow.xyz imports for guards and objectives. Its lexer accepts strings in single or double quotes. Appendix B gives the grammar.
| Operator | Meaning | Example |
|---|---|---|
==, != | Equality | status == 'approved' |
<, >, <=, >= | Comparison | amount > 0 |
&&, ||, ! | Boolean | a > 0 && b > 0 |
+, -, *, /, % | Arithmetic | balances[from] - amount >= 0 |
name[key] | Map access | balances[from] |
tokens('p'), sum, count, minOf, maxOf | Marking aggregates (see Objective Functions) | tokens('stock') > 0 |
Arcs
An arc connects a place to a transition (input) or a transition to a place (output).
{
"from": "balances",
"to": "transfer",
"weight": 1,
"keys": ["from"],
"value": "amount"
}
| Field | Required | Type | Default | Description |
|---|---|---|---|---|
from | Yes | string | — | Source element ID |
to | Yes | string | — | Target element ID |
weight | No | integer | 1 | Tokens consumed/produced (min 1); a threshold on read and inhibitor arcs |
type | No | "inhibitor" or "read" | normal | Arc kind (in the Go type, not in the schema file) |
kinetic | No | boolean | true | Whether an input place scales the firing rate (in the Go type only) |
keys | No | array of strings | — | Map access keys for data places |
value | No | string | "amount" | Value binding name |
The schema file has no type field, but go-pflow’s Arc does, and the vet clinic model in sim.pflow.xyz’s catalog (its JSON) uses both kinds, for example {"from": "wait_emergency", "to": "start_wellness", "type": "inhibitor"}. Neither kind moves tokens. An inhibitor arc blocks the transition while its place holds at least weight tokens. A read arc allows the transition only while its place holds at least weight tokens. These are the contextual arcs of Appendix E, outside the incidence matrix. Setting kinetic: false keeps an input arc’s enabling and consumption but removes its place from the rate product. go-pflow’s metamodel/validation.go rejects three things here: an unknown type, which is not quietly run as a normal arc; a read arc that does not run place → transition; and kinetic: false on any arc other than a consuming place → transition arc.
Constraints
An invariant that must always hold.
{
"id": "conservation",
"expr": "received + validated + shipped + completed == 1"
}
| Field | Required | Type | Description |
|---|---|---|---|
id | Yes | string | Unique identifier |
expr | Yes | string | Boolean expression over place token counts |
Views
view is one prose statement of what an application built on the model should be (“let two players play on the board; a click fires that cell’s move transition”). views decomposes it into screens. Each entry is a named projection of the model, the places and transitions one screen shows, plus a prompt for whoever builds that screen and links to the screens it can navigate to.
{
"id": "board",
"title": "Play",
"role": "board",
"prompt": "The nine cells as a grid; a click fires that cell's move for the player whose turn it is.",
"places": ["x00", "o00", "turn_x", "turn_o"],
"transitions": ["x_play_00", "o_play_00"],
"links": ["trust"]
}
| Field | Required | Type | Description |
|---|---|---|---|
id | Yes | string | Unique view identifier, referenced by links |
title | No | string | Human-readable screen name |
role | No | string | Kind of screen; conventional values are board, dashboard, controls, advisor, trust and log |
prompt | No | string | This screen’s share of the presentation intent, as prose |
places | No | array of strings | Places the screen shows (empty means all) |
transitions | No | array of strings | Transitions the screen may fire (empty means all) |
links | No | array of strings | IDs of the views reachable from this one |
Nothing executes view or a view’s prompt; they are read by whoever writes the application. The references are checkable, though. go-pflow’s types do not check them, but sim.pflow.xyz refuses to store a model in which a view names a place, transition or linked view that does not exist, repeats a view id, or gives a role outside the six listed above. Both fields are part of the model’s content hash, so the same net presented as a game and as a dashboard is two models. Chapter 18 shows where a published application built from them is served.
Simulation
ODE simulation configuration for AI move evaluation.
{
"objective": "win_x - win_o",
"players": {
"x": {
"maximizes": true,
"turnPlace": "turn_x",
"transitions": ["move_x_0", "move_x_1"]
},
"o": {
"maximizes": false,
"turnPlace": "turn_o",
"transitions": ["move_o_0", "move_o_1"]
}
},
"solver": {
"tspan": [0, 10],
"dt": 0.01,
"rates": {
"move_x_0": 1.0,
"move_o_0": 1.0
}
}
}
In the Go type a player’s maximizes has no default: when the key is absent it decodes as false and the player minimizes, whereas the schema file declares a default of true. Write it out for every player.
Objective Functions
The objective field is a numeric guard-DSL expression, using arithmetic and the aggregate functions below. The same functions are available to guards and constraints. Except for tokens, each function takes a place-ID prefix and ranges over every token place whose ID starts with the argument. The definitions are MakeAggregates in go-pflow’s tokenmodel/guard/aggregate.go, which also accepts min and max as names for minOf and maxOf. The same file’s MakeAggregatesWithData extends the four prefix functions to a map-valued data place, ranging over the map’s values, but sim.pflow.xyz’s evaluators bind the marking-only MakeAggregates.
| Function | Description | Example |
|---|---|---|
tokens('place') | Token count at exactly that place | tokens('goal') |
sum('prefix') | Total tokens across matching places | sum('score') |
count('prefix') | Number of matching places holding at least one token | count('inventory') |
minOf('prefix') | Smallest count among matching places (0 if none match) | minOf('health') |
maxOf('prefix') | Largest count among matching places (0 if none match) | maxOf('score') |
Solver Configuration
| Field | Type | Default | Description |
|---|---|---|---|
tspan | [number, number] | [0, 10] | Time-span hint |
dt | number | 0.01 | Time-step hint |
rates | object | each transition’s rate, else 1.0 | Per-transition firing rates |
The tspan and dt defaults are the schema file’s. go-pflow’s SolverConfig documents both fields as hints for clients that read them. Its stochastic package uses rates but takes the horizon and sample grid from its own options, not from these fields.
Minimal Example
A small model that satisfies the schema:
{
"name": "toggle",
"places": [
{"id": "off", "initial": 1},
{"id": "on"}
],
"transitions": [
{"id": "switch"}
],
"arcs": [
{"from": "off", "to": "switch"},
{"from": "switch", "to": "on"}
]
}
This defines a one-shot toggle: a token starts in off, the switch transition fires, and the token moves to on, where it stays because nothing consumes from on. The model uses only the four required fields. on takes the default initial of 0, and both arcs take the default weight of 1. The schema’s minimums are one place, one transition and one arc, so a model with a single place and a single arc would also validate. This one was checked by reading it against the schema file and go-pflow’s types, not by storing it.
Appendix D: Glossary
- Arc
- A directed connection between a place and a transition (input arc) or a transition and a place (output arc). Arcs define the flow relation of the net. Each arc has a weight (default 1) specifying how many tokens are consumed or produced.
- Bipartite graph
- A graph whose nodes divide into two disjoint sets, with edges only between sets, never within. Petri nets are bipartite: places connect to transitions, transitions connect to places, but places never connect directly to places.
- Bounded
- A net is bounded if every place has a finite maximum token count across all reachable markings. A net is -bounded if no place ever exceeds tokens. Boundedness is a safety property — it guarantees the system can’t accumulate unbounded resources.
- CID (Content Identifier)
- A hash-based identifier for content-addressed data. In the pflow ecosystem, CIDs identify JSON-LD models deterministically — the same model always produces the same CID regardless of where or when it’s computed (Chapter 16).
- Compression ratio ()
- For a transition, tokens consumed divided by tokens produced. is the core; is an algebraic observer that destroys state to produce a verdict. It is read from the transition’s input and output arc weights, its columns of and , so it lies inside the incidence structure, where every analysis of can see it. See Core–observer boundary.
- Conservation law
- An equation where is a vector of weights and is the incidence matrix. Conservation laws prove that weighted sums of token counts remain constant across all firings. Example: in an SIR model, for all time.
- Contextual arc
- A read arc (fires only if a place holds a token, without consuming it) or an inhibitor arc (fires only if it holds none). Neither appears in the incidence matrix, since neither changes the marking. Nets with contextual arcs do not generate the free symmetric monoidal category of ordinary nets (Montanari & Rossi, 1995); they are the categorical half of the core–observer boundary, and the natural home of guards.
- Continuous relaxation
- Replacing discrete token counts with continuous concentrations and firing rules with differential equations. The Petri net becomes a system of ODEs via mass-action kinetics, enabling simulation with numerical solvers (Chapter 3).
- Core–observer boundary
- Two distinct boundaries that older material treated as one. The algebraic boundary () lies inside and separates transitions the tropical eigenvalue and uniform R1CS can handle from those they cannot; it does not affect composition. The contextual boundary (read/inhibitor arcs) lies outside and breaks free composition; it does not affect . Canonical statement in Appendix E.
- Deadlock
- A marking where no transition is enabled. The system is stuck — no further computation is possible. go-pflow’s
reachabilityanalyzer reports every such marking it explores asDeadMarkings; its narrowerDeadlockslist is a heuristic for “stuck, not finished” that skips a marking which drained to empty (reachability/analyzer.go). - Enabled
- A transition is enabled at a marking if every input place has at least as many tokens as the corresponding arc weight: for all input places . An enabled transition may fire; a disabled one cannot.
- Equilibrium
- A state where all derivatives are approximately zero — the system has stopped changing. go-pflow’s
SolveUntilEquilibriumstops early once the largest absolute derivative stays below a tolerance (default ) for several consecutive checks (solver/equilibrium.go; Appendix A). - Event sourcing
- A state management pattern where state is computed by replaying an immutable log of events from the initial state: . In Petri net terms, events are transition firings and state is the marking (Chapter 20).
- Firing rule
- The execution semantics of Petri nets. When a transition fires, it atomically removes tokens from input places and adds tokens to output places according to arc weights. The new marking is where is the unit vector for transition .
- Groth16
- A zero-knowledge proof system used in pflow to prove one Petri net firing between two committed markings. Proofs are constant-size — 128 bytes on BN254, two compressed G1 points and one G2 — and verify in constant time, at the cost of a per-circuit trusted setup (Chapter 12).
- Guard
- A boolean expression attached to a transition that must evaluate to true for the transition to be enabled, in addition to the standard token requirements. Guards extend the firing rule with data-dependent conditions. A guard reads the marking without changing it, so, like a contextual arc, it has no entry in and takes the transition outside the free structure of Appendix E; it is recomputed from the marking on every step and stored nowhere.
- Incidence matrix
- The matrix where is the output matrix (tokens produced) and is the input matrix (tokens consumed). Each column represents a transition; each row represents a place. The entry is the net change in place when transition fires (Chapter 2).
- Interleaving vs. partial-order semantics
- Two readings of concurrent behavior. Interleaving semantics considers one firing at a time and asks which markings are reachable; partial-order (unfolding) semantics additionally records which firings were independent. Encoding a read arc as a consume-then-restore self-loop is exact under the first and inequivalent under the second (Vogler, Semenov & Yakovlev, 1998). A single-transition ZK proof has only interleaving semantics.
- JSON-LD
- JSON for Linked Data. The pflow ecosystem uses JSON-LD as its model interchange format, with
@context: "https://pflow.xyz/schema". JSON-LD makes models self-describing and content-addressable (Chapter 16). - Liveness
- A transition is live if it can eventually fire from every reachable marking (possibly after other transitions fire first). A net is live if all transitions are live. Liveness means the system never permanently loses capability. go-pflow reports this as
Live, and the weaker quasi-liveness — every transition fires in some reachable marking — asQuasiLive; a quasi-live net can still deadlock (reachability/analyzer.go). - Marking
- The distribution of tokens across all places at a given moment; the state of the Petri net. Written as a vector where is the token count at place . The initial marking is the starting state.
- Mass-action kinetics
- A rate law from chemistry where the rate of a reaction is proportional to the product of reactant concentrations. As go-pflow implements it, the continuous firing rate of transition is , where is the rate constant: first order in every input place, whatever the arc weight. The weight enters only the stoichiometry, so place drains at times the flux (
solver/ode.go; Chapter 3). - MiMC (Minimal Multiplicative Complexity)
- A hash function designed for efficiency inside arithmetic circuits. Used in pflow’s zero-knowledge proofs to hash Petri net markings into state roots. In gnark’s BN254 implementation it costs 330 constraints per field element (110 rounds of three multiplications — derived from the code in Chapter 12, not measured).
- Monotonic expansion
- The discipline of a schema that only grows: new facts can be added, existing facts are never retracted, so learning more never invalidates what was already known (Chapter 16). The history places of Chapters 6 and 7 follow the same discipline at the level of a single net. See Write-once place.
- ODE (Ordinary Differential Equation)
- An equation relating a function to its derivatives. The continuous relaxation of a Petri net produces a system of ODEs: where is the rate vector (Chapter 3).
- P-invariant
- A vector such that . The weighted sum is constant for all reachable markings. P-invariants prove conservation laws — they identify quantities that are preserved by every transition firing (Chapter 2).
- Petri net
- A mathematical modeling language consisting of places, transitions, arcs, and tokens. Formally, a tuple where is a set of places, is a set of transitions, is the flow relation, is the weight function, and is the initial marking.
- Place
- A node in a Petri net representing a condition, resource, or state. Places hold tokens. Drawn as circles. In the continuous relaxation, token counts become continuous concentrations.
- Reachability graph
- The graph of all markings reachable from the initial marking through sequences of transition firings. Each node is a marking, each edge is a transition firing. The reachability graph may be infinite for unbounded nets.
- SDE (Stochastic Differential Equation)
- Here, specifically the chemical Langevin equation: continuous state evolving under the same propensities SSA uses, but with intrinsic firing noise built into the diffusion term rather than sampled as discrete events. Cheap to sweep like the ODE, with an honest variance band like SSA — the regime between them. Distinct from a layer of exogenous Brownian motion added to an ODE for external uncertainty (a price feed, say), which answers a different question (Chapter 3).
- SSA (Stochastic Simulation Algorithm)
- The discrete engine’s execution method (Gillespie’s direct method): pick the next transition to fire and the time until it fires, both drawn from the model’s own propensities, then repeat. Produces one exact discrete sample path, or an ensemble of them, rather than a mean-field trajectory — the right tool when small counts or gating (read arcs, inhibitors, reachable capacities, guards) make the continuous relaxation inapplicable (Chapter 3).
- State equation
- The algebraic relation where is the firing count vector (how many times each transition has fired). A necessary but not sufficient condition for reachability — the actual firing sequence must also be valid.
- State root
- A hash that stands for a state. The book uses the term in two senses. In the ZK circuits of Chapters 12 and 14 it is the MiMC hash of a marking, a public commitment to a private state; it carries no salt, so it hides the marking only when the candidate markings are too many to enumerate. In Chapter 20 it is a hash of a simulation trajectory: if the Go server and JavaScript browser produce the same one from the same model, the implementations agree. Chapter 20 describes that comparison but does not yet link the test that runs it.
- Token
- A marker in a place. Tokens represent the presence of a resource, the truth of a condition, or a unit of something being processed. In the discrete model, tokens are non-negative integers. In the continuous relaxation, they become non-negative real numbers.
- Transition
- A node in a Petri net representing an event, action, or chemical reaction. Transitions consume tokens from input places and produce tokens in output places. Drawn as rectangles. In the continuous relaxation, transitions have firing rates.
- Tsit5
- Tsitouras 5th-order Runge-Kutta method with embedded 4th-order error estimator. The default ODE solver in go-pflow (
solver.Solveuses it when no method is given,solver/ode.go) and in pflow.xyz (petri-solver.js). Steps adaptively, rejecting a step whose embedded error estimate exceeds theAbstol/Reltoltolerance (Appendix A). - URDNA2015
- Universal RDF Dataset Normalization Algorithm 2015. Used in pflow to canonicalize JSON-LD models before hashing, so that, under the same
@context, documents asserting the same RDF graph produce identical content identifiers regardless of key order or formatting (SealJSONLDininternal/seal/seal.go; Chapter 16). - Weight
- The number of tokens consumed or produced by an arc when its transition fires. A weight of on an input arc means the transition requires at least tokens in the source place and removes tokens when firing. Default weight is 1.
- Zero-knowledge proof
- A cryptographic protocol where a prover convinces a verifier that a statement is true without revealing any information beyond the truth of the statement. In pflow, a proof shows that one named transition fired validly between two committed markings. The transition ID is public; the marking stays hidden only as far as the verifier cannot reconstruct it from public data (Chapter 12, “What ZK Doesn’t Hide”).
Ecosystem Vocabulary
Terms coined in this book and the blog it grew from, rather than inherited from Petri net theory. Each entry names where the term was introduced.
Core–observer boundary — see the entry above; introduced in Earned Compression.
- Declare, then derive
- The Metamodel working discipline. The model is declared once as data; analysis, the running application, proofs and, in this ecosystem’s own deployment tooling, the infrastructure that serves it are computed from that document. Nothing downstream is hand-written to agree with the model, so a downstream artifact that disagrees with it has gone stale or been edited by hand, and re-deriving it exposes the difference (see Drift; Chapter 21; The Model Is the App).
- Drift
- Disagreement between a declared artifact and the world it describes — a manifest and a host, a vendored module and its upstream, two implementations of one net. Metamodel does not prevent drift; it makes drift detectable by comparing two values: a manifest against a host, a vendored file against its lockfile, a trace against the golden trace (Chapters 20, 21).
- Edge-matching composition
- Two nets compose by sharing a place, the way two tiles meet because their edges agree. No glue code is written to make them fit; the shared place is the interface. Invariants carry across in a specific sense: if a P-invariant of each component agrees with the other on the shared places, together they define a P-invariant of the composite — the theorem
invariant_lift, kernel-checked in Lean (proofs/PflowProofs/InvariantLift.lean). A component’s invariant extended by zeros is not in general an invariant of the composite, and liveness does not carry across at all (Appendix E; Chapters 4, 21; A Tiling for Computation). - Golden trace
- A canonical firing sequence and its resulting markings, compared byte-for-byte with each implementation’s output.
pflow-polyglot/parity/trace.goldenis one six-line trace for thirty-nine programs in ten languages.make parityruns the twenty Go, Rust, Python and JavaScript programs under Bazel and fails the build on any divergence;make parity-nativechecks the Ruby, Julia, Haskell, Bash and Lean programs against the same file, skipping any toolchain that is not installed. The two Solidity programs are in neither gate (pflow-polyglot/README.md; Chapter 20). - Internal DSL (as a failure mode)
- A model expressed as code in a host language that constructs a net — Rust macros, Python calls, Solidity structs. Five such ports of an early version of this work claimed to encode the same thing and could not prove it, because the specification existed only as five programs. The fix was to make the model a document (Chapter 21; book
ROADMAP.md§Lineage). - Journey
- A workflow whose control flow is a Petri net declared in a markdown document’s frontmatter, with one prompt per transition in the body. The document is both the documentation and the runtime — there is no second copy of the control flow to drift (Chapter 21).
- Manifest
- The declared description of an application — a handful of fields and a marking in one YAML file — from which its service entry, virtual host, certificate and uptime check are derived. The infrastructure instance of declare-then-derive (Chapter 21).
- Metamodel
- Capitalised: a model for making models — the cross-cutting claim of this book. A small, fixed alphabet — place, transition, arc, guard — whose local composition rules generate an unbounded space of specific, checkable systems, because a model written in it is a value rather than a program. Lowercase
metamodel, in code font, is a Go package implementing one instance of the vocabulary (Chapter 21; A Tiling for Computation). - Model is a value, not a program
- The single fact Metamodel rests on. A value can be hashed, diffed, composed and checked by a machine that has never seen any of our runtimes; what a program does can, in general, only be found by running it. Content addressing (Chapter 16), dual implementation (Chapter 20) and the golden trace all depend on it.
- Polyglot forms
- The five shapes an implementation of one model can take — interpreter (a generic engine reads the document), lambda (the net as a pure step function), generated (source emitted from the document), contract (on-chain), proof (the program checks its claims over every reachable marking before it prints anything; in Lean the check is a theorem the kernel accepts at compile time) — all held to one golden trace (The Proof Form;
pflow-polyglot/FORMS.md). - Tropical past, predicate future
- The tense structure of an executing model. Write-once places and the event log are the past — monotone and irreversible, the boolean case of tropical accumulation. Guards are the future — predicates recomputed from the marking on every step and stored nowhere. The marking is the present, the boundary where they meet. All three are data in the one model document (Chapter 6; Appendix E; The Zipper Whose Hole Is a Universe).
- Write-once place
- A place that no move takes a token back from: once a token arrives, the transitions that wrote it never consume it. History places are the canonical case —
X11andO02in the tic-tac-toe net of Chapter 6,_D2_01in the Sudoku net of Chapter 7. Their only downstream transitions are the pattern and constraint collectors that turn a completed pattern into a verdict. The smallest instance of tropical accumulation (Appendix E).
Appendix E: Categorical Foundations
This appendix sets out the categorical framework behind the constructions in this book. It is not required for any chapter — every result in the main text is stated and used without category theory. For readers with some background in abstract algebra, the categorical perspective gives a vocabulary for why some of the techniques compose, and for where composition stops.
Most of what follows is a reading, not a construction. The free-category theorem is published mathematics; the functors, lenses and sub-categories built on it below are asserted, not formally defined and checked. What is checked by machine — one Lean theorem about invariants under gluing, the generated per-model Lean proofs, and tests of the go-pflow and pflow-jl composition code — is named where it is used, and its status is tracked in the book’s PROOF-ROADMAP.md.
Symmetric Monoidal Categories
A symmetric monoidal category (SMC) is a category equipped with:
- A bifunctor (the monoidal product)
- A unit object such that
- Natural isomorphisms for associativity:
- A symmetry:
satisfying coherence conditions (the pentagon and hexagon diagrams).
In plain terms: objects can be placed side by side (), the grouping doesn’t matter (associativity), doing nothing is an option (), and the order doesn’t matter (symmetry).
Petri Nets as Free SMCs
The central theorem, due to Meseguer-Montanari (1990) and refined by Sassone (1995):
Theorem. A Petri net generates a free symmetric monoidal category whose:
- Objects are elements of — multisets of places (i.e., markings)
- Morphisms are equivalence classes of firing sequences
- Monoidal product is multiset addition:
- Unit is the empty marking: for all
- Symmetry permutes components of the multiset
“Free” means the only equalities between morphisms are those forced by the SMC axioms. The category captures exactly the net’s concurrent behavior.
Generators
Each transition is a generating morphism:
where and are the multisets of input and output places. Every morphism in is built from these generators by sequential composition () and parallel composition ().
What “Free” Buys You
The free construction means:
-
No hidden identifications. Two firing sequences are equal in only if the SMC axioms force them to be. If two sequences differ in their causal structure, they’re different morphisms.
-
Universal property. Any assignment of the net’s places and transitions into another symmetric monoidal category extends uniquely to a monoidal functor out of ; the precise statement, with its strictness conditions, is Sassone’s. The functors of the next section are offered as interpretations of this kind.
-
Concurrency is structural. Two transitions that share no places compose via , not , so concurrency is expressed directly by the monoidal product rather than simulated by interleaving.
Functors: Structure-Preserving Maps
A monoidal functor maps objects to objects and morphisms to morphisms while preserving the monoidal structure: .
Three kinds of derived artifact in this book can be read as functors out of . None has been constructed as one; each subsection says what the reading maps where, and what in the code backs it.
The ODE Functor
Mass-action kinetics can be read as a monoidal functor from the discrete net category to a category of dynamical systems:
- Objects (markings) map to concentration vectors; places, the generators, to their coordinates
- Transitions (morphisms) map to rate equations: , the product taken over the distinct input places of , each to the first power whatever its arc weight; the weight scales only how much is consumed (go-pflow
solver/ode.go) - The monoidal product maps to independence:
The last property is the shape of the decoupling lemma behind the incidence reduction of Chapters 6 and 13. In the analysis net, each accumulator place has its own catalytic source and its own drain transitions and shares no place with any other accumulator, so the net is a of components. With unit rates each accumulator obeys , where is its drain count, and setting gives the equilibrium . The lemma is proved directly, without category theory, in the incidence-reduction paper (pflow-rs papers/integer-reduction/main.tex), and the equilibria are asserted by the test_integer_reduction_* tests in pflow-rs crates/pflow/src/lib.rs for tic-tac-toe, poker, Connect Four and Hex. The functor reading describes why the equations separate; it does not prove that they do.
The Proof Forms
The two proof forms are the weakest fit for the functor reading. The Groth16 compilation maps markings to witness vectors and transitions to R1CS constraint blocks, one block per transition, with the fired transition selected by its public index (Chapters 12 and 13); the circuit construction is fixed, and only the topology arrays generated from the incidence matrix change from net to net. The Lean form is generated per model: pflow-polyglot’s tools/codegen -lang lean emits theorems about the net’s step function — the reachable set is closed under firing, every reachable marking is 1-safe, each vector of a basis of the P-invariants (the left nullspace of ) is conserved, and, when the net is conflict-free and has a single terminal marking, that marking is its only deadlock — which the Lean kernel checks by decide over the reachable set (lean/proof.lean). What the two share is the property the Metamodel needs: neither proof is written by hand for a particular net. Change the document and the proof is regenerated from it.
The Analysis Functor
The incidence reduction (Chapters 6 and 13) can be read as a functor from the net category to strategic values:
- Markings map to vectors of strategic scores, one per place
- The mapping reads the diagonal of , where is the 0/1 biadjacency matrix of positions against the constraints (win lines) they take part in; the diagonal entry is the position’s constraint count, which becomes its drain count in the analysis net
- The monoidal product maps to independent evaluation:
The paper calls incidence reduction a diagonal approximation to eigenvector centrality of , and the two agree on center > corner > edge on the tic-tac-toe boards it checks (3×3 by hand, 5×5 and 7×7 numerically); whether they can disagree on a less symmetric topology is listed there as open.
Lenses in Monoidal Categories
A lens, in a category with products (the cartesian case of the optics in Riley’s thesis), is a pair of morphisms:
- Get — extract a view from the state
- Put — update the state given a new view
subject to: Get-Put (putting what you got changes nothing) and Put-Get (getting after putting returns what you put).
The analysis net of Chapters 6 and 13 has the shape of a lens; the laws have not been checked for it:
- Get: given a marking , read strategic values from drain arc counts. The view is the equilibrium vector where .
- Put: update the marking (make a move) and the drain counts shift — blocked win lines drop out, remaining connections determine new values. This is the dynamic evaluation of Chapter 6.
Product Decomposition
Lenses compose in parallel: a lens on and a lens on give a lens on . The converse fails in general — a lens on a product need not split into one lens per factor, because its view may depend on both.
The analysis lens splits for Get: by the decoupling lemma each accumulator’s equilibrium depends only on its own drain count, so the view is one lens per position, composed in parallel. It does not split for Put. A move blocks win lines, and a blocked line removes a drain from every position on it, so one update changes several positions’ views at once. The coupling lives in the drain counts, not in the ODE, which stays decoupled for any fixed set of drains; the dynamic evaluator of Chapter 6 accordingly recounts the live lines for every empty position after each move.
Tropical Past, Predicate Future
The free SMC says which compositions are valid. It has no privileged present: every marking is just another object. Execution needs one — the marking a simulation reads on every step — and it can be added as a reading of what the net’s own document already contains, rather than as a second structure beside the net.
Every executing model in this book carries three kinds of data, and each has a tense:
| Data | Tense | Algebra | Property |
|---|---|---|---|
| Write-once places and the event log | Past | Boolean semiring; in timed nets, | Monotone: no move takes a token back |
| The marking | Present | Free commutative monoid | The state the step is about |
| Guards and enabledness | Future | Predicates on | Recomputed on every step, never stored |
The past is tropical. History places (Chapter 6) are write-once: no move transition takes a token back, and the only transitions that consume one are the pattern collectors that turn a completed line into a verdict. Under the moves, a set of write-once places behaves as the boolean semiring — OR to accumulate, AND to detect a pattern — which is the degenerate case of the tropical semiring that timed nets use to accumulate longest paths (the blog post Tropical Petri Nets). The same monotonicity is what makes the event log replayable (Chapter 20) and the schema safe to grow (Chapter 16): a fact, once absorbed, never changes.
The future is predicate. A guard is a question — am I enabled? — answered from the current marking and discarded, never a value held in the model. Nothing about the future is stored, which is why nothing about it can drift: the only way two implementations disagree about what fires next is to disagree about .
The present is the boundary. The marking is simultaneously the output of accumulation and the argument to every guard. Change it and a different past is relevant and a different future is enabled. Chapter 6 shows the split on a net small enough to see whole: history places past, board and turn places present, the eighteen move transitions and their enabling conditions future. (Tic-tac-toe has no guards in the contextual sense; its future is plain enabledness.)
This is where the categorical reading stops and the Metamodel reading (Chapter 21) begins. The SMC is structure without execution. Execution is the same document read with tenses — and because all three tenses are data in that one document, two implementations that disagree about any of them can be caught by a byte-for-byte trace comparison (the golden trace of Chapter 20) wherever the trace exercises the disagreement, rather than by argument.
Net Types as Sub-SMCs
A net type classifies whole nets, so the level to read it at is one up from : the category of open nets, whose morphisms are whole nets between boundary multisets of places. There, each of the five net types from Chapter 4 is a candidate sub-SMC — a class of nets with extra structure that should be closed under composition:
| Net Type | Additional Structure |
|---|---|
| WorkflowNet | Single-token restriction: morphisms are paths in a free category |
| ResourceNet | Conservation: a P-invariant, a vector in the left kernel of the incidence matrix () |
| GameNet | Both: sequential paths with conserved resources |
| ComputationNet | Rate structure: a monoidal functor to |
| ClassificationNet | Threshold structure: a transition needs tokens of evidence — an input arc of weight (a threshold written as a guard is contextual, and falls outside ; see below) |
Closure is asserted, not proved, for all five. The nearest thing to a check is for a different class, the settlement nets of the blog post The Category Settle: pflow-jl gives a membership predicate and tests closure under random wirings (src/settle.jl), and says itself that this is a test, not a proof.
The typed links (EventLink, DataLink, TokenLink, GuardLink) are the gluing data for composition. The CompositeNet is a pushout, not a coproduct. The coproduct is the disjoint sum of the components — every net side by side, nothing shared, which is what you get from a bundle with no links. Each link then glues along a boundary: a TokenLink or DataLink identifies two places, an EventLink identifies two transitions. Gluing a coproduct along a shared boundary is exactly a pushout, and go-pflow computes it the way the universal property suggests — as a quotient by the equivalence relation the links generate, rather than pairwise (metamodel/compose_flatten.go, with a union-find over places and another over transitions). Taking the equivalence closure is what makes the construction associative: linking and yields one three-element class regardless of the order the links are given. A GuardLink identifies nothing. go-pflow lowers it to a read or inhibitor arc across the boundary, or to a conjunct of the target transition’s guard, so a GuardLink makes the composite contextual and takes it outside in the sense of the next section.
The distinction matters for behavior, not just bookkeeping. The coproduct preserves each component’s behavior; a quotient identifies, and can therefore remove behavior. That is the formal reason composition refines rather than extends (Chapter 4): a rendezvous is a coequalizer, and a coequalizer can take behavior away.
Where the Free Structure Stops: Two Boundaries
Every chapter that splits a net into a core and an observer (Chapters 6 and 12) is using one of two different boundaries, and they do not coincide. This section is the canonical statement; the chapters cite it rather than restate it.
The boundary is algebraic and lives inside . For a transition write , the ratio of tokens consumed to tokens produced. A core transition has and, in the nets of this book, one producer and one consumer per place — the timed event graph property. A transition with (a win detector consuming three history tokens and a turn token to produce one verdict) breaks that property. Three consequences follow, all of them facts about : the tropical eigenvalue is undefined across it (Tropical Petri Nets; the pflow-jl netting experiment below shows the one-producer-one-consumer property failing at exactly the fan-in places), the R1CS encoding stops being uniform (Chapter 12), and the ODE treats it as a sink. What does not follow is any failure of composition. The Meseguer–Montanari theorem above has no hypothesis about fan-in; a transition is an ordinary generating morphism of .
The contextual boundary is categorical and lives outside . A read arc tests that a place holds a token without consuming it; an inhibitor arc tests that it holds none. Neither has an entry in the incidence matrix — records net change, and these arcs change nothing. Montanari and Rossi (1995) showed that nets with such arcs do not generate the free SMC: a transition’s enablement depends on marking that its pre/post boundary does not express, so the morphism is no longer determined by its source and target. This breaks composition. It does not touch : a contextual arc adds nothing to either count, so the guarded transition keeps whatever it had — for the ERC-20 transfer of Chapter 12, which moves amount tokens from one balance to another.
| ordinary arcs only | has contextual arcs | |
|---|---|---|
| core | guard — outside , algebraically invisible | |
| verdict transitions — composes freely, breaks and uniform R1CS | crosses both |
The two worked examples in this book sit in the two off-diagonal cells, which is what makes the boundaries easy to conflate: each example breaks exactly one thing. The overdraft guard of Chapter 12 is categorically an observer and algebraically core; the tic-tac-toe pattern collectors of Chapter 6 are algebraically observers and categorically core.
In tense terms, the contextual boundary is where the predicate future lives. A read arc is a predicate on the marking that cannot express, recomputed every step — which is why guards sit outside rather than inside it.
The circuit dissolves one boundary and not the other. The standard encoding of a read arc as a self-loop (consume, then produce back) is inequivalent under partial-order semantics: it serializes firings the read arc allowed to be concurrent, so the unfolding changes (Vogler, Semenov & Yakovlev, 1998). Under interleaving semantics the reachability set is identical. A Groth16 proof certifies one firing, and one firing has only interleaving semantics; so inside the circuit the self-loop is exact, and a guard pulled into the proof as a range check on an auxiliary witness is a faithful encoding. The boundary survives compilation unchanged, because the circuit is a compilation of .
Throughput composes as a bound, not a value. For open nets glued along a boundary place, , with equality only when no cycle through the glue has a larger mean weight than the best local cycle. Gluing creates cycles that belong to neither component, so throughput cannot be read off the parts. What can be: the lower bound for free, and Karp’s algorithm (1978) run over the glue cycles only. The circuit composes outright, and conservation composes under the compatibility condition of the next section; does not.
Composition Preserves Safety, Not Liveness
Composing two typed nets along links is a pushout: it identifies places or transitions, and identifies nothing else. What a component keeps depends on which it identifies.
When only transitions are identified (EventLinks), the fused transition fires only when every participant can, so every firing sequence of the composite, projected onto one component’s transitions, is a firing sequence of that component alone. A safety property of the component — “no reachable marking looks like this” — then survives composition. go-pflow checks this on the Orders + Inventory bundle of Chapter 4, which is linked by two EventLinks: every reachable composite marking, projected onto Orders, is reachable in Orders alone (TestProjectionRefinement), and composition shrinks Inventory’s reachable state space (TestEventLinkRestrictsBehavior), both in metamodel/compose_verify_test.go. That is a check on one bundle, not a proof for every one.
When places are identified (TokenLinks, DataLinks), the other component can put tokens into the shared place or take them out, and the guarantee weakens. The netting experiment in pflow-jl (docs/netting-experiment.md, tests in test/test_netting.jl) glues a netting transition onto a three-party settlement cycle along the cycle’s three pending places. The composite reaches a marking whose restriction to the cycle is all zeros, which the cycle alone can never reach; the cycle’s bound of three tokens in flight survives only as an inequality, because the glued transition only removes tokens. P-invariants go the same way:
- Restriction holds. Every P-invariant of the composite, restricted to a component’s places, is a P-invariant of that component — a component’s transitions touch only its own places.
- Extension by zero fails. The cycle’s invariant, all six places weighted 1, is not an invariant of the composite; the composite’s only invariant weights the new
clearedplace 3, i.e. . - Gluing compatible invariants holds, and is proved. If and are P-invariants of the two parts and agree on the identified places, the they induce is a P-invariant of the glued net. This is the theorem
invariant_lift, checked by the Lean kernel in core Lean 4 (proofs/PflowProofs/InvariantLift.lean). It covers gluing along places only, not transition fusion.
So the assume-guarantee reasoning of Chapter 4 — each component is verified in isolation, and composition only needs to check the boundaries — holds as stated for rendezvous along transitions. For shared places the boundary check has real work to do: a component’s conservation law is guaranteed to carry over when the other side has an invariant that agrees with it on the shared places, and not otherwise.
Liveness — “this transition can always eventually fire” — is a statement about what the component can do, and a quotient can take that away under either kind of link. In the netting experiment every transition of the cycle is live; in the composite, the four firings send_ab, send_bc, send_ca, net_abc reach a dead marking, and none of the seven transitions is live. Composition refines; it does not extend.
References
- Meseguer, J. & Montanari, U. (1990). Petri Nets are Monoids. Information and Computation, 88(2). The original proof that firing sequences form a free commutative monoidal category.
- Sassone, V. (1995). On the Category of Petri Net Computations. TAPSOFT. Refines the construction to symmetric monoidal categories with the correct equivalence on morphisms.
- Baez, J.C. & Stay, M. (2011). Physics, Topology, Logic and Computation: A Rosetta Stone. New Structures for Physics, Springer. Places Petri nets alongside circuits, proofs, and programs as structures living in symmetric monoidal categories.
- Fong, B. (2015). The Algebra of Open and Interconnected Systems. PhD thesis, Oxford. Formalizes composition of open systems (including Petri nets) via decorated cospans in a symmetric monoidal category.
- Master, J. (2020). Generalized Petri Nets. The Topos Institute. Extends Petri net semantics to broader categorical frameworks.
- Riley, M. (2018). Categories of Optics. MSc thesis, Cambridge. The formal theory of lenses and optics in monoidal categories.
- Montanari, U. & Rossi, F. (1995). Contextual Nets. Acta Informatica, 32(6). Read arcs as contextual dependencies; nets with them do not generate the free SMC.
- Vogler, W., Semenov, A. & Yakovlev, A. (1998). Unfolding and Finite Prefix for Nets with Read Arcs. CONCUR 1998. The self-loop encoding of a read arc is inequivalent under unfolding semantics — and only there.
- Baez, J.C. & Master, J. (2020). Open Petri Nets. Mathematical Structures in Computer Science, 30(3). Open nets as morphisms between boundaries of places, composed by gluing (cospans); the structure the Preface’s canonical-carrier claim is about.
- Mayr, E.W. (1981). An Algorithm for the General Petri Net Reachability Problem. STOC 1981. With Kosaraju (1982), reachability for ordinary nets is decidable.
- Kosaraju, S.R. (1982). Decidability of Reachability in Vector Addition Systems. STOC 1982.
- Leroux, J. & Schmitz, S. (2019). Reachability in Vector Addition Systems is Primitive-Recursive in Fixed Dimension. LICS 2019. The Ackermann upper bound.
- Czerwiński, W. & Orlikowski, Ł. (2021). Reachability in Vector Addition Systems is Ackermann-complete. FOCS 2021. The matching lower bound, shown independently by Leroux (2021), The Reachability Problem for Petri Nets is Not Primitive Recursive, FOCS 2021.
- Lipton, R.J. (1976). The Reachability Problem Requires Exponential Space. Yale technical report 62. With Rackoff (1978), coverability is EXPSPACE-complete.
- Rackoff, C. (1978). The Covering and Boundedness Problems for Vector Addition Systems. Theoretical Computer Science, 6(2).
- Minsky, M.L. (1967). Computation: Finite and Infinite Machines. Prentice-Hall. Two-counter machines are Turing-complete; zero tests on two places are all an inhibitor net needs to simulate one.
- Karp, R.M. (1978). A characterization of the minimum cycle mean in a digraph. Discrete Mathematics, 23(3). Computes the tropical eigenvalue; restricted to glue cycles, it is the compositional throughput step.