Skip to content

Runs, delivery and topologies

sequential_analysis.run

Run: one concrete execution of a procedure.

The run owns everything that must survive the process: inferential state, statistical random state, topology buffers, source positions, the history digest and provenance. It is the single writer of the inferential state; runtimes may acquire observations concurrently but hand them to Run.offer one at a time.

Run

start(runtime=None)

CREATED or PAUSED -> RUNNING. runtime names the execution mode for provenance.

close()

End the run and close its observation log. The final state stays available for checkpointing.

offer(obs)

Hand one arriving observation to the run.

delivery -> topology -> validate -> transition -> commit -> notify. Returns the output events produced (often none or one).

An observation the topology cannot use (unknown input, missing key or event time) and a statistical input that violates the procedure's contract are invalid inputs, handled by on_invalid. Ordering errors are not: OrderingError from delivery (the strict policy) or from the topology (an input observed twice for one key, event time going backwards) stops the run, as those policies were chosen to.

offer_batch(batch)

Transport-level batching: exactly the element-wise fold, nothing more.

step(x)

Apply one statistical input directly, bypassing delivery and topology.

Not available while an observation log is attached: the log would no longer hold the whole history, and replaying it would silently give a different run.

checkpoint()

A JSON-serializable value sufficient to continue this run elsewhere.

restore(procedure, checkpoint, *, topology=None, delivery=None, consumers=(), on_invalid=None, log=FROM_CHECKPOINT, clock=time.time) classmethod

Continue an existing run from a checkpoint.

The run keeps its identity and history digest. It is returned PAUSED; start() (or a runtime) resumes it. To begin a new run from an old state, construct Run(..., initial_state=..., initialized_from=...) instead: the numbers may be identical, the provenance is not.

The observation log is restored together with the run. By default the log recorded in the checkpoint is reopened from its path; pass an ObservationLog to use a moved copy, or log=None to continue without one. Either way the log is verified against the checkpoint and cut back to it: records written after the checkpoint are deleted, and their number is recorded in the restore event. Observations after the checkpoint must come again from the sources; preserving them for sources that cannot replay is the application's job (see ObservationLog).

The run keeps its on_invalid policy, its max_invalid_streak and the current streak. A policy that raises a custom exception class is recorded by name only, so that class has to be passed again as on_invalid.

validate_checkpoint(checkpoint)

Check the structure of a checkpoint; raise IncompatibleCheckpoint naming the first problem.

A checkpoint is data that may have been edited, truncated or written by another version, so it is checked before any of it is trusted.

checkpoint_id(checkpoint)

Content hash of a checkpoint.

sequential_analysis.delivery

Delivery: per-source ordering and deduplication.

This is a runtime concern. It decides which observations reach the topology and in what per-source order; it never looks at values.

Policies

arrival deliver in arrival order; duplicates (same source and seq) are dropped when dedup is on sequence hold observations back until the per-source sequence is contiguous, then release them in sequence order strict reject gaps with OrderingError; late duplicates are dropped when dedup is on and rejected otherwise

positions() is the source checkpoint: for every source, the next sequence number that has not yet been delivered. Observations held back by the sequence policy are deliberately not persisted; after a restore they are fetched again from the source, starting at its position.

The duplicates counter is informational: after a restore, duplicates that skip_to filters before they reach delivery are not counted again.

Delivery

delivered(obs)

True if this observation was already delivered (a restored run must not receive it again).

skip(obs)

Pass over an observation that will never be delivered (dropped by the runtime).

Under the arrival policy its sequence number counts as consumed, so that later ones are not held up behind the gap and a restored run does not receive it after all.

skip_range(source, first, stop)

Declare that the sequence numbers first..stop-1 of source do not exist.

For sources numbered with gaps by design (Kafka offsets of a compacted or transactional topic): without it the arrival policy keeps every number seen beyond a gap, and the checkpoint grows. A gap ahead of numbers not yet delivered is remembered until they are; it is not part of the checkpoint (an adapter that reads the source again declares it again). Only the arrival policy can pass over numbers.

push(obs)

Accept one arriving observation; return those now deliverable, in order.

restore(state)

Restore positions from a checkpoint; a value of the wrong type is refused (ValueError), not converted.

sequential_analysis.topology

Data topology: how logical inputs are related before inference.

A topology operator turns delivered observations into statistical inputs. Operators may hold state (observations waiting for a partner); that state is part of the run checkpoint, because it has been consumed from the sources but has not yet reached the procedure.

Confluence

An operator is confluent if its output sequence depends only on the per-input order of observations, not on how the inputs interleave. PositionalPair and TimeAlign are confluent. Independent, KeyJoin and AsOfJoin are not: their output follows arrival (or completion) order, so the ordering policy is part of the experiment and is recorded in provenance.

Topology

Bases: ABC

spec() abstractmethod

JSON description, recorded in provenance and checked on restore.

push(obs) abstractmethod

Accept one delivered observation; return zero or more statistical inputs.

map(fn, name=None)

Apply a stateless transformation to every emitted input.

fn should be a Transform, whose name, version and configuration are recorded; a plain function needs a name, and only that is.

Independent

Bases: Topology

Unpaired samples: every observation is a statistical input of its own.

PositionalPair

Bases: _Buffered

Pair the i-th observation of every input: (A_1, B_1), (A_2, B_2), ...

KeyJoin

Bases: _Buffered

Join observations that carry the same key. Emits in completion order.

TimeAlign

Bases: _Buffered

Align two time-ordered inputs within a tolerance.

The heads of the two queues are paired when their event times differ by at most tolerance; otherwise the earlier head has no partner and is discarded. Discarded observations change the observation history, so they are counted and the count is checkpointed.

AsOfJoin

Bases: Topology

Attach to every bar what a stream of events said up to the bar's time.

bars is a regular stream (prices, returns); events an irregular one (news items scored by sentiment, trades, alerts), each event a number. Every bar is emitted at once, with its value -- a number under the name bars, or a mapping of named numbers -- and, for the events that arrived since the previous bar and whose time is not after the bar's:

<prefix>_count   how many there were
<prefix>_sum     the sum of their values

and with a half_life, the influence of all events so far, each decaying by half every half_life units of time:

<prefix>_decayed        sum of value * 2^-(bar time - event time) / half_life
<prefix>_decayed_count  the same with every value 1

An event whose time is after the bar waits for a later bar. An event that arrives after a bar later than its own time goes to the next bar and is counted as late: the bar could not have known it. So a bar never sees an event that had not arrived when it did, and to rule out look-ahead in a replay the event's time must be when it became available (received, parsed and scored), not when it was published. Times must not decrease within either input. The decay is computed with portable_exp2, so that the join's output, which enters the recorded history, is the same in every executor.

Not confluent: what a bar sees depends on which events arrived before it, so a replay must deliver both inputs in their original order.

InvalidInput dataclass

Stands, in a topology's output, for an input a transformation could not map.

It keeps its place among the inputs, so that the run applies the inputs before it, reports it as invalid input and then goes on.

Mapped

Bases: Topology

A topology followed by a stateless map or filter (return None to drop).

push(obs)

Map every input the inner topology emits.

A transformation that fails on an input (a value of the wrong type that reached it before any contract could see it, a missing field) makes that input invalid, not the run: an InvalidInput takes its place in the output, and the run reports and skips it in order.

difference(a, b, out='x')

Map a paired input {a, b} to the single input {out: a - b}.

sequential_analysis.runtime

Runtimes: disposable machinery that moves observations into a run.

Nothing here is checkpointed. Both runtimes end in the same place, a serialized sequence of run.offer calls, which is why the procedure needs no asynchronous interface and no internal locking.

run_sync(run, source, *, stop_on_terminal=True)

Pull observations from source and offer them in order. Returns the number consumed.

run_async(run, producers, *, maxsize=64, overflow='block', stop_on_terminal=True) async

Concurrent acquisition, ordered delivery, serialized transitions.

Each producer pushes into one bounded queue; a single consumer drains it into the run. overflow="block" applies backpressure to producers. overflow="drop" discards observations when the queue is full; that changes the observation history, so drops are counted on the run (counters["dropped_by_runtime"]) and recorded in its checkpoint. A dropped sequence number counts as consumed: later observations are not held up behind it, and a restored run does not receive it.

sequential_analysis.consumers

Scientific consumers: they see outputs, never state.

A consumer is any callable taking an OutputEvent. Exceptions raised by a consumer are caught by the run and recorded; they never affect inference. A consumer that wants to influence the experiment acts on a source or an actuator, not on the run.

Recorder

Keeps every event in memory.

JsonlSink

Appends one JSON line per output to a file.

The file stays open between events; sync is "flush" or "fsync", see sequential_analysis.files. Close the sink, or use it as a context manager, when the run is over.

sequential_analysis.persistence

Checkpoint storage. Checkpoints are plain JSON values; this module only moves them to disk.

save_checkpoint(path, checkpoint)

Write atomically: a crash leaves either the old file or the new one, never a torn one.

sequential_analysis.core

The statistical boundary: observations, procedures, reference trajectory.

A Sequential Procedure is the transition

(S_t, O_t, R_t) = F(S_{t-1}, X_t, R_{t-1})

and nothing else. It does not know where X_t came from, how it was scheduled, where S_t is stored or what happens to O_t.

Observation dataclass

One value as delivered by an adapter, before topology.

input -- logical input the value is bound to value -- the observed value (must be JSON-serializable to be logged) source -- identity of the physical source; defaults to the input name seq -- per-source sequence number, used for ordering and deduplication key -- join key, used by key-based topologies time -- event time, used by time-aligned topologies

Procedure

Bases: ABC, Generic[S, O]

Semantic contract of a Sequential Procedure.

The base class is a convenience, not a requirement: Run only relies on the attributes and methods below, so any object providing them conforms.

States must be immutable values. step returns a new state and must not modify its arguments; this is what makes state updates transactional and checkpoints trivially consistent.

config() abstractmethod

JSON-serializable parameters that determine F.

inputs() abstractmethod

Contracts of the logical inputs.

initial_state() abstractmethod

The default initial state S_0.

step(state, x, rng) abstractmethod

Return (S_t, O_t) from S_{t-1} and X_t.

rng carries R_{t-1} on entry and R_t on return; it is None for deterministic procedures. The caller commits both together.

Raise ContractViolation for an input that turns out to be invalid only during the step; the run treats it like a contract violation. Any other exception is a failure of the procedure.

is_terminal(state)

Terminal states are absorbing: no further transitions are applied.

envelope_problem(obs)

Why delivery cannot handle an arriving observation, or None if it can.

Delivery orders and deduplicates by source and sequence number, and checkpoints its position per source, so these must be exact: the input and source names strings, the sequence number None or an int within 2**53. Such an observation is invalid input; it is not delivered, so it is not in the observation log either.

recording_problem(obs)

Why an observation cannot be recorded exactly, or None if it can.

Values must be int, float, str, bool, None, or lists and dicts (with string keys) of these, with floats finite, integers within 2**53 and strings encodable as UTF-8; keys str or int; event times finite numbers. Anything else -- numpy scalars, Fraction, tuples, UUIDs, subclasses of int or float -- would come back from an observation log as something else, so a run treats such an observation as invalid input, whether or not it keeps a log, and the adapter is the place to convert it.

decode_fields(cls, data)

A state dataclass from its JSON form, with the type of every field checked.

Integers are counts (non-negative), floats are finite, a decision is one of DECISIONS, and no field may be missing or extra: a checkpoint is data that may have been edited, and the next step must not be the first to notice. Raises ValueError (TypeError for a wrong shape).

require_state(condition, message)

A decoded state must be one the procedure can reach; ValueError otherwise.

refuse_terminal(procedure, state)

A stopped procedure takes no further observations.

Run never offers them; this guards loops that call step directly.

checked_step(procedure, state, x, rng)

procedure.step, with every numerical failure reported as NumericalError.

Overflow or a math domain error inside the transition, and a new state or output holding NaN, infinity or an integer beyond 2**53 -- which could be neither reported nor checkpointed -- all become NumericalError, and nothing is returned to commit.

statistical_rng(procedure, seed)

Initial statistical random state R_0, or None for deterministic procedures.

trajectory(procedure, inputs, *, seed=None, state=None)

Reference semantics: fold F over an ordered input history.

This is the definition every runtime is tested against. It has no scheduling, no persistence and no consumers.

sequential_analysis.contracts

Input contracts: what a valid statistical input is.

InputContract dataclass

Contract of one logical input.

kind -- "real", "integer" or "binary" shape -- () for a scalar, (d,) for a length-d vector lower / upper -- inclusive domain bounds, applied element-wise unit -- recorded in provenance; adapters are responsible for conversion

validate_input(procedure, x)

Check one statistical input against a procedure's contracts.

A statistical input is a non-empty mapping from logical input names to values. Procedures with joint_inputs = True need every declared input in every step (paired or one-sample analyses); the others accept any non-empty subset (independent samples arriving one at a time).

sequential_analysis.errors

Error classes of the package (the paper's table of errors says which layer is responsible for what).

Not every row of that table has a class: source errors are the source's own exceptions, serialization errors those of json and the file system, and consumer errors are caught and recorded rather than raised.

SequentialAnalysisError

Bases: Exception

Base class for all errors raised by this package.

ContractViolation

Bases: SequentialAnalysisError

A statistical input does not satisfy the procedure's input contract.

InvalidInputStreak

Bases: SequentialAnalysisError

Too many consecutive invalid inputs: the source, not a message, is probably broken.

OrderingError

Bases: SequentialAnalysisError

An observation violates the delivery or topology ordering policy.

NumericalError

Bases: SequentialAnalysisError

A state transition produced a non-finite or otherwise invalid value.

LifecycleError

Bases: SequentialAnalysisError

An operation is not permitted in the current run status.

IncompatibleCheckpoint

Bases: SequentialAnalysisError

A checkpoint does not match the procedure, topology or delivery it is restored into.