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": {}}
}
  • apiVersion is the document contract (thinglogic/v1alpha1) and kind is Pipeline. A document with any other value is refused — the service never guesses which contract was meant.

  • metadata.name is the pipeline’s name; metadata.description is free text.

  • spec is the executable graph. ui.layout is editor furniture (node positions keyed by node id) and is stored verbatim; nothing executes from it.

  • A node may pin a catalog version explicitly. 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 → k1 and p1 → 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.kind is tumbling (windows aligned to the epoch, [k*size, (k+1)*size)), sliding (slide_s required; every covering window), or count (closes on its Nth sample; count required, and size_s/slide_s are refused). A count window is order-driven: it has no watermark, no allowed_lateness_s, and an out-of-order sample simply joins the count window that is open when it arrives. Its window_start/window_end are the earliest/latest sample instants it covered.

  • time_basis is event_time (default; the watermark is the greatest event instant seen) or receipt_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’s metric is the aggregate’s as alias; it also carries window_start, window_end, window_complete, sample_count, aggregate and source_metric.

  • output_every_s adds an output frequency: while a window is still open, a PARTIAL aggregate rides out at most once per interval and carries window_complete: false with the sample_count it 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 (or drain).

  • 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.

  • drain emits buffered windows with window_complete: false, so a consumer can tell a stopped pipeline from a window that closed (or, for a count window, a window that filled).

  • fn is avg, min, max, sum, count, first, last, the descriptive statistics stddev, variance and median, or a percentile written p<nn> (p0..p100). stddev and variance are sample statistics (the n-1 denominator); 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 reports 0.0. median is exactly the 50th percentile; percentiles use linear interpolation between the two closest ranks. first, last and 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_s is bounded at one day.

  • metric_name narrows the input to one metric; otherwise group_by must include metric, because values of different metrics never share an aggregate. value is also a legal group_by field: fn: count grouped by value counts 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 reports 0 once its window has closed, never before, and only once.

  • moving-stat — the mean or median of the last n arrivals of a key. Until n samples exist the record says warming_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_signal is -1/0/+1 and peak_zscore the z that decided it.

  • trend — a field rose (direction: "increase") or fell by at least percentage percent within window_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 to ok, warning_low/high or alarm_low/high. The control limits are inclusive.

  • collect — the values of a count or time window as one list record, capped by the required max_values; a truncated list says how many values it withheld.

  • top-k — the limit most (or least, order: "asc") frequent values of a field within each window, ranked with top_rank/top_key/top_count.

  • stats-summary — count/min/max/sum/mean/median plus SAMPLE standard deviation and variance and any requested percentiles, 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 than max_values is 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 for timeout_s. silence fires once per episode; a resume emits one resumed record (emit_resume: false turns that off).

  • absence — a record on a is not followed by one on b within within_s (“dispatched but no pickup acknowledgement”). start_expression and cancel_expression choose which records arm and discharge the pattern; a B for a different key never cancels an A.

  • sequence — a then b within within_s, matched on key. match_policy is first (each A pairs at most once) or every (every eligible pair is emitted).

  • co-occurrence — a and b both within within_s, in either order (“e-stop and motor fault together”), with the same match_policy.

  • rate-change — the event rate changed by at least percentage percent 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 left and right. kind is inner (emit only pairs) or left (also emit a left record that times out, with right_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_s behind 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 own metric / value / device_id describe the left side. join_complete says whether the result came from a closed window — a drained pipeline reports false.

  • Buffering is bounded (10,000 records across both sides). On overflow a left join 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), or unavailable (no provider is configured, or the read failed). missing_reference_fields names every requested field that could not be supplied — a missing reference is never a silent null.

  • Reference fields are added under prefix (default ref_); the input payload is otherwise preserved. reference_age_s, reference_freshness_s and reference_fresh declare 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 field, operation, output

Arithmetic

add, subtract, multiply, divide, modulo

exactly one of operand.field or operand.constant

Unary

negate, abs

none

Rounding

round

decimals (0–12, required) and optional rounding: half_up, half_even, down, up

Trigonometry

sin, cos, tan, asin, acos, atan

optional angle_unit: rad (default) or deg

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"}}

target

Reads

Result

double

string, int, double

a number; a string must parse as one

int

string, int, double

a whole number, truncated toward zero (not rounded)

boolean

string, bool, int, double

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

"true", "True", "TRUE", "1"

true

"false", "False", "FALSE", "0"

false

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"}}

operation

Operands

Result

and

2 or more

true when all are true

or

2 or more

true when any is true

xor

2 or more

true when an odd number are true

nand

2 or more

not (all)

nor

2 or more

not (any)

xnor

2 or more

not (odd) — true when an even number are true

not

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

string, bool

eq, neq

int, double

eq, neq, gt, gte, lt, lte

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"}}

algorithm

Offered

sha256, sha512

yes

md5, sha1

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:

clock

What it is

processing_time

when this platform processed the record

event_time

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"}}

unit

Measures

bytes

the byte count (an integer)

kib

the byte count divided by 1024

mib

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

field

the string field to parse

output

where the milliseconds go (a new field)

format

optional strftime pattern. Absent or empty means ISO-8601

time_zone

optional IANA zone (e.g. Asia/Tokyo, America/New_York)

A time with no offset is never assumed to be UTC. The platform refuses in the two places it can:

  • If format cannot produce a UTC offset (it has no %z or %Z) and no time_zone is 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_zone is 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"}}

unit

Result

milliseconds

the difference, as an integer

seconds, minutes, hours

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

year, month, day

the local calendar date

hour, minute, second

the local time of day

millisecond

0–999

weekday

Monday is 1 … Sunday is 7 (ISO-8601)

iso_week

1–53, the ISO week number

iso_year

the ISO week-numbering year, which is not always year

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

field

both

the list to read; must be declared list upstream

operation

both

count or split

output

count

the new integer field holding the length

element_field

split

the new field holding one element

max_elements

split

required cap, 1–10000

keep_fields

split

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:

window.kind

Members

Boundary

time

size_s

calendar-aligned to size_s, so two devices that started a second apart share a window

count

size

every size samples for that key

cron

expression, time_zone

a 5-field cron fire time; time_zone is UTC in this version

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

value_field

the numeric field to compress (default value)

deviation

required, positive: the ribbon’s half-width

min_interval_s

never emit two retained points closer than this

max_interval_s

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.

What the three share

Member

Meaning

key

the field the state is keyed by; default device_id

key_ttl_s

evict a key not seen for this many event-time seconds

max_keys

the most keys held (default 10000, ceiling 100000); the oldest is evicted

Every eviction is counted, and every record the node cannot judge — an unkeyable record, or one whose watched/value field is missing or mistyped — is emitted unchanged with an error status and a located entry in its errors field. A reducer never swallows what it could not judge.

The catalogue says which nodes hold state: each node type carries a state declaration ({kind, keyed_by, ttl_s, bounded_by}) in GET /api/v1/catalog — window for rate-limit, keyed for on-change and sdt-compress, and null for every pure function.

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

transition-detect

did the value go from A to B? (a boolean field per record)

edge-detect

forward the record where a boolean turned, optionally only if it is still there after delay_s

edge-counter

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

state-duration

how long the field stayed at one value; emits on exit, optionally a periodic heartbeat

signal-interval

time from signal A rising to signal B rising (request → door-open)

task-duration

time between consecutive changes of a task field, with an optional process id

state-buffer

the values collected while in a state, emitted as a capped list on exit

state-label

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-reproject converts between it and WGS84.

Node

What it does

geo-point

Create a Point from a latitude/longitude pair, or from site-frame x/y.

geo-distance

Distance to another point, or to a fixed point — a radius geofence.

geo-speed

Speed between successive positions of one device.

geo-trajectory

A rolling LineString of a device’s recent positions.

geo-buffer

A polygon around a point (circle) or around a geometry (hull).

geo-reproject

Convert a geometry between WGS84 and a site-local frame.

geo-grid

Assign a point to a cell of a metric grid.

geo-validate

Report whether a geometry is well formed (and, optionally, drop bad records).

geo-zone

Report which site zone a device is in, and when it enters or leaves.

geocode

Turn an address into latitude/longitude.

reverse-geocode

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-speed counts a duplicate timestamp instead of dividing by Δt = 0, and a sample closer than min_interval_s to its reference does not move it;

  • geo-trajectory writes no LineString until it has two points (warming_up);

  • geo-validate with on_invalid: "drop" counts the dropped records;

  • geo-buffer refuses a geometry whose buffered form would exceed max_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

GET /pipelines/schema

The document’s JSON Schema (2020-12), with the nested models in $defs.

POST /pipelines/validate

Judges a document without saving anything.

POST /pipelines/import

Validates and creates a draft pipeline from the document.

GET /pipelines/{pipeline_id}/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, code and the content type are the contract; title is fixed per code and never assembled from the input;

  • detail describes 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/~1 escaping per RFC 6901) and the stable code an 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.