Pipeline

class gpype.backend.pipeline.Pipeline[source]

Bases: Pipeline

Brain-Computer Interface pipeline for real-time data processing.

Extends ioiocore Pipeline for BCI applications with automatic logging to platform-specific directories. Manages node lifecycle, data flow connections, and real-time execution of interconnected processing nodes.

__init__()[source]

Initialize Pipeline with platform-specific logging directory.

__repr__()[source]

One line: the mode, the nodes, and the state.

Pipeline(batch, 3 nodes: eeg -> bp -> out, stopped) for a pipeline that is one line; otherwise the sources and the sinks, Pipeline(realtime, 5 nodes, sources [a, b], sinks [c], running). A node is counted as its author wrote it: the chain the pipeline builds around it is that node. Never raises.

Return type:

str

property event_margin_ms

How late an event may arrive and still be placed, in ms.

One number for the whole pipeline – see TimelineManager.DEFAULT_EVENT_MARGIN_MS for what it buys and what it costs. A property rather than a constructor argument because deserialize builds its instance with object.__new__ and never runs __init__, so a constructor-only setting would be absent on exactly the pipelines a document produced.

Kept here rather than on the timeline, even though the timeline is where placement reads it: start() releases the timeline and builds a fresh one, deliberately, so that a run cannot inherit the previous one’s master election or epoch. A margin written to the timeline before start() went with it – measured, every value from 0 to 100 ms produced the same 10-frame hold, because placement was reading the default off an object that had just been replaced.

Returns:

The margin in milliseconds.

add_node(node)[source]

Add a node to the pipeline, wrapping it if it needs a chain.

connect is the ordinary way in and does the same thing; this is the other one, and it has to agree. A core added here and connected afterwards would otherwise reach the pipeline twice – once bare and once inside its chain – which starts the core’s acquisition thread twice and writes it into the document twice.

Unlike connect this does not register the node in _elements, which is unchanged and deliberate: _elements holds what was connected, and _validate_has_signal says so.

Parameters:

node – Node or chain to add.

Return type:

None

chain_of(node)[source]

Return the chain carrying node, or None.

The question a caller asks now that assembly is not the node’s own business: a public node is not a chain, and the chain this pipeline built around it is found here. A hand-written chain answers for itself.

Accepts a node this pipeline does not carry and answers None rather than raising: a test or a tool may reasonably ask about a node it has not connected yet, and an exception would make the question harder to ask than the reach-in it replaces.

Parameters:

node – A node handed to connect, or one nested inside a chain that was.

Returns:

The chain, the node itself where it is already one, or None when this pipeline does not carry it.

property failure

The entry that ended the run, or None if it has not failed.

ioiocore sets ERROR, stops the pipeline and only then calls the handler that records this, so a poll can see ERROR first. Until the handler has run – or for good, if a raising stop() keeps it from running – the entry is read from ioiocore’s log instead. A failure therefore implies ERROR, but not yet STOPPED.

Returns:

A log entry carrying the message, the node and the source location.

raise_if_failed()[source]

Raise if the run has failed, naming the node and the cause.

Overridden to name failure. ioiocore’s names its latest error, a different entry once stopping has logged another.

Raises:

RuntimeError – If the pipeline is in an error condition.

Return type:

None

get_nodes()[source]

Report every node in this pipeline and its current state.

Intended for anything driving a pipeline from outside – a control plane, a monitoring view – which otherwise has to reach into private implementation attributes to answer “what is in here, and is it healthy”. Chain internals are included, since a chain is a container and the node that actually failed is inside it.

Return type:

list[dict]

Returns:

One entry per node, each with its name, class, whether it is an internal node of a chain, its state and cycle counter when the node exposes them, and its control surface:

  • id – the document id to address a control at, or None for a node carrying no configuration.

  • actions – the declared action names, sorted, empty when the node declares none.

  • controllable – whether the node has a usable control channel, meaning it declares both halves. Two fields rather than one, because a node may well have actions and no state, or state and no actions.

LOAD_WARNING_DUTY = 0.7

Duty above which a node is reported as short of headroom. Chosen below 1.0 rather than at it: a pipeline that is exactly keeping up has no margin for the next scope repaint or garbage collection, and the useful warning is the one that arrives before frames are actually late.

get_load()[source]

Report how much of the real-time budget the pipeline is using.

Each node times its own step(); this divides that by the wall time since the previous call, which is the only denominator that is right for every driving mode. A rate-derived one – frame size over sampling rate – is wrong for any source paced per sample: FixedRateSource wakes once per sample whatever the frame size, so dividing by the frame period would report several times more headroom than exists.

Reading resets the counters, so two calls a second apart describe that second. The first call after start() covers everything since the nodes were built, including setup, and is not representative.

Returns:

headroom (1 - duty, so 1.0 is idle and 0.0 is saturated), duty, elapsed_s, busiest naming the node with the highest duty, short_of_headroom naming every node over LOAD_WARNING_DUTY, and nodes, one row per node with its name, class, duty, worst_cycle_ms and cycles.

Return type:

dict

get_control(node_id)[source]

Read the full control state of one node.

Parameters:

node_id (Union[str, Node]) – The node’s document id, as reported by get_nodes(), or the node itself.

Return type:

dict

Returns:

The node’s whole control state, as a copy – mutating it cannot reach the node.

Raises:
  • KeyError – If no node in this pipeline carries that id, or the node given is not one of this pipeline’s.

  • AttributeError – If the node declares no control channel.

  • TypeError – If the node’s answer is not a JSON-representable dict.

set_control(node_id, arg)[source]

Apply a partial control update to one node.

The update merges: arg names only what changes, so a one-field change stays one field and two clients need no get-before-set to avoid overwriting each other. Any key the node’s own get_control does not report is refused before the node sees it – the getter is the key set.

Parameters:
  • node_id (Union[str, Node]) – The node’s document id, or the node itself.

  • arg (dict) – The keys to change.

Return type:

dict

Returns:

The resulting full control state, so a set is also a get. A copy, as in get_control().

Raises:
  • KeyError – If no node carries that id, the node given is not one of this pipeline’s, or arg holds a key the node does not accept – that message names both the offending keys and the accepted ones.

  • TypeError – If arg is not a dict, or the node’s answer is not a JSON-representable dict.

  • AttributeError – If the node declares no control channel.

  • ValueError – Whatever the node raises when the resulting combination is not usable. Propagated deliberately: only the node knows its own cross-field rules.

invoke_action(node_id, name, arg)[source]

Run one declared action on one node.

Parameters:
  • node_id (Union[str, Node]) – The node’s document id, or the node itself.

  • name (str) – The action name, as reported by get_nodes().

  • arg (dict) – The action’s argument; may be empty.

Return type:

Optional[dict]

Returns:

Whatever the action reports, or None when it reports nothing.

Raises:
  • KeyError – If no node in this pipeline carries that id, or the node given is not one of this pipeline’s.

  • AttributeError – If the node declares no action of that name. An ordinary method is not an action, so this is also what an attempt to call anything else by name gets – which is what keeps the rest of the class unreachable.

  • TypeError – If arg is not a dict, or the result is not a JSON-representable dict or None.

  • ValueError – Whatever the action itself raises.

attach_probe(node_id, port='out', max_rate=None)[source]

Publish what one port emits, live, for a subscriber to watch.

A debugging instrument. The port keeps working exactly as it did: a probe copies what goes past and never consumes, delays or modifies it.

What arrives is a subsample, not the signal. The probe decimates to max_rate and applies no anti-aliasing filter, because a filter would make this a measurement instrument and the number read off a probe must never be mistaken for one. The published context says so – it carries the delivered rate, the decimation factor and antialiased: false.

The returned stream id is also the permission to watch: it carries random bytes, because the broker’s subscribe capability is granted per connection rather than per stream, so anyone holding a session’s reader token could otherwise watch any probe whose id they guessed. Hand it only to whoever asked.

Costs nothing while nobody is subscribed: the probe checks before it copies.

Parameters:
  • node_id (Union[str, Node]) – Document id of the node to probe, as get_nodes() reports it, or the node itself.

  • port (str) – Name of its output port.

  • max_rate (float) – Samples per second to deliver, at most. Defaults to probe.DEFAULT_MAX_RATE_HZ.

Returns:

The stream id to subscribe to.

Return type:

str

Raises:
  • KeyError – If no node in this pipeline carries that id, or the node given is not one of this pipeline’s.

  • ValueError – If the node has no such output port, or if this process has no running broker to publish on.

  • RuntimeError – Where no thread can be started (Pyodide).

detach_probe(stream_id)[source]

Stop and remove one probe.

Parameters:

stream_id (str) – What attach_probe() returned.

Returns:

True if a probe was removed, False if there was none.

Return type:

bool

list_probes()[source]

Report every probe attached to this pipeline.

Returns:

One entry per probe, each naming the node and port it watches, its decimation, how many samples it has sent, how many frames it dropped, and how many connections are currently watching it.

Return type:

list[dict]

connect(source, target)[source]

Connect two nodes to establish data flow in the pipeline. Nodes are automatically added to pipeline if not already present.

Parameters:
  • source (Union[Node, dict]) – Source node or port specification. Use dict for specific ports (e.g., node[“port_name”]).

  • target (Union[Node, dict]) – Target node or port specification. Use dict for specific ports (e.g., node[“port_name”]).

Raises:

ValueError – If this edge would make a feedback loop illegal – see _describe_component_violation(). The edge is undone before raising, so the pipeline is left exactly as it was before this call.

CLOCK_SYNC_TIMEOUT_S = 30.0

How long an edge’s start waits for its clock to converge on the server’s reference, in seconds. As long as a receiving Link waits for a context, so an edge started before its server keeps working.

static rezero_reference()[source]

Zero this process’s reference clock, in a new epoch.

The server’s half of the time base (D-TIME-20, D-TIME-67). Edges sync their clocks to the reference this process answers clock probes with, and every stamp this process reads is in it. Zeroing it when a pipeline is loaded keeps stamps small and starts a new epoch, which an edge synced to the previous one is told about.

Under SERVER residency deserialize() calls this, which is how the g.Pype runtime’s load zeroes it. A process that loads pipelines any other way calls it itself.

Return type:

int

Returns:

The new epoch.

Raises:

RuntimeError – While any pipeline in this process is running: its stamps would move by the whole reference at once.

start()[source]

Start the pipeline and begin real-time data processing.

Initiates execution of all nodes according to their configured connections and timing. Runs continuously until stop() is called. This method is non-blocking.

On an edge that builds a source, first relates its clock to the server’s reference, and raises if that does not converge within CLOCK_SYNC_TIMEOUT_S (ClockSyncError).

SETUP_GRACE_S = 0.5

How long start() waits for the first cycles to report a setup failure, in seconds. ioiocore runs setup() on a node’s first cycle rather than in start(), so without a wait there is nothing to look at yet. Bounded because a node fed only by a sparse event stream sets up when its first event arrives, which may be never.

SETUP_POLL_S = 0.005

Poll interval while waiting, so a healthy pipeline pays only the time it actually needs – one frame period, typically.

MAX_BATCH_CYCLES = 1000000

Safety stop for the batch driver. A batch source emits its whole recording in one cycle, so the loop below normally runs once; this only bounds a source that reports “more” forever, which would otherwise be an unkillable loop rather than an error.

execution_mode()[source]

How this pipeline will be driven, as declared by its sources.

Read from the sources rather than from their time base: a recording paced to the clock is an ordinary realtime pipeline, so the two properties are independent and only one of them says how to drive the pipeline.

Return type:

str

Returns:

A value from Constants.ExecutionMode.

Raises:

ValueError – If the pipeline has no source, or if its sources disagree – a pipeline cannot be half batch.

run()[source]

Process a recording from end to end and return the results.

The batch counterpart of start(). Where a realtime pipeline is started, left running and stopped by the caller, a batch pipeline is driven: this call returns when the whole recording has passed through the last node.

It executes on the calling thread and creates none of its own, which is what makes an exception in a node arrive as an ordinary Python traceback through the caller’s line rather than as a log entry from a monitoring thread.

Return type:

Union[Result, dict, None]

Returns:

The Result of the single Collector in the pipeline; a dict of results keyed by node name if there is more than one; None if there is no Collector, in which case the run’s output went wherever its sinks put it.

Raises:
  • ValueError – If the pipeline is not a batch pipeline – see execution_mode() and _validate_batch().

  • Exception – Whatever a node raises, unchanged. The node’s frame and the caller’s line are both in the traceback.

fit()[source]

Fit every fittable node in this pipeline, then apply the result.

The offline half of “fit offline, deploy online” (D-BATCH-16): drives a batch run exactly like run(), except every Fittable node in the pipeline fits on the whole recording first, instead of requiring state that was never loaded. A node not inheriting Fittable runs exactly as it would under run().

Return type:

Union[Result, dict, None]

Returns:

Whatever run() returns – a fit run is a batch run, with the same single-Collector-or-dict-or-None contract.

Raises:
  • ValueError – If this pipeline holds no fittable node. Use run() for an ordinary batch pipeline.

  • Exception – Whatever run() raises, unchanged.

run_all(files, source=None)[source]

Run this pipeline’s document once per file, in input order.

The many-file counterpart of run() (LQ-R3): this pipeline is never driven itself. Instead, once per file, its document is rebuilt with that file’s name in place of the one this pipeline was constructed with, given fresh ids (D-BATCH-72, so the several pipelines this builds in one process do not collide in ioiocore’s id registry), deserialized into a fresh Pipeline, and run. Each result carries its own provenance (LQ-P2), naming that file’s own input digest.

Owner’s decision (document-rebuild form, D-BATCH-104): a factory form – run_all(build_fn, files), calling build_fn fresh per file – would also run a script-only pipeline (Apply), which this form cannot. Rebuilding from the document is what makes every file run the identical, already- validated pipeline rather than trusting a callback to reconstruct it consistently, and it is what lets a caller build the template pipeline once, from a document someone else wrote, with no author script to call back into at all.

The failure policy is fail-fast: the first file that raises stops the run, with its path in the message and the original exception as __cause__ (D-BATCH-104, beside D-BATCH-52’s pure propagation). Nothing before it is retried, and nothing after it runs.

Parameters:
  • files (list) – Paths to run the document against, in order. Each becomes the single batch source’s file_name.

  • source (Optional[str]) – Name of the node whose file_name to replace. None (the default) finds this pipeline’s one source – a batch pipeline permits exactly one (_validate_batch()) – and needs naming only where a caller wants a specific node addressed by name regardless.

Returns:

{file: result}, in files order – each value whatever run() returns for that file (a Result, a dict of them, or None).

Return type:

dict

Raises:
  • ValueError – If this pipeline is not BATCH, if it does not have exactly one source and source names none, if source names a node that is not a source, if a file is listed twice (the results are keyed by file), or if the pipeline holds a function node (D-BATCH-70) – checked once, before any file is read.

  • Exception – Whatever the failing file’s run raised, chained as __cause__ of a RuntimeError naming that file.

STREAM_REPORT_S = 30.0

How long after start() a server waits before naming the streams nothing at the far end has answered, in seconds. The Link’s own context budget: the processes of one pipeline may be started in any order, and within it an edge that has not connected is still starting rather than missing.

stop()[source]

Stop the pipeline and terminate all data processing.

Gracefully shuts down all nodes, releasing threads and hardware connections. Always call stop() before program termination, especially when using hardware interfaces.

Logging resources outlive a stop() so that a pipeline can be started again; call close() to release those as well.

close()[source]

Dispose the pipeline and release its master timeline.

ioiocore’s close() stops the pipeline through its own implementation, bypassing this class’s stop(), so the timeline has to be discarded here as well. Safe to call repeatedly.

BUNDLE_KEY = 'bundle'

Key under which a package bundle travels inside the payload.

REQUIREMENTS_KEY = 'requirements'

a list of name==version strings (D-CORE-109). Absent when there are none.

Type:

Key under which a document’s pins travel

ARTIFACTS_KEY = 'artifacts'

Key under which every fitted node’s state travels inside the document, keyed by its own content digest (D-BATCH-91, LQ-F2): {sha256: {encoding, data, meta}}. A fitted node’s own config carries only the digest, under fittable.ARTIFACT_KEY.

serialize(packages=None, requirements=None)[source]

Serialize the pipeline configuration to a dictionary.

Parameters:
  • packages (Optional[list[str]]) – Top-level packages to carry along, for nodes whose classes are not installed on the executing host. A node from an uninstalled package cannot be rebuilt there, however complete its configuration is.

  • requirements (Optional[list[str]]) – Exact pins, name==version, of what the document needs beyond g.Pype, written under REQUIREMENTS_KEY. A deployment that opted in installs them when it loads the document. The pipeline keeps them: a later call without them, and the provenance record of each run, write them again (D-CORE-109). None writes the pins kept, from an earlier call or the document this pipeline was rebuilt from, as that document carried them; an empty list writes none, and keeps none.

Returns:

Dictionary containing the complete pipeline configuration,

including nodes, connections, parameters, and metadata.

Return type:

dict

Raises:
  • ValueError – If the pipeline holds a function node – Apply or an @gp.node – naming it. A document could not rebuild it (D-BATCH-70).

  • RequirementError – If a requirement is not an exact pin, or names a distribution twice, naming every such entry.

static check(data, install=False)[source]

Refuse a document the allow-list or requirement check refuses.

The document-level half of deserialize(), which calls it first, so the order is written only here. The modules the document’s nodes name are checked against the deployment’s allow-list. Then, where the deployment installs a document’s pins (GPYPE_PACKAGE_INDEX is set) and the document has some, they are checked for form and against what is installed, and, with install, every absent one is installed. Last, for a document carrying packages, their code is checked for imports this host cannot satisfy.

Nothing else happens: no bundle is unpacked, nothing is put on the import path, no module a node names is imported and no node is built. A validator can therefore ask whether a check would refuse a document, in the terms loading it uses, without loading it. The load can still refuse a document that passes: for its format revision, or with a BundleError as its bundle is unpacked.

Without install, pip never runs, and a pin that is absent here may be what supplies a missing import; so while any pin is absent, the missing imports are not refused. The load installs the pins first and refuses them then.

Parameters:
  • data (dict) – Serialized pipeline configuration dictionary.

  • install (bool) – Install the document’s absent pins, where the deployment opted in. deserialize() passes True.

Raises:
  • ModuleNotAllowedError – If the document names a module this deployment does not permit, naming every such module.

  • RequirementError – If a pin is not exact, or a pinned wheel needs a distribution nothing pins or provides.

  • RequirementConflictError – If a pin names a version other than the one installed here, or, with install, a pinned wheel needs another version of an installed distribution or would overwrite its files.

  • InstallerError – If the pins cannot be installed.

  • MissingRequirementsError – If the document’s bundled code imports a package this host does not have, naming every such package.

Return type:

None

static restore_requirements()[source]

Reinstall the pins the package cache records, with no network.

For the process that starts a deployment: in a container the cache is a volume and the environment is the image’s, so the pins installed before a restart are installed again from the cache, each wheel copied out of it and checked against the hash recorded at its download (D-CORE-88, D-CORE-117). Entry by entry: one whose distribution is installed at another version now is skipped and reported, as is one whose wheel this interpreter does not install, is missing or was replaced, one pip refuses or that would overwrite another distribution’s files, and one whose own pip call does not finish within 600 s; the others are installed. Does nothing where GPYPE_PACKAGE_INDEX is not set.

Whoever can write the cache can have a wheel installed here, with no document involved: the cache must be writable only by the deployment.

Returns:

{"enabled": bool, "installed": [...], "present": [...], "skipped": [{"requirement": str, "reason": str}]}, JSON-safe.

Return type:

dict

Raises:

InstallerError – Before anything is installed, if the cache’s manifest cannot be read, another install holds the cache for longer than 1200 s, this interpreter’s wheel tags cannot be read, or this interpreter, its site-packages or its pip cannot install. At any point, possibly after some entries were installed, which the next call reports as present, if pip cannot be started or the cache or a private directory beside pip cannot be used.

static installer_config()[source]

Whether this deployment installs a document’s pins, and how.

Read once from GPYPE_PACKAGE_INDEX and GPYPE_PACKAGE_CACHE, for a control plane to report. Nothing can set it but the deployment’s environment.

Returns:

{"enabled": bool, "index": str or None, "cache": str}, JSON-safe, the index’s credentials redacted.

Return type:

dict

static deserialize(data)[source]

Deserialize a pipeline configuration from a dictionary.

Rebuilding a node imports the module it names, so a document is executable input. It is checked first (check(), with install=True): the modules it names against the deployment’s allow-list; then its pins, installing every absent one where the deployment opted in; then any bundled code for imports this host cannot satisfy – all before any bundle is written to disk and put on the import path, so an untrusted payload is never unpacked for a document that was going to be refused. Without the opt-in, nothing is installed for it.

Any packages carried in the payload are then unpacked and put on the import path, because rebuilding a node imports its class. The rebuilt pipeline keeps the document’s pins as the document carried them, and its serialize() writes them again; they are validated where they are installed.

Parameters:

data (dict) – Serialized pipeline configuration dictionary.

Returns:

A new Pipeline instance with the specified configuration.

Return type:

Pipeline

Raises: