Data engineer comparing signal plots and checking SciPy lfilter state between chunks in a Python workspace.

SciPy lfilter: Preserve Filter State Across Signal Chunks

Fri, Nov 27, 2026

An eight-sample signal does not become a different physical signal merely because an upstream reader delivers samples 0–3 today and 4–7 in the next call. Yet that apparently innocuous change, from one array to two arrays, creates a numerical-history obligation. A causal IIR filter must enter sample 4 carrying the state produced by samples 0–3. Reset that state, substitute a recent output for it, associate it with the wrong signal, or attach it to the wrong sample offset, and scipy.signal.lfilter can still return a perfectly ordinary array of the expected length while the filtered history is wrong.

SciPy documents lfilter as a direct-form-II transposed difference-equation filter. If zi is omitted, initial rest is assumed; when zi is supplied, the returned zf contains the final delay values. SciPy also recommends second-order sections for most filtering tasks because they have fewer numerical problems. This article deliberately uses a first-order lfilter fixture instead: the state is one number, every expected value is an exact dyadic rational, and the distinction between “last output” and “filter state” is visible without turning the exercise into a high-order stability study.

The laboratory below is EXPECTED / NOT EXECUTED. No lfilter, lfiltic, or lfilter_zi behavioral case was run. Accordingly, every evidence record begins with executed=false and observed=null. The goal is a qualified filtered candidate plus a continuation checkpoint, not an automatic production deployment.

Define the continuous-signal contract

The object being qualified is one finite observation of a named signal, not a collection of transport chunks. Its contract has four coordinates: a stable stream_id, an integer sample position, a fixed coefficient revision, and an explicitly declared prehistory. A chunk is admissible only when its half-open interval [start, stop) begins at the checkpoint’s next_sample_index.

The output obligation is correspondingly precise: one correctly attributed filtered value for every admitted source sample, followed by the numerical state needed if another contiguous sample arrives. Array length alone is insufficient. An eight-element result can contain eight values produced from the wrong history.

For this laboratory, the bounded application decisions are:

Decision

Meaning

ACCEPT

Candidate reconciles against the literal oracle, source ledger, state context, and required case evidence.

REPAIR

A known reset, representation, or ownership defect can be reconstructed from qualified evidence.

HOLD

Required context (initial policy, ownership, offset, coefficients, or history) is unknown or inconsistent.

REPLAY_FROM_SOURCE

Retained raw samples are available and rebuilding from an earlier qualified boundary is safer than guessing state.

RERUN

Runtime/profile or laboratory revision changed, so the qualification evidence must be regenerated.

A finite observation may end with a nonzero delay. That is not an incomplete result. Appending zero-valued inputs to make the delay vanish would add samples that were never part of the declared signal and therefore change the contract. Unlike a decoder with a terminal finalization operation, lfilter produces one output per admitted input sample; there is no decoder-style flush documented by this API. zf is simply continuation state.

Pin the first-order filter and input profile

The proposed profile is local Linux, CPython 3.12.14, NumPy 2.3.5, SciPy 1.17.0, CPU-resident ordinary NumPy float64 arrays, one dimension, finite nonempty chunks, sequential calls, and axis=-1. The wrapper stops on a profile mismatch instead of silently attaching old qualification evidence to another runtime.

The coefficients are fixed:

b = np.array([0.5], dtype=np.float64)
a = np.array([1.0, -0.5], dtype=np.float64)
COEFFICIENT_REVISION = "one-pole-half-v1"

SciPy 1.17.0 says zi must have length max(len(a), len(b)) - 1, which is one here. It also says omitting zi assumes initial rest and that zf is returned only when zi is provided. The laboratory therefore supplies an explicit one-element zero state even for the rest baseline whenever it needs both y and zf.

This fixture is intentionally not general production-filter advice. SciPy explicitly recommends sosfilt and second-order-section designs for most filtering tasks because of numerical considerations. The first-order transfer function here is chosen because state semantics (not high-order numerical conditioning) are under examination. That narrow use fits alongside the broader scientific Python toolkit, without implying that every real signal-processing pipeline should use direct-form lfilter. The linked Refonte article is contextual rather than authoritative for SciPy API behavior.

The SciPy 1.17.0 pages also document experimental Array API backend support, but that wider backend surface is excluded here; this qualification admits ordinary NumPy CPU arrays only.

Name the state owner and next sample index

A naked array such as array([0.0625]) cannot tell you what produced it. The application-owned checkpoint therefore carries the state vector together with its meaning:

@dataclass(frozen=True)
class Checkpoint:
    stream_id: str
    next_sample_index: int
    coefficient_revision: str
    b: np.ndarray
    a: np.ndarray
    initialization_policy: str
    zi: np.ndarray

stream_id and next_sample_index come from an independent source ledger, not from comparing sample values. That matters particularly for zero-valued regions: identical values cannot authenticate which signal or which position they represent.

Each test case starts with fresh state. F03’s deliberate reset cannot leak into F04; F08’s swapped ownership cannot contaminate F09. A qualification laboratory that reuses mutated diagnostic state between cases makes its own evidence order-dependent.

Author the sample-by-sample recurrence oracle

The source literals are fixed independently of SciPy:

L = [2, 0, 0, 0, 0, 0, 0, 0]
R = [0, 0, 0, 0, 0, 0, 0, 0]
STEP = [1, 1, 1, 1, 1, 1, 1, 1]
SAMPLE_INDICES = [0, 1, 2, 3, 4, 5, 6, 7]

SciPy’s documented difference equation is

scipy-img-first

for this first-order case, because there are no higher numerator terms. With b0=1/2, a0=1, and a1=-1/2, the recurrence becomes

scipy-img-second

That derivation follows from the documented difference-equation formulation rather than from observing a SciPy result.

Under initial rest, y[-1]=0. Therefore the authored L outputs are:

n

x[n]

y[n]

delay after n

0

2

1

1/2

1

0

1/2

1/4

2

0

1/4

1/8

3

0

1/8

1/16

4

0

1/16

1/32

5

0

1/32

1/64

6

0

1/64

1/128

7

0

1/128

1/256

For this filter’s direct-form-II transposed state equation, the single delay after sample n is -a1*y[n] = y[n]/2. That relationship is special to these coefficients; it must not be generalized to arbitrary filters. SciPy’s documentation identifies the internal d variables as the state variables used by the direct-form-II transposed implementation.

R, being all zeros under initial rest, has zero output and zero delay throughout.

The source arrays themselves remain retained evidence. The same discipline used to preserve the raw source and its grain applies here at a narrower numerical boundary: do not overwrite the only copy of the admitted samples while diagnosing a transform. The linked article discusses dataset cleaning, not IIR semantics.

Keep literal expectations independent of SciPy

The rational oracle uses fractions.Fraction from integer numerator/denominator pairs. Python’s fractions documentation defines exact rational arithmetic and supports constructing a Fraction directly from two integers. The consulted 3.12 documentation currently renders as Python 3.12.16; that page is not evidence that the proposed runtime was exactly that patch. The operations used below are longstanding Fraction arithmetic.

from fractions import Fraction

def fraction_oracle(integer_samples, y_minus_1):
    previous = Fraction(y_minus_1)
    outputs = []
    delays = []
    for raw_x in integer_samples:
        x = Fraction(int(raw_x), 1)
        y = (x + previous) / 2
        z = y / 2
        outputs.append(y)
        delays.append(z)
        previous = y
    return outputs, delays

L_Y_LITERAL = [
    Fraction(1, 1), Fraction(1, 2), Fraction(1, 4), Fraction(1, 8),
    Fraction(1, 16), Fraction(1, 32), Fraction(1, 64), Fraction(1, 128),
]
L_Z_LITERAL = [
    Fraction(1, 2), Fraction(1, 4), Fraction(1, 8), Fraction(1, 16),
    Fraction(1, 32), Fraction(1, 64), Fraction(1, 128), Fraction(1, 256),
]

assert fraction_oracle(L, Fraction(0, 1)) == (L_Y_LITERAL, L_Z_LITERAL)

Only after the rational and literal tables agree are they converted to float64.

def f64(fracs):
    return np.array([float(v) for v in fracs], dtype=np.float64)

For this short dyadic fixture, every expected fraction has an exact binary floating-point representation. That makes exact comparison appropriate here, not generally. NumPy documents assert_array_equal(..., strict=True) as checking shape and dtype as well as values and disabling scalar special treatment; its documentation also notes that matching NaNs compare equal, so the laboratory performs a separate finiteness check first.

Establish the complete-signal baseline

F01 is a one-call comparison case for L, beginning with explicit zi=[0.0]. Its EXPECTED / NOT EXECUTED output is the eight literal values above, and its expected final state is [1/256].

One-call filtering is not the oracle. It is a useful reference path, but an implementation and its own output cannot independently prove themselves correct. The independent recurrence and literal ledger remain authoritative for this fixture.

The baseline also records source identities (L,0) through (L,7), input and output shapes, initial and final delay, coefficient copies, and source copies. Supplying zi explicitly is important because SciPy returns zf only when zi is supplied.

The reusable guards are straightforward:

def require_finite_vector(name, value, expected_len=None):
    arr = np.asarray(value)
    if arr.ndim != 1:
        raise ValueError(f"{name}: expected 1-D array")
    if arr.dtype != np.float64:
        raise TypeError(f"{name}: expected float64")
    if len(arr) == 0:
        raise ValueError(f"{name}: empty arrays are not admitted")
    if expected_len is not None and len(arr) != expected_len:
        raise ValueError(f"{name}: expected length {expected_len}")
    if not np.isfinite(arr).all():
        raise ValueError(f"{name}: non-finite value")
    return arr

def assert_exact(actual, expected):
    require_finite_vector("actual", actual)
    require_finite_vector("expected", expected)
    np.testing.assert_array_equal(actual, expected, strict=True)

The eventual F01 run must additionally prove that its input arrays and coefficient arrays remain equal to saved copies. That preservation check is an authored laboratory requirement, not a claim that a prior behavioral execution established nonmutation.

Preserve delay state across different chunk partitions

F02 processes L[0:4] and then L[4:8]. The expected first output is [1, 1/2, 1/4, 1/8]; the expected returned state is [1/16]. The second call receives exactly that returned state, with owner L and next_sample_index=4.

The expected tail is [1/16, 1/32, 1/64, 1/128], ending in [1/256]. This is the core lfilter zi zf handoff: SciPy documents zi as the incoming filter-delay vector and zf as the final delay vector when initial state is supplied. The tutorial likewise describes retaining intermediate state so the difference-equation calculation can be restarted in the same state.

The boundary check is not simply len(zf) == 1. Before the second call, the envelope must say: owner L, next index 4, coefficient revision one-pole-half-v1, initialization policy initial-rest, state [1/16].

There is a useful conceptual comparison with state ownership across UTF-8 chunks: both tasks require intermediate state to remain attached to one logical input across arbitrary chunks. But the terminal rule is different. The UTF-8 article deals with decoder finalization; lfilter has no corresponding terminal flush in this contract.

Vary chunk sizes without changing the initial history

F04 starts fresh and partitions the same L as lengths 1,2,5: [0:1], [1:3], and [3:8].

Its expected boundary delays are respectively [1/2], [1/8], and [1/256]. Concatenating the three expected output pieces still yields:

[1, 1/2, 1/4, 1/8, 1/16, 1/32, 1/64, 1/128]

F04 is checked directly against the independent manifest, not merely against F01. Otherwise two paths that shared the same mistake could falsely validate each other.

The exact-equality claim is intentionally narrow. It relies on these eight values being dyadic float64 numbers and on this specific short recurrence. It is not a claim that arbitrary long IIR streams, different implementations, alternate backends, or coefficients requiring rounded arithmetic will be bitwise identical.

Expose the reset and last-output failures

F03 repeats F02’s two four-sample chunks but deliberately supplies zi=[0.0] again for the second call. Its expected prefix remains correct. The expected tail is four zeros, with final state [0].

The important evidence is the first call’s returned [1/16], which existed and was discarded. All eight source samples can still receive output values. Shape and sample count therefore cannot prove IIR filter state continuity.

F05 demonstrates a subtler error. It prepares a correct fresh prefix through sample 3, then passes [1/8], the previous filtered output, as the next zi. That vector has the right dtype and the right one-element shape, but it represents the wrong numerical quantity.

The expected F05 tail is:

[1/8, 1/16, 1/32, 1/64]

and expected final state is [1/128].

Why? At sample 3, y[3]=1/8; the state required before sample 4 is half of that output, namely 1/16. Passing 1/8 doubles the entering delay. The defect is therefore not “forgot to retain a recent number.” It is “retained a number whose representation does not match lfilter’s required internal state.”

F03 is classified as REPAIR_RESET_STATE if the discarded qualified state is still available. F05 is REPAIR_STATE_REPRESENTATION if approved history permits reconstructing the required delay. Their faulty candidates remain preserved; repair produces a separate candidate rather than rewriting the diagnostic evidence.

Reconstruct a qualified boundary state

F06 starts from a fresh validated prefix and an approved historical output y[3]=1/8. It does not pass that output directly as zi. Instead it asks lfiltic to transform stated signal history into the internal state representation:

zi_reconstructed = signal.lfiltic(
    b,
    a,
    y=np.array([1.0 / 8.0], dtype=np.float64),
)

SciPy documents lfiltic as constructing lfilter state from prior output and optional prior input vectors. For y, the most recent value comes first: {y[-1], y[-2], ...}.

For this fixture, the expected reconstructed state is [1/16]. Continuing the original source at L[4:8] should therefore produce the original tail and end at [1/256]. F06 is EXPECTED / NOT EXECUTED until an actual run demonstrates those results.

Limit recovery to the history the filter actually needs

The key distinction is representation. y[3]=1/8 is historical output. zi=[1/16] is the direct-form-II transposed delay required to enter sample 4. lfiltic exists to convert specified input/output history into that internal initial-condition vector.

One previous output suffices here because len(a)-1 == 1 and the numerator has no prior-input term: len(b)-1 == 0. That is a property of this admitted first-order filter. SciPy’s lfiltic documentation explicitly defines how many previous y and x terms correspond to filter orders.

Do not turn F06 into a generic “last output restores any IIR” rule. A higher-order or different transfer function can require several prior outputs and inputs. If stream identity, offset, coefficient revision, or required history is unqualified, the appropriate decision is HOLD or REPLAY_FROM_SOURCE, not state invention.

Choose initial rest or steady-step history explicitly

F07 contains two separately declared initialization paths over STEP.

The initial-rest path starts with zi=[0.0]. Its expected outputs are:

[1/2, 3/4, 7/8, 15/16, 31/32, 63/64, 127/128, 255/256]

with expected final state [255/512].

The second path represents an already settled unit step. SciPy documents lfilter_zi as computing the initial state corresponding to the steady state of the step response; it solves for an initial condition whose response to all ones is constant. For these coefficients, the authored expected state is [1/2]. Under the declared prehistory y[-1]=1, the expected output is eight ones, and the final state remains [1/2].

Both are legitimate mathematical problems. They are not interchangeable policies.

Calling lfilter_zi at every arbitrary chunk boundary would not reconstruct the actual history of the preceding chunk. Its documented purpose is steady-step initialization, not unknown-history recovery. Under an application contract that declares initial rest, silently substituting steady-state initialization receives HOLD_INITIAL_POLICY, even if the resulting first samples appear visually smoother.

The approved prehistory belongs to the signal contract. The numerical routine cannot infer from aesthetic smoothness whether the sensor was previously at rest, already exposed to a steady input, restarted after a gap, or entered from another known history.

Keep each signal's state with its owner

F08 introduces the only two-signal ownership comparison. It prepares independent fresh prefixes for L and R. The expected prefix checkpoint states are [1/16] for L and [0] for R.

The diagnostic then intentionally bypasses the ownership wrapper and swaps those numeric vectors before processing the two second chunks.

Expected result:

Stream

Wrong incoming state

Expected wrong tail

Expected final state

L

0

[0,0,0,0]

[0]

R

1/16

[1/16,1/32,1/64,1/128]

[1/256]

Both calls use valid one-element float64 arrays. Nothing about the numerical vector itself authenticates its origin. A checked wrapper must therefore reject a checkpoint whose stream_id differs from the requested stream before calling SciPy.

A channel sum can conceal two wrong streams

F08 has a deliberately treacherous invariant. At every second-half sample index, the swapped outputs still sum to the correct combined L+R value. The missing tail from L has merely migrated into R.

Therefore even exact aggregate agreement cannot establish per-signal correctness. The reconciliation unit must be the tuple (stream_id, sample_index, output), plus checkpoint ownership, rather than a channel sum.

This is also why “per-channel filter state” is more than a data-structure convention. The state vector is numerical history for a particular signal. Moving it to another signal preserves its shape while changing its meaning.

Nothing in this sequential two-signal example establishes thread safety, concurrent mutation behavior, or distributed-stream isolation. Those are explicitly outside scope.

Reorder stream processing without exchanging states

F09 starts fresh, processes both four-sample prefixes correctly, and stores checkpoints keyed by stream_id. It then processes R[4:8] before L[4:8].

That call order must be irrelevant because the lookup key, not loop position, selects each checkpoint. Before filtering, the wrapper validates owner, start offset, coefficient revision, initialization policy, state shape, dtype, and finiteness.

The expected complete results are the original eight literal L outputs and eight zeros for R; expected final states are L=[1/256] and R=[0].

F09 also requires exactly sixteen output identities:

(L,0) ... (L,7)
(R,0) ... (R,7)

each occurring once. A numerically correct array associated with the wrong identity fails reconciliation.

The broader lesson is architectural but local: SciPy owns the numerical operation, while the application owns the envelope that authenticates where the state belongs. lfilter documents the state vector and its filtering semantics; it does not document an application-level stream ID, sample offset, coefficient revision label, or checkpoint registry. Those are authored controls.

Reject overlap and gaps before filtering

F10 begins by preparing a fresh valid L prefix through index 3. Its checkpoint therefore has next_sample_index=4.

Two second-chunk attempts are then made:

overlap_start3 -> source slice L[3:7]
gap_start5     -> source slice L[5:8]

Both must be rejected by the application guard before another lfilter call. The overlap variant receives HOLD_OFFSET; so does the gap variant. There is no accepted candidate output and the checkpoint remains unchanged.

The call accounting must be worded carefully. The earlier valid-prefix preparation did require filtering. What remains zero is the number of additional filter invocations made for each rejected continuation attempt.

The guard is conceptually simple:

def check_boundary(cp, requested_stream_id, start_index, revision, init_policy):
    if cp.stream_id != requested_stream_id:
        raise OwnershipError("checkpoint owner mismatch")
    if start_index != cp.next_sample_index:
        raise OffsetError(
            f"expected start {cp.next_sample_index}, got {start_index}"
        )
    if cp.coefficient_revision != revision:
        raise CoefficientError("coefficient revision mismatch")
    if cp.initialization_policy != init_policy:
        raise InitializationPolicyError("initialization policy mismatch")

Do not silently drop sample 3 from the overlap, synthesize sample 4 for the gap, deduplicate by value, or infer sample positions from the arrays. Those would be new source-admission policies.

These errors are not claimed SciPy exceptions. They are application-owned safeguards placed ahead of SciPy because a numerical filtering API cannot know the source ledger’s identity semantics.

Reconcile every case with retained evidence

The laboratory below is designed to become executable evidence only when someone deliberately invokes --run. As presented here, it has not been executed. The specified package profile (Python 3.12.14, NumPy 2.3.5, SciPy 1.17.0) must not be conflated with behavioral qualification or even with proof of imported module origins. An eventual run records both metadata and file locations.

#!/usr/bin/env python3
from future import annotations

import argparse
import copy
import json
import platform
import sys
from dataclasses import asdict, dataclass
from fractions import Fraction
from importlib import metadata

import numpy as np
import scipy
from scipy import signal

EXPECTED_PYTHON = "3.12.14"
EXPECTED_NUMPY = "2.3.5"
EXPECTED_SCIPY = "1.17.0"

REV = "one-pole-half-v1"
INIT_REST = "initial-rest"
INIT_STEADY_STEP = "steady-unit-step"

B = np.array([0.5], dtype=np.float64)
A = np.array([1.0, -0.5], dtype=np.float64)

L_INT = [2, 0, 0, 0, 0, 0, 0, 0]
R_INT = [0, 0, 0, 0, 0, 0, 0, 0]
STEP_INT = [1, 1, 1, 1, 1, 1, 1, 1]
SAMPLE_INDICES = list(range(8))

L = np.array(L_INT, dtype=np.float64)
R = np.array(R_INT, dtype=np.float64)
STEP = np.array(STEP_INT, dtype=np.float64)

class BoundaryError(RuntimeError):
    pass

class OwnershipError(BoundaryError):
    pass

class OffsetError(BoundaryError):
    pass

class CoefficientError(BoundaryError):
    pass

class InitializationPolicyError(BoundaryError):
    pass

@dataclass(frozen=True)
class Checkpoint:
    stream_id: str
    next_sample_index: int
    coefficient_revision: str
    b: np.ndarray
    a: np.ndarray
    initialization_policy: str
    zi: np.ndarray

@dataclass
class CaseRecord:
    case_id: str
    path: str
    status_label: str = "EXPECTED / NOT EXECUTED"
    executed: bool = False
    observed: object = None
    expected: object = None
    decision: str = ""
    filter_calls: int = 0

def frac_oracle(samples, y_minus_1):
    previous = Fraction(y_minus_1)
    ys, zs = [], []
    for raw in samples:
        x = Fraction(int(raw), 1)
        y = (x + previous) / 2
        z = y / 2
        ys.append(y)
        zs.append(z)
        previous = y
    return ys, zs

L_Y_FRAC = [
    Fraction(1), Fraction(1, 2), Fraction(1, 4), Fraction(1, 8),
    Fraction(1, 16), Fraction(1, 32), Fraction(1, 64), Fraction(1, 128),
]
L_Z_FRAC = [
    Fraction(1, 2), Fraction(1, 4), Fraction(1, 8), Fraction(1, 16),
    Fraction(1, 32), Fraction(1, 64), Fraction(1, 128), Fraction(1, 256),
]
R_Y_FRAC = [Fraction(0)] 8
R_Z_FRAC = [Fraction(0)] 8
STEP_REST_Y_FRAC = [
    Fraction(1, 2), Fraction(3, 4), Fraction(7, 8), Fraction(15, 16),
    Fraction(31, 32), Fraction(63, 64), Fraction(127, 128), Fraction(255, 256),
]

def f64(fracs):
    return np.array([float(v) for v in fracs], dtype=np.float64)

L_Y = f64(L_Y_FRAC)
R_Y = f64(R_Y_FRAC)
STEP_REST_Y = f64(STEP_REST_Y_FRAC)

def check_literal_oracle():
    assert frac_oracle(L_INT, Fraction(0)) == (L_Y_FRAC, L_Z_FRAC)
    assert frac_oracle(R_INT, Fraction(0)) == (R_Y_FRAC, R_Z_FRAC)
    ys, = fracoracle(STEP_INT, Fraction(0))
    assert ys == STEP_REST_Y_FRAC

def exact(actual, expected, label):
    actual = np.asarray(actual)
    expected = np.asarray(expected)
    if not np.isfinite(actual).all():
        raise AssertionError(f"{label}: actual contains non-finite values")
    if not np.isfinite(expected).all():
        raise AssertionError(f"{label}: expected contains non-finite values")
    np.testing.assert_array_equal(actual, expected, strict=True)

def admit_chunk(x):
    if not isinstance(x, np.ndarray):
        raise TypeError("chunk must be an ordinary numpy.ndarray")
    if x.ndim != 1 or x.size == 0:
        raise ValueError("chunk must be finite, nonempty and one-dimensional")
    if x.dtype != np.float64:
        raise TypeError("chunk must have dtype float64")
    if not np.isfinite(x).all():
        raise ValueError("chunk contains non-finite values")
    return x

def validate_zi(zi):
    zi = np.asarray(zi)
    if zi.shape != (1,) or zi.dtype != np.float64:
        raise ValueError("zi must be a one-element float64 vector")
    if not np.isfinite(zi).all():
        raise ValueError("zi must be finite")
    return zi

def checkpoint(stream_id, next_index, init_policy, zi):
    return Checkpoint(
        stream_id=stream_id,
        next_sample_index=next_index,
        coefficient_revision=REV,
        b=B.copy(),
        a=A.copy(),
        initialization_policy=init_policy,
        zi=validate_zi(np.asarray(zi, dtype=np.float64)).copy(),
    )

def validate_boundary(cp, stream_id, start_index, init_policy):
    if cp.stream_id != stream_id:
        raise OwnershipError
    if cp.next_sample_index != start_index:
        raise OffsetError
    if cp.coefficient_revision != REV:
        raise CoefficientError
    if cp.initialization_policy != init_policy:
        raise InitializationPolicyError
    exact(cp.b, B, "checkpoint b")
    exact(cp.a, A, "checkpoint a")
    validate_zi(cp.zi)

def filter_checked(cp, stream_id, start_index, chunk, init_policy):
    validate_boundary(cp, stream_id, start_index, init_policy)
    x = admit_chunk(chunk)
    x_before = x.copy()
    b_before, a_before = B.copy(), A.copy()
    y, zf = signal.lfilter(B, A, x, axis=-1, zi=cp.zi.copy())
    exact(x, x_before, "source preserved")
    exact(B, b_before, "b preserved")
    exact(A, a_before, "a preserved")
    return (
        np.asarray(y, dtype=np.float64),
        checkpoint(stream_id, start_index + len(x), init_policy, zf),
    )

def env():
    return {
        "python": platform.python_version(),
        "numpy_metadata": metadata.version("numpy"),
        "scipy_metadata": metadata.version("scipy"),
        "numpy_module": getattr(np, "__file__", None),
        "scipy_module": getattr(scipy, "__file__", None),
        "platform": platform.platform(),
    }

def require_profile():
    e = env()
    wanted = (EXPECTED_PYTHON, EXPECTED_NUMPY, EXPECTED_SCIPY)
    got = (e["python"], e["numpy_metadata"], e["scipy_metadata"])
    if got != wanted:
        raise RuntimeError(f"profile mismatch: expected {wanted}, got {got}")
    return e

def identities(stream_id, start, count):
    return [(stream_id, i) for i in range(start, start + count)]

def run_cases():
    require_profile()
    check_literal_oracle()
    out = {}

    # F01
    cp0 = checkpoint("L", 0, INIT_REST, [0.0])
    y, cp1 = filter_checked(cp0, "L", 0, L.copy(), INIT_REST)
    exact(y, L_Y, "F01 y")
    exact(cp1.zi, np.array([1/256], dtype=np.float64), "F01 zf")
    out["F01"] = (y, cp1)

    # F02
    cp0 = checkpoint("L", 0, INIT_REST, [0.0])
    y1, cp = filter_checked(cp0, "L", 0, L[0:4].copy(), INIT_REST)
    exact(cp.zi, np.array([1/16], dtype=np.float64), "F02 boundary")
    y2, cp = filter_checked(cp, "L", 4, L[4:8].copy(), INIT_REST)
    exact(np.concatenate([y1, y2]), L_Y, "F02 y")
    out["F02"] = (np.concatenate([y1, y2]), cp)

    # F03: deliberately reset second chunk
    cp0 = checkpoint("L", 0, INIT_REST, [0.0])
    y1, correct_boundary = filter_checked(cp0, "L", 0, L[0:4].copy(), INIT_REST)
    reset_cp = checkpoint("L", 4, INIT_REST, [0.0])
    y2, wrong_final = filter_checked(reset_cp, "L", 4, L[4:8].copy(), INIT_REST)
    exact(y2, np.zeros(4, dtype=np.float64), "F03 wrong tail")
    out["F03"] = (np.concatenate([y1, y2]), correct_boundary, wrong_final)

    # F04: chunks 1,2,5
    cp = checkpoint("L", 0, INIT_REST, [0.0])
    pieces = []
    for start, stop, expected_z in [(0,1,1/2),(1,3,1/8),(3,8,1/256)]:
        y, cp = filter_checked(cp, "L", start, L[start:stop].copy(), INIT_REST)
        exact(cp.zi, np.array([expected_z], dtype=np.float64), "F04 boundary")
        pieces.append(y)
    exact(np.concatenate(pieces), L_Y, "F04 y")
    out["F04"] = (np.concatenate(pieces), cp)

    # F05: wrong representation, previous output used as zi
    cp0 = checkpoint("L", 0, INIT_REST, [0.0])
    y1, = filterchecked(cp0, "L", 0, L[0:4].copy(), INIT_REST)
    wrong_cp = checkpoint("L", 4, INIT_REST, [1/8])
    y2, cp = filter_checked(wrong_cp, "L", 4, L[4:8].copy(), INIT_REST)
    exact(y2, np.array([1/8,1/16,1/32,1/64], dtype=np.float64), "F05 tail")
    exact(cp.zi, np.array([1/128], dtype=np.float64), "F05 final")
    out["F05"] = (np.concatenate([y1, y2]), cp)

    # F06: reconstruct from approved y[3]
    zi = signal.lfiltic(B, A, y=np.array([1/8], dtype=np.float64))
    exact(zi, np.array([1/16], dtype=np.float64), "F06 reconstructed zi")
    cp = checkpoint("L", 4, INIT_REST, zi)
    y2, cp = filter_checked(cp, "L", 4, L[4:8].copy(), INIT_REST)
    exact(y2, L_Y[4:8], "F06 tail")
    out["F06"] = (y2, cp)

    # F07 rest path
    cp = checkpoint("STEP", 0, INIT_REST, [0.0])
    y_rest, cp_rest = filter_checked(cp, "STEP", 0, STEP.copy(), INIT_REST)
    exact(y_rest, STEP_REST_Y, "F07 rest")
    exact(cp_rest.zi, np.array([255/512], dtype=np.float64), "F07 rest zf")

    # F07 steady-step path
    zi = signal.lfilter_zi(B, A)
    exact(zi, np.array([1/2], dtype=np.float64), "F07 steady zi")
    cp = checkpoint("STEP", 0, INIT_STEADY_STEP, zi)
    y_steady, cp_steady = filter_checked(
        cp, "STEP", 0, STEP.copy(), INIT_STEADY_STEP
    )
    exact(y_steady, np.ones(8, dtype=np.float64), "F07 steady")
    exact(cp_steady.zi, np.array([1/2], dtype=np.float64), "F07 steady zf")
    out["F07"] = {
        "initial_rest": (y_rest, cp_rest),
        "steady_step": (y_steady, cp_steady),
    }

    # F08: unguarded ownership-swap diagnostic
    cpL0 = checkpoint("L", 0, INIT_REST, [0.0])
    cpR0 = checkpoint("R", 0, INIT_REST, [0.0])
    yL1, cpL = filter_checked(cpL0, "L", 0, L[:4].copy(), INIT_REST)
    yR1, cpR = filter_checked(cpR0, "R", 0, R[:4].copy(), INIT_REST)
    yL2, zL = signal.lfilter(B, A, L[4:].copy(), zi=cpR.zi.copy())
    yR2, zR = signal.lfilter(B, A, R[4:].copy(), zi=cpL.zi.copy())
    exact(yL2, np.zeros(4, dtype=np.float64), "F08 L tail")
    exact(yR2, L_Y[4:], "F08 R tail")
    exact(yL2 + yR2, L_Y[4:] + R_Y[4:], "F08 aggregate")
    out["F08"] = (yL1, yR1, yL2, zL, yR2, zR)

    # F09: reverse second-half call order, preserve owners
    cpL0 = checkpoint("L", 0, INIT_REST, [0.0])
    cpR0 = checkpoint("R", 0, INIT_REST, [0.0])
    yL1, cpL = filter_checked(cpL0, "L", 0, L[:4].copy(), INIT_REST)
    yR1, cpR = filter_checked(cpR0, "R", 0, R[:4].copy(), INIT_REST)
    states = {"L": cpL, "R": cpR}
    yR2, states["R"] = filter_checked(
        states["R"], "R", 4, R[4:].copy(), INIT_REST
    )
    yL2, states["L"] = filter_checked(
        states["L"], "L", 4, L[4:].copy(), INIT_REST
    )
    exact(np.concatenate([yL1,yL2]), L_Y, "F09 L")
    exact(np.concatenate([yR1,yR2]), R_Y, "F09 R")
    out["F09"] = (states, yL1, yL2, yR1, yR2)

    # F10: valid prefix, then two guarded invalid attempts
    cp0 = checkpoint("L", 0, INIT_REST, [0.0])
    , qualified = filterchecked(cp0, "L", 0, L[:4].copy(), INIT_REST)
    before = copy.deepcopy(qualified)
    rejected = {}
    for name, start in [("overlap_start3", 3), ("gap_start5", 5)]:
        try:
            validate_boundary(qualified, "L", start, INIT_REST)
        except OffsetError:
            rejected[name] = "HOLD_OFFSET"
        else:
            raise AssertionError(f"F10 {name}: expected rejection")
        exact(qualified.zi, before.zi, f"F10 {name} checkpoint unchanged")
        assert qualified.next_sample_index == before.next_sample_index
    out["F10"] = rejected

    return out

PLAN = {
    "research_date": "2026-11-27",
    "executed": False,
    "observed": None,
    "status": "EXPECTED / NOT EXECUTED",
    "cases_required": [
        "F01","F02","F03","F04","F05","F06","F07","F08","F09","F10"
    ],
    "required_subpaths": [
        "F07.initial_rest",
        "F07.steady_step",
        "F10.overlap_start3",
        "F10.gap_start5",
    ],
}

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--run",
        action="store_true",
        help="execute behavioral cases; without this flag only emit the plan",
    )
    args = parser.parse_args()

    check_literal_oracle()

    if not args.run:
        print(json.dumps(PLAN, indent=2))
        return

    results = run_cases()
    print(json.dumps({
        "executed": True,
        "environment": env(),
        "cases_present": sorted(results.keys()),
    }, indent=2))

if name == "__main__":
    main()

A preparation-only invocation is therefore:

python qualify_lfilter.py

A future behavioral run must be deliberate:

python qualify_lfilter.py --run

No output from either command is claimed here.

The manifest is fixed before execution:

Case

Path

Expected numerical result

Application result

F01

one-call L

Literal 8 outputs; zf=[1/256]

candidate comparison

F02

L 4+4, carried state

exact literal L

ACCEPT if reconciled

F03

L 4+4, reset

tail all zero; discarded [1/16] retained

REPAIR_RESET_STATE

F04

L 1+2+5

exact literal L; boundaries 1/2, 1/8, 1/256

ACCEPT if reconciled

F05

previous output as state

tail 1/8…1/64; zf=1/128

REPAIR_STATE_REPRESENTATION

F06

lfiltic reconstruction

reconstructed 1/16; correct tail

REPAIR candidate, then qualify

F07

rest + steady-step subpaths

transient rest path; eight ones for steady path

policy-dependent

F08

swapped L/R states

two individually wrong tails; correct sum

REPAIR_OWNERSHIP

F09

R continuation before L

both streams remain correct

ACCEPT if reconciled

F10

overlap + gap variants

no continuation filter call accepted

HOLD_OFFSET

Approval of the filtered series says nothing about any later detector or selection rule. That separation is the point of the adjacent SciPy peak-selection policy validation: a transform can satisfy its own contract while a downstream policy answers a different question.

Separate expected case results from observed evidence

Every pre-execution evidence item should look like this:

{
  "case_id": "F02",
  "path": "carried-state-4-plus-4",
  "status": "EXPECTED / NOT EXECUTED",
  "executed": false,
  "observed": null,
  "expected": {
    "stream_id": "L",
    "sample_indices": [0,1,2,3,4,5,6,7],
    "output": [1.0,0.5,0.25,0.125,0.0625,0.03125,0.015625,0.0078125],
    "boundary_zf": [0.0625],
    "final_zf": [0.00390625]
  },
  "decision_if_reconciled": "ACCEPT"
}

A future run should retain the actual environment, command line, imported module origins, script/source revision, raw observations, state transitions, and deviations. It must not populate observed by copying expected.

A useful acceptance checker operates on evidence, not just arrays:

REQUIRED_CASES = {f"F{i:02d}" for i in range(1, 11)}
REQUIRED_SUBPATHS = {
    "F07.initial_rest",
    "F07.steady_step",
    "F10.overlap_start3",
    "F10.gap_start5",
}

def accept_bundle(bundle):
    if bundle.get("executed") is not True:
        return "HOLD_NOT_EXECUTED"

    case_ids = {c["case_id"] for c in bundle.get("cases", [])}
    if case_ids != REQUIRED_CASES:
        return "HOLD_INCOMPLETE_CASE_SET"

    paths = {
        f'{c["case_id"]}.{p["name"]}'
        for c in bundle["cases"]
        for p in c.get("subpaths", [])
    }
    if not REQUIRED_SUBPATHS <= paths:
        return "HOLD_MISSING_REQUIRED_SUBPATH"

    if not bundle.get("source_preservation_ok"):
        return "HOLD_SOURCE_RECONCILIATION"
    if not bundle.get("sample_identity_multiplicity_ok"):
        return "HOLD_SAMPLE_IDENTITY"
    if not bundle.get("checkpoint_context_ok"):
        return "HOLD_STATE_CONTEXT"
    if not bundle.get("literal_oracle_ok"):
        return "HOLD_NUMERICAL_ORACLE"

    return "ACCEPT_QUALIFIED_CANDIDATE"

That last string still means a bounded filtered candidate is qualified. It does not mean production deployment is automatically authorized.

Negative diagnostics require the same distinction. F03 and F05 may reproduce their expected bad outcomes exactly; the diagnostic test would then be behaving as designed while the resulting filtered candidates remain rejected. “Expected failure reproduced” and “candidate approved” are different fields.

NumPy’s strict array comparison helps here because shape and dtype can be checked together with exact values, but its documentation explicitly cautions about floating-point equality in general. This fixture’s exact comparison policy is justified only by the short dyadic values selected for this laboratory.

Recover from the last qualified boundary

Recovery begins by identifying the last checkpoint whose context and numerical history were actually qualified. Do not overwrite faulty outputs or the old checkpoint. Stage a new candidate from that trusted boundary and retain the defect evidence separately.

Condition

Decision

Recovery

Complete source, literal outputs, ownership, offsets, coefficients and final state reconcile

ACCEPT

Retain candidate and continuation state for the bounded scope.

Correct state was discarded but a qualified checkpoint/history exists

REPAIR

Reprocess from that boundary.

Last output was confused with internal state

REPAIR

Use qualified history plus lfiltic where the admitted filter history is sufficient.

State vector belongs to another signal

REPAIR

Restore the owner-specific checkpoint or replay each signal independently.

Initial-rest versus steady-step policy is unknown

HOLD

Obtain owner-approved prehistory; do not choose by appearance.

Next sample index, coefficient revision, or state ownership is unknown

HOLD

Do not filter the continuation.

Sufficient approved history is unavailable but raw samples remain

REPLAY_FROM_SOURCE

Recompute from an earlier qualified source boundary.

Runtime/profile or laboratory code changes

RERUN

Regenerate evidence under the new profile.

The practical recovery sequence is: preserve the faulty candidate; identify the last qualified checkpoint; verify stream identity, next sample index, coefficient revision, initialization policy, and retained source interval; reconstruct state only from approved history; recompute into a separate candidate; reconcile every (stream_id, sample_index) exactly once; and only then make the bounded acceptance decision.

A code rollback by itself cannot retract numerical values or external actions that may already have escaped downstream. This laboratory deliberately includes no external effects, durable transactions, message brokers, concurrency, or distributed delivery guarantees.

Responsibility should also be explicit. The signal owner declares stream identity and prehistory. The scientific-computing engineer owns coefficients and the state representation. The stream engineer owns offset admission and checkpoint binding. The independent reviewer owns reconciliation against the source ledger and oracle. A wider discussion of streaming integration and recovery ownership can provide architectural context, but its discussion of brokers and distributed processing is outside this local numerical qualification.

The resulting artifact should be described precisely: a qualified filtered candidate and continuation state for the declared finite fixture and runtime profile. It is not certification of arbitrary filters, arbitrary coefficients, long-running streams, alternate Array API backends, concurrent callers, or production infrastructure.

Develop numerical foundations with Refonte Learning Data Science & AI

The operational lesson is broader than one SciPy call: numerical Python becomes reviewable when assumptions are explicit, raw inputs remain attributable, expected mathematics is independent of the implementation under test, and evidence distinguishes planned behavior from measured behavior.

Refonte Learning’s current Data Science & AI program page lists a three-month program and 12–14 hours/week in its program-specific block, with competencies including Python Data Science, statistical modelling, machine learning and predictive modelling, model optimization, exploratory analysis/data visualization, and application to industry projects. Its FAQ names Python, Jupyter Notebook, and NumPy among the tools used. The page identifies Dr. John Anderson as an educational mentor and says that, upon successful completion, Refonte Learning offers a Training Certificate and a Certificate of Internship.

The admission block says applicants must be working toward a bachelor’s or higher-level degree, while a generic FAQ later says there are no strict prerequisites. Confirm final eligibility with Refonte Learning. The FAQ also gives a variable duration description, so confirm how that wording relates to the three-month program-specific block. SciPy, lfilter, lfiltic, lfilter_zi, this exact laboratory, taught package versions, individual mentoring cadence, and internship allocation also require confirmation.

For learners who want to strengthen the Python, statistical, and analytical foundations that support careful work like this, explore Refonte Learning’s Data Science & AI program.