parcelnfa is a small complex-event-processing engine for parcel-hub scans. Alert rules are written in a short pattern language (SEQ, NOT ... WITHIN, Kleene plus, three event-selection strategies), parsed by a hand-written recursive-descent parser, compiled to NFAs and run per parcel over a stream whose scans arrive out of order. The engine uses only the Python standard library; typer provides the command line. The behaviour of the selection strategies is fixed by a brute-force oracle that the runtime is tested against, not by reading the code.
All data in this repository is synthetic: a seeded simulator generates the hub day.
A carrier's sorting hubs emit a scan whenever a parcel is inducted, sorted, loaded onto a trailer, unloaded, departs, is delivered or hits an exception. Operations want an alert within minutes for patterns that span several scans:
- a parcel loaded onto a trailer for the wrong hub that departs without being unloaded (
misroute), - a parcel inducted with no sort scan at that hub within 20 minutes (
missing_sort), - three exception scans within two hours (
damaged), - any scan after a delivered scan (
after_delivery).
Hand-written per-parcel state machines miss interleavings, fire twice, react to handheld scanners that sync their scans late, and leak state for parcels that never complete a pattern. Here every rule is a declarative pattern, the matches are deterministic functions of the scans, and state is dropped as soon as the event-time watermark proves a run can no longer complete.
flowchart LR
A["rules/*.pat<br/>pattern files"] --> B["lang.py<br/>recursive-descent parser"]
B --> C["compile.py<br/>AST to NFA, validation"]
D["scans.jsonl<br/>arrival order"] --> E["reorder buffer<br/>released by watermark"]
C --> F["runtime.py<br/>keyed NFA runs"]
E --> F
F -->|"prune runs past WITHIN,<br/>fire absence timeouts"| F
F --> G["alerts.jsonl<br/>deterministic alert ids"]
H["oracle.py<br/>brute-force matcher"] -.->|"must agree"| F
I["gen.py<br/>injected anomalies"] -.->|"must be recovered"| G
Language. A rule is PATTERN name SEQ(elements) [WITHIN d] KEY attr [STRATEGY STRICT|NEXT|ANY] [EMIT ALL|ONCE PER KEY]. An element is type [+ | {N,}] [var] [WHERE cond AND ...]; * matches any type; NOT makes it an absence, either between two elements or last with a WITHIN deadline. Conditions compare var.attr or literals with == != < <= > >=. Parse and compile errors carry line and column; format_pattern prints canonical text that re-parses to an equal AST. A builder API (pattern(...).seq(event(...), absent(...))) produces the same AST.
Compilation. The AST becomes an NFA whose states q0..qn mean "the first k elements are bound". Edges are take, loop (Kleene repeat), proceed (leave a Kleene state once the minimum count is met) and ignore, each guarded by a type test and predicates over the current and earlier bindings. Validation rejects unknown bindings, a trailing Kleene element, adjacent Kleene elements, a leading or doubled NOT and a trailing NOT without a deadline.
Runtime. Scans enter a buffer; the watermark is the newest timestamp minus the allowed out-of-orderness (2 minutes by default). Scans with ts below the watermark are released in (ts, scan_id) order, so the outcome does not depend on arrival order. Each rule keeps runs per key. A run is dropped when the watermark passes its start plus WITHIN. A trailing absence with deadline D fires when the watermark passes D, i.e. when no scan with ts <= D can still arrive. Alert ids are a hash of the rule, the key and the matched scan ids; scans seen before (by scan id) are dropped.
Strategies. STRICT: the matched events are consecutive in the key's stream. NEXT (skip-till-next-match): from each start event, every single-event element binds the earliest qualifying later event and a Kleene element takes every qualifying event up to the next element's event. ANY (skip-till-any-match): all tuples that satisfy order, predicates, WITHIN and absences. ANY over a Kleene element is exponential, and a rule without WITHIN never prunes its runs, so they accumulate per key. A key that holds more than the match cap (10,000 partial matches by default, linear growth included) raises MatchExplosionError naming the key; add or shorten WITHIN, or raise the cap.
Python 3.11 or newer.
python -m venv .venv
.venv/bin/pip install -e ".[dev]"
.venv/bin/pytest -q
# simulate a hub day (6,000 parcels, about 46,000 scans) and run the four rules over it
.venv/bin/parcelnfa gen --out data
.venv/bin/parcelnfa run rules/ --events data/scans.jsonl --truth data/truth.json --out data/alerts.jsonl
# show the NFA of a rule
.venv/bin/parcelnfa explain rules/misroute.patparcelnfa run rules/ --events tests/data/sample_scans.jsonl runs the committed 200-scan sample; its five alerts are in tests/data/golden_alerts.jsonl.
parcelnfa explain rules/misroute.pat:
rule misroute strategy=NEXT emit=ONCE PER KEY key=parcel_id within=4h
q0 (start)
take load l WHERE l.trailer_dest != l.parcel_dest -> q1
ignore -> q0
q1
absent unload u -> kills the run
take depart d WHERE d.trailer_dest == l.trailer_dest -> q2
ignore -> q1
q2 (accept)
parcelnfa run rules/ --events data/scans.jsonl --truth data/truth.json on the simulated hub day:
scans read: 46,150 (re-sent copies dropped: 226, too late: 0, without key: 0)
alerts: 140
after_delivery 10
damaged 25
misroute 60
missing_sort 45
peak live runs: 588
against the injected anomalies:
rule injected alerted precision recall look-alikes suppressed
after_delivery 10 10 1.000 1.000 0 of 0
damaged 25 25 1.000 1.000 20 of 20
misroute 60 60 1.000 1.000 40 of 40
missing_sort 45 45 1.000 1.000 30 of 30
2026-03-02 00:29:51 missing_sort key=P001805 scans=S0000058
2026-03-02 00:31:24 missing_sort key=P002815 scans=S0000073
2026-03-02 00:48:29 missing_sort key=P000868 scans=S0000244
... 137 more in data/alerts.jsonl
The simulated day has 3 hubs, 6,000 parcels and 45,924 distinct scans, delivered out of order by up to two minutes, with 226 scans re-sent. It injects 60 misroutes, 45 parcels without a timely sort scan, 25 parcels with 3 or 4 exceptions and 10 parcels scanned after delivery, plus look-alikes that must not alert: 40 parcels loaded wrong but unloaded and reloaded correctly, 30 parcels whose sort scan is 19 minutes after induct but reaches the server 90 seconds late, and 20 parcels with exactly two exceptions.
- Release in event time, not arrival time. The reorder buffer releases scans in
(ts, scan_id)order once the watermark passes them. Alerts then do not depend on how scanners batch their syncs (a test shuffles arrival order 20 times within the 2-minute bound and gets identical alert sets). The price is latency: nothing is evaluated until the watermark passes a scan, and a scan more than the bound behind the newest one is counted as late and dropped. - An absence is decided by the watermark.
NOT sort WITHIN 20mafter an induct at 10:00:00.000 fires when the watermark exceeds 10:20:00.000. A sort at exactly 10:20:00.000 still cancels the alert, one at 10:20:00.001 does not. This is why the late-syncing sort scans in the simulation do not cause false alerts; the cost is that an alert is never earlier than the deadline plus the out-of-orderness bound. NEXTis greedy, then checked. Each element binds the earliest qualifying event;NOTandWITHINare checked on that one candidate. If a forbidden event sits in between, the run dies instead of backtracking to a later binding:SEQ(a, b, NOT x, c)overa b1 x b2 chas noNEXTmatch, whileANYfinds(a, b2, c)(pinned intests/test_strategies.py). That keepsNEXTlinear in the number of runs and is what the oracle encodes, so the runtime and the oracle cannot silently diverge on it. A Kleene state remembers a blockedNOTevent in a flag that the next Kleene take clears.- The explosion cap counts partial matches.
ANYwithb+doubles the live runs of a key with everyb. Counting runs, not completed matches, makes the guard trip while the matches are still being built: with 1a, 25band 1cit stops at the cap instead of enumerating 2^25 subsets. The error names the rule and the key. It does not degrade to sampling, so the operator has to switch the rule toNEXTor tighten it. - Bounded state, with one exception. Runs are removed through a heap keyed by expiry, so pruning cost follows the number of expiring runs rather than the number of keys, and a test checks the invariant at every watermark advance of the hub day. Scan ids for duplicate detection are kept for one hour of event time.
EMIT ONCE PER KEYremembers every key it has fired for, so that set grows with the number of alerted keys. - The oracle shares nothing but the AST. It enumerates all index subsequences of up to 12 events and has its own predicate evaluation. Property tests with 200 random streams per case compare it with the runtime for six patterns and all three strategies.
GITHUB_ACTIONS=true CI=true COLUMNS=80 .venv/bin/pytest -q120 tests pass (the last run took about 10 seconds). They cover:
- the parser: every
rules/*.patround-trips through canonical text, six malformed patterns report line and column, validation errors; - the strategy fixtures from the language description (
a1 b1 a2 b2,a1 c b1,a b1 b2 c) and Kleene minimum counts; - oracle agreement: hypothesis, 200 examples for each of 6 patterns and 3 strategies, including a
NOTin the middle, a trailingNOTwith a deadline, a predicate on an earlier binding andWITHIN; - the absence boundary at 10:20:00.000 and 10:20:00.001, and a sort arriving out of order;
- the hub day: injected parcel ids equal the alerted ones for every rule, no look-alike alerts, no live run past its horizon at any watermark advance, peak live runs 588 (limit 5,000);
- the explosion guard (exponential ANY and linear growth without WITHIN), the without-key count, replay of a scan file twice, arrival-order independence, and the CLI against the committed golden alerts.
rules/ the four hub rules (*.pat)
src/parcelnfa/
lang.py AST, lexer, parser, canonical printer, builder API
compile.py validation and AST -> NFA, `describe()` for `explain`
runtime.py reorder buffer, watermark, keyed runs, absences, dedup, explosion cap
oracle.py brute-force matcher defining STRICT / NEXT / ANY
gen.py seeded hub simulator, anomalies, look-alikes, ground truth
events.py Event and Alert value types, JSONL reader
cli.py `parcelnfa run | explain | gen`
tests/ pytest and hypothesis tests; data/ holds the 200-scan sample and golden alerts
.github/workflows/ci.yml lint, format check, tests, build on Python 3.12 and 3.13
MIT. See LICENSE.
