Event Streaming LabPython · Bytewax

Chapter 25 · Real Bytewax

Detect an event sequence

Two failures followed by success is a stateful question.

Prerequisite When is a streaming answer final?.

What you’ll learn

Implement a bounded per-key sequence recognizer and name its ordering, horizon and reset policy.

The question

The operations team wants to investigate devices that fail repeatedly before succeeding. A filter can find individual failures, but it cannot explain whether two failures belong to the same recent sequence.

A sequence recognizer remembers partial matches per key. Our real Bytewax stateful_map retains at most two recent failure timestamps per device. A success emits a match only when two failures remain within an inclusive horizon, then clears the sequence state. The fixture is ordered within each device; absence and arbitrary late-event reordering are separate problems.

Predict the result

d1 fails at 0 and 3, succeeds at 4, fails at 8 and 9, then succeeds at 11. d2 fails at 1 and succeeds at 20. Source arrival order preserves each device’s event order.

How many d1 matches should a ten-second horizon produce? Does a success without enough recent failures count?

Run the experiment

The editor contains the published example. Select Run with the code unchanged.

Python prepares in the background while you read. First use can download about 84 MiB. Your code runs only when you select Run; each run starts with clean experiment state.

Ctrl+Enter or ⌘+Enter runs the code.

Edits are saved in this browser when storage is available.

Troubleshooting

If Python stops responding, restart the environment and try again. Your code and last completed result are kept.

View the published result

The course build ran the published code to generate this output.

{
  "alerts": [
    {
      "device": "d1",
      "at": 4,
      "failures": [
        0,
        3
      ]
    },
    {
      "device": "d1",
      "at": 11,
      "failures": [
        8,
        9
      ]
    }
  ],
  "horizon": 10,
  "boundary": "Two failures then success, per-key ordered fixture and inclusive horizon. No absence timer or arbitrary late-event reordering."
}

Read the result

In alerts, read the device, at, and failures for each match. The policy sends alerts for d1 at 4 and 11 and clears the matched history after each success.

Change the experiment

Replace horizon=10 with horizon=2 in the editor. Select Run again. Compare alerts. At success times 4 and 11, which of the two d1 failure timestamps now falls outside the lookback? The model accepts a failure exactly on the boundary.

Return to the editor
Runtime, source code and downloads

Runtime and reset details explain what stays ready and what is isolated on each run. Download Python packages the published helpers with the code in your editor.

Browse the sources for Bytewax windows and authored models, Kafka log and group exercises, live Kafka input, checkpoint recovery and processing patterns.

Inspect the operator implementation

The editor calls this exact function. See how it connects the operators and applies the policy. Shared imports and collection helpers are in the complete patterns module and course module. Download Python includes both.

def detect_sequence(horizon=10):
    if horizon<=0: raise ValueError('horizon must be positive')
    events=[('d1','fail',0),('d2','fail',1),('d1','fail',3),('d1','ok',4),
            ('d1','fail',8),('d1','fail',9),('d1','ok',11),('d2','ok',20)]
    flow=Dataflow('failure_then_success')
    source=op.input('events',flow,TestingSource(events,batch_size=1))
    keyed=op.key_on('device',source,lambda e:e[0])
    def step(state,event):
        device,kind,at=event
        failures=[t for t in (state or []) if t>=at-horizon]
        if kind=='fail':return (failures+[at])[-2:],None
        alert={'device':device,'at':at,'failures':failures} if len(failures)>=2 else None
        return None,alert
    detected=op.stateful_map('sequence',keyed,step)
    alerts=op.filter('matches',detected,lambda row:row[1] is not None)
    rows=sorted([row for _,row in collect(flow,alerts)],key=lambda r:(r['at'],r['device']))
    return {'alerts':rows,'horizon':horizon,
            'boundary':'Two failures then success, per-key ordered fixture and inclusive horizon. No absence timer or arbitrary late-event reordering.'}

Define what is consumed by a match

Overlapping matches can reuse one event or consume it. A restart can replay part of a match. Decide whether a success resets all failures, how duplicate event IDs behave, and which match identity makes an external alert idempotent.

A horizon is more than a comparison

This callback only prunes a device’s remembered failures when another event arrives. A production resource bound may also need cleanup for devices that never return. The state-expiry lesson and sequence/absence reading distinguish answer semantics from actual retention.

Work, state and recovery costs

Where used, n counts input events, k counts retained distinct keys, r counts overlapping windows per event and z counts output matches. Bounds assume the stated algorithm. Collecting, sorting and displaying results adds work.

QuestionMechanism and boundary
WorkAt most two remembered failures are checked per event, so this callback has constant-sized per-key work; key routing is separate engine work.
StateAt most two timestamps per observed device, without automatic cleanup of devices that never return. Total state still depends on key cardinality.
MovementAll evidence is local. Delivering alerts to an external system adds rate limits, retries and duplicate-effect handling.
ProgressOnly incoming events trigger this recognizer. Silence does not prove an absence condition without a separate timer/progress contract.
RecoveryA replay can reconstruct or repeat a match. Stable event and match identities are needed before claiming idempotent alert delivery.

Think it through

If the final success never arrives, can this event-driven callback alone declare that a device failed to recover within ten seconds?

Show hints
  1. Hint 1

    Silence does not call a per-event callback.

  2. Hint 2

    A timeout needs a clock and a notification/progress mechanism.

  3. Hint 3

    Late success and timeout correction require another explicit policy.

Show explanation

No. An absence pattern needs scheduled notification and a declared time/progress boundary. Define whether it uses processing time or event time, what counts as idle input, and how a late success revises an alert. Counting duplicate deliveries as separate failures is another risk unless identities are deduplicated first.

ReferencesFunction documentation and helper source

References open in a new tab; course helpers are documented separately from library APIs. Bytewax links target the official 0.21.1 definitions and API docstrings.

Experiment scope

A real Bytewax state machine over a bounded per-key ordered fixture. It is not Flink CEP, an absence-timer implementation or a general out-of-order pattern engine.

Primary reference →
Reading marks track what you’ve read independently of your runs.