The pipeline document¶
A pipeline is a dataflow graph: telemetry enters at a source, is evaluated by one or more processors, and results are delivered to sinks. ThingLogic accepts a pipeline as a document — one versioned JSON object with a stable schema — so an editor, a CLI, and a CI job all produce and consume the same bytes.
This page is the contract for that document: its envelope, how edges bind typed ports, what the validator guarantees, and what each operation returns.
The envelope¶
{
"apiVersion": "thinglogic/v1alpha1",
"kind": "Pipeline",
"metadata": {"name": "Boiler overheat", "description": ""},
"spec": {
"nodes": [
{"id": "s1", "type": "source", "subtype": "device-mqtt-stream",
"config": {"scope_id": "scope-1"}},
{"id": "p1", "type": "processor", "subtype": "threshold",
"config": {"metric_name": "temperature", "operator": "gt", "threshold_value": 80.0}},
{"id": "k1", "type": "sink", "subtype": "thingband-sink",
"config": {"sink_id": "sink-1"}}
],
"edges": [
{"from": {"node": "s1", "port": "out"}, "to": {"node": "p1", "port": "in"}},
{"from": {"node": "p1", "port": "out"}, "to": {"node": "k1", "port": "in"}}
]
},
"ui": {"layout": {}}
}
apiVersionis the document contract (thinglogic/v1alpha1) andkindisPipeline. A document with any other value is refused — the service never guesses which contract was meant.metadata.nameis the pipeline’s name;metadata.descriptionis free text.specis the executable graph.ui.layoutis editor furniture (node positions keyed by node id) and is stored verbatim; nothing executes from it.A node may pin a catalog
versionexplicitly. Omitted, it means the type’s current version; an unknown pin is refused rather than substituted.
Edges bind typed ports¶
A node type is not just a name — it declares typed INPUT and OUTPUT ports. For
example the built-in source device-mqtt-stream has one output port out of type
device_telemetry; threshold has input in (device_telemetry) and output
out (threshold_alarm); the ThingBand sink has input in
(threshold_alarm).
An edge therefore names both ends: an output port of one node and an input port of another.
{"from": {"node": "s1", "port": "out"}, "to": {"node": "p1", "port": "in"}}
The validator checks every edge at both ports:
the named node exists and the named port exists on its type;
the upstream port’s data type is the downstream port’s data type;
the upstream payload can supply every field the downstream port requires.
A connection that fails any check is refused at the edge, naming the port. Connecting a telemetry source directly to an alarm sink is a type mismatch — it is refused, never compiled into a rule that evaluates nothing.
The ports of every node type are published in the catalog
(GET /api/v1/catalog), each with its data_type and payload schema, alongside
the version the node type is currently at.
Shapes that execute¶
A deployed pipeline executes as a program: the service compiles the whole graph into one program per pipeline and the worker runs that program. Every ordinary dataflow shape is supported:
a single processor —
s1 → p1 → k1;serial stages —
s1 → p1 → p2 → k1;fan-out — one node feeding several downstream nodes, e.g.
s1 → p1 → k1andp1 → k2;multiple sources — two sources feeding the same or different processors;
multiple sinks — results delivered to more than one sink.
A processor may take several inbound edges only when its type declares several
input ports, and then each port takes exactly one edge. A single-input processor
(in) accepts one; the fusion nodes below name their branches separately
(union takes in1 and in2; join takes left and right). A declared
input port with no inbound edge is refused with input_port_unbound; a port fed
by more than one edge is refused with input_port_multiple. Both name the node
and the port. Source with inbound edges, sink with outbound edges, cycles,
unreachable sinks and port type/schema mismatches are refused as before.
Each refusal is a located, structured error — see below — and names the node it is about.
Window aggregates¶
processor.window-aggregate computes values over a time window and emits them
as telemetry, so a downstream processor acts on an aggregate exactly as it acts
on a raw sample:
{"id": "wa1", "type": "processor", "subtype": "window-aggregate",
"config": {
"window": {"kind": "tumbling", "size_s": 60},
"time_basis": "event_time",
"allowed_lateness_s": 5,
"group_by": ["device_id", "metric"],
"metric_name": "temperature",
"aggregates": [{"fn": "avg", "as": "avg_temperature"}]
}}
window.kindistumbling(windows aligned to the epoch,[k*size, (k+1)*size)),sliding(slide_srequired; every covering window), orcount(closes on its Nth sample;countrequired, andsize_s/slide_sare refused). A count window is order-driven: it has no watermark, noallowed_lateness_s, and an out-of-order sample simply joins the count window that is open when it arrives. Itswindow_start/window_endare the earliest/latest sample instants it covered.time_basisisevent_time(default; the watermark is the greatest event instant seen) orreceipt_time(the wall clock).A window closes when the watermark reaches
end + allowed_lateness_s, and one record is emitted per (window, group key, aggregate). The record’smetricis the aggregate’sasalias; it also carrieswindow_start,window_end,window_complete,sample_count,aggregateandsource_metric.output_every_sadds an output frequency: while a window is still open, a PARTIAL aggregate rides out at most once per interval and carrieswindow_complete: falsewith thesample_countit covered. The closed window still emits its complete record, so the cadence is additive — it never replaces the closed emission. The cadence is evaluated when a record arrives: an idle window emits nothing until the next record (ordrain).A sample that arrives after its window closed is dropped and counted (visible in the run’s node metrics), never silently folded in. Within a window, samples aggregate in event order, not arrival order.
drainemits buffered windows withwindow_complete: false, so a consumer can tell a stopped pipeline from a window that closed (or, for a count window, a window that filled).fnisavg,min,max,sum,count,first,last, the descriptive statisticsstddev,varianceandmedian, or a percentile writtenp<nn>(p0..p100).stddevandvarianceare sample statistics (then-1denominator); a window with fewer than two samples has no spread, so that aggregate emits no record and the refusal is counted in the node’s metrics (insufficient_samples) — it never reports0.0.medianis exactly the 50th percentile; percentiles use linear interpolation between the two closest ranks.first,lastand the percentiles follow event order, not arrival order.Evaluation is bounded: a sliding window that would put one sample in more than 1000 windows is refused, a count window larger than 100000 samples is refused, and
output_every_sis bounded at one day.metric_namenarrows the input to one metric; otherwisegroup_bymust includemetric, because values of different metrics never share an aggregate.valueis also a legalgroup_byfield:fn: countgrouped byvaluecounts how often each distinct reported value occurs.
A configuration the runtime cannot execute is refused at deploy with a located
node_config_not_executable issue at /spec/nodes/N/config — a document that
saves is a document that runs.
Window statistics and anomaly detection¶
Nine processors compute a statistic over the recent past of a keyed feed. Five pass the record through with the statistic appended; four emit a new record when a window closes or a ranking is produced. Every one carries a status field, so a consumer can tell a measured value from a warming-up or refused one.
event-rate— events/second per key over a time window (window_s), or the event count and rate of a count batch (mode: "batch",batch_size). A key that goes silent reports0once its window has closed, never before, and only once.moving-stat— the mean or median of the lastnarrivals of a key. Untilnsamples exist the record sayswarming_up: true; it never presents a partial window as a full one.change-detect-cusum— Welford running mean/variance plus a CUSUM of standardised deviations (k,h,warmup_n). Each sample is scored against the history BEFORE it, then folded in; an alarm resets the accumulators.peak-detect— smoothed z-score peaks (lag,threshold,influence);peak_signalis -1/0/+1 andpeak_zscorethe z that decided it.trend— a field rose (direction: "increase") or fell by at leastpercentagepercent withinwindow_s, measured against the oldest sample still in the window. A zero baseline has no percentage and says so.limit-bands— four control/warning limits map a value took,warning_low/highoralarm_low/high. The control limits are inclusive.collect— the values of a count or time window as one list record, capped by the requiredmax_values; a truncated list says how many values it withheld.top-k— thelimitmost (or least,order: "asc") frequent values of a field within each window, ranked withtop_rank/top_key/top_count.stats-summary— count/min/max/sum/mean/median plus SAMPLE standard deviation and variance and any requestedpercentiles, over a list field (input: "list") or a keyed time window (input: "window",window_s). A window with fewer than two samples omits the sample statistics rather than writing zeros, and a list longer thanmax_valuesis refused rather than silently truncated.
Every keyed node takes key (default device_id), key_ttl_s and max_keys;
state is per key and bounded, and evictions are counted in the run’s node
metrics. A value the node cannot read (missing, null, non-numeric) produces an
error status with a located entry in its *_errors field — never a silent
zero — while the record itself continues downstream.
Temporal patterns¶
Five processors detect a pattern across time rather than a statistic over a
window. The three two-input patterns name their ports a and b, and their
CONDITIONS are ordinary expressions in the same language as
processor.expression — type-checked against the port they guard, with errors
that name the line and column in your expression:
silence— a key stops sending fortimeout_s.silencefires once per episode; a resume emits oneresumedrecord (emit_resume: falseturns that off).absence— a record onais not followed by one onbwithinwithin_s(“dispatched but no pickup acknowledgement”).start_expressionandcancel_expressionchoose which records arm and discharge the pattern; a B for a different key never cancels an A.sequence—athenbwithinwithin_s, matched onkey.match_policyisfirst(each A pairs at most once) orevery(every eligible pair is emitted).co-occurrence—aandbboth withinwithin_s, in either order (“e-stop and motor fault together”), with the samematch_policy.rate-change— the event rate changed by at leastpercentagepercent between consecutive windows; a key that goes silent reports the drop to zero once.
clock declares which clock the timers use. event_time (the default for
absence, sequence, co-occurrence and rate-change) fires on the watermark as the
stream advances — ordering-correct while records keep arriving. processing_time
(the default for silence) fires on the worker’s timer tick, which is the only
clock that can notice a feed that has STOPPED. Every pattern buffer is bounded
by max_pending and every bound’s refusals are counted in the node’s metrics.
Fusion nodes¶
Three processors combine telemetry streams. They are ordinary nodes in the same
graph: they take typed telemetry inputs, emit device_telemetry, and may feed
any downstream processor, including another fusion node.
Union — merge two streams, tagged¶
processor.union declares inputs in1 and in2 and no configuration. Every
output record names the branch it came from: union_source is the input port
and union_source_node the feeding node; the same facts appear as
tags.source / tags.source_node, written last so a record cannot spoof them.
Union does not deduplicate — the output carries every record from both
inputs.
Join — pair two streams by key and event-time window¶
{"id": "j1", "type": "processor", "subtype": "join",
"config": {"kind": "inner", "window_s": 60, "allowed_lateness_s": 5,
"key_fields": ["device_id"]}}
Inputs are
leftandright.kindisinner(emit only pairs) orleft(also emit a left record that times out, withright_present: false).Two records pair when their key fields agree and their event instants differ by at most
window_s. Pairing is deterministic: each record pairs at most once and the earliest unmatched partner (by event instant, then record id) is chosen, so arrival order cannot decide which pair forms.A record that falls more than
window_s + allowed_lateness_sbehind the greatest event instant seen on either side can no longer pair. It is dropped and counted (late_dropped), visible in the run’s node metrics.Both payloads are prefixed (
left_*,right_*) so a field named on both sides cannot collide; the record’s ownmetric/value/device_iddescribe the left side.join_completesays whether the result came from a closed window — a drained pipeline reportsfalse.Buffering is bounded (10,000 records across both sides). On overflow a
leftjoin evicts the oldest right-side record first; otherwise the oldest record is evicted. Every eviction is counted (buffer_bound_dropped).
Enrich — attach reference fields¶
{"id": "e1", "type": "processor", "subtype": "enrich",
"config": {"reference": {"resource": "thinghub.device",
"key_field": "device_id",
"fields": ["name"], "freshness_s": 60}}}
The reference read goes through the same per-resource authorization as any other read; the runtime never reads a reference itself.
Every output record declares
reference_status:present(a row was returned),missing(no row for this key), orunavailable(no provider is configured, or the read failed).missing_reference_fieldsnames every requested field that could not be supplied — a missing reference is never a silent null.Reference fields are added under
prefix(defaultref_); the input payload is otherwise preserved.reference_age_s,reference_freshness_sandreference_freshdeclare how current the row was at the record’s event time. A record older than the freshness bound is marked not fresh, not dropped.
Fusion nodes are never flattened: a graph that carries one always executes as a
composed program, and the catalog (GET /api/v1/catalog) publishes their port
arity alongside every other node type.
The executable processor set is threshold, windowed-threshold,
window-aggregate, union, join, enrich, expression, filter and map.
An expression, filter or map node is judged by the same document validator as
any other node; its config additionally must be executable against the input
field map derived from its upstream port, and a node that is not is refused with
a located issue at /spec/nodes/N/config.
Expressions, filters and maps¶
processor.expression, processor.filter and processor.map evaluate the
thinglogic-expr/v2 CEL profile over the incoming telemetry record. They take
device_telemetry in and emit device_telemetry, and their configs are:
{"id": "e1", "type": "processor", "subtype": "expression",
"config": {"fields": [{"name": "temp_f", "expression": "in.value * 1.8 + 32.0"}]}}
{"id": "f1", "type": "processor", "subtype": "filter",
"config": {"expression": "in.metric == \"temperature\" && in.value > 10.0"}}
{"id": "m1", "type": "processor", "subtype": "map",
"config": {"fields": [{"name": "temp_f", "expression": "in.value * 1.8 + 32.0"}],
"rename": {"value": "raw_value"}, "drop": ["device_id"]}}
Every expression is statically typed against the input schema, and a filter’s
expression must be boolean. The full language — operators, string functions,
implicit time variables, bounds, forbidden constructs, error spans and the
POST /api/v1/expressions/check authoring endpoint — is the
expressions page. A runtime evaluation error is counted on the
node and the record continues; it never stops the pipeline.
Math¶
processor.math computes one numeric field from a telemetry field, using an
operation from a fixed list — a form-driven preset over the same expression
profile, not a second language. It takes device_telemetry in and emits
device_telemetry with the computed field appended.
{"id": "m1", "type": "processor", "subtype": "math",
"config": {"field": "value", "operation": "multiply",
"operand": {"constant": 3.6}, "output": "speed_kmh"}}
Group |
Operations |
Config beyond |
|---|---|---|
Arithmetic |
|
exactly one of |
Unary |
|
none |
Rounding |
|
|
Trigonometry |
|
optional |
angle_unit converts a direct function’s argument to radians and an inverse
function’s result to degrees. A member the chosen operation does not read is
refused rather than ignored.
Every result is a double. output may not be the source field, a required
telemetry field, or a field the runtime writes. A record whose evaluation fails
(out of a function’s domain, a divide by zero) is still emitted, with
math_status: "error" and the reason in math_errors — the record is never
silently dropped.
Type conversion¶
processor.convert-type changes one field’s type. It takes
device_telemetry in and emits device_telemetry, with the converted value
written to a new field — or back to the source field, which is what you want
when the field itself is the one with the wrong type.
{"id": "c1", "type": "processor", "subtype": "convert-type",
"config": {"field": "value", "target": "int", "output": "value"}}
|
Reads |
Result |
|---|---|---|
|
|
a number; a string must parse as one |
|
|
a whole number, truncated toward zero (not rounded) |
|
|
a strict boolean |
Boolean conversion. A number is true when it is not zero. A boolean field
is already a boolean. A string is read with this exact vocabulary, and
nothing else:
Accepted |
Becomes |
|---|---|
|
|
|
|
Those eight spellings are the whole vocabulary — three casings of each word, plus
the two digits. Everything else — "yes", "maybe", mixed casing such as
"tRuE", "True " with whitespace, "01", "1.0", an empty string — is
not accepted and is not silently treated as false. It is an error,
below.
A field whose declared type is dyn cannot be converted: the conversion has to
be chosen from a known source type, and dyn does not state one.
A value the conversion cannot read is an error, never a default and never a
coercion: the record is still emitted, the converted field is not written,
convert_status is "error" and convert_errors carries the field and the
reason. An in-place conversion that fails leaves the original value untouched.
A successful record carries convert_status: "converted". output may equal
field (in place); otherwise it may not be a required telemetry field or a
field the runtime writes.
Boolean logic¶
processor.boolean-logic combines declared boolean fields with one
enumerated operation, or inverts a single field. It takes device_telemetry in
and emits device_telemetry with the result written to output — which may be
one of the operands, so an inverter can write back to the field it reads.
{"id": "b1", "type": "processor", "subtype": "boolean-logic",
"config": {"operation": "and", "fields": ["armed", "online"],
"output": "both_ready"}}
|
Operands |
Result |
|---|---|---|
|
2 or more |
true when all are true |
|
2 or more |
true when any is true |
|
2 or more |
true when an odd number are true |
|
2 or more |
|
|
2 or more |
|
|
2 or more |
|
|
exactly 1 |
the inverse |
Every listed field must be declared bool. A field of any other declared type
— including dyn — is refused when the document is validated, because the node
reads a field’s type rather than guessing it.
A successful record carries boolean_status: "computed". A record the
evaluation cannot read (for example, a field missing at runtime) is still
emitted: the output field is not written, boolean_status is "error", and
boolean_errors carries the field and the reason — the same fail-closed rule as
type conversion.
Switch¶
processor.switch maps one field to an ordered list of cases and writes the
first matching result to a new field, or a default when nothing matches.
{"id": "w1", "type": "processor", "subtype": "switch",
"config": {"field": "metric", "output": "category",
"cases": [{"operator": "eq", "value": "temperature",
"result": "climate"},
{"operator": "eq", "value": "vibration",
"result": "motion"}],
"default": "other"}}
Cases are evaluated in order; the first match wins. Every case is
{operator, value, result}, and default is required.
Field type |
Operators allowed |
|---|---|
|
|
|
|
A case value must be of the field’s type (a string field takes a string
value), and every result and the default must share one type — all
strings, all integers, all numbers, or all booleans. That shared type is the
output field’s declared type.
Every emitted record carries switch_status — "matched" or "default" — and
switch_case, the zero-based index of the matched case (-1 when the
default applies). A record the evaluation cannot read is still emitted with the
output field not written, switch_status: "error", and switch_errors
carrying the field and the reason.
Hashing¶
processor.hash-fields replaces the values of one or more fields with one
pseudonymous field. It is how you send data to an external sink without
sending the identity it belongs to.
{"id": "h1", "type": "processor", "subtype": "hash-fields",
"config": {"fields": ["device_id", "scope_id"], "output": "pseudonym",
"algorithm": "sha256"}}
|
Offered |
|---|---|
|
yes |
|
no — refused, they are not a safe pseudonymisation |
A keyed (HMAC) mode is not offered: it would need a tenant secret reference, and this runtime has no place to resolve one. Passing a secret inline is not an option, so the mode is refused rather than weakened.
The pseudonym is deterministic, and the input to it is part of this contract. For each field, in the order you list them:
<field-name> "=" <canonical value> <0x1F>
is appended, and the digest is sha256 (or sha512) over the UTF-8 bytes of
that text, as lowercase hex. Canonical values: a string is its own text, an
integer is decimal, a number uses the shortest form that round-trips (21.5,
not 21.500000), and a boolean is true or false. Because the field names
and their order are part of the input, reordering fields changes every
pseudonym — treat the list as part of your data contract.
drop_sources (default false) also removes the hashed fields from the record.
It may not remove a required telemetry field.
A record the hash cannot read — a listed field is missing, or holds a list,
object or null — is still emitted with the pseudonym not written,
hash_status: "error", and hash_errors carrying the field and the reason.
A success carries hash_status: "hashed".
Timestamps¶
processor.timestamp-enrich appends one named time to the record as integer
milliseconds. There are two, and they are different facts:
|
What it is |
|---|---|
|
when this platform processed the record |
|
when the device says the sample was taken |
{"id": "t1", "type": "processor", "subtype": "timestamp-enrich",
"config": {"output": "processed_at", "clock": "processing_time"}}
The clock is required and there is no default: a node that silently picked one
would make the platform’s receipt time and the device’s sample time look like the
same thing. event_time is copied from the record’s envelope — it does not
change what the device reported, and the event-time field itself (ts) cannot be
the output: appending must never overwrite an existing field.
Every emitted record carries timestamp_status: "enriched". This node cannot
fail on a record, so it has no error field.
Payload size¶
processor.event-size measures the payload’s size and appends it, for
bandwidth accounting.
{"id": "e1", "type": "processor", "subtype": "event-size",
"config": {"output": "payload_bytes", "unit": "bytes"}}
|
Measures |
|---|---|
|
the byte count (an integer) |
|
the byte count divided by 1024 |
|
the byte count divided by 1048576 |
The units are binary and named that way on purpose: “KB” and “MB” are read as either 1000 or 1024, and a bandwidth figure two readers disagree about is worse than a less familiar name.
The size is deterministic, and the measured form is part of this contract.
The payload is serialised as JSON with sorted keys, no whitespace
(separators , and :), and non-ASCII characters left as UTF-8 — then the byte
length of that UTF-8 is the size. The record’s envelope (ids, lineage) is not
measured: only the payload a sink would receive. Because the payload’s ts
field is derived from the sample time, a different sample time is a different
payload and therefore a different size.
A payload that cannot be serialised is still emitted with the size not
written, event_size_status: "error", and event_size_errors carrying the
reason. A success carries event_size_status: "measured".
Parsing dates and times¶
processor.parse-datetime turns a string field into a number: integer
milliseconds since the Unix epoch (UTC). Feeds that send time as text need this
before anything can subtract or split it.
{"id": "d1", "type": "processor", "subtype": "parse-datetime",
"config": {"field": "reported", "output": "event_ts_ms",
"time_zone": "Asia/Tokyo"}}
Member |
Meaning |
|---|---|
|
the string field to parse |
|
where the milliseconds go (a new field) |
|
optional strftime pattern. Absent or empty means ISO-8601 |
|
optional IANA zone (e.g. |
A time with no offset is never assumed to be UTC. The platform refuses in the two places it can:
If
formatcannot produce a UTC offset (it has no%zor%Z) and notime_zoneis given, the document is invalid — that combination would have to assume a zone for every record.With ISO text the offset may or may not be present, so it is checked per record: text without an offset and no configured
time_zoneis an error, never a UTC fallback.
An offset present in the text always wins: it names the instant. time_zone is
used only when the text does not.
A record that cannot be parsed is still emitted with the output field not
written, datetime_status: "error", and datetime_errors carrying the reason.
A success carries datetime_status: "parsed".
Durations¶
processor.duration appends the difference between two instants, in a unit
you choose. Both operands are integer epoch-millisecond fields — which is what
parse-datetime and timestamp-enrich produce.
{"id": "u1", "type": "processor", "subtype": "duration",
"config": {"start_field": "start_ms", "end_field": "end_ms",
"output": "elapsed_ms", "unit": "milliseconds"}}
|
Result |
|---|---|
|
the difference, as an integer |
|
the difference divided by 1000 / 60000 / 3600000, fractional |
start_field must differ from end_field, and both must be declared int. Text
is not parsed here: parse it first, so the rule about time zones lives in one
place.
A negative result is reported as measured. If end_field is earlier than
start_field, the difference is negative — that means the record’s two times
disagree about order (a late sample, a clock skew), which is a fact worth seeing.
Add a filter if the pipeline should act on it.
A record missing either operand is still emitted with the duration not
written, duration_status: "error", and duration_errors carrying the reason.
A success carries duration_status: "computed".
Timestamp parts¶
processor.timestamp-parts splits one instant into the wall-clock facts a
shift or weekday analysis needs. It reads an integer epoch-millisecond field and
writes one integer field per part you ask for.
{"id": "v1", "type": "processor", "subtype": "timestamp-parts",
"config": {"field": "ts_ms", "time_zone": "Asia/Tokyo",
"parts": {"year": "local_year", "weekday": "local_weekday"}}}
parts maps a part name to the field it is written into, so one place
names every field the node adds.
Part |
Value |
|---|---|
|
the local calendar date |
|
the local time of day |
|
0–999 |
|
Monday is 1 … Sunday is 7 (ISO-8601) |
|
1–53, the ISO week number |
|
the ISO week-numbering year, which is not always |
time_zone is required, and there is no default. A date and an hour are
local facts: the same instant is the 8th at 15:00 in UTC, the 9th at 00:00 in
Tokyo, and the 8th at 10:00 in New York. A default would put a zone you never
chose into every field this node writes.
Use iso_year with iso_week, not year. The ISO week-numbering year
differs from the calendar year at the boundary: 2027-01-01 is ISO week 53 of
2026. Grouping by (year, iso_week) would split that week across two groups.
A record whose field is missing, or is not an integer, is still emitted with no
part written, timestamp_parts_status: "error", and timestamp_parts_errors
carrying the reason. A success carries timestamp_parts_status: "computed".
Arrays¶
processor.array-ops does one of two things with a list field, chosen by
operation:
{"id": "n1", "type": "processor", "subtype": "array-ops",
"config": {"operation": "count", "field": "bags", "output": "bag_count"}}
{"id": "n2", "type": "processor", "subtype": "array-ops",
"config": {"operation": "split", "field": "bags",
"element_field": "bag", "max_elements": 500}}
count writes the list’s length to a new integer field. The list itself is
untouched, so a pipeline can count a list and still split it downstream. A count
never overwrites the field it measures.
split emits one record per element. Each emitted record carries the
element in element_field and the kept parent fields; the list being split is
removed from every one of them.
Member |
Applies to |
Meaning |
|---|---|---|
|
both |
the list to read; must be declared |
|
both |
|
|
|
the new integer field holding the length |
|
|
the new field holding one element |
|
|
required cap, 1–10000 |
|
|
which parent fields to keep; omit to keep all |
The cap is required, and truncation is reported. A third-party feed can send
a list of any length, and one record fanning out into millions is an
amplification bug rather than a feature. When a list is longer than
max_elements, the node emits the leading elements and marks every emitted
record array_ops_status: "truncated", with array_ops_errors naming how many
were withheld — a truncated record is never indistinguishable from a complete
one.
An empty list emits no record at all. There is no element to carry, and
inventing one would fabricate a row the feed never sent. The node counts these
(empty_lists in its metrics) so the absence is visible.
A record whose field is missing or is not a list is emitted unchanged with
array_ops_status: "error" and a located reason in array_ops_errors.
Reducing a feed¶
Robots send telemetry far faster than most destinations need. Three processors
reduce a feed, and all three share one discipline: their state is per key
(default device_id), bounded (max_keys, optional key_ttl_s), and
measured in event time — so a replay of the same stream produces the same
output as the live run.
Rate limit¶
{"id": "n1", "type": "processor", "subtype": "rate-limit",
"config": {"window": {"kind": "time", "size_s": 10}, "select": "last"}}
One record per key per window. The window is one of:
|
Members |
Boundary |
|---|---|---|
|
|
calendar-aligned to |
|
|
every |
|
|
a 5-field cron fire time; |
select chooses what the window emits: first emits at window open (one
record’s latency), last emits the window’s newest record at close, and all
emits the buffered batch at close — max_buffer is required for all.
A batch cut by max_buffer marks every record it emits rate_limit_status: "truncated" and names the withheld count in rate_limit_errors. A record whose
event time is behind its key’s current window is dropped and counted
(late_dropped); it is never back-filled into a window that has already
emitted.
Report by exception¶
{"id": "n2", "type": "processor", "subtype": "on-change",
"config": {"field": "mode_name", "key_ttl_s": 3600}}
Emits a record only when the watched field’s value changes, tracked separately
for every key. The first record of a key is emitted (on_change_status: "first") — dropping it would make a device’s initial state invisible until it
moved — and every later emission is a real transition ("changed").
Swinging-door compression¶
{"id": "n3", "type": "processor", "subtype": "sdt-compress",
"config": {"deviation": 0.5, "max_interval_s": 60}}
Keeps the points that carry the signal’s shape and drops the ones that do not.
deviation is required: it is the half-width of the ribbon, in the value
field’s units, and therefore the most the signal may drift between retained
points. There is no default — a default would decide, on the author’s behalf,
how much of the signal may be lost.
Member |
Meaning |
|---|---|
|
the numeric field to compress (default |
|
required, positive: the ribbon’s half-width |
|
never emit two retained points closer than this |
|
force an emission on a flat signal (a heartbeat) |
When the door closes, the last point that was still inside is emitted
(sdt_status: "retained"), not the point that broke it. drain emits the final
point ("final"), so a compressed series ends where the raw one did.
Reading state off a feed¶
Five more processors answer the questions an operator asks of a device’s state. Two are mappers over one record; three are keyed like the reducers above.
State from flags¶
{"id": "n1", "type": "processor", "subtype": "to-state",
"config": {"cases": [{"field": "door_open", "equals": true, "state": "open"},
{"field": "charging", "equals": true, "state": "charging"}],
"default": "idle", "output": "state"}}
Cases are evaluated in the order written and the first match wins, so a more
specific case goes first. A field that is not boolean/string/int, or an equals
of the wrong type for the field, is refused at validate time.
Labels from numbers¶
{"id": "n2", "type": "processor", "subtype": "label",
"config": {"field": "value",
"rules": [{"operator": "lt", "value": 20, "label": "low"},
{"operator": "between", "values": [20, 80], "label": "ok"},
{"operator": "gt", "value": 80, "label": "full"}],
"default": "unknown", "output": "band"}}
Operators: lt, lte, gt, gte, eq, neq, between. First match wins.
Overlapping between ranges are reported as a warning naming both rules —
the document still runs, and the first rule still applies.
Transitions, edges and counts¶
Node |
What it answers |
|---|---|
|
did the value go from |
|
forward the record where a boolean turned, optionally only if it is still there after |
|
how many times did it turn (boolean edges) or change (string/int, optionally only to one value)? |
All three are keyed (key, default device_id) and bounded (max_keys,
key_ttl_s), exactly like the reducers.
A delayed edge is CONFIRMED, not assumed. With delay_s, edge-detect holds
the edge until a later record’s event time reaches the deadline and forwards it
only if the value is still at the new level. A bounce inside the window cancels
the edge (counted as bounces_cancelled), and an edge still pending when the
pipeline is drained is not emitted (counted as edges_unconfirmed) — the
stream never showed that it held.
Episodes: durations, intervals and labels¶
An episode is a stretch of time a device spends in one state, between two signals, or inside one task. Five nodes measure one, all in event time:
Node |
What it records |
|---|---|
|
how long the field stayed at one value; emits on exit, optionally a periodic heartbeat |
|
time from signal A rising to signal B rising (request → door-open) |
|
time between consecutive changes of a task field, with an optional process id |
|
the values collected while in a state, emitted as a capped list on exit |
|
a label decided by an aggregate rule over those values |
{"id": "n4", "type": "processor", "subtype": "state-duration",
"config": {"field": "mode", "unit": "s", "watch_value": "blocked"}}
An episode that never ends is never invented. A device that goes silent
mid-state has no duration — the end is missing, not zero — so an open episode
is counted (open_at_drain) and not emitted when the pipeline drains. The
same applies to a state-buffer whose state never ends.
state-buffer requires max_values, and a buffer that hit the cap says
truncated on the record it emits, naming how many samples were withheld.
Location: points, distance and zones¶
A location node carries a geometry as a GeoJSON object in one field
(geometry by default) and its coordinate reference beside it, in
geometry_crs. Two references are supported:
EPSG:4326— WGS84 longitude/latitude, GeoJSON’s own reference;site:<id>— a site-local frame: a declared origin (latitude, longitude) and rotation, with x/y in metres. Robots report local map coordinates, so this is the frame a fleet actually uses;geo-reprojectconverts between it and WGS84.
Node |
What it does |
|---|---|
|
Create a Point from a latitude/longitude pair, or from site-frame x/y. |
|
Distance to another point, or to a fixed point — a radius geofence. |
|
Speed between successive positions of one device. |
|
A rolling LineString of a device’s recent positions. |
|
A polygon around a point (circle) or around a geometry (hull). |
|
Convert a geometry between WGS84 and a site-local frame. |
|
Assign a point to a cell of a metric grid. |
|
Report whether a geometry is well formed (and, optionally, drop bad records). |
|
Report which site zone a device is in, and when it enters or leaves. |
|
Turn an address into latitude/longitude. |
|
Turn a point into the nearest site or place. |
{"id": "p1", "type": "processor", "subtype": "geo-point",
"config": {"latitude_field": "lat", "longitude_field": "lng"}}
Distances are metres on the WGS84 sphere. method: "planar" is available
only in a declared site frame: without an origin there is no metric plane to
measure in, and the document is refused rather than guessed at.
Every node states its outcome. Successes write a status such as computed,
entered, valid or resolved; a refusable input writes error and a located
entry in the node’s *_errors list. A value that could not be measured is
absent, never zero:
geo-speedcounts a duplicate timestamp instead of dividing by Δt = 0, and a sample closer thanmin_interval_sto its reference does not move it;geo-trajectorywrites no LineString until it has two points (warming_up);geo-validatewithon_invalid: "drop"counts the dropped records;geo-bufferrefuses a geometry whose buffered form would exceedmax_vertices.
Zones and addresses are reference data. geo-zone, geocode and
reverse-geocode read them through the platform’s authorized reference lookup,
never by reaching out themselves. Results are cached with a hard entry cap, and
when no lookup is configured the node reports unavailable and counts it — the
record continues downstream, and nothing is invented.
Four operations¶
All paths are under /api/v1.
Operation |
What it does |
|---|---|
|
The document’s JSON Schema (2020-12), with the nested models in |
|
Judges a document without saving anything. |
|
Validates and creates a draft pipeline from the document. |
|
Exports the pipeline as a canonical document. |
Validate is an answer, not a failure¶
POST /pipelines/validate answers 200 whether or not the document is valid:
{
"valid": false,
"validated_against": {"document_api_version": "thinglogic/v1alpha1",
"catalog_revision": "…", "node_types": {"…": {}}},
"errors": [{"code": "input_port_unbound", "severity": "error",
"detail": "…", "node_id": "p2", "pointer": "/spec/nodes/2"}],
"warnings": []
}
The caller asked a question; “no” is an answer, and the response carries every reason. Nothing is written: no pipeline row, no publish.
validated_against is the receipt of the judgment: the document contract
version and, per node type, the exact version and typed ports that were applied.
A valid: true is therefore always “valid against that catalog”, not a claim
about some other day.
Import refuses with a problem document¶
POST /pipelines/import creates a draft on success (201). On refusal it
returns 422 with Content-Type: application/problem+json:
{
"type": "https://docs.fgai/thinglogic/errors/pipeline_document_invalid",
"title": "Pipeline document failed validation",
"status": 422,
"detail": "…",
"instance": "/api/v1/pipelines/import",
"code": "pipeline_document_invalid",
"errors": [{"code": "port_type_mismatch", "field": "to.port",
"detail": "…", "pointer": "/spec/edges/0/to/port",
"expected": "device_telemetry", "actual": "threshold_alarm"}]
}
The rules for every refusal on this surface:
status,codeand the content type are the contract;titleis fixed per code and never assembled from the input;detaildescribes this occurrence; it never contains the document’s contents (credential material is refused under its own code,credential_in_config, naming the key path but never echoing the value);errors[]locates each problem with a JSON Pointer into the document (/spec/nodes/2/config/metric_name,~0/~1escaping per RFC 6901) and the stablecodean editor switches on;prose is an addition, never the handle.
Shape refusals use their own codes: unsupported_api_version,
unsupported_kind, and document_shape_invalid for a document that does not
match the published schema.
Export is canonical¶
GET /pipelines/{pipeline_id}/document returns the pipeline as a document in
canonical form: object keys sorted, compact separators, defaulted members always
present (inputs: [], outputs: [], ui.layout: {}), null members absent.
The round-trip law is:
import(export(x)) == export(x) (byte-identical under canonical JSON)
It is deliberately not import(x) == export(x): an input document may omit
defaults and carry nulls, while the canonical form always emits defaults and
drops nulls. Export normalises once; importing an export reproduces it exactly.
Deploy, stop, and dry-run¶
POST /api/v1/pipelines/{pipeline_id}/deploy freezes the graph into one
immutable revision and publishes one program for the pipeline, not one rule
per processor. The response’s execution_mode says which compiler ran: flat
for a pipeline that is behaviourally a single source, one processor and one sink
(executed as an independent rule), topology for every other graph (executed as
a program by the shared runtime).
POST /api/v1/pipelines/{pipeline_id}/stop accepts {"mode": "drain"} (the
default) or {"mode": "discard"}. Draining a composed pipeline flushes buffered
event-time window state and delivers it before stopping; discarding drops that
state. Drain is asynchronous — the operation stays RUNNING until the workers
acknowledge — while a flat pipeline stops synchronously.
POST /api/v1/pipelines/{pipeline_id}/dry-run evaluates the active revision
against a bounded sample and writes nothing. For a composed pipeline it runs the
same runtime the worker runs and reports simulated_destinations per sink,
with synthetic dry-run: topic labels. That receipt is evidence, not delivery:
it says nothing about whether a real message reached a destination.
Versioning¶
The document contract is versioned by apiVersion; the catalog of node types is
versioned per type and identified as a whole by the catalog_revision in the
receipt. A breaking change to the envelope or semantics is a new apiVersion
(v1alpha2), not a silent reinterpretation of v1alpha1.
Pipelines are saved as drafts by this surface; deployment, revisions, and the draft-versus-deployed comparison are separate operations.