Event Streaming LabPython · Bytewax

Chapter 46 · Bytewax + correction policy

Resolve the streaming incident

One pipeline. Several plausible explanations.

Prerequisite Defend the complete design.

What you’ll learn

Diagnose a wrong total using identity, validation, event-time progress, corrections and sink semantics.

The question

The bicycle shop reports that its [0,10) sales total is wrong after a replay. A duplicate, a delayed order and an invalid amount all arrive during the same sequence. Changing one knob without tracing the evidence can fix one symptom and introduce another.

The capstone runs one real Bytewax keyed state machine. Its callback validates amounts, remembers accepted IDs, applies an authored single-window cleanup/correction policy and publishes replacement totals into a local sink view. Watermark control records are predetermined inputs to our policy; they are not Bytewax EventClock measurements. No recovery configuration or external transactional sink is attached. Inspect the callback to identify which work belongs to the engine and which decisions belong to the application.

Follow the first divergence through the whole pipeline
  1. ContractReject invalid recordsAccount for every rejected input.
  2. IdentitySuppress duplicate aRetain the chosen duplicate horizon.
  3. Time policyRevise total 10 → 15Apply the authored late-data rule.
  4. FinalityRoute later c separatelyA final visible total does not count every arrival.

Conceptual diagram. The capstone combines real Bytewax state with a labelled correction policy. Export runs to compare observed evidence.

Predict the result

Every order belongs to the window from 0 up to 10 seconds. The model receives a (£10) twice, advances the watermark to 10, receives b (£5) and bad (−£3), advances the watermark to 15, then receives c (£7).

The deliveries contain a twice (£10), b late (£5), an invalid negative amount and c after cleanup (£7). What should the stored result contain under this policy?

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.

{
  "sink": {
    "0": {
      "revision": 2,
      "total": 15
    }
  },
  "late": [
    "c"
  ],
  "invalid": [
    "bad"
  ],
  "duplicates": [
    "a"
  ],
  "trace": [
    {
      "input": {
        "id": "a",
        "time": 2,
        "amount": 10
      },
      "watermark": -1,
      "total": 10,
      "revision": 0,
      "late": [],
      "invalid": [],
      "duplicates": []
    },
    {
      "input": {
        "id": "a",
        "time": 2,
        "amount": 10
      },
      "watermark": -1,
      "total": 10,
      "revision": 0,
      "late": [],
      "invalid": [],
      "duplicates": [
        "a"
      ]
    },
    {
      "input": {
        "watermark": 10
      },
      "watermark": 10,
      "total": 10,
      "revision": 1,
      "late": [],
      "invalid": [],
      "duplicates": [
        "a"
      ]
    },
    {
      "input": {
        "id": "b",
        "time": 4,
        "amount": 5
      },
      "watermark": 10,
      "total": 15,
      "revision": 2,
      "late": [],
      "invalid": [],
      "duplicates": [
        "a"
      ]
    },
    {
      "input": {
        "id": "bad",
        "time": 6,
        "amount": -3
      },
      "watermark": 10,
      "total": 15,
      "revision": 2,
      "late": [],
      "invalid": [
        "bad"
      ],
      "duplicates": [
        "a"
      ]
    },
    {
      "input": {
        "watermark": 15
      },
      "watermark": 15,
      "total": 15,
      "revision": 2,
      "late": [],
      "invalid": [
        "bad"
      ],
      "duplicates": [
        "a"
      ]
    },
    {
      "input": {
        "id": "c",
        "time": 6,
        "amount": 7
      },
      "watermark": 15,
      "total": 15,
      "revision": 2,
      "late": [
        "c"
      ],
      "invalid": [
        "bad"
      ],
      "duplicates": [
        "a"
      ]
    }
  ],
  "note": "Real Bytewax keyed state; authored watermark controls/correction policy; no external transactional sink or configured checkpoint."
}

Read the result

Read sink, duplicates, invalid, and late. The final sink row contains revision 2 and total 15. Compare it with the revisions shown in trace. Each revision replaces that window’s previous row.

Change the experiment

Select Export run after the first successful run. Replace deduplicate=True with deduplicate=False in the editor. Select Run again. Export that run, then replace deduplicate=False, allowed_lateness=5 with deduplicate=True, allowed_lateness=0 and select Run again. Export the last run. Compare sink, duplicates, and late and identify the first differing trace row for each change.

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.

Submission: make a defensible decision

Keep three artifacts: the baseline run record, a deliberately broken run, and a repaired-policy proposal. Include the exact accepted IDs, side-output reasons and expected sink state. State whether the repair changes the business contract. A successful Run button only establishes execution, not the quality of the diagnosis.

Acceptance rubric

A strong explanation balances receipts against accepted, duplicate, invalid and late paths; identifies why the first divergent step matters; distinguishes upserts from contributions; names state-growth and recovery costs; and proposes independent edge cases. The worked reasoning is a reference, not a score or secure assessment. Finish by relating the local mechanisms to the distributed readings and the operational evidence you would collect.

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
WorkReference hash membership and keyed sink updates are expected O(1); copied trace lists add historical cost.
StateRemembered accepted IDs, output revision and diagnostic history. The model does not implement retention expiry for dedup IDs.
MovementOne Bytewax worker applies the incident policy and writes replacement totals to an in-memory view.
ProgressThe supplied watermark actions trigger the first revision and cleanup. Check the trace to see which inputs fall between those points.
RecoveryThis replay starts with empty state. A real restore would need source position, accepted IDs, window progress and a way to apply sink revisions safely.

Think it through

Write an incident report that distinguishes a policy-correct result from a complete account of all business sales. What would you change if c must eventually count?

Show hints
  1. Hint 1

    A total can be correct under a discard policy while omitting a real sale.

  2. Hint 2

    A late-data path needs a consumer and a reconciliation procedure.

  3. Hint 3

    List which guarantees would require a real broker and checkpointed processing engine.

Show explanation

Report the accepted total, rejected/duplicate identities, watermark/cleanup conventions, revision semantics and source boundaries. If c must count, extend retention or provide an audited correction/rebuild path with stable IDs and idempotent effects. Test boundary equality, a duplicate after retention expiry, an unknown schema, an idle partition and a sink failure. The bounded helper cannot establish distributed recovery; validate those cases in the real deployment.

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.

  • Key ownership and callback state

    Read the keyed stream contract and the callback’s (updated_state, emitted_value) result.

  • Separate operator state from application rules

    Identity checks, validation, late-event classification and output revisions are implemented in the callback.

  • Course helper implementation

    These are functions written for this course, not additional library APIs. Inspect their parameters, operator calls and authored policies. The source shown is generated from the same Python files packaged with Run and Download Python.

Experiment scope

This is a deterministic incident fixture, not a production architecture or a real checkpoint/restart test.

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