Python API reference
Import every name below from engine.public, not from the module that defines it. Each entry says which release it first appeared in, or that it is not yet released. A default shown as <built-in default> is computed, such as an empty container or a built-in function.
Everything that is not listed in this reference is internal: every other module of the engine and every name with a leading underscore. It may change in any release without notice, even if it looks stable. What counts as a breaking change to the names listed here, and how the version responds, is in the stability policy.
Contents
- Declaring a Node Type:
NodeTypeDefinition,NodeTypeIdentity,EventTypeDefinition,load_node_type_definition,validate_node_type_definition - Configuration:
load_node_config,validate_candidate,ConfigVerdict - Checking a candidate config:
check_candidate,CandidateCheck,ConnectionOutcome,BuiltConnector,preview_candidate,PreviewReport,RecordReport - Carrying a config to an appliance with no route to the repository:
build_config_bundle,ConfigBundleBuild - Writing the subscribe and project lists once:
SourceKeyEntry,ExpandedMapping,expand_source_keys - Transforming records:
TransformationRegistry,TransformFunc,MappingRule,build_rule_based_transform - Connecting to a system:
SystemConnector,ConnectorRegistry,ConnectorFactory,ConnectionCheckResult - Conformance:
ConformanceHarness,run_conformance_suite,ConformanceReport,ConformanceCheckResult,ActivityLog,TriggerQueue - Workflows and gates:
WorkflowRegistry,Task,TaskResult,WorkflowPattern,Step,Gate,GateDecision,EvaluationMode - Chunking documents:
ChunkingRegistry,ChunkingStrategy,ChunkingStrategySpec,register_chunking_strategy,Chunk - Errors:
KindredError,ConfigValidationError
Declaring a Node Type
NodeTypeDefinition
Class (data model). Since 0.1.0.
NodeTypeDefinition(*, identity: NodeTypeIdentity, config_schema: dict[str, Any], event_types: list[EventTypeDefinition] = <built-in default>)
A Node Type's declaration: its Identity, Configuration Schema and event types.
The Node Type Agreement has six facets. Three are data and are carried here: Identity &
Metadata (identity), Configuration Schema (config_schema, a JSON Schema every config
file for this Node Type must satisfy) and Event/Data Model (event_types). The Conformance
Suite and Communication Interface are behaviour, not data, and are not on this model.
Build one with validate_node_type_definition or load_node_type_definition, which
also check that the schemas are valid.
Fields
| Field | Type | Default |
|---|---|---|
identity |
NodeTypeIdentity |
required |
config_schema |
dict[str, Any] |
required |
event_types |
list[EventTypeDefinition] |
<built-in default> |
Example
>>> from engine.public import EventTypeDefinition, NodeTypeDefinition, NodeTypeIdentity
>>> node_type = NodeTypeDefinition(
... identity=NodeTypeIdentity(name="Demo Sensor", version="1.0.0"),
... config_schema={"type": "object"},
... )
>>> node_type.event_types
[]
NodeTypeIdentity
Class (data model). Since 0.1.0.
NodeTypeIdentity(*, name: str, version: str, relevant_peer_node_types: list[str] = <built-in default>)
The Identity & Metadata facet: what a Node Type is, its version and its peers.
version must be MAJOR.MINOR.PATCH. relevant_peer_node_types names the Node Types
this one works alongside, and is empty by default.
Fields
| Field | Type | Default |
|---|---|---|
name |
str |
required |
version |
str |
required |
relevant_peer_node_types |
list[str] |
<built-in default> |
Example
>>> from engine.public import NodeTypeIdentity
>>> NodeTypeIdentity(name="Demo Sensor", version="1.0.0").relevant_peer_node_types
[]
EventTypeDefinition
Class (data model). Since 0.1.0.
EventTypeDefinition(*, name: str, description: str, fields: dict[str, Any] = <built-in default>)
One entry in a Node Type's Event/Data Model facet.
fields is a JSON Schema fragment describing the event's structured fields. It is open:
an integrator defines their own, and validate_node_type_definition checks that it is a
valid JSON Schema.
Fields
| Field | Type | Default |
|---|---|---|
name |
str |
required |
description |
str |
required |
fields |
dict[str, Any] |
<built-in default> |
Example
>>> from engine.public import EventTypeDefinition
>>> event = EventTypeDefinition(
... name="Reading", description="A sensor reading",
... fields={"type": "object", "properties": {"value": {"type": "number"}}},
... )
>>> event.name
'Reading'
load_node_type_definition
Function. Since 0.1.0.
load_node_type_definition(node_type_dir: Path) -> NodeTypeDefinition
Read node_type_dir/node_type.json and validate it.
A Node Type's declaration lives in a directory as a file named node_type.json; this
reads that file and applies validate_node_type_definition.
Parameters
| Name | Type | Default |
|---|---|---|
node_type_dir |
Path |
required |
Returns
NodeTypeDefinition
Raises
FileNotFoundError: there is nonode_type.jsoninnode_type_dir.json.JSONDecodeError: the file is not valid JSON.ConfigValidationError: the declaration is invalid (seevalidate_node_type_definition).
Example
>>> import json, tempfile
>>> from pathlib import Path
>>> from engine.public import load_node_type_definition
>>> with tempfile.TemporaryDirectory() as tmp:
... _ = (Path(tmp) / "node_type.json").write_text(json.dumps({
... "identity": {"name": "Demo Sensor", "version": "1.0.0"},
... "config_schema": {"type": "object"},
... }))
... load_node_type_definition(Path(tmp)).identity.name
'Demo Sensor'
validate_node_type_definition
Function. Since 0.1.0.
validate_node_type_definition(data: dict[str, Any]) -> NodeTypeDefinition
Validate a raw Node Type declaration and return it as a NodeTypeDefinition.
Three things are checked: the declaration's own shape (identity, event types); that
config_schema is a valid JSON Schema, because it goes on to govern every config file for
the Node Type; and that each event type's fields is a valid JSON Schema, because live
events are validated against it. A bad schema fails here, at declaration time, rather than
breaking ingestion the first time a real record is checked.
Parameters
| Name | Type | Default |
|---|---|---|
data |
dict[str, Any] |
required |
Returns
NodeTypeDefinition
Raises
ConfigValidationError: the declaration, its Configuration Schema or an event type'sfieldsschema is invalid.
Example
>>> from engine.public import validate_node_type_definition
>>> node_type = validate_node_type_definition({
... "identity": {"name": "Demo Sensor", "version": "1.0.0"},
... "config_schema": {"type": "object", "required": ["endpoint"]},
... })
>>> node_type.identity.name
'Demo Sensor'
Configuration
load_node_config
Function. Since 0.1.0.
load_node_config(node_type: NodeTypeDefinition, config_path: Path, *, shared_dir: Path | None = None) -> dict[str, Any]
Load a config file, decrypt it if needed, resolve $shared references and validate it.
Returns the parsed document: the envelope (node_type, node_type_version,
config_version and config) as it was on disk after decryption, with any $shared
fragment references replaced by their real values. A file with no $shared references
comes back unchanged.
shared_dir is where "$shared": "<name>" references are looked up. It may be omitted
for a file that has none.
Parameters
| Name | Type | Default |
|---|---|---|
node_type |
NodeTypeDefinition |
required |
config_path |
Path |
required |
shared_dir |
Path | None |
None |
Returns
dict[str, Any]
Raises
ConfigValidationError: the document does not match the envelope, names a different Node Type or version thannode_type, has aconfigthat violates the Node Type's Configuration Schema, or has a$sharedreference that cannot be resolved (or any reference whenshared_dirwas not given).SecretDecryptionError: the file is encrypted and could not be decrypted. This class is aKindredErrorbut is not in the public surface, so catchKindredErrorand do not rely on the class itself.
Example
>>> import json, tempfile
>>> from pathlib import Path
>>> from engine.public import load_node_config, validate_node_type_definition
>>> node_type = validate_node_type_definition({
... "identity": {"name": "Demo Sensor", "version": "1.0.0"},
... "config_schema": {"type": "object", "required": ["endpoint"]},
... })
>>> with tempfile.TemporaryDirectory() as tmp:
... path = Path(tmp) / "config.json"
... _ = path.write_text(json.dumps({
... "node_type": "Demo Sensor", "node_type_version": "1.0.0",
... "config_version": 1, "config": {"endpoint": "http://sensor.local"},
... }))
... load_node_config(node_type, path)["config"]
{'endpoint': 'http://sensor.local'}
validate_candidate
Function. Since 0.1.0.
validate_candidate(config_path: Path, node_types: Mapping[str, NodeTypeDefinition], *, shared_dir: Path | None = None) -> ConfigVerdict
Check a config file the same way load_node_config would, and report instead of raising.
The file is checked against the Node Type it names, looked up in node_types (a mapping
from Node Type name to its definition). A bad file produces an invalid ConfigVerdict
rather than an exception, and the verdict's text carries no config value: a value marked
x-sensitive is scrubbed from every message.
Parameters
| Name | Type | Default |
|---|---|---|
config_path |
Path |
required |
node_types |
Mapping[str, NodeTypeDefinition] |
required |
shared_dir |
Path | None |
None |
Returns
ConfigVerdict
Example
>>> import json, tempfile
>>> from pathlib import Path
>>> from engine.public import validate_candidate, validate_node_type_definition
>>> node_type = validate_node_type_definition({
... "identity": {"name": "Demo Sensor", "version": "1.0.0"},
... "config_schema": {"type": "object", "required": ["endpoint"]},
... })
>>> with tempfile.TemporaryDirectory() as tmp:
... path = Path(tmp) / "config.json"
... _ = path.write_text(json.dumps({
... "node_type": "Demo Sensor", "node_type_version": "1.0.0",
... "config_version": 1, "config": {},
... }))
... verdict = validate_candidate(path, {"Demo Sensor": node_type})
>>> verdict.valid, verdict.failure
(False, 'invalid')
ConfigVerdict
Class (dataclass). Since 0.1.0.
ConfigVerdict(valid: bool, errors: tuple[str, ...] = (), node_type: str | None = None, failure: Optional[Literal['unreadable', 'undecryptable', 'invalid', 'wrong_node_type']] = None)
The outcome of checking a candidate config file, with no config value in its text.
valid is the answer. When it is false, errors holds one message per problem and
failure says which kind it was: "unreadable" (not a readable file), "undecryptable"
(encrypted and could not be decrypted), "invalid" (fails validation) or
"wrong_node_type" (names a Node Type that was not offered). node_type is the Node
Type the file names, when it could be read. The dataclass is frozen.
Fields
| Field | Type | Default | Description |
|---|---|---|---|
valid |
bool |
required | |
errors |
tuple[str, ...] |
() |
|
node_type |
str | None |
None |
|
failure |
Optional[Literal['unreadable', 'undecryptable', 'invalid', 'wrong_node_type']] |
None |
What kind of failure, for a caller that must answer each differently; None when valid. |
Example
>>> from engine.public import ConfigVerdict
>>> ConfigVerdict(valid=True, node_type="Demo Sensor")
ConfigVerdict(valid=True, errors=(), node_type='Demo Sensor', failure=None)
Checking a candidate config
check_candidate
Function. Since 0.2.0.
check_candidate(config_path: Path, node_type_dir: Path, *, shared_dir: Path | None = None, connect: bool = False, timeout_seconds: float = 5.0, mqtt_wait_seconds: float = 5.0, db_sample: bool = False, extra_builders: Mapping[str, Callable[[dict[str, Any]], BuiltConnector]] | None = None, connector_sections: Mapping[str, Sequence[tuple[str, str]]] | None = None) -> CandidateCheck
Check a candidate config against the Node Type definitions in node_type_dir.
The config is validated the way a Node validates it when it loads, plus the check that every
source key a connector declares is projected. With connect=False (the default) that is all:
no target is reached, nothing is staged and nothing is written. With connect=True a config
that passes also has each of its connectors tested against its target, so the targets must be
reachable from this machine; a live Node may hold a session on the same target. An encrypted
config is never decrypted when no age key is available: the result is "skipped", with no
verdict.
timeout_seconds bounds connecting. mqtt_wait_seconds is how long an MQTT connector
waits for one message on its subscriptions (0 to not wait, at most 60); a quiet topic is a
result, not a failure. Both are checked whether or not connect is set. db_sample is
off by default: only with it does a database log connector also read one row of its table and
return it as the sample, so a plain connection check never reads a row from the target's
database, and mqtt_wait_seconds does not turn it on. The row is plant data.
extra_builders and connector_sections let a connector of your own be tested. A builder
is a function from the config section (a dict) to a BuiltConnector, keyed by connector
type; it replaces a built-in builder of the same type. connector_sections maps a Node Type
name to the (config key, connector type) pairs of its connector sections; it adds Node Types
the check does not already know and cannot change a built-in one. Both are used only with
connect=True, though connector_sections is checked either way. A builder must open
nothing until the connector is asked to test: the check closes every connector it built.
Parameters
| Name | Type | Default |
|---|---|---|
config_path |
Path |
required |
node_type_dir |
Path |
required |
shared_dir |
Path | None |
None |
connect |
bool |
False |
timeout_seconds |
float |
5.0 |
mqtt_wait_seconds |
float |
5.0 |
db_sample |
bool |
False |
extra_builders |
Mapping[str, Callable[[dict[str, Any]], BuiltConnector]] | None |
None |
connector_sections |
Mapping[str, Sequence[tuple[str, str]]] | None |
None |
Returns
CandidateCheck
Raises
KindredError: the Node Type directory is missing, holds nonode_type.jsonor holds one that does not load. The raised class is not in the surface, so catchKindredError.ValueError:timeout_secondsis not positive and finite,mqtt_wait_secondsis out of range,db_sampleis not a bool, orconnector_sectionsnames a built-in Node Type or is malformed.
Example
>>> import json, tempfile
>>> from pathlib import Path
>>> from engine.public import check_candidate
>>> with tempfile.TemporaryDirectory() as tmp:
... node_types = Path(tmp) / "node-types"
... node_types.mkdir()
... _ = (node_types / "node_type.json").write_text(json.dumps({
... "identity": {"name": "Demo Sensor", "version": "1.0.0"},
... "config_schema": {"type": "object", "required": ["endpoint"]},
... }))
... config = Path(tmp) / "config.json"
... _ = config.write_text(json.dumps({
... "node_type": "Demo Sensor", "node_type_version": "1.0.0",
... "config_version": 1, "config": {"endpoint": "http://sensor.local"},
... }))
... check = check_candidate(config, node_types)
>>> check.state, check.node_type, check.findings
('passed', 'Demo Sensor', ())
>>> check.connection_state, check.connection_reason
('skipped', 'the connection check was not requested')
>>> from engine.public import BuiltConnector, ConnectionCheckResult, SystemConnector
>>> class Sensor(SystemConnector):
... def test_connection(self):
... return ConnectionCheckResult(success=True, message="sensor answered")
>>> with tempfile.TemporaryDirectory() as tmp:
... node_types = Path(tmp) / "node-types"
... node_types.mkdir()
... _ = (node_types / "node_type.json").write_text(json.dumps({
... "identity": {"name": "Demo Sensor", "version": "1.0.0"},
... "config_schema": {"type": "object", "required": ["sensor"]},
... }))
... config = Path(tmp) / "config.json"
... _ = config.write_text(json.dumps({
... "node_type": "Demo Sensor", "node_type_version": "1.0.0",
... "config_version": 1, "config": {"sensor": {"endpoint": "http://sensor.local"}},
... }))
... check = check_candidate(
... config, node_types, connect=True,
... extra_builders={"sensor": lambda section: BuiltConnector(
... Sensor(), section["endpoint"], frozenset())},
... connector_sections={"Demo Sensor": [("sensor", "sensor")]},
... )
>>> check.connection_state, [(c.name, c.state, c.message) for c in check.connections]
('passed', [('sensor', 'passed', 'sensor answered')])
CandidateCheck
Class (dataclass). Since 0.2.0.
CandidateCheck(state: Literal['passed', 'failed', 'skipped'], findings: tuple[tuple[str, str], ...] = (), reason: str | None = None, node_type: str | None = None, connection_state: Literal['passed', 'failed', 'skipped'] = 'skipped', connection_reason: str | None = None, connections: tuple[ConnectionOutcome, ...] = ())
What checking a candidate config found, with no config value in any message.
state is the verdict on the config itself: "passed" (valid), "failed" (findings
says why) or "skipped" (no verdict at all: the config is encrypted and no age key is
available, and reason says so). node_type is the Node Type the config names, when it
could be read. The connection check never reports "passed" for a part that did not run:
connection_state is "skipped", with connection_reason, when connections were not
requested, the config did not pass, or no connector could be tested. The dataclass is frozen.
Fields
| Field | Type | Default | Description |
|---|---|---|---|
state |
Literal['passed', 'failed', 'skipped'] |
required | |
findings |
tuple[tuple[str, str], ...] |
() |
Each problem as a (rule, message) pair. The rule is one of "unreadable", "undecryptable", "unknown_node_type", "node_type_version", "source_section", "schema" and "mapping_consistency". |
reason |
str | None |
None |
Why there is no verdict, when state is "skipped". |
node_type |
str | None |
None |
|
connection_state |
Literal['passed', 'failed', 'skipped'] |
'skipped' |
"failed" if any connector failed, else "skipped" if any was skipped or none ran, else "passed". |
connection_reason |
str | None |
None |
Why the connection check was skipped, when connection_state is "skipped". |
connections |
tuple[ConnectionOutcome, ...] |
() |
One outcome per connector the config declares; empty unless the config passed and connections were requested. |
Example
>>> from engine.public import CandidateCheck
>>> check = CandidateCheck("failed", findings=(("schema", "endpoint is required"),))
>>> check.state, check.findings[0][0], check.connection_state
('failed', 'schema', 'skipped')
ConnectionOutcome
Class (dataclass). Since 0.2.0.
ConnectionOutcome(name: str, connector_type: str, state: Literal['passed', 'failed', 'skipped'], message: str, target: str | None = None, sample: Any | None = None, sample_truncated: bool = False)
One connector's result in a connection check, its sample scrubbed of the config's secrets.
name is the config section the connector was built from and connector_type its type.
state is "passed", "failed" (including a connector that did not answer in time or
could not be built) or "skipped" (no builder is known for its type). message says why,
with no secret of the config in it. The dataclass is frozen.
Fields
| Field | Type | Default | Description |
|---|---|---|---|
name |
str |
required | |
connector_type |
str |
required | |
state |
Literal['passed', 'failed', 'skipped'] |
required | |
message |
str |
required | |
target |
str | None |
None |
Where the connector connected, with no credential in it; None when none was built. |
sample |
Any | None |
None |
What a passing connector returned: JSON values only, cut to a size, the config's own secrets removed. It is whatever the target returned, so it can still hold plant data that is not a secret of the config. None for a connector that failed, was skipped or returned nothing. |
sample_truncated |
bool |
False |
True when sample was cut to a size. |
Example
>>> from engine.public import ConnectionOutcome
>>> outcome = ConnectionOutcome("source", "mqtt", "passed", "connected")
>>> outcome.state, outcome.target, outcome.sample
('passed', None, None)
BuiltConnector
Class (dataclass). Since 0.2.0.
BuiltConnector(connector: SystemConnector, target: str, secrets: frozenset[str], url_secrets: frozenset[str] = frozenset(), usernames: frozenset[str] = frozenset(), sampler: Callable[[float, float], ConnectionCheckResult] | None = None, sampler_reads_stored_data: bool = False)
A connector built from a config section, with what a report may say about it.
A connector builder (what check_candidate takes in extra_builders) returns one of these.
target is where the connector connects, with no credential in it; secrets are the config
values a report must never show (usernames lets the base64 of username:secret be
recognised). A result built from the connector has these removed. The dataclass is frozen.
Fields
| Field | Type | Default | Description |
|---|---|---|---|
connector |
SystemConnector |
required | |
target |
str |
required | |
secrets |
frozenset[str] |
required | |
url_secrets |
frozenset[str] |
frozenset() |
The part of secrets that only an endpoint URL's userinfo holds (scrubbed in context). |
usernames |
frozenset[str] |
frozenset() |
|
sampler |
Callable[[float, float], ConnectionCheckResult] | None |
None |
sampler(wait, connect_timeout): waits up to wait seconds for one example from the target, on a session of its own, after connecting within connect_timeout. Set only by a builder whose connector has nothing to return on a plain connection check; the connector's own test_connection() is unchanged. Not called by the health check. |
sampler_reads_stored_data |
bool |
False |
True when sampler reads a record the target stores (a database row) and not a message the target sends. The dry-run then calls it only when asked for a database sample, never because a wait was set, and passes it no wait. A plain connection check reads no such record. |
Example
>>> from engine.public import BuiltConnector, ConnectionCheckResult, SystemConnector
>>> class Printer(SystemConnector):
... def test_connection(self):
... return ConnectionCheckResult(success=True, message="printer answered")
>>> built = BuiltConnector(Printer(), "tcp://printer.local:9100", frozenset({"s3cret"}))
>>> built.target, sorted(built.secrets), built.sampler
('tcp://printer.local:9100', ['s3cret'], None)
preview_candidate
Function. Since 0.2.0.
preview_candidate(config_path: Path, node_type_dir: Path, sample_path: Path, *, section: str | None = None, identity_field: str | None = None, event_type: str | None = None, shared_dir: Path | None = None) -> PreviewReport
Run a candidate config's mapping over a sample file and report its gaps, offline.
config_path is the candidate config, node_type_dir the directory of Node Type
definitions it is checked against and sample_path a captured file of source records (a JSON
array or JSON lines). The mapping is the connector section's field_map, or its
state_transition_rules when it has any, as a Node uses them. section names that
section; leave it off when the config has exactly one of opcua, mqtt,
database_log and rest.
identity_field is the canonical field that identifies the entity; it is needed unless the
Node Type is one that fixes it. event_type names one of the Node Type's event types, whose
schema is then applied to each event; without it no schema is, as a Node that passes none.
The sample is treated as the section's primary record.
A config or sample that cannot be used gives an "unusable" report rather than raising. The
report holds names and counts only: no sample value, and no value of the config.
Parameters
| Name | Type | Default |
|---|---|---|
config_path |
Path |
required |
node_type_dir |
Path |
required |
sample_path |
Path |
required |
section |
str | None |
None |
identity_field |
str | None |
None |
event_type |
str | None |
None |
shared_dir |
Path | None |
None |
Returns
PreviewReport
Example
>>> import json, tempfile
>>> from pathlib import Path
>>> from engine.public import preview_candidate
>>> folder = Path(tempfile.mkdtemp())
>>> mapping = {"source_keys": ["id", "spare"], "field_map": {"order_id": "id"}}
>>> files = {
... "node_type.json": {
... "identity": {"name": "Press", "version": "1.0.0"},
... "config_schema": {"type": "object"},
... },
... "config.json": {
... "node_type": "Press",
... "node_type_version": "1.0.0",
... "config_version": 1,
... "config": {"mqtt": mapping},
... },
... "sample.json": [{"id": "A1", "spare": 3}],
... }
>>> for name, content in files.items():
... _ = (folder / name).write_text(json.dumps(content))
>>> report = preview_candidate(
... folder / "config.json", folder, folder / "sample.json", identity_field="order_id"
... )
>>> report.state, report.unprojected_keys
('gaps', ('spare',))
PreviewReport
Class (dataclass). Since 0.2.0.
PreviewReport(state: Literal['clean', 'gaps', 'unusable'], reason: str | None = None, details: tuple[str, ...] = (), node_type: str | None = None, section: str | None = None, record_count: int = 0, unprojected_keys: tuple[str, ...] = (), matched: int = 0, unmatched: int = 0, flagged: int = 0, null_field_counts: tuple[tuple[str, int], ...] = (), unread_field_counts: tuple[tuple[str, int], ...] = (), records: tuple[RecordReport, ...] = (), records_omitted: int = 0, field_names_omitted: int = 0, dead_rules: tuple[tuple[int, int], ...] = (), dead_rules_omitted: int = 0, no_catch_all: bool = False)
What previewing a candidate's mapping over a sample found, with no value in it.
state is "clean" (nothing to fix), "gaps" (a subscribed key is never projected, a
rule can never be reached, a record is unmatched or flagged, or a field is unset or unread) or
"unusable" (the config, Node Type or sample could not be used; reason says why and
details adds the config's own findings). The counts cover the whole sample; only the first
20 records with gaps are listed in records. The dataclass is frozen.
Fields
| Field | Type | Default | Description |
|---|---|---|---|
state |
Literal['clean', 'gaps', 'unusable'] |
required | |
reason |
str | None |
None |
|
details |
tuple[str, ...] |
() |
For an unusable config, what the config check found, with no config value in it. |
node_type |
str | None |
None |
|
section |
str | None |
None |
The config section whose mapping was previewed. |
record_count |
int |
0 |
|
unprojected_keys |
tuple[str, ...] |
() |
Subscribed keys the mapping never reads, all of them (each name cut to a length). |
matched |
int |
0 |
|
unmatched |
int |
0 |
|
flagged |
int |
0 |
|
null_field_counts |
tuple[tuple[str, int], ...] |
() |
Canonical fields left empty, with how many records hit each; the most often first. |
unread_field_counts |
tuple[tuple[str, int], ...] |
() |
Record fields the mapping never reads, with how many records hit each. |
records |
tuple[RecordReport, ...] |
() |
|
records_omitted |
int |
0 |
How many records with gaps are not listed in records. |
field_names_omitted |
int |
0 |
How many field names the two count lists left out to stay within their size. |
dead_rules |
tuple[tuple[int, int], ...] |
() |
Rules no record can reach, as (position, shadowed_by) pairs, counting rules from 0: the rule at position is never used because the earlier rule at shadowed_by matches every record it would. Positions only, never a value of a rule. At most 50 are listed. |
dead_rules_omitted |
int |
0 |
How many dead rules dead_rules left out to stay within its size. |
no_catch_all |
bool |
False |
True when the section has rules and none has an empty when. A note: it does not make the state "gaps", because a record no rule matches passing through unchanged can be wanted. |
Example
>>> from engine.public import PreviewReport
>>> report = PreviewReport("unusable", reason="the sample file is empty")
>>> report.state, report.records
('unusable', ())
RecordReport
Class (dataclass). Since 0.2.0.
RecordReport(index: int, matched: bool, flagged: bool, null_fields: tuple[str, ...], unread_fields: tuple[str, ...], empty_required: tuple[str, ...])
The gaps in one sample record, by field name; no value of the record is in it.
index is the record's position in the sample, counting from 0. matched is false for a
record no rule covered. flagged is true when the event failed the event schema asked for.
null_fields are canonical fields left empty because the record lacked their source field,
unread_fields are record fields the mapping never reads, and empty_required are the
schema's required fields left empty. A list cut to a size ends with a "(+N more)" entry.
The dataclass is frozen.
Fields
| Field | Type | Default |
|---|---|---|
index |
int |
required |
matched |
bool |
required |
flagged |
bool |
required |
null_fields |
tuple[str, ...] |
required |
unread_fields |
tuple[str, ...] |
required |
empty_required |
tuple[str, ...] |
required |
Example
>>> from engine.public import RecordReport
>>> record = RecordReport(0, True, False, (), ("spare",), ())
>>> record.index, record.unread_fields
(0, ('spare',))
Carrying a config to an appliance with no route to the repository
build_config_bundle
Function. Since 0.9.0.
build_config_bundle(repo: Path, ref: str, config_path: str, node_type_dir: Path, *, shared_dir: Path | None = None) -> ConfigBundleBuild
Read config_path at ref of the git repository repo and build a bundle of it.
The file is checked against the Node Type definitions in node_type_dir the way
check_candidate checks one, with no connection check, and a bundle is built only when that
check did not fail. config_path is a path to a .json file inside the repository; a
path ending .enc.json is an encrypted config, and the bundle names its file accordingly.
The repository is only read. Nothing is staged and nothing is written.
Parameters
| Name | Type | Default |
|---|---|---|
repo |
Path |
required |
ref |
str |
required |
config_path |
str |
required |
node_type_dir |
Path |
required |
shared_dir |
Path | None |
None |
Returns
ConfigBundleBuild
Raises
KindredError: the work could not be done: git is not installed,repois not a git repository,reforconfig_pathis not shaped like one, the Node Type directory cannot be used, or the file cannot be carried in a bundle (it is not UTF-8 text, or it is too large). The raised class is not in the surface, so catchKindredError.
Example
>>> import json, subprocess, tempfile
>>> from pathlib import Path
>>> from engine.public import build_config_bundle
>>> with tempfile.TemporaryDirectory() as tmp:
... root = Path(tmp)
... node_types = root / "node-types"
... node_types.mkdir()
... _ = (node_types / "node_type.json").write_text(json.dumps({
... "identity": {"name": "Demo Sensor", "version": "1.0.0"},
... "config_schema": {"type": "object", "required": ["endpoint"]},
... }))
... repo = root / "site-config"
... repo.mkdir()
... _ = (repo / "config.json").write_text(json.dumps({
... "node_type": "Demo Sensor", "node_type_version": "1.0.0",
... "config_version": 1, "config": {"endpoint": "http://sensor.local"},
... }))
... git = ["git", "-C", str(repo), "-c", "user.name=a", "-c", "user.email=a@b.c"]
... steps = (["init", "-q", "-b", "main"], ["add", "."], ["commit", "-q", "-m", "c"])
... for step in steps:
... subprocess.run(git + step, check=True).check_returncode()
... build = build_config_bundle(repo, "main", "config.json", node_types)
>>> build.state
'built'
>>> check, bundle = build.check, build.bundle
>>> assert check is not None and bundle is not None
>>> check.state, check.connection_state
('passed', 'skipped')
>>> sorted(bundle)
['commit', 'content', 'format_version', 'name', 'ref']
ConfigBundleBuild
Class (dataclass). Since 0.9.0.
ConfigBundleBuild(state: Literal['built', 'invalid', 'not_found'], ref: str, commit: str | None = None, check: CandidateCheck | None = None, bundle: dict[str, Any] | None = None)
What building a config bundle found, with no config value in any message.
state is "built" (bundle holds the bundle), "invalid" (the offline check
failed; check says why and there is no bundle) or "not_found" (the ref, or the config
file at that ref, is not in the repository). check is the offline check of the file; its
connection_state is "skipped" because nothing is connected to. A built bundle whose
check.state is "skipped" was not validated here, because the config is encrypted and
this machine has no age key: the appliance validates it when it stages it. The dataclass is
frozen.
Fields
| Field | Type | Default | Description |
|---|---|---|---|
state |
Literal['built', 'invalid', 'not_found'] |
required | |
ref |
str |
required | The ref as it was given. |
commit |
str | None |
None |
The full commit id the ref resolved to, when it resolved. |
check |
CandidateCheck | None |
None |
The offline check of the file; none when the file was not found. |
bundle |
dict[str, Any] | None |
None |
The bundle, ready to write as JSON; none unless state is "built". |
Example
>>> from engine.public import ConfigBundleBuild
>>> build = ConfigBundleBuild("not_found", ref="no-such-branch")
>>> build.state, build.commit, build.bundle
('not_found', None, None)
Writing the subscribe and project lists once
SourceKeyEntry
Class (dataclass). Since 0.2.0.
SourceKeyEntry(source_key: str, maps_to: tuple[str, ...] = (), node_id: str | None = None, record: int | None = None)
One source key: how it is subscribed and which canonical fields it feeds.
maps_to are the canonical fields the key is projected to (field_map entries); leave it
empty when the source's mapping is state_transition_rules. node_id is the OPC UA node
the key is read from and is required there, not allowed for MQTT. record is OPC UA only:
None is the primary record, i is additional_records[i]. The dataclass is frozen.
Fields
| Field | Type | Default |
|---|---|---|
source_key |
str |
required |
maps_to |
tuple[str, ...] |
() |
node_id |
str | None |
None |
record |
int | None |
None |
Example
>>> from engine.public import SourceKeyEntry
>>> entry = SourceKeyEntry("job_id", maps_to=("order_id",))
>>> entry.source_key, entry.maps_to
('job_id', ('order_id',))
ExpandedMapping
Class (dataclass). Since 0.2.0.
ExpandedMapping(connector: str, entries: tuple[SourceKeyEntry, ...], source_keys: tuple[str, ...], extra_fields: tuple[Mapping[str, str], ...], record_extra_fields: Mapping[int, tuple[Mapping[str, str], ...]], field_map: Mapping[str, str])
The two lists a config holds, expanded from one set of entries.
extra_fields (OPC UA, primary record) and source_keys (MQTT) are the subscribe side;
record_extra_fields holds each additional record's extra_fields by its index.
field_map is the project side. The dataclass is frozen.
Fields
| Field | Type | Default |
|---|---|---|
connector |
str |
required |
entries |
tuple[SourceKeyEntry, ...] |
required |
source_keys |
tuple[str, ...] |
required |
extra_fields |
tuple[Mapping[str, str], ...] |
required |
record_extra_fields |
Mapping[int, tuple[Mapping[str, str], ...]] |
required |
field_map |
Mapping[str, str] |
required |
Example
>>> from engine.public import SourceKeyEntry, expand_source_keys
>>> expanded = expand_source_keys("mqtt", [SourceKeyEntry("job_id", ("order_id",))])
>>> expanded.config_fragment()
{'source_keys': ['job_id'], 'field_map': {'order_id': 'job_id'}}
ExpandedMapping.config_fragment
Method.
ExpandedMapping.config_fragment() -> dict[str, Any]
The config keys to merge into the connector's section, as plain data.
An additional record's extra_fields are in record_extra_fields, because the record's
own node_id is the caller's.
ExpandedMapping.render
Method.
ExpandedMapping.render() -> str
The subscribe and project sides of every entry, one entry per line, side by side.
expand_source_keys
Function. Since 0.2.0.
expand_source_keys(connector: str, entries: Sequence[SourceKeyEntry], *, state_transition_rules: list[MappingRule] | None = None) -> ExpandedMapping
Expand entries into the subscribe and project lists for connector.
A source key repeated across entries is subscribed once per place it is read (one per OPC UA
record) and its maps_to fields are merged. Every subscribed key must end up projected: by
maps_to into field_map, or, when state_transition_rules is given, by a rule that
reads it. Rules and maps_to cannot be combined, because a Node ignores field_map once
any rule exists.
Parameters
| Name | Type | Default |
|---|---|---|
connector |
str |
required |
entries |
Sequence[SourceKeyEntry] |
required |
state_transition_rules |
list[MappingRule] | None |
None |
Returns
ExpandedMapping
Raises
ConfigValidationError:connectoris unknown; an entry is malformed; two source keys feed one canonical field;maps_tois used alongside rules; the same key is declared twice for one OPC UA record; or a subscribed key is never projected (all such keys are named).
Example
>>> from engine.public import SourceKeyEntry, expand_source_keys
>>> expanded = expand_source_keys("mqtt", [SourceKeyEntry("job_id", ("order_id",))])
>>> expanded.source_keys, dict(expanded.field_map)
(('job_id',), {'order_id': 'job_id'})
Transforming records
TransformationRegistry
Class. Since 0.1.0.
TransformationRegistry(default_transform: Callable[[dict[str, Any]], dict[str, Any]] = <built-in default>)
Maps a source type to the TransformFunc that turns its raw records into event fields.
The registry starts with only a generic fallback that passes a record through unchanged, so
every source type can be transformed before anything is registered. Registering the source
type "generic" replaces the fallback.
Parameters
| Name | Type | Default |
|---|---|---|
default_transform |
Callable[[dict[str, Any]], dict[str, Any]] |
<built-in default> |
Constructor
Build a registry whose generic fallback is default_transform.
The default passes a record through unchanged.
Example
>>> from engine.public import MappingRule, TransformationRegistry
>>> from engine.public import build_rule_based_transform
>>> registry = TransformationRegistry()
>>> registry.register("sensor", build_rule_based_transform(
... [MappingRule(then={"value": "reading"})]))
>>> registry.transform("sensor", {"reading": 1.5})
{'value': 1.5}
>>> registry.transform("unknown", {"reading": 1.5})
{'reading': 1.5}
TransformationRegistry.register
Method.
TransformationRegistry.register(source_type: str, transform: Callable[[dict[str, Any]], dict[str, Any]]) -> None
Register transform for source_type, replacing any earlier registration.
Registering the source type "generic" replaces the fallback.
TransformationRegistry.registered_source_types
Property.
TransformationRegistry.registered_source_types -> frozenset[str]
Every source type with a registered transform, "generic" included.
TransformationRegistry.transform
Method.
TransformationRegistry.transform(source_type: str, record: dict[str, Any]) -> dict[str, Any]
Transform record with the transform registered for source_type.
An unregistered source type uses the generic fallback, so this never raises for an unknown type.
TransformFunc
Type alias. Since 0.1.0.
TransformFunc = Callable[[dict[str, Any]], dict[str, Any]]
transform(record) -> canonical event fields. Never raises for a well-formed dict input, including one with no fields matching any expected key (returns whatever it can rather than erroring).
MappingRule
Class (data model). Since 0.1.0.
MappingRule(*, when: dict[str, Any] = <built-in default>, then: dict[str, str] = <built-in default>, literals: dict[str, Any] = <built-in default>)
One declarative rule: if when matches a record, build a result from it.
when is {source_field: expected_value}. A record matches only if every entry agrees,
and an empty when always matches. A field that is absent from the record never matches an
entry, even one expecting None: when={"error_code": None} matches a record that
carries error_code: null, not one that lacks the field.
The result is built from two parts. then is {canonical_field: source_field}, read from
the matched record. literals is {canonical_field: constant}, applied on top.
Fields
| Field | Type | Default |
|---|---|---|
when |
dict[str, Any] |
<built-in default> |
then |
dict[str, str] |
<built-in default> |
literals |
dict[str, Any] |
<built-in default> |
Example
>>> from engine.public import MappingRule
>>> rule = MappingRule(
... when={"event": "data_change"},
... then={"value": "reading"},
... literals={"source": "client-server"},
... )
>>> rule.then
{'value': 'reading'}
build_rule_based_transform
Function. Since 0.1.0.
build_rule_based_transform(rules: list[MappingRule]) -> Callable[[dict[str, Any]], dict[str, Any]]
Build a TransformFunc that applies the first rule in rules that matches.
Use it when a source's shape depends on which kind of record it is reporting: one template per condition rather than a single fixed column mapping. A record that matches no rule is returned unchanged.
Parameters
| Name | Type | Default |
|---|---|---|
rules |
list[MappingRule] |
required |
Returns
Callable[[dict[str, Any]], dict[str, Any]]
Example
>>> from engine.public import MappingRule, build_rule_based_transform
>>> transform = build_rule_based_transform([
... MappingRule(when={"event": "data_change"}, then={"value": "reading"},
... literals={"source": "client-server"}),
... ])
>>> transform({"event": "data_change", "reading": 42})
{'value': 42, 'source': 'client-server'}
>>> transform({"event": "heartbeat"})
{'event': 'heartbeat'}
Connecting to a system
SystemConnector
Class. Since 0.1.0.
SystemConnector()
Base class for every connector type: a Node's link to its target system.
A connector implements test_connection() and nothing else is required. How it fetches
data (poll, subscribe, a one-shot query) differs too much between target systems to share an
interface beyond that health check.
Example
>>> from engine.public import ConnectionCheckResult, SystemConnector
>>> class AlwaysUp(SystemConnector):
... def test_connection(self):
... return ConnectionCheckResult(success=True, message="up")
>>> AlwaysUp().test_connection().success
True
SystemConnector.test_connection
Method.
SystemConnector.test_connection() -> ConnectionCheckResult
Attempt a live round-trip against the target system.
Never raises. An unreachable target, rejected credentials or a malformed response are
reported through ConnectionCheckResult.success and .message.
ConnectorRegistry
Class. Since 0.1.0.
ConnectorRegistry()
Maps a connector type to the factory that builds its SystemConnector.
A factory is a ConnectorFactory: a function from a validated config dict to a connector.
The registry starts empty, and asking for a type nothing was registered for is an error
(unlike the transformation and chunking registries, which fall back to a generic default).
Constructor
Build an empty registry: no connector type is registered by default.
Example
>>> from engine.public import ConnectionCheckResult, ConnectorRegistry, SystemConnector
>>> class Demo(SystemConnector):
... def __init__(self, config):
... self.config = config
... def test_connection(self):
... return ConnectionCheckResult(success=True, message="up")
>>> registry = ConnectorRegistry()
>>> registry.register("demo", Demo)
>>> registry.build("demo", {"endpoint": "http://x"}).test_connection().message
'up'
ConnectorRegistry.build
Method.
ConnectorRegistry.build(connector_type: str, config: dict[str, Any]) -> SystemConnector
Build the SystemConnector for connector_type from config.
config is the connector's own section of a config that has already been validated.
Raises
ConfigValidationError: no factory is registered forconnector_type. A Node Type that declares an unknown connector type is a configuration error; there is no fallback.
ConnectorRegistry.register
Method.
ConnectorRegistry.register(connector_type: str, factory: Callable[[dict[str, Any]], SystemConnector]) -> None
Register factory for connector_type, replacing any earlier registration.
ConnectorRegistry.registered_connector_types
Property.
ConnectorRegistry.registered_connector_types -> frozenset[str]
Every connector type that has a registered factory.
ConnectorFactory
Type alias. Since 0.1.0.
ConnectorFactory = Callable[[dict[str, Any]], SystemConnector]
factory(config) -> a built SystemConnector, config already schema-validated against that connector type's own Configuration Schema fragment.
ConnectionCheckResult
Class (data model). Since 0.1.0.
ConnectionCheckResult(*, success: bool, message: str, sample: Any | None = None)
The outcome of one Connector Health Check.
success says whether the round-trip worked, message explains it, and sample is an
optional example of what came back.
Fields
| Field | Type | Default |
|---|---|---|
success |
bool |
required |
message |
str |
required |
sample |
Any | None |
None |
Example
>>> from engine.public import ConnectionCheckResult
>>> ConnectionCheckResult(success=True, message="reachable").sample is None
True
Conformance
ConformanceHarness
Class (dataclass). Since 0.1.0.
ConformanceHarness(node_type: NodeTypeDefinition, event_type_name: str, registered_source_type: str, unregistered_source_type: str, valid_raw_record: dict[str, Any], malformed_raw_record: dict[str, Any], ingest: Callable[[str, dict[str, Any], dict[str, Any] | None], Any], extract_event_fields: Callable[[Any], dict[str, Any]] = <built-in default>, unresponsive_exceptions: tuple[type[Exception], ...] = <built-in default>, enqueue_with_stable_id: Callable[[str, dict[str, Any], UUID], None] | None = None)
What a Node Type supplies to be run through the Conformance Suite.
A harness describes one Node Type's ingest path in a common shape, so the suite can check it without knowing how it is built.
Fields
| Field | Type | Default | Description |
|---|---|---|---|
node_type |
NodeTypeDefinition |
required | the Node Type's declaration. |
event_type_name |
str |
required | the declared event type the checks validate against. |
registered_source_type |
str |
required | a source type the Node Type has a transform for. |
unregistered_source_type |
str |
required | a source type nothing was registered for. |
valid_raw_record |
dict[str, Any] |
required | a raw record that should ingest cleanly. |
malformed_raw_record |
dict[str, Any] |
required | a raw record that should come out failing the event type's schema. |
ingest |
Callable[[str, dict[str, Any], dict[str, Any] | None], Any] |
required | (source_type, raw, event_schema) to whatever the Node Type's own ingest path returns. event_schema is the event type's schema, or None. |
extract_event_fields |
Callable[[Any], dict[str, Any]] |
<built-in default> |
pulls a plain dict of event fields out of what ingest returned. The default returns it unchanged, which suits an ingest that already returns a dict. |
unresponsive_exceptions |
tuple[type[Exception], ...] |
<built-in default> |
the exception types that mean the target is unreachable. The first is used to simulate an unreachable target. The default is httpx.HTTPError and the engine's own error for an unreachable OPC UA sidecar. |
enqueue_with_stable_id |
Callable[[str, dict[str, Any], UUID], None] | None |
None |
optional (source_type, raw, trigger_id) for a Node Type that enqueues Triggers. None when it has no enqueue path. |
Example
>>> from engine.public import (
... ConformanceHarness, MappingRule, TransformationRegistry,
... build_rule_based_transform, validate_node_type_definition,
... )
>>> node_type = validate_node_type_definition({
... "identity": {"name": "Demo Sensor", "version": "1.0.0"},
... "config_schema": {"type": "object"},
... "event_types": [{
... "name": "Reading", "description": "A sensor reading",
... "fields": {"type": "object", "required": ["value"],
... "properties": {"value": {"type": "number"}}},
... }],
... })
>>> registry = TransformationRegistry()
>>> registry.register("sensor", build_rule_based_transform(
... [MappingRule(then={"value": "value"})]))
>>> harness = ConformanceHarness(
... node_type=node_type, event_type_name="Reading",
... registered_source_type="sensor", unregistered_source_type="other",
... valid_raw_record={"value": 1.5}, malformed_raw_record={"value": "n/a"},
... ingest=lambda source_type, raw, schema: registry.transform(source_type, raw),
... )
>>> harness.event_schema["required"]
['value']
ConformanceHarness.event_schema
Property.
ConformanceHarness.event_schema -> dict[str, Any]
The declared fields schema of this harness's event_type_name.
Raises
ValueError:event_type_namedoes not name an event type the Node Type declares. The suite reports this as a failed check rather than aborting the run.
run_conformance_suite
Function. Since 0.1.0.
run_conformance_suite(harness: ConformanceHarness, activity_log: ActivityLog, trigger_queue: TriggerQueue, node_instance_id: str) -> ConformanceReport
Run every Conformance Suite check against harness and return the full report.
The checks are schema conformance, idempotent event handling, giving up cleanly when the
target is unreachable, flagging malformed data instead of guessing at it, and falling back
to the generic transform for an unregistered source type. One failing check does not stop
the others: an exception inside a check becomes a failed ConformanceCheckResult whose
detail names it.
activity_log and trigger_queue are provided by the caller, with their schemas
already created, and node_instance_id labels the entries the run writes. Both stores are
Postgres-backed, so a database must be reachable (see ActivityLog for the settings). The
run appends entries to the Activity
Log, which cannot be deleted, and enqueues a test Trigger, so give the TriggerQueue a
table of its own (table_name) rather than a production one.
Parameters
| Name | Type | Default |
|---|---|---|
harness |
ConformanceHarness |
required |
activity_log |
ActivityLog |
required |
trigger_queue |
TriggerQueue |
required |
node_instance_id |
str |
required |
Returns
ConformanceReport
Example
>>> from engine.public import (
... ActivityLog, ConformanceHarness, MappingRule, TransformationRegistry,
... TriggerQueue, build_rule_based_transform, run_conformance_suite,
... validate_node_type_definition,
... )
>>> node_type = validate_node_type_definition({
... "identity": {"name": "Demo Sensor", "version": "1.0.0"},
... "config_schema": {"type": "object"},
... "event_types": [{
... "name": "Reading", "description": "A sensor reading",
... "fields": {"type": "object", "required": ["value"],
... "properties": {"value": {"type": "number"}}},
... }],
... })
>>> registry = TransformationRegistry()
>>> registry.register("sensor", build_rule_based_transform(
... [MappingRule(then={"value": "value"})]))
>>> harness = ConformanceHarness(
... node_type=node_type, event_type_name="Reading",
... registered_source_type="sensor", unregistered_source_type="other",
... valid_raw_record={"value": 1.5}, malformed_raw_record={"value": "n/a"},
... ingest=lambda source_type, raw, schema: registry.transform(source_type, raw),
... )
>>> log, queue = ActivityLog(), TriggerQueue(table_name="trigger_queue_example")
>>> log.ensure_schema()
>>> queue.ensure_schema()
>>> report = run_conformance_suite(harness, log, queue, "docs-example")
>>> report.passed
True
ConformanceReport
Class (dataclass). Since 0.1.0.
ConformanceReport(results: list[ConformanceCheckResult])
Every ConformanceCheckResult from one run_conformance_suite call.
results is in the order the checks ran, and passed is true only if every one passed.
Fields
| Field | Type | Default |
|---|---|---|
results |
list[ConformanceCheckResult] |
required |
Example
>>> from engine.public import ConformanceCheckResult, ConformanceReport
>>> report = ConformanceReport(results=[
... ConformanceCheckResult(name="a", passed=True, detail=""),
... ConformanceCheckResult(name="b", passed=False, detail="ValueError: boom"),
... ])
>>> report.passed
False
ConformanceReport.passed
Property.
ConformanceReport.passed -> bool
True only if every individual check passed.
ConformanceCheckResult
Class (dataclass). Since 0.1.0.
ConformanceCheckResult(name: str, passed: bool, detail: str)
The result of one named Conformance Suite check.
passed says whether the check held and detail is a human-readable sentence: what was
verified when it passed, or the exception text when it did not.
Fields
| Field | Type | Default |
|---|---|---|
name |
str |
required |
passed |
bool |
required |
detail |
str |
required |
Example
>>> from engine.public import ConformanceCheckResult
>>> ConformanceCheckResult(name="schema_conformance", passed=True, detail="ok").passed
True
ActivityLog
Class. Since 0.1.0.
ActivityLog(settings: Settings | None = None)
Append-only record of what a Node did, kept in Postgres.
Task runs, ingestion outcomes and failures are appended as entries, and entries are never
updated or deleted. Construct it with no arguments to use the process-wide settings, which
are read from the environment variables listed in the repository's .env.example (the
POSTGRES_* connection and OLLAMA_BASE_URL) or from a .env file in the directory
you run from. Call ensure_schema() once before first use.
In the public surface this class exists to be built and handed to run_conformance_suite.
Only the constructor and ensure_schema are covered; every other member is internal.
Parameters
| Name | Type | Default |
|---|---|---|
settings |
Settings | None |
None |
Constructor
Build an ActivityLog against settings, or the process-wide default.
Example
>>> from engine.public import ActivityLog
>>> log = ActivityLog()
>>> log.ensure_schema()
ActivityLog.ensure_schema
Method.
ActivityLog.ensure_schema() -> None
Create the Activity Log table if it does not exist, and guard it as append-only.
Safe to call repeatedly, and from several processes starting at once. Raises SchemaGenerationError, changing nothing, when the database records another schema generation than this engine's.
TriggerQueue
Class. Since 0.1.0.
TriggerQueue(settings: Settings | None = None, *, table_name: str = 'trigger_queue')
A Postgres-backed queue of Triggers for one Node instance.
table_name defaults to the production table. Give each queue that must not share rows
with another (a test, say) its own name, and call ensure_schema() before first use.
In the public surface this class exists to be built and handed to run_conformance_suite.
Only the constructor and ensure_schema are covered; every other member is internal.
Parameters
| Name | Type | Default |
|---|---|---|
settings |
Settings | None |
None |
table_name |
str |
'trigger_queue' |
Constructor
Build a TriggerQueue against table_name, or the process-wide default settings.
Example
>>> from engine.public import TriggerQueue
>>> queue = TriggerQueue(table_name="trigger_queue_example")
>>> queue.ensure_schema()
TriggerQueue.ensure_schema
Method.
TriggerQueue.ensure_schema() -> None
Create this queue's table if it doesn't already exist.
Workflows and gates
WorkflowRegistry
Class. Since 0.1.0.
WorkflowRegistry()
Builds a Task for each of the five Workflow patterns.
A step is a function of one argument, Step. Each method binds its arguments into a Task
that has not run yet; call execute() on it.
Example
>>> from engine.public import WorkflowRegistry
>>> registry = WorkflowRegistry()
>>> task = registry.parallelization(
... "both", 10, [lambda n: n + 1, lambda n: n * 2], aggregate=sum)
>>> task.execute().value
31
WorkflowRegistry.evaluator_optimizer
Method.
WorkflowRegistry.evaluator_optimizer(name: str, data: Any, generate: Callable[[Any], Any], gate: Gate, *, proceed_branch: str = 'proceed', max_iterations: int = 3) -> Task
Build an Evaluator-Optimizer Task: generate, let gate judge, and repeat.
generate receives the previous candidate (the original data the first time). The
loop ends when the Gate resolves to proceed_branch or after max_iterations rounds.
The value of the executed Task's TaskResult is an object with value (the last
candidate), converged (true if the Gate reached proceed_branch) and iterations
(how many rounds ran). A candidate that never reaches proceed_branch is still
returned as the best effort, with converged false, rather than raising or looping
without a bound.
WorkflowRegistry.orchestrator_workers
Method.
WorkflowRegistry.orchestrator_workers(name: str, data: Any, plan: Callable[[Any], list[Any]], worker: Callable[[Any], Any], aggregate: Callable[[list[Any]], Any]) -> Task
Build an Orchestrator-Workers Task: plan subtasks, run a worker on each, then aggregate.
plan splits data into subtasks, decided at run time from the data. worker
runs on each one and aggregate combines the results.
WorkflowRegistry.parallelization
Method.
WorkflowRegistry.parallelization(name: str, data: Any, steps: list[Callable[[Any], Any]], aggregate: Callable[[list[Any]], Any]) -> Task
Build a Parallelization Task: run steps concurrently, then aggregate.
Every step runs over data at the same time and aggregate combines their results.
aggregate receives the results in the order of steps, whichever finished first. With
no steps it receives an empty list.
WorkflowRegistry.prompt_chaining
Method.
WorkflowRegistry.prompt_chaining(name: str, data: Any, steps: list[Callable[[Any], Any]]) -> Task
Build a Prompt Chaining Task: run steps over data in sequence.
Each step receives the previous step's output, and the last step's output is the result.
WorkflowRegistry.routing
Method.
WorkflowRegistry.routing(name: str, data: Any, gate: Gate, routes: dict[str, Callable[[Any], Any]]) -> Task
Build a Routing Task: gate picks a branch and that branch's route runs alone.
routes maps a branch name to the step to run. Every branch the Gate can produce, its
fallback included, needs a route. Executing the Task raises KeyError when the Gate
resolves to a branch with no route.
Task
Class (dataclass). Since 0.1.0.
Task(name: str, pattern: WorkflowPattern, run: Callable[[], Any])
A discrete unit of work: a name, its pattern and a bound run.
run is a function of no arguments with everything already bound to it. Get a Task from
one of WorkflowRegistry's methods rather than constructing it, so run matches its
pattern. execute() calls run and wraps the value in a TaskResult.
Fields
| Field | Type | Default |
|---|---|---|
name |
str |
required |
pattern |
WorkflowPattern |
required |
run |
Callable[[], Any] |
required |
Example
>>> from engine.public import WorkflowRegistry
>>> task = WorkflowRegistry().prompt_chaining("double", 4, [lambda n: n * 2])
>>> task.execute().value
8
Task.execute
Method.
Task.execute() -> TaskResult
Run this Task to its end and return its TaskResult.
Whatever the Task's steps raise propagates unchanged.
TaskResult
Class (dataclass). Since 0.1.0.
TaskResult(pattern: WorkflowPattern, value: Any)
What running a Task produced, tagged with the pattern that ran it.
pattern is the Task's WorkflowPattern and value is whatever the pattern returned.
Fields
| Field | Type | Default |
|---|---|---|
pattern |
WorkflowPattern |
required |
value |
Any |
required |
Example
>>> from engine.public import TaskResult, WorkflowPattern
>>> TaskResult(pattern=WorkflowPattern.ROUTING, value=3).value
3
WorkflowPattern
Enumeration. Since 0.1.0.
The five Workflow patterns a Task can follow.
PROMPT_CHAINING runs steps in sequence, each feeding the next. ROUTING lets a Gate
pick one branch to run. PARALLELIZATION runs steps at once and aggregates the results.
ORCHESTRATOR_WORKERS plans subtasks and runs a worker over each. EVALUATOR_OPTIMIZER
generates, then loops until a Gate approves or a bound is reached.
Members
| Member | Value |
|---|---|
PROMPT_CHAINING |
'prompt_chaining' |
ROUTING |
'routing' |
PARALLELIZATION |
'parallelization' |
ORCHESTRATOR_WORKERS |
'orchestrator_workers' |
EVALUATOR_OPTIMIZER |
'evaluator_optimizer' |
Example
>>> from engine.public import WorkflowPattern
>>> WorkflowPattern.ROUTING.value
'routing'
Step
Type alias. Since 0.1.0.
Step = Callable[[Any], Any]
An ordinary, non-branching Workflow activity - a "custom function call".
Gate
Class. Since 0.1.0.
Gate(mode: EvaluationMode, evaluate: Callable[[Any], str], *, branches: frozenset[str] | None = None, fallback: str | None = None)
A configurable branching step: looks at data and resolves to one named branch.
evaluate(data) returns a branch name and carries all of the mode-specific logic. The Gate
records which EvaluationMode was used and, when branches is given, keeps the result
inside that set: a branch outside it resolves to fallback instead of raising. When
branches is not given nothing is enforced and the name evaluate returns is used as
it is, which suits a Gate that can only ever return names from a known set.
Parameters
| Name | Type | Default |
|---|---|---|
mode |
EvaluationMode |
required |
evaluate |
Callable[[Any], str] |
required |
branches |
frozenset[str] | None |
None |
fallback |
str | None |
None |
Constructor
Build a Gate.
evaluate returns a branch name. branches, when given, is the closed set of names it
may return, for a Gate whose branches come from data (a classifier with one branch per known
category). fallback is then required, must be a member of branches, and is what any
name outside the set resolves to.
Raises
ValueError:branchesis given without afallback, or thefallbackis not a member ofbranches.
Example
>>> from engine.public import EvaluationMode, Gate
>>> gate = Gate(
... EvaluationMode.RULE,
... lambda temperature: "alarm" if temperature > 90 else "ok",
... branches=frozenset({"ok", "alarm", "review"}),
... fallback="review",
... )
>>> gate.decide(95).branch
'alarm'
Gate.decide
Method.
Gate.decide(data: Any) -> GateDecision
Evaluate data and resolve to one branch.
When evaluate returns a branch outside the declared branches, the decision is the
fallback with used_fallback set. It does not raise for an unrecognised branch.
GateDecision
Class (dataclass). Since 0.1.0.
GateDecision(branch: str, mode: EvaluationMode, used_fallback: bool = False)
The branch a Gate chose for one piece of data, and how.
mode is the Gate's evaluation mode. used_fallback is true when the Gate's own
evaluation named a branch outside its declared set and the fallback branch was used instead.
Fields
| Field | Type | Default | Description |
|---|---|---|---|
branch |
str |
required | |
mode |
EvaluationMode |
required | |
used_fallback |
bool |
False |
True when evaluate returned a branch outside the registered set and Gate substituted the mandatory fallback instead. |
Example
>>> from engine.public import EvaluationMode, GateDecision
>>> GateDecision(branch="proceed", mode=EvaluationMode.RULE)
GateDecision(branch='proceed', mode=<EvaluationMode.RULE: 'rule'>, used_fallback=False)
EvaluationMode
Enumeration. Since 0.1.0.
How a Gate reached its decision.
RULE is a deterministic check (threshold, category, boolean, compound condition) with no
model call. STATISTICAL compares a statistical or ML score against a configured bar.
LLM is a language-model judgment. All three resolve in one synchronous pass.
Members
| Member | Value | Description |
|---|---|---|
RULE |
'rule' |
Threshold/categorical/boolean/compound-condition checks - deterministic, no model call. |
STATISTICAL |
'statistical' |
A statistical/ML score compared against a configured bar. |
LLM |
'llm' |
An LLM judgment - still resolves synchronously in one pass, same as the other two modes. |
Example
>>> from engine.public import EvaluationMode
>>> EvaluationMode.RULE.value
'rule'
Chunking documents
ChunkingRegistry
Class. Since 0.1.0.
ChunkingRegistry(default_strategy: Callable[[str], list[Chunk]] = <built-in default>)
Maps a document type to the strategy that splits it, with a generic fallback.
A strategy is a ChunkingStrategy: a function from text to a list of Chunk. The
registry starts with only the fallback, a fixed-size overlapping character window, so every
document type can be chunked before anything is registered. Registering the document type
"generic" replaces the fallback.
Parameters
| Name | Type | Default |
|---|---|---|
default_strategy |
Callable[[str], list[Chunk]] |
<built-in default> |
Constructor
Build a registry whose generic fallback is default_strategy.
The default is a fixed-size overlapping character window.
Example
>>> from engine.public import Chunk, ChunkingRegistry
>>> def by_step(text):
... return [Chunk(text=step, sequence=i) for i, step in enumerate(text.split(";"))]
>>> registry = ChunkingRegistry()
>>> registry.register("work-instruction", by_step)
>>> [c.text for c in registry.chunk("work-instruction", "step one;step two")]
['step one', 'step two']
>>> len(registry.chunk("unknown-type", "any text"))
1
ChunkingRegistry.chunk
Method.
ChunkingRegistry.chunk(document_type: str, text: str) -> list[Chunk]
Chunk text with the strategy registered for document_type.
An unregistered document type uses the generic fallback, so this never raises for an unknown type.
ChunkingRegistry.register
Method.
ChunkingRegistry.register(document_type: str, strategy: Callable[[str], list[Chunk]]) -> None
Register strategy for document_type, replacing any earlier registration.
Registering the document type "generic" replaces the fallback.
ChunkingRegistry.registered_document_types
Property.
ChunkingRegistry.registered_document_types -> frozenset[str]
Every document type with a registered strategy, "generic" included.
ChunkingStrategy
Type alias. Since 0.1.0.
ChunkingStrategy = Callable[[str], list[Chunk]]
strategy(text) -> chunks, in document order. Never raises for any text input, including empty text (returns [] rather than erroring).
ChunkingStrategySpec
Class (dataclass). Since 0.5.0.
ChunkingStrategySpec(name: str, version: int, build: Callable[[dict[str, Any]], Callable[[str], list[Chunk]]], schema: dict[str, Any] = <built-in default>, defaults: dict[str, Any] = <built-in default>, check: Callable[[dict[str, Any]], tuple[str, str] | None] | None = None, stamps_locator: bool = False)
A chunking strategy that a document type catalogue can name and configure.
Fields
| Field | Type | Default | Description |
|---|---|---|---|
name |
str |
required | The name a catalogue entry gives as strategy.name: lower case letters, digits and underscores, starting with a letter. |
version |
int |
required | The version of the strategy's code. A change to what the strategy does for the same parameters must raise it, because it is part of the identity of a configuration. |
build |
Callable[[dict[str, Any]], Callable[[str], list[Chunk]]] |
required | Turns validated parameters, with the defaults filled in, into the chunking function. |
schema |
dict[str, Any] |
<built-in default> |
JSON Schema for the parameters; the default accepts none. |
defaults |
dict[str, Any] |
<built-in default> |
Parameter values used when the catalogue entry gives none. |
check |
Callable[[dict[str, Any]], tuple[str, str] | None] | None |
None |
Looks at the parameters, defaults filled in, after the schema passes. Returns the name of the parameter at fault and what is wrong with it, or None. |
stamps_locator |
bool |
False |
Whether every chunk the strategy makes carries a locator in its metadata that names the place in the document it came from and does not depend on the chunk's size or sequence. A document type may draft instruction claims only under a strategy that does, because a claim points at its place by that locator. |
Example
>>> from engine.public import Chunk, ChunkingStrategySpec
>>> spec = ChunkingStrategySpec(
... name="by_semicolon",
... version=1,
... build=lambda params: lambda text: [
... Chunk(text=part, sequence=i) for i, part in enumerate(text.split(";"))
... ],
... )
>>> spec.build({})("a;b")[1].text
'b'
register_chunking_strategy
Function. Since 0.5.0.
register_chunking_strategy(spec: ChunkingStrategySpec) -> None
Make spec available to the document type catalogue under spec.name.
Call it before the Node loads its configuration: the catalogue is checked when it loads, and
a strategy.name that is not registered by then is refused. Registering a name again
replaces the earlier registration, as ChunkingRegistry.register does.
Parameters
| Name | Type | Default |
|---|---|---|
spec |
ChunkingStrategySpec |
required |
Returns
None
Raises
ValueError: the name is malformed or is one of the four built-in strategies, or the version is not a positive integer.
Example
>>> from engine.public import Chunk, ChunkingStrategySpec, register_chunking_strategy
>>> register_chunking_strategy(
... ChunkingStrategySpec(
... name="whole_text",
... version=1,
... build=lambda params: lambda text: [Chunk(text=text, sequence=0)],
... )
... )
Chunk
Class (data model). Since 0.1.0.
Chunk(*, text: str, sequence: int, metadata: dict[str, Any] = <built-in default>)
One piece of a chunked document.
sequence is the chunk's 0-indexed position in the document it came from. metadata
is free-form and empty by default.
Fields
| Field | Type | Default | Description |
|---|---|---|---|
text |
str |
required | |
sequence |
int |
required | 0-indexed position within the document this chunk came from. |
metadata |
dict[str, Any] |
<built-in default> |
Example
>>> from engine.public import Chunk
>>> Chunk(text="Torque the bolts to 40 Nm.", sequence=0)
Chunk(text='Torque the bolts to 40 Nm.', sequence=0, metadata={})
Errors
KindredError
Class. Since 0.1.0.
Base class for the exceptions the engine defines.
Catch it to handle the engine's own failures without naming each kind; exceptions that are not in the public surface are still subclasses of it. Some functions also let a standard exception through (a missing file, say), and their entries list those under Raises.
Example
>>> from engine.public import ConfigValidationError, KindredError
>>> issubclass(ConfigValidationError, KindredError)
True
ConfigValidationError
Class. Since 0.1.0.
A Node Type declaration or a config file failed validation.
The message says what failed and where. For a field marked x-sensitive in the
Configuration Schema it never contains the offending value.
Example
>>> from engine.public import ConfigValidationError, validate_node_type_definition
>>> try:
... validate_node_type_definition({})
... except ConfigValidationError:
... print("rejected")
rejected
Release: v0.11.0