Chapter 3 · Resolve and operate

Stateful streaming inference without future leakage

For streaming inference, the state transition, ordering policy, deduplication rule, and model version are all part of the model.

65–90 min2 key conceptsReviewed 26 Aug 2026
01 · Production proposition

Long support conversations must be routed while preserving temporal context.

This chapter moves from key and version state to prove replay parity. We will make the idea concrete in a small code example before placing it back inside a production system with a declared latency, cost, and operator-capacity budget.

Decision

Feed a recorded event stream through the production transition one event at a time and compare every score and state checksum with the online trace.

Evidence

Verify the behavior illustrated in stream_state.py, then measure decision utility, slice reliability, and system latency.

Failure consequence

A bidirectional model and globally normalized features use future events unavailable at authorization. An unsafe release must degrade to a named baseline or the last known-good version.

02 · Guided chapter

Build the idea one layer at a time.

A streaming model is not just a trained network behind an endpoint. Its hidden state is a small, evolving database keyed by entity and governed by time.

Offline evaluation often reconstructs an entire ordered history, while production receives one event at a time, sometimes late or twice. If those paths initialize, update, or expire state differently, identical events yield different predictions. Replay parity requires the online transition to be the single source of truth.

Causality also constrains repair. Reordering a late event into past state can silently change decisions that were already made. Define an explicit policy: reject, process in arrival order, or recompute future state while preserving an audit trail. Add state TTLs for inactive entities and idempotency keys for retries.

Keep in view
  • teacher forcing
  • state TTL
WORKED PATH

Follow the reasoning before touching the code.

  1. 01

    Key and version state

    Store state by stable entity ID together with model version, last accepted event time, and expiration. Never reuse state across incompatible model versions.

  2. 02

    Make one atomic transition

    Read state, validate event identity and time, score, update state, and commit the event ID atomically so retries cannot advance memory twice.

  3. 03

    Prove replay parity

    Feed a recorded event stream through the production transition one event at a time and compare every score and state checksum with the online trace.

pythonstream_state.py
states = {}

def process(entity, event_id, event_time, value):
    state = states.setdefault(entity, {'sum': 0, 'time': -1, 'results': {}})
    if event_id in state['results']:
        return state['results'][event_id]
    if event_time < state['time']:
        raise ValueError('late event requires replay')
    score = value + 0.1 * state['sum']
    state['sum'] += value
    state['time'] = event_time
    state['results'][event_id] = score
    return score

print(process('acct-7', 'e1', 10, 4))
print(process('acct-7', 'e1', 10, 4))

A tiny state transition rejects duplicates and out-of-order events.

READ THE EXAMPLE

What to notice

  • The repeated event returns the same result without adding its value twice.
  • The check uses event time for causal order; a production implementation would also expire `seen` IDs and state under a declared TTL.
YOUR TURN Pause and predict before revealing the answer.

What must happen when model version v2 changes the hidden-state shape?

Need a hint?

Old bytes have meaning only under the transition that produced them.

Check your reasoning

Namespace state by model version and either cold-start v2 or migrate it with a tested transformation. Reading v1 state as v2 state is an invalid, usually silent schema change.

Bring forward

Lessons 1, 2, 3, 4 in this course.

03 · Formal treatment

Connect the chapter to the course’s quantitative spine.

For streaming inference, the state transition, ordering policy, deduplication rule, and model version are all part of the model. The lstm cell-state update below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.

Formal treatment
ct=ft⊙ct−1+it⊙gtc_t = f_t \odot c_{t-1} + i_t \odot g_t

LSTM cell-state update

Symbol, shape or unit contract
SymbolMeaning / shape / unit
c_tcell state
f_tforget gate
i_tinput gate
g_tcandidate state
Open derivation and numerical substitution

Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.

  1. Write the named inputs: c_t, f_t, i_t, g_t.
  2. Substitute one small, hand-checkable batch before vectorizing.
  3. Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c11(inputs)
assert is_finite(value)
04 · Deterministic lab

Change one assumption and make the tradeoff visible.

Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.

Estimate

BPTT context lab

Change truncation length and compare retained context with activation memory.

tokens
Primary73.3%
Secondary25.0%
DiagnosisBalanced

Assumption: Single recurrent layer; memory normalized to the 256-token configuration.

Open nonvisual data table
ItemComputed stateInterpretation
8-token signalretained91.0%
16-token signalretained90.1%
32-token signalretained88.2%
64-token signalretained84.3%
128-token signaltruncated5.0%
05 · Production implications

Trace the complete operating path.

Carry the chapter’s central idea into the system: For streaming inference, the state transition, ordering policy, deduplication rule, and model version are all part of the model. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.

  1. 01

    Turn “Key and version state” into a written invariant and a failing test.

  2. 02

    Promote stream_state.py from illustration to a versioned implementation with representative fixtures.

  3. 03

    Use “Prove replay parity” as the release checkpoint: Feed a recorded event stream through the production transition one event at a time and compare every score and state checksum with the online trace.

  4. 04

    Serve or materialize behind explicit a declared latency, cost, and operator-capacity budget.

  5. 05

    Join telemetry to mature outcomes and retain a rollback path.

Observability

Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.

Cost

Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.

Failure modes

A bidirectional model and globally normalized features use future events unavailable at authorization. Add a detector, owner, mitigation, and stop condition for this class of failure.

Alternatives

Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.

06 · Check understanding

Explain the contract, not just the vocabulary.

Browser-graded checkpointPass ≥ 80%
01What does f_t near one do?
02When is bidirectional encoding invalid?
03Why chronological sequence validation?
07 · Apply in production

Causal stateful risk model

Specify an LSTM with temporal splits, masking, BPTT diagnostics, and replay/online state parity.

  • Causal sequence dataset
  • Baseline and recurrent comparison
  • Gradient/state diagnostics
  • Late-event and state policy
Open assignment and rubric
08 · Sources & next depth

Read primary material with a purpose.

09 · Production resolution

Return to the opening failure.

Define causal cutoffs, keyed state, reset/TTL, duplicates, late events, and replay/online parity.

For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce a masked sequence model with bptt, recurrent gates, and attention precursors.

Course production assignmentCausal stateful risk model