Algorithm Search⌘K

Algorithmresearch

NFA-based event pattern matching (SASE)

Also called SASE, NFA with match buffer.

Evaluate event sequence patterns with an automaton over the stream and a shared buffer of partial matches, then apply predicates and windows.

Time
O(k^2 M + k n) worstO(k^2 M + k) amortized
Space
O(k n) extra
Where
M = the number of matches that end with the current event; k = the number of positive components of the pattern; n = the number of events of one partition in the last W time units
Properties
deterministicexactnot externalnot in placeonlinerecursive
Origin
Eugene Wu, Yanlei Diao, Shariq Rizvi, 2006

SASE, by Wu, Diao and Rizvi (2006), finds sequence patterns such as "an item leaves a shelf, then passes the exit, with no checkout in between, all within 12 hours" in a stream of events. Its matcher reads the stream like a nondeterministic automaton with one state per component of the pattern, but it keeps the partial matches in shared active instance stacks. Each stack entry points to the newest entry of the previous stack, and the matches are built from these pointers by a depth-first search at the moment their last event arrives. Predicates, the time window and negation are then checked on each match, and the window and equality tests are pushed into the stacks to prune them early.

In plain words

You watch a stream of events and must report every time an A was followed later by a B and then by a C within five minutes. Other events may come in between. Keep one pile of cards for A, one for B and one for C. When a B arrives, put its card on the B pile and write on it how many A cards were on the A pile at that moment: any of those A cards can come before this B. Do the same for C with the B pile. When a C arrives, follow its note to the B cards that came before it, then their notes to the A cards, and read out each chain. Throw away cards older than five minutes. A chain is found once, when its C arrives.

The problem

The input is a stream of events in time order, each with a type, a timestamp and attributes. A pattern in the core of the SASE language has the form

EVENT SEQ(E_1 e_1, ..., E_k e_k)  WHERE conditions  WITHIN W

where some components may be negated, written !(E e)!(E\ e). A match is a choice of events e1,…,eke_1, \dots, e_k with the given types, in stream order, with ek.ts−e1.ts≤We_k.ts - e_1.ts \le W, that satisfies the conditions, and with no event of a negated type, satisfying its conditions, between its neighbours. This is the problem of complex event processing for sequence patterns. SASE uses the selection that SASE+ later called skip till any match: other events may lie between the events of a match, and every combination is reported, so one event can be part of many matches. Conditions of the form e1.id=e2.id=⋯e_1.\mathrm{id} = e_2.\mathrm{id} = \cdots are equivalence tests; they say that a match is about one object.

The algorithm

  1. SASE(SEQ(E_1, ..., E_k) WITHIN W) ▷ stack i holds instances of E_i; each entry is (event, RIP)
  2. PUSH(e) ▷ events come in timestamp order
  3. 1S ← the stacks of the partition of e ▷ one set of stacks per value of the equivalence attribute
  4. 2drop the entries older than e.ts - W from the bottom of every stack of S; keep e if its type is negated
  5. 3for i ← k down to 1 with E_i = type of e do
  6. 4if i = 1 or stack i - 1 of S is not empty then
  7. 5push (e, RIP = the index of the top of stack i - 1) onto stack i
  8. 6if i = k then CONSTRUCT(e)
  9. CONSTRUCT(e)
  10. 7for each path from e that steps from an entry of stack i to an entry of stack i - 1 at or below its RIP, down to stack 1 do
  11. 8if the path fits the window, no negated event lies between its neighbours, and the WHERE conditions hold then
  12. 9emit the path in stream order as a match

The automaton has one state per positive component. An event of type EiE_i moves a run from state i−1i - 1 to state ii, and a run may also stay in its state when an event does not fit. A plain automaton would copy a run for each choice; the stacks share all runs: an entry on stack ii stands for every run that reached state ii with this event, and its RIP stands for all the runs that it extends.

Line L3 goes from the last component down, so an event whose type occurs twice in the pattern does not extend a run with itself. The search of line L7 tries the candidates from the top of the RIP range down and stops at the first one from which it finds no path; the correctness proof shows that the lower ones cannot have a path either.

Example

The pattern is SEQ(a,b,c)\mathrm{SEQ}(a, b, c) WITHIN 5, without equivalence tests. The stream is a@1,b@2,a@3,c@4,b@5,c@6,c@9a@1, b@2, a@3, c@4, b@5, c@6, c@9, and the stacks count their entries from 0.

event stack a stack b (RIP) stack c (RIP) matches
a@1 a@1
b@2 a@1 b@2 (0)
a@3 a@1, a@3 b@2 (0)
c@4 a@1, a@3 b@2 (0) c@4 (0) (a@1, b@2, c@4)
b@5 a@1, a@3 b@2 (0), b@5 (1) c@4 (0)
c@6 a@1, a@3 b@2 (0), b@5 (1) c@4 (0), c@6 (1) (a@1, b@5, c@6), (a@3, b@5, c@6), (a@1, b@2, c@6)
c@9 b@5 (1) c@4 (0), c@6 (1), c@9 (1) none

At c@4, the RIP of c@4 is 0, so the only candidate is b@2, whose RIP 0 gives a@1; the entry a@3 came after b@2 and is above its RIP. At c@6, the search tries b@5 first, whose RIP 1 allows both a@3 and a@1, and then b@2. At c@9, the pruning of line L2 removes every entry older than 4, which is a@1, a@3 and b@2. The entry b@5 remains, but its RIP range on stack a is now empty, so the search stops at once.

With the negation SEQ(a,!b,c)\mathrm{SEQ}(a, !b, c) WITHIN 5 on the same stream, the only match is (a@3, c@4). The pairs (a@1, c@4), (a@1, c@6) and (a@3, c@6) each have a bb between them, and c@9 is more than 5 after both aa events.

The SASE papers use as an example a shoplifting query over RFID readings: a SHELF reading, then an EXIT reading for the same tag, with no COUNTER reading for that tag in between, within 12 hours. The equality on the tag is an equivalence test, so each tag gets its own stacks.

Correctness

The proof is in the correctness proof; every statement there is a theorem for the code on this page.

  • RIP. The entries of stack i−1i - 1 at or below the RIP of an entry are exactly the entries that came before it.
  • Completeness. Each event of a window match is on its stack when the last event arrives, because the window keeps it from being pruned and the earlier events of the match make each stack non-empty when the next one arrives.
  • Search. A lower entry on a stack has a smaller RIP, so if it has a path to stack 1, every entry above it has one too. So the search, which stops at the first candidate without a path, still finds all paths, and each path once.
  • Theorem. Every match is emitted exactly once, at the arrival of its last event. The negation test is exact because the negated events between two events of a match are not older than the first event of the match, so pruning keeps them.
Proof: The stack-based matcher reports every match once, at the arrival of its last eventfull

We use the line numbers of the pseudocode. The pattern is SEQ(E1,…,Ek)\mathrm{SEQ}(E_1, \dots, E_k) WITHIN WW with the skip-till-any-match selection. The events arrive in stream order x1,x2,…x^1, x^2, \dots with timestamps that never decrease, and we write p(x)p(x) for the position of event xx. A match is a tuple (e1,…,ek)(e_1, \dots, e_k) of events with p(e1)<⋯<p(ek)p(e_1) < \cdots < p(e_k), the type of eie_i equal to EiE_i, ek.ts−e1.ts≤We_k.ts - e_1.ts \le W, all events in the same partition when there is an equivalence test, no event of a negated type of the same partition strictly between the neighbours of the negation, and the predicate true. Without the last two conditions we call the tuple a window match.

The stacks of one partition see only the events of that partition, so we fix one partition and drop it from the notation. A stack entry is an event with its RIP. Pruning removes entries from the bottom of a stack only, and the absolute index of an entry never changes, so "the entries at or below index rr" is well defined.

Lemma 1 (RIP). Let yy be an entry of stack i≥2i \ge 2 with RIP rr. The entries of stack i−1i - 1 with an index at most rr are exactly the entries that were pushed onto stack i−1i - 1 before yy arrived.

Proof. Stack i−1i - 1 receives its entries in stream order, and line L5 sets rr to its top when yy is pushed. An event of type Ei−1=EiE_{i-1} = E_i is pushed onto both stacks, but line L3 goes from the last position down, so it is pushed onto stack ii, with rr taken, before it is pushed onto stack i−1i - 1. So it is not below its own RIP. □\square

Lemma 2 (window matches are in the stacks). Let (e1,…,ek)(e_1, \dots, e_k) be a window match. Then, when eke_k is processed and after the pruning of line L2, every eie_i is an entry of stack ii.

Proof. For every ii and every time τ≤ek.ts\tau \le e_k.ts, we have ei.ts≥e1.ts≥ek.ts−W≥τ−We_i.ts \ge e_1.ts \ge e_k.ts - W \ge \tau - W, so line L2 never removes eie_i up to the processing of eke_k. We show by induction on ii that eie_i is pushed onto stack ii. Line L4 always lets an event of type E1E_1 onto stack 1. For i≥2i \ge 2, the event ei−1e_{i-1} is on stack i−1i - 1 when eie_i arrives, by the induction hypothesis and because it is not pruned; so the stack is not empty and line L5 pushes eie_i onto stack ii. □\square

Lemma 3 (liveness is monotone). Call an entry live if a path that steps from each entry to a present entry at or below its RIP leads from it to stack 1. If an entry y′y' of stack ii is live and the entry yy is above y′y' in the same stack, then yy is live.

Proof. By induction on ii. Every entry of stack 1 is live. For i≥2i \ge 2, the entry yy arrived after y′y', and the top of stack i−1i - 1 only grows, so RIP(y)≥RIP(y′)\mathrm{RIP}(y) \ge \mathrm{RIP}(y'). A present live entry z′z' at or below RIP(y′)\mathrm{RIP}(y') is then also at or below RIP(y)\mathrm{RIP}(y), so yy is live. □\square

Lemma 4 (construction). When the current event ee is pushed onto stack kk, line L7 produces each window match that ends with ee exactly once, and nothing else.

Proof. The search starts at the entry of ee, which line L5 has just put on top of stack kk. From an entry of stack ii, it tries the present entries of stack i−1i - 1 at or below the RIP, from the newest down, and it stops at the first one from which it finds no path. By Lemma 3, the live candidates are a top segment of this range, so the search visits all of them and then stops; and by induction on ii, the search from an entry finds a path exactly when the entry is live, and then it finds all its paths. So line L7 produces every path from ee to stack 1, each once, because a path is a sequence of distinct entries.

Each path is a window match: by Lemma 1 the positions decrease along the path, the stacks give the types, and every present entry has a timestamp at least e.ts−We.ts - W after line L2, so e1.ts≥e.ts−We_1.ts \ge e.ts - W. Conversely, let (e1,…,ek)(e_1, \dots, e_k) be a window match with ek=ee_k = e. By Lemma 2 each eie_i is a present entry of stack ii, and ei−1e_{i-1} was pushed before eie_i arrived, so it is at or below the RIP of eie_i by Lemma 1. So the tuple is a path. □\square

Theorem 1. Over the whole stream, the matcher emits every match exactly once, and it emits it while it processes the last event of the match.

Proof. A search starts only at the current event, so a tuple can be produced only while its last event is processed, and by Lemma 4 the window matches that end with ee are produced exactly once then. Line L8 keeps a window match if and only if it is a match. The window test is exact. For a negation between positions i−1i - 1 and ii, the matcher keeps the events of the negated types of the partition, pruned like the stacks. Any such event strictly between ei−1e_{i-1} and eie_i has a timestamp at least e1.ts≥e.ts−We_1.ts \ge e.ts - W, so it has not been pruned, and the test sees it. The predicate is checked as given. ■\blacksquare

Theorem 2 (cost of a construction). Let MM be the number of window matches that end with the current event. The search visits at most k2M+kk^2 M + k entries.

Proof. A live entry that the search visits lies on a path that the search produces, and each path has kk entries, so at most kMk M live entries are visited. A live entry makes at most one call on a candidate that is not live, the one where it stops. A call on an entry that is not live tries only its top candidate, which is also not live by Lemma 3, so it follows a single chain of at most k−1k - 1 further entries. This gives at most kM+kM(k−1)=k2Mk M + k M (k - 1) = k^2 M visits when M≥1M \ge 1, and at most kk when M=0M = 0, where the start entry itself is not live. □\square

The other work per event is O(k)O(k) for lines L3 to L5 and, amortized, O(1)O(1) per entry for the pruning of line L2, because each entry is pruned once. The negation test of line L8 costs at most the number of stored negated events per match. The tests count the visits of the search and check the bound.

Complexity

Costs are per event in the word RAM, for one partition.

  • Theorem. The search of a construction visits at most k2M+kk^2 M + k entries, where MM is the number of window matches that end with the event. So its cost is output-sensitive: it never follows a path that does not end in a window match, apart from one failed probe per entry on a match path. This is a worst-case bound per event.
  • Pushes and pruning. Lines L3 to L5 cost O(k)O(k) per event. Line L2 may remove up to knk n entries in one step, which is the worst case, but each entry is removed once, so it costs O(1)O(1) amortized per pushed entry.
  • Space. Each event of the last WW time units is on at most kk stacks, so the stacks use O(kn)O(k n) space for a partition with nn such events.
  • The output. With skip till any match, the number of matches can grow as nkn^k in a window of nn events, so no algorithm can report them all in less time. This is the reason for the more selective strategies of SASE+.
  • The paper's measurements. Wu et al. report experiments on the effect of pushing the window and the equivalence tests into the stacks. These are measurements, and this page does not repeat their numbers.

Properties

  • Online. A match is emitted as soon as its last event arrives, and no earlier time is possible, since the match is not complete before.
  • Exact and deterministic for a stream in timestamp order.
  • Late data. The stacks and the RIP pointers need the events in timestamp order. The code on this page refuses an event that is older than the previous one. A stream with bounded disorder goes through a K-slack buffer first: it holds each event until an event at least DD time units newer has arrived, and then releases the events in order. The tests shuffle the stream within a bounded delay with a seeded generator, pass it through the buffer, and get the same matches as on the sorted stream. Each match is then reported up to DD time units later. An event later than DD breaks the order, so a system must drop it, count it, or send it to a side output; it cannot join a match whose last event was already processed.

Variants and improvements

  • Pushing the window down. Without pruning, the stacks grow with the whole stream and the search builds sequences that the window test later rejects. Pruning by e.ts−We.ts - W, as in line L2, is the SASE optimization that pushes the window into the scan.
  • Partitioned stacks. With an equivalence test, one set of stacks per value of the attribute keeps unrelated events apart, so the RIP ranges hold only candidates that pass the test. This is the other main optimization of the paper.
  • SASE+ and the match buffer. SASE+ (2008) adds Kleene closure, written E+E+, and four event selection strategies: strict contiguity (the events of a match are adjacent in the stream), partition contiguity (adjacent within the partition), skip till next match (irrelevant events are skipped, but a relevant event is not ignored), and skip till any match. Its automaton, an NFA with a buffer, keeps the runs of the automaton and stores their events in one shared match buffer, so that runs with a common prefix share it. This page does not give the details of that buffer, because it could not confirm them.
  • Other engines. Cayuga, ZStream and the CEP libraries of stream processors such as Flink use other automata or trees of operators. The complex event processing page compares the main approaches.

When to use it

Use the stack-based scheme for sequence patterns with time windows where many combinations are wanted, for example in monitoring, fraud detection and RFID tracking, and where the events can be ordered by time first. Use a selection strategy such as skip till next match when only the first or a few matches per start event matter, because skip till any match can produce very many matches. For patterns that are plain joins over windows, a sliding window join may be simpler.

Pitfalls

  • Too many matches. Skip till any match reports every combination, which can be exponential in kk. Set the window and the selection strategy with care.
  • Negation at the ends. A negation before the first or after the last positive component needs a different rule: the code on this page allows negation only between two positive components, and a trailing negation can be decided only when the window has passed.
  • Equal timestamps. Events with the same timestamp need a fixed order, such as the order of arrival or an event id, or the meaning of "followed by" is not defined.
  • Predicates checked late. Conditions that are checked only after the search cost time for every rejected match. Push equivalence tests into the partitions, and simple conditions on one event into the scan.
  • Disorder. Feeding out-of-order events into the stacks gives wrong RIP ranges. Reorder first, with a bound on the delay.

Implementations

This page did not confirm the details of the authors' implementation. The Python code on this page has the stacks with RIP pointers, the pruning by the window, partitioned stacks for one equivalence attribute, negation between positive components, a predicate on the whole match, and a K-slack buffer for bounded disorder. Its tests compare the matches with a brute-force search over all tuples of events, check that each match is emitted at the arrival of its last event, and check the bound on the number of visited entries.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

sase_event_matching.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sase-event-matching/. The authors are listed in prov/482Z67.jsonl.

"""Sequence pattern matching in the style of SASE (Wu, Diao and Rizvi, SIGMOD 2006).

The pattern is SEQ(E_1, ..., E_k) WITHIN W, with the "skip till any match"
selection: every choice of events e_1, ..., e_k in stream order with
e_i of type E_i and e_k.ts - e_1.ts <= W is a match. Options:

- partition: an equivalence test [key]; all events of a match have the same
  key, and each key gets its own set of stacks (partitioned stacks);
- negated: {i: type}, which forbids an event of that type (with the same key)
  strictly between e_{i-1} and e_i, for 1 <= i < k (0-based positions);
- predicate: a function of the tuple of events, checked after construction.

Each position i has a stack of instances (an active instance stack). An entry
holds the event and RIP, the index of the newest entry in stack i - 1 when
the event arrived. Every entry at or below RIP came earlier, so the paths that
follow the RIP pointers from an entry of the last stack are exactly the
sequences that end with it. Entries older than now - W are pruned.

The matcher needs its input in stream order: timestamps that never decrease.
Reorder puts a stream with bounded disorder back into order first.
"""

import heapq
from dataclasses import dataclass, field
from typing import Any, Callable, Iterable, Optional


@dataclass(frozen=True)
class Event:
    type: str
    ts: int
    key: Any = None
    value: Any = None
    eid: int = 0


@dataclass
class _Stack:
    base: int = 0  # the absolute index of entries[0]
    entries: list = field(default_factory=list)  # (event, rip, stream position)

    def top(self) -> int:
        return self.base + len(self.entries) - 1

    def get(self, idx: int):
        return self.entries[idx - self.base]


class SaseMatcher:
    def __init__(
        self,
        types: list[str],
        window: int,
        partition: bool = False,
        negated: Optional[dict[int, str]] = None,
        predicate: Optional[Callable[[tuple], bool]] = None,
    ):
        if not types:
            raise ValueError("the pattern needs at least one positive component")
        negated = dict(negated or {})
        for i in negated:
            if not 1 <= i < len(types):
                raise ValueError("a negation must lie between two positive components")
        self.types, self.window, self.partition = list(types), window, partition
        self.negated, self.predicate = negated, predicate
        self.k = len(types)
        self.parts: dict[Any, list[_Stack]] = {}
        self.neg_events: dict[Any, list[tuple[int, Event]]] = {}  # (position, event)
        self.pos = 0  # the position of the next event in the stream
        self.last_ts = None
        self.visits = 0  # stack entries visited by construction

    def _prune(self, stacks: list[_Stack], negs: list, now: int) -> None:
        lo = now - self.window
        for st in stacks:
            drop = 0
            while drop < len(st.entries) and st.entries[drop][0].ts < lo:
                drop += 1
            if drop:
                del st.entries[:drop]
                st.base += drop
        while negs and negs[0][1].ts < lo:
            negs.pop(0)

    def push(self, e: Event) -> list[tuple[Event, ...]]:
        """Add the next event; return the matches that end with it."""
        if self.last_ts is not None and e.ts < self.last_ts:
            raise ValueError("events must come in timestamp order; use Reorder")
        self.last_ts = e.ts
        p = self.pos
        self.pos += 1
        key = e.key if self.partition else None
        stacks = self.parts.setdefault(key, [_Stack() for _ in range(self.k)])  # @line L1
        negs = self.neg_events.setdefault(key, [])
        self._prune(stacks, negs, e.ts)  # @line L2
        if e.type in self.negated.values():
            negs.append((p, e))
        out = []
        for i in range(self.k - 1, -1, -1):  # @line L3
            if self.types[i] != e.type:
                continue
            if i == 0 or stacks[i - 1].entries:  # @line L4
                rip = stacks[i - 1].top() if i > 0 else -1
                stacks[i].entries.append((e, rip, p))  # @line L5
                if i == self.k - 1:
                    out.extend(self._construct(stacks, negs, e))  # @line L6
        return out

    def _construct(self, stacks, negs, e) -> list[tuple[Event, ...]]:
        found = []
        last = stacks[self.k - 1]
        start = last.get(last.top())

        def dfs(i: int, entry, path: list) -> bool:
            """Extend path (positions k-1 down to i) through the RIP of entry."""
            self.visits += 1
            if i == 0:
                found.append(tuple(reversed(path)))  # @line L7
                return True
            st = stacks[i - 1]
            any_match = False
            idx = entry[1]
            # newest first; an entry lower in the stack has fewer predecessors,
            # so after the first entry without a path, all lower ones fail too
            while idx >= st.base:
                cand = st.get(idx)
                if not dfs(i - 1, cand, path + [cand]):
                    break
                any_match = True
                idx -= 1
            return any_match

        dfs(self.k - 1, start, [start])
        out = []
        for path in found:
            events = tuple(x[0] for x in path)
            if events[-1].ts - events[0].ts > self.window:  # @line L8
                continue
            if any(self._blocked(negs, path[i - 1][2], path[i][2], t) for i, t in self.negated.items()):
                continue
            if self.predicate is not None and not self.predicate(events):
                continue
            out.append(events)  # @line L9
        return out

    @staticmethod
    def _blocked(negs, a: int, b: int, t: str) -> bool:
        return any(a < p < b and n.type == t for p, n in negs)


class Reorder:
    """A K-slack buffer: it holds events until no earlier event can still come.

    It assumes that an event with timestamp t arrives before every event with
    a timestamp of t + D or more. It releases events in (ts, eid) order."""

    def __init__(self, delay: int):
        self.delay, self.heap, self.top = delay, [], None

    def push(self, e: Event) -> list[Event]:
        heapq.heappush(self.heap, (e.ts, e.eid, e))
        self.top = e.ts if self.top is None else max(self.top, e.ts)
        out = []
        while self.heap and self.heap[0][0] <= self.top - self.delay:
            out.append(heapq.heappop(self.heap)[2])
        return out

    def flush(self) -> list[Event]:
        out = [heapq.heappop(self.heap)[2] for _ in range(len(self.heap))]
        return out


def run(matcher: SaseMatcher, events: Iterable[Event], delay: Optional[int] = None):
    """Feed events (through a Reorder buffer when delay is given); return the matches."""
    out = []
    if delay is None:
        for e in events:
            out.extend(matcher.push(e))
        return out
    buf = Reorder(delay)
    for e in events:
        for x in buf.push(e):
            out.extend(matcher.push(x))
    for x in buf.flush():
        out.extend(matcher.push(x))
    return out
test_sase_event_matching.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sase-event-matching/. The authors are listed in prov/482Z67.jsonl.

import itertools
import random

import pytest

from sase_event_matching import Event, Reorder, SaseMatcher, run


def stream_of(spec):
    """spec: a string such as 'a1 b2 c4'; type letter, then timestamp."""
    return [Event(tok[0], int(tok[1:]), eid=i) for i, tok in enumerate(spec.split())]


def ids(matches):
    return sorted(tuple(e.eid for e in m) for m in matches)


def brute_force(events, types, window, partition=False, negated=None, predicate=None):
    """Every increasing index tuple that fits the pattern, from scratch."""
    events = sorted(events, key=lambda e: (e.ts, e.eid))
    negated = negated or {}
    out = []
    for idx in itertools.combinations(range(len(events)), len(types)):
        seq = [events[i] for i in idx]
        if any(e.type != t for e, t in zip(seq, types)):
            continue
        if seq[-1].ts - seq[0].ts > window:
            continue
        if partition and len({e.key for e in seq}) > 1:
            continue
        bad = False
        for i, t in negated.items():
            for j in range(idx[i - 1] + 1, idx[i]):
                n = events[j]
                if n.type == t and (not partition or n.key == seq[0].key):
                    bad = True
        if bad or (predicate is not None and not predicate(tuple(seq))):
            continue
        out.append(tuple(e.eid for e in seq))
    return sorted(out)


def random_events(rng, n, types="abcx", keys=(1, 2), span=30):
    ts = sorted(rng.randrange(span) for _ in range(n))
    return [Event(rng.choice(types), t, rng.choice(keys), rng.randint(0, 9), eid=i) for i, t in enumerate(ts)]


def test_page_example():
    ev = stream_of("a1 b2 a3 c4 b5 c6 c9")
    m = SaseMatcher(["a", "b", "c"], window=5)
    got = []
    for e in ev:
        got.append(ids(m.push(e)))
    # c4 ends a1 b2 c4; c6 ends a1 b2, a1 b5, a3 b5; c9 ends nothing within 5
    assert got == [[], [], [], [(0, 1, 3)], [], [(0, 1, 5), (0, 4, 5), (2, 4, 5)], []]
    neg = SaseMatcher(["a", "c"], window=5, negated={1: "b"})
    assert ids(run(neg, ev)) == [(2, 3)]


def test_rip_pointers_and_pruning():
    ev = stream_of("a1 b2 a3 c4 b5 c6 c9")
    m = SaseMatcher(["a", "b", "c"], window=5)
    for e in ev[:5]:
        m.push(e)
    st = m.parts[None]
    assert [(x[0].eid, x[1]) for x in st[1].entries] == [(1, 0), (4, 1)]
    m.push(ev[5])
    m.push(ev[6])  # now = 9: entries before ts 4 are gone
    assert [x[0].eid for x in st[0].entries] == []
    assert st[0].base == 2
    assert [x[0].eid for x in st[1].entries] == [4]


@pytest.mark.parametrize("seed", [1, 2, 3])
def test_random_matches_brute_force(seed):
    rng = random.Random(seed)
    for _ in range(40):
        k = rng.randint(1, 3)
        types = [rng.choice("abc") for _ in range(k)]
        window = rng.randint(0, 12)
        partition = rng.random() < 0.5
        negated = {}
        if k >= 2 and rng.random() < 0.5:
            negated = {rng.randint(1, k - 1): rng.choice("abx")}
        predicate = None
        if rng.random() < 0.3:
            predicate = lambda s: s[0].value <= s[-1].value
        ev = random_events(rng, rng.randint(0, 22))
        m = SaseMatcher(types, window, partition, negated, predicate)
        emitted = []
        for e in ev:
            for match in m.push(e):
                assert match[-1] is e  # each match is reported when its last event arrives
                emitted.append(match)
        assert ids(emitted) == brute_force(ev, types, window, partition, negated, predicate)


def test_out_of_order_with_reorder_buffer():
    rng = random.Random(77)
    for _ in range(30):
        ev = random_events(rng, rng.randint(1, 25))
        D = rng.randint(1, 4)
        # shuffle within a bounded delay: an event arrives less than D time units late
        arrival = sorted(ev, key=lambda e: e.ts + rng.random() * D)
        types, window = ["a", "b", "c"], 10
        m = SaseMatcher(types, window, partition=True)
        assert ids(run(m, arrival, delay=D)) == brute_force(ev, types, window, partition=True)


def test_reorder_releases_in_order():
    rng = random.Random(5)
    ev = random_events(rng, 40)
    arrival = sorted(ev, key=lambda e: e.ts + rng.random() * 3)
    buf = Reorder(3)
    out = []
    for e in arrival:
        out.extend(buf.push(e))
    out.extend(buf.flush())
    assert [e.eid for e in out] == [e.eid for e in ev]


def test_construction_visits_are_bounded_by_matches():
    """Each visited entry lies on a match path or is one failed probe per entry on one."""
    rng = random.Random(8)
    for _ in range(20):
        ev = random_events(rng, 30, types="abc", keys=(1,), span=40)
        m = SaseMatcher(["a", "b", "c"], window=8)
        total = 0
        for e in ev:
            before = m.visits
            matches = m.push(e)
            total += len(matches)
            assert m.visits - before <= 3 * 3 * len(matches) + 3
        assert total == len(brute_force(ev, ["a", "b", "c"], 8))


def test_errors():
    with pytest.raises(ValueError):
        SaseMatcher([], 3)
    with pytest.raises(ValueError):
        SaseMatcher(["a", "b"], 3, negated={0: "x"})
    m = SaseMatcher(["a"], 3)
    m.push(Event("a", 5))
    with pytest.raises(ValueError):
        m.push(Event("a", 4))

History

Wu, Diao and Rizvi presented SASE at SIGMOD 2006, with the language, the plan of a sequence scan followed by selection, window, negation and transformation, and the optimizations for windows and equivalence tests. Agrawal, Diao, Gyllstrom and Immerman extended the language with Kleene closure in SASE+ at SIGMOD 2008, with a formal automaton model and the event selection strategies. Cugola and Margara (2012) surveyed this line of work together with data stream systems.

References

  1. Eugene Wu, Yanlei Diao and Shariq Rizvi, High-performance complex event processing over streams, Proceedings of ACM SIGMOD 2006, pages 407 to 418, the SASE language with SEQ, negation, WHERE and WITHIN, the query plan with sequence scan and construction over active instance stacks followed by selection, window, negation and transformation, and the optimizations that push the window and the equivalence tests into the scan with partitioned stacks (general locator)
  2. Jagrati Agrawal, Yanlei Diao, Daniel Gyllstrom and Neil Immerman, Efficient pattern matching over event streams, Proceedings of ACM SIGMOD 2008, pages 147 to 160, the SASE+ language with Kleene closure, the NFA with a shared match buffer, and the event selection strategies strict contiguity, partition contiguity, skip till next match and skip till any match (general locator)
  3. Gianpaolo Cugola and Alessandro Margara, Processing flows of information: from data stream to complex event processing, ACM Computing Surveys 44(3), 2012, article 15, the survey of event processing languages and of automaton-based detection, which places SASE among the systems that use automata (general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.amortized
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example