#Connecting eLucid8 to your data
The elucid8 command reads data from files and programs, computes, and writes results to files and programs. Where data comes from and where it goes says what inputs (data sources and data services) and outputs are, and how the playground's become a deployment's. This page shows what connects today and how, with recipes that run as written. The table below lists every system with what it can do and a link to its recipe: files, PostgreSQL, MySQL, SQL Server, DuckDB, SQLite, Amazon S3 and compatible stores, Kafka, MQTT, a REST API, a webhook, live streams and live destinations, and Snowflake, BigQuery and Databricks as sources.
#The picture
inputs elucid8 destinations
────── ─────── ────────────
CSV, JSON-lines, Parquet ──┐ ┌──> files: JSON lines, CSV, frames,
and Arrow files │ │ NumPy .npz, Apache Arrow,
databases (SQLite, │ elucid8 run │ Apache Parquet
PostgreSQL, …) ├──> a batch: queries and ─────┼──> pandas, Polars, DuckDB, NumPy
streams (Kafka, MQTT, …) │ outputs, then exit │ (reading those files)
REST APIs │ ├──> databases (SQLite, PostgreSQL, …)
through a connector ────┘ elucid8 serve ├──> webhooks, queues, other systems
program live: new rows arrive, │ through a connector program
standing queries and ─────┴──> live subscribers: only what changed
outputs answered again
#What works today
Files and programs are built in. Other systems are connected by connector programs: the Python package elucid8 has some, named in deploy.json with "connector" (Connectors by name), and any other is a short program you write (a template is below, and every Download from the website has one, connectors/connector_template.py).
A connector is a program that runs with your rights, so from 0.23.0 elucid8 starts one only with your permission: at a terminal the first elucid8 run or serve of a recipe below asks once and records your yes beside its deploy.json; in a script, pass --allow-programs (Programs need your permission).
| tool | as an input | as a destination |
|---|---|---|
| CSV, JSON-lines, Parquet and Arrow files | built in: "from": "file.csv" (or .jsonl, .parquet, .arrows), with timestamps (time, or a column named ts), a value for points with no row (fill), a column per coordinate (wide) and versions (Command reference) | built in: JSON lines, CSV, frames, NumPy .npz, Apache Arrow and Apache Parquet (Output formats); a column per coordinate (wide), and records that are eod left out ("skip": "eod") |
| a program of yours | built in: a connector serves an input's rows (Programs as sources and sinks) | built in: a connector takes an output's records |
| PostgreSQL | the Python package's connector, "connector": "postgres": a table or a query (recipe) | the same connector: each record upserted by its key (recipe) |
| DuckDB, MySQL (and MariaDB), SQL Server (and Azure SQL) | the Python package's connectors, "duckdb", "mysql", "sqlserver": a table or a query (recipes: DuckDB, MySQL and SQL Server) | the same connectors: each record written by its key (recipes: DuckDB, MySQL and SQL Server) |
| Snowflake, BigQuery, Databricks | the Python package's connectors, "snowflake", "bigquery", "databricks": a query (recipe; not yet run against the warehouses themselves) | not yet: write a file (Parquet) and load it |
| SQLite and other databases | a connector program (recipe) | a connector program that writes each record by its key (recipe) |
| Amazon S3 and compatible stores (MinIO, Cloudflare R2, …), Google Cloud Storage | the Python package's connector, "connector": "s3": a CSV, JSON-lines or Parquet object, or a folder of them (recipe) | the same connector: a Parquet object (recipe) |
| REST APIs and webhooks | the Python package's connector, "connector": "http": JSON, JSON lines or CSV from a URL (recipe) | the same connector: one POST of JSON per batch of records (recipe) |
| Kafka | the Python package's connector, "connector": "kafka": a topic, read whole; and python3 -m elucid8.connectors.kafka stream, its new messages sent to elucid8 serve as rows (recipe) | the same connector: one message a record (recipe) |
| MQTT | the Python package's connector, "connector": "mqtt": retained messages; and python3 -m elucid8.connectors.mqtt stream into elucid8 serve (recipe) | the same connector: one message a record, retained if wanted (recipe) |
| other streams | rows sent to elucid8 serve as they arrive (recipe), or a connector program | a connector program |
| pandas, Polars, DuckDB, NumPy, Arrow tools | built in: the Parquet or Arrow files they write, read directly (recipe) | built in: Apache Parquet, Apache Arrow, NumPy .npz, CSV, JSON lines and frames, which they read directly (recipe, recipe; Using eLucid8 from your code) |
| live data | elucid8 serve: new rows with advance, as they arrive (The long-running service); or, with no program sending them, a file replayed a coordinate a tick, or a clock's ticks (Inputs given rows over time) | elucid8 serve: standing queries, and outputs that send only the records that changed |
#Data source or data service?
Outside data reaches a program as an input, in one of two ways, and the question to ask is whether the answer exists before your program asks for it. The program is the same either way: deploy.json decides. A data source is data that already exists, which the program reads (a table, a file, a database). Its timestamps are the data's own (a time column in the file, or a time for each coordinate), and 0 where the data give none: never the time it was read. A data service is data made on request: at each point the program asks an outside program (an AI model, a web API), and the answer is data stamped with the time it arrived.
| The answer… | Use | Examples |
|---|---|---|
| exists whether or not your program asks | a data source: an input read from a file or a connector | sensor readings, prices, weather observations, purchases |
| is computed on request, at the point your program asks about | a data service: an input answered on demand by a program | score this reading with an AI model, translate this text, classify this image |
| depends only on which point you ask about | either | the weather forecast for an hour and a city; an exchange rate at a minute; the map position of a store |
- A data source takes nothing from the program. Its rows are fixed by the data:
reading = input("reading", t : inf), as many as the file or connector gives. - A data service answers at the point it is asked.
model = input("model", n : inf), asked asscore = model[n = reading], is asked at each point about that reading, and with another reading it gives another answer. A question is asked only for the points actually wanted, once each. Its deadline (deadlineMs), retries and reuse are the input's settings indeploy.json, not part of the program. - When the answer depends only on the point, a data source fetches everything in advance (a connector that reads the forecast for every hour and city), and a data service fetches only the points the program asks for (
weather = input("weather", hour : 24, city : 50), answered on demand). The program is the same in both cases. Choose the data source when most points will be needed or the data should be kept and versioned; the data service when few will. - An outside value with no dimensions (the latest price, the temperature now) gives the same answer whatever the program asks, so read it as stored data: an input fed by a connector.
Services are described in Data services.
#The connector protocol, in brief
A connector is a program in any language, started by elucid8 and bound in deploy.json with "process". They talk in lines of JSON on the program's standard input and output, each message with an id that its reply repeats (every message and field):
- As a source, it is asked
{"id":1,"op":"read","source":"reading","dimensions":["sensor","t"],"box":[…],"have":null}and answers{"id":1,"version":"…","rows":2}followed by that many rows, one per line,{"sensor":0,"t":0,"value":12.5}. The version names the data: the same rows, the same version, soelucid8reuses what it computed from them. - As a destination, it is sent
begin,{"id":1,"op":"begin","format":"elucid8-table/1","output":"results","dimensions":["sensor","t"],"values":["total"],"names":["total"],"records":6}(the table's form, which a destination refuses when it does not know it; the output's dimensions and values;names, the program's value each holds, which an error's origin names; and how many records follow), then the records in batches,{"id":2,"op":"records","output":"results","records":[{"context":{"sensor":0,"t":0},"outcomes":{"total":{"kind":"value","value":12.5,"ts":0}}}]}, thenend, and answers each{"id":2,"ok":true}. A batch that fails is sent again, so a destination writes each record over the one with the same key (itscontext). - Credentials never go in a file: the binding names the environment variables the program receives (
"env": ["DATABASE_URL"]), and the program reads them. It receives no others; a program that runs other commands (psql) needsPATHnamed too.
#The program the recipes use
Every recipe runs this program, three sensors' readings with each sensor's running total and an alarm over 30:
File program.el8:
-- Three sensors' readings, each sensor's running total, and an alarm over 30.
reading = input("reading", sensor : 3, t : 10)
total = reading fby.t (total + next.t reading)
alarm = reading > 30
output("total") = total
output("alarm") = alarm
reading is an input: the program says nothing about where its rows come from, and each recipe's deploy.json says it. total and alarm go out on two channels, and a recipe that writes them to a database names the two side by side, "results": { "channels": ["total", "alarm"], "to": … }, one record per point with both values.
Each recipe's folder holds the program's plan.json (from the website's Download, or compiled: Using eLucid8 with AI coding agents shows how) and the elucid8 command, beside the files the recipe gives.
#The connector template
A source and a destination in one short Python program, standard library only. Change read_rows to read your rows, and write_records to write your records; the rest answers the protocol.
File template/connector_template.py:
#!/usr/bin/env python3
"""A connector for eLucid8: a program that serves a source's rows, takes an output's records, or both.
Bind it in deploy.json as a source, "process": ["python3", "connector_template.py"], or as an output's
"to": {"process": [...]}. elucid8 sends it one JSON message per line on standard input, and it answers
one per line on standard output (elucid8-lang.org/learn/connecting). Standard library only.
Credentials: name them in the binding's "env" and read them here with os.environ; never in files.
"""
import hashlib
import json
import sys
stored = {} # the records written so far, by key
def read_rows(request):
"""Read your rows here: one dict per point, the source's dimensions and "value" (None: no value).
request["source"] names the source, request["dimensions"] its dimensions, and request["box"] the
coordinates asked for. This example serves three fixed rows.
"""
return [{"sensor": 0, "t": 0, "value": 12.5}, {"sensor": 0, "t": 1, "value": 14.0}, {"sensor": 1, "t": 0, "value": 9.0}]
def write_records(output, records):
"""Write your records here. Each has "context" (its key) and "outcomes" (value name: outcome).
A batch may be sent again: write a record over the one with the same key. This example keeps
them in memory and writes them all to <output>.jsonl.
"""
for r in records:
stored[json.dumps(r["context"], sort_keys=True)] = r
with open(output + ".jsonl", "w") as f:
for key in sorted(stored):
f.write(json.dumps(stored[key]) + "\n")
def answer(message, rows=()):
sys.stdout.write(json.dumps(message) + "\n")
for row in rows:
sys.stdout.write(json.dumps(row) + "\n")
sys.stdout.flush()
for line in sys.stdin:
m = json.loads(line)
try:
if m["op"] == "read":
rows = read_rows(m)
# The version names the data: the same rows, the same version, so earlier answers are reused.
version = hashlib.sha256(json.dumps(rows, sort_keys=True).encode()).hexdigest()[:16]
if version == m.get("have"):
answer({"id": m["id"], "version": version, "unchanged": True})
else:
answer({"id": m["id"], "version": version, "rows": len(rows)}, rows)
elif m["op"] == "records":
write_records(m["output"], m["records"])
answer({"id": m["id"], "ok": True})
else: # "begin" and "end" need nothing here
answer({"id": m["id"], "ok": True})
except Exception as e: # elucid8 makes every point of the source an error naming the connector
answer({"id": m["id"], "error": {"code": "failed", "message": str(e)}})
Bound as both the source and an output's destination:
File template/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "process": ["python3", "connector_template.py"] } }
},
"outputs": {
"results": { "channels": ["total", "alarm"], "over": "sensor = 0..1, t = 0..1", "to": { "process": ["python3", "connector_template.py"] } }
}
}
# In the template folder:
./elucid8 run plan.json --config deploy.json --query "total[sensor = 0, t = 0..1]"
./elucid8 run plan.json --config deploy.json --output results
cat results.jsonl
{"name":"total","context":{"sensor":0,"t":0},"outcome":{"kind":"value","value":12.5,"ts":0}}
{"name":"total","context":{"sensor":0,"t":1},"outcome":{"kind":"value","value":26.5,"ts":0}}
{"context": {"sensor": 0, "t": 0}, "outcomes": {"total": {"kind": "value", "value": 12.5, "ts": 0}, "alarm": {"kind": "value", "value": false, "ts": 0}}}
{"context": {"sensor": 0, "t": 1}, "outcomes": {"total": {"kind": "value", "value": 26.5, "ts": 0}, "alarm": {"kind": "value", "value": false, "ts": 0}}}
{"context": {"sensor": 1, "t": 0}, "outcomes": {"total": {"kind": "value", "value": 9, "ts": 0}, "alarm": {"kind": "value", "value": false, "ts": 0}}}
{"context": {"sensor": 1, "t": 1}, "outcomes": {"total": {"kind": "error", "error": "missing", "message": "input reading has no data at this point", "origin": {"name": "reading", "context": {"sensor": 1, "t": 1}}, "via": {"length": 1, "path": [{"name": "reading", "context": {"sensor": 1, "t": 1}}]}, "ts": 0}, "alarm": {"kind": "error", "error": "missing", "message": "input reading has no data at this point", "origin": {"name": "reading", "context": {"sensor": 1, "t": 1}}, "via": {"length": 1, "path": [{"name": "reading", "context": {"sensor": 1, "t": 1}}]}, "ts": 0}}}
Sensor 1 has no reading at t = 1, where sensor 0 has one, so its total and alarm there are missing data: an error of kind missing naming the reading. Where a point with no row means nothing happened (sparse data), give the input "fill": {"missing": 0}; where each line ends at its own last row (an input whose lines are lists of different lengths), give it "ragged": true (Command reference).
#Recipe: SQLite as a source and as a destination
A source that reads a table (Python's sqlite3) and a destination that writes each record over the one with the same key (Node.js 24's node:sqlite; no package to install).
File sqlite/sqlite_source.py:
#!/usr/bin/env python3
"""A process source for eLucid8: serves a SQLite table's rows (elucid8-lang.org/learn/command-reference#programs-as-sources-and-sinks).
python3 sqlite_source.py DATABASE TABLE [--no-version]
The table has a column per dimension of the source (named after it), a `value` column (a number,
text, or NULL for missing data) and, optionally, an `outcome` column holding an outcome in the JSON
form of eLucid8's results (for an Error, or a number JSON cannot hold), which wins over `value`.
For each request `{"id", "op": "read", "source", "dimensions", "box", "have"}` it reads the rows
inside the box, names their version by a hash of what it read, and answers `{"id", "version",
"rows": n}` followed by n lines, one row each, as JSON-lines data files write them; or, when the
version is the one the runtime holds (`have`), `{"id", "version", "unchanged": true}`. With
--no-version it gives no version, so nothing computed from its rows is reused across queries.
Standard library only.
"""
import hashlib
import json
import math
import sqlite3
import sys
def number(x):
"""A number as a row's value: JSON for finite numbers, an outcome for the others and -0."""
if isinstance(x, float) and (math.isnan(x) or math.isinf(x) or (x == 0 and math.copysign(1, x) < 0)):
special = "NaN" if math.isnan(x) else ("-0" if x == 0 else ("Infinity" if x > 0 else "-Infinity"))
return None, {"kind": "value", "value": {"special": special}, "ts": 0}
return x, None
def read(db, table, request, versioned):
dims = request["dimensions"]
where, args = [], []
for axis in request.get("box", []):
if "range" in axis:
where.append('"%s" BETWEEN ? AND ?' % axis["name"])
args += axis["range"]
else:
where.append('"%s" IN (%s)' % (axis["name"], ",".join("?" * len(axis["labels"]))))
args += axis["labels"]
columns = [c[1] for c in db.execute('PRAGMA table_info("%s")' % table)]
has_outcome = "outcome" in columns
select = ", ".join(['"%s"' % d for d in dims] + ['"value"'] + (['"outcome"'] if has_outcome else []))
sql = 'SELECT %s FROM "%s"%s ORDER BY %s' % (select, table, (" WHERE " + " AND ".join(where)) if where else "", ", ".join('"%s"' % d for d in dims))
lines = []
for row in db.execute(sql, args):
point = {d: row[i] for i, d in enumerate(dims)}
outcome = row[len(dims) + 1] if has_outcome else None
if outcome is not None:
point["outcome"] = json.loads(outcome)
else:
value, special = number(row[len(dims)])
if special is not None:
point["outcome"] = special
else:
point["value"] = value
lines.append(json.dumps(point, separators=(",", ":")))
version = hashlib.sha256("\n".join(lines).encode()).hexdigest()[:16] if versioned else None
return version, lines
def main():
if len(sys.argv) < 3:
sys.exit(__doc__)
path, table = sys.argv[1], sys.argv[2]
versioned = "--no-version" not in sys.argv[3:]
for line in sys.stdin:
request = json.loads(line)
reply = {"id": request["id"]}
try:
# A new connection for each request, so that each read sees the database as it is now.
db = sqlite3.connect(path)
try:
version, rows = read(db, table, request, versioned)
finally:
db.close()
reply["version"] = version
if version is not None and version == request.get("have"):
reply["unchanged"] = True
rows = []
else:
reply["rows"] = len(rows)
except Exception as e: # the runtime makes every read of the source an Error naming it
reply = {"id": request["id"], "error": {"code": "read_failed", "message": str(e)}}
rows = []
sys.stdout.write(json.dumps(reply) + "\n")
for r in rows:
sys.stdout.write(r + "\n")
sys.stdout.flush()
if __name__ == "__main__":
main()
File sqlite/sqlite_sink.ts:
// A process sink for eLucid8: an output's records into a SQLite table, one row per record, upserted by
// key (elucid8-lang.org/learn/command-reference#programs-as-sources-and-sinks). Node.js 24 runs it directly (`node:sqlite`; no package):
//
// node --no-warnings sqlite_sink.ts DATABASE TABLE [--crash-once MARKER]
//
// `begin` creates the table if needed: a column per dimension (the key) and a column per value, holding
// the value's outcome in the JSON form of eLucid8's results. Each `records` message is written in one
// transaction: a record whose key the table holds overwrites it (INSERT … ON CONFLICT DO UPDATE), so a
// batch the runtime sends again leaves the table as one delivery would. Every delivery is also logged,
// in order, in `deliveries` (sequence number, output, key as JSON), so that tests can see what arrived.
//
// --crash-once MARKER (for tests): if the file MARKER does not exist, create it and stop after writing
// the second `records` message, without replying, as a sink that fails between committing and answering.
import { existsSync, writeFileSync } from "node:fs";
import { createInterface } from "node:readline";
import { DatabaseSync } from "node:sqlite";
const [path, table, ...rest] = process.argv.slice(2);
if (path === undefined || table === undefined) {
process.stderr.write("usage: node sqlite_sink.ts DATABASE TABLE [--crash-once MARKER]\n");
process.exit(2);
}
const crashMarker = rest[0] === "--crash-once" ? rest[1] : undefined;
const q = (name: string) => `"${name.replaceAll('"', '""')}"`;
// An integer coordinate is stored as an SQLite integer (a JavaScript number would be stored as a real).
const coordinate = (c: number | string) => (typeof c === "number" ? BigInt(c) : c);
const db = new DatabaseSync(path);
db.exec("CREATE TABLE IF NOT EXISTS deliveries (seq INTEGER PRIMARY KEY AUTOINCREMENT, output TEXT, key TEXT)");
let upsert: ReturnType<DatabaseSync["prepare"]> | undefined;
let dims: string[] = [];
let values: string[] = [];
let batches = 0;
const logged = db.prepare("INSERT INTO deliveries (output, key) VALUES (?, ?)");
interface Message {
id: number;
op: "begin" | "records" | "end";
output: string;
dimensions?: string[];
values?: string[];
records?: { context: Record<string, number | string>; outcomes: Record<string, unknown> }[];
}
function handle(m: Message): void {
if (m.op === "begin") {
dims = m.dimensions ?? [];
values = m.values ?? [];
const cols = [...dims.map(q), ...values.map((v) => `${q(v)} TEXT`)];
const key = dims.length > 0 ? `, PRIMARY KEY (${dims.map(q).join(", ")})` : "";
db.exec(`CREATE TABLE IF NOT EXISTS ${q(table as string)} (${cols.join(", ")}${key})`);
const all = [...dims, ...values];
const update = values.map((v) => `${q(v)} = excluded.${q(v)}`).join(", ");
const conflict = dims.length > 0 ? ` ON CONFLICT (${dims.map(q).join(", ")}) DO UPDATE SET ${update}` : "";
upsert = db.prepare(`INSERT INTO ${q(table as string)} (${all.map(q).join(", ")}) VALUES (${all.map(() => "?").join(", ")})${conflict}`);
} else if (m.op === "records") {
if (upsert === undefined) throw new Error("records before begin");
db.exec("BEGIN");
for (const r of m.records ?? []) {
upsert.run(...dims.map((d) => coordinate(r.context[d] as number | string)), ...values.map((v) => JSON.stringify(r.outcomes[v])));
logged.run(m.output, JSON.stringify(r.context));
}
db.exec("COMMIT");
batches += 1;
if (crashMarker !== undefined && batches === 2 && !existsSync(crashMarker)) {
writeFileSync(crashMarker, "crashed once\n");
process.exit(3); // committed, never answered: the runtime sends the batch again
}
}
process.stdout.write(`${JSON.stringify({ id: m.id, ok: true })}\n`);
}
createInterface({ input: process.stdin }).on("line", (line: string) => {
const m = JSON.parse(line) as Message;
try {
handle(m);
} catch (e) {
process.stdout.write(`${JSON.stringify({ id: m.id, error: { code: "write_failed", message: String(e) } })}\n`);
}
});
A database to read (yours already has its own), and a script that shows the results table:
File sqlite/make_db.py:
# make_db.py: a SQLite database of readings, for the recipe (yours already has its own).
import sqlite3
db = sqlite3.connect("shop.db")
db.execute("CREATE TABLE IF NOT EXISTS readings (sensor INTEGER, t INTEGER, value REAL)")
db.execute("DELETE FROM readings")
db.executemany("INSERT INTO readings VALUES (?, ?, ?)", [(0, 0, 12.5), (0, 1, 14.0), (0, 2, 31.0), (1, 0, 9.0), (1, 1, 11.5)])
db.commit()
File sqlite/show.py:
# show.py: the results table the destination wrote.
import sqlite3
for row in sqlite3.connect("results.db").execute("SELECT sensor, t, total, alarm FROM results ORDER BY sensor, t"):
print(*row)
File sqlite/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "process": ["python3", "sqlite_source.py", "shop.db", "readings"] }, "over": "sensor = 0..2, t = 0..9" }
},
"outputs": {
"results": { "channels": ["total", "alarm"], "over": "sensor = 0..1, t = 0..2", "to": { "process": ["node", "--no-warnings", "sqlite_sink.ts", "results.db", "results"] } }
}
}
# In the sqlite folder:
python3 make_db.py
./elucid8 run plan.json --config deploy.json --output results
python3 show.py
0 0 {"kind":"value","value":12.5,"ts":0} {"kind":"value","value":false,"ts":0}
0 1 {"kind":"value","value":26.5,"ts":0} {"kind":"value","value":false,"ts":0}
0 2 {"kind":"value","value":57.5,"ts":0} {"kind":"value","value":true,"ts":0}
1 0 {"kind":"value","value":9,"ts":0} {"kind":"value","value":false,"ts":0}
1 1 {"kind":"value","value":20.5,"ts":0} {"kind":"value","value":false,"ts":0}
1 2 {"kind":"error","error":"missing","message":"input reading has no data at this point","origin":{"name":"reading","context":{"sensor":1,"t":2}},"via":{"length":1,"path":[{"name":"reading","context":{"sensor":1,"t":2}}]},"ts":0} {"kind":"error","error":"missing","message":"input reading has no data at this point","origin":{"name":"reading","context":{"sensor":1,"t":2}},"via":{"length":1,"path":[{"name":"reading","context":{"sensor":1,"t":2}}]},"ts":0}
For your own data: the input's table has a column per dimension, named after it, and a value column; give its file and table on the command line. The destination creates its table, with a column per dimension (the key) and one per value.
#Recipe: PostgreSQL as a source and as a destination
The Python package's PostgreSQL connector, postgres, reads a table (or a query) and writes each record over the one with the same key. Install it with its client library, psycopg: pip install "elucid8[postgres]". The database is named by DATABASE_URL in the environment, never in a file; the bindings name it in env.
File postgres/setup.sql:
-- setup.sql: a readings table, for the recipe (yours already has its own).
SET client_min_messages = warning;
DROP TABLE IF EXISTS readings;
CREATE TABLE readings (sensor integer, t integer, value double precision, PRIMARY KEY (sensor, t));
INSERT INTO readings VALUES (0, 0, 12.5), (0, 1, 14), (0, 2, 31), (1, 0, 9), (1, 1, 11.5);
DROP TABLE IF EXISTS results;
File postgres/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "connector": "postgres", "settings": { "table": "readings" } }, "env": ["DATABASE_URL"] }
},
"outputs": {
"results": { "channels": ["total", "alarm"], "over": "sensor = 0..1, t = 0..2", "to": { "connector": "postgres", "settings": { "table": "results" }, "env": ["DATABASE_URL"] } }
}
}
# In the postgres folder, with DATABASE_URL set to your database:
psql "$DATABASE_URL" -q -f setup.sql
./elucid8 run plan.json --config deploy.json --query "total[sensor = 0, t = 0..2]"
./elucid8 run plan.json --config deploy.json --output results
psql "$DATABASE_URL" -At -c "SELECT sensor, t, total, total_kind, alarm FROM results ORDER BY sensor, t"
{"name":"total","context":{"sensor":0,"t":0},"outcome":{"kind":"value","value":12.5,"ts":0}}
{"name":"total","context":{"sensor":0,"t":1},"outcome":{"kind":"value","value":26.5,"ts":0}}
{"name":"total","context":{"sensor":0,"t":2},"outcome":{"kind":"value","value":57.5,"ts":0}}
0|0|12.5|value|f
0|1|26.5|value|f
0|2|57.5|value|t
1|0|9|value|f
1|1|20.5|value|f
1|2||error|
elucid8 runs the connector as python3 -m elucid8.connectors.postgres; if the package is installed in another Python (a virtual environment), set ELUCID8_PYTHON to that Python's path. Sensor 1 has no reading at t = 2, where sensor 0 has one, so its total there is missing data: total_kind is error (its kind, missing, in total_error) and total is NULL.
Settings:
table(alsoschema.table) orquery(aSELECT): the rows an input reads; a destination writestable. Only the rows inside the input entry'soverare read.url_env: the variable holding the connection string,postgresql://user:password@host:5432/db(defaultDATABASE_URL). Without it, PostgreSQL's own variables (PGHOST,PGUSER,PGPASSWORD,PGDATABASE, …) are used: name the ones you set inenv.value: the column holding the values, when it is notvalue.connect_timeout(seconds, default 10),statement_timeout_ms(none by default), andcreate(a destination: create the table if it does not exist; defaulttrue).
What it reads: a column per dimension of the input, named after it (text for a dimension with names); value (a number, a boolean or text; NULL is missing data, as an empty CSV cell is); optionally ts, each row's timestamp (whole milliseconds, or a timestamp column); and optionally outcome, an error written as eLucid8 writes one ({"kind": "error", "error": "data", "message": "sensor fault", "ts": 0}), which wins over value. The rows give exactly what the same rows in a JSON-lines file give. Their version is a hash of the rows read, so after a change, elucid8 computes again only what read the rows that changed.
What it writes: a record's key is its dimensions, so a record written again replaces the row with the same key. A table it creates has a column per dimension (the primary key) and, for each value v, v (its type from the first value written: double precision, boolean, text or jsonb), v_kind (value, eod or error), v_error (an error's kind, such as missing), v_origin (where it started, as a query writes a point), v_message (its cause in words), v_ts (the timestamp, bigint) and v_trail (its detail and chain, as jsonb), as Arrow and Parquet records are written. A table you create needs those columns and a unique key on the dimensions.
When it fails (the server does not answer, the password is wrong, the query is not valid), every point of the input is an error naming the connector, such as input reading: its connector failed: auth_failed: postgres: … password authentication failed for user "postgres"; a destination's batch is sent again, up to the binding's attempts, and then the output fails.
#Recipe: DuckDB as a source and as a destination
The Python package's duckdb connector (pip install "elucid8[duckdb]") reads any SQL DuckDB answers, a table, a query or read_parquet('…') over many files, and writes records into a table by their key.
File duckdb/setup.py:
# setup.py: a DuckDB database with a readings table, for the recipe (yours already has its own).
import duckdb
db = duckdb.connect("shop.duckdb")
db.execute("CREATE OR REPLACE TABLE readings (sensor INTEGER, t INTEGER, value DOUBLE)")
db.execute("INSERT INTO readings VALUES (0, 0, 12.5), (0, 1, 14), (0, 2, 31), (1, 0, 9), (1, 1, 11.5)")
db.execute("DROP TABLE IF EXISTS results")
db.close()
File duckdb/show.py:
# show.py: the results table the destination wrote.
import duckdb
for row in duckdb.connect("shop.duckdb", read_only=True).execute("SELECT sensor, t, total, total_kind, alarm FROM results ORDER BY sensor, t").fetchall():
print(*row)
File duckdb/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "connector": "duckdb", "settings": { "database": "shop.duckdb", "query": "SELECT sensor, t, value FROM readings" } } }
},
"outputs": {
"results": { "channels": ["total", "alarm"], "over": "sensor = 0..1, t = 0..2", "to": { "connector": "duckdb", "settings": { "database": "shop.duckdb", "table": "results" } } }
}
}
# In the duckdb folder:
python3 setup.py
./elucid8 run plan.json --config deploy.json --query "total[sensor = 0, t = 0..2]"
./elucid8 run plan.json --config deploy.json --output results
python3 show.py
{"name":"total","context":{"sensor":0,"t":0},"outcome":{"kind":"value","value":12.5,"ts":0}}
{"name":"total","context":{"sensor":0,"t":1},"outcome":{"kind":"value","value":26.5,"ts":0}}
{"name":"total","context":{"sensor":0,"t":2},"outcome":{"kind":"value","value":57.5,"ts":0}}
0 0 12.5 value False
0 1 26.5 value False
0 2 57.5 value True
1 0 9.0 value False
1 1 20.5 value False
1 2 None error None
Settings: database (the file, relative to the configuration's folder) or database_env; table or query; value; create. A source opens the file read-only for each read; a destination holds it until the output ends. DuckDB does not keep −0 apart from 0, so a destination refuses a batch holding −0, and a source may read either for the other; NaN and the infinities are kept.
#Recipe: MySQL and SQL Server as sources and destinations
The Python package's mysql connector (pip install "elucid8[mysql]", with PyMySQL; MariaDB too) and sqlserver connector (pip install "elucid8[sqlserver]", with pymssql; Azure SQL too) read a table or a query and write records by their key, as the PostgreSQL connector does. The connection string comes from MYSQL_URL (mysql://user:password@host:3306/database) or SQLSERVER_URL (mssql://user:password@host:1433/database), with special characters percent-escaped.
File mysql/setup.py:
# setup.py: a readings table, for the recipe (yours already has its own).
import os
from urllib.parse import unquote, urlsplit
import pymysql
u = urlsplit(os.environ["MYSQL_URL"])
db = pymysql.connect(host=u.hostname, port=u.port, user=unquote(u.username), password=unquote(u.password), database=u.path[1:])
with db.cursor() as c:
c.execute("DROP TABLE IF EXISTS readings")
c.execute("DROP TABLE IF EXISTS results")
c.execute("CREATE TABLE readings (sensor INT, t INT, value DOUBLE, PRIMARY KEY (sensor, t))")
c.execute("INSERT INTO readings VALUES (0, 0, 12.5), (0, 1, 14), (0, 2, 31), (1, 0, 9), (1, 1, 11.5)")
db.commit()
File mysql/show.py:
# show.py: the results table the destination wrote.
import os
from urllib.parse import unquote, urlsplit
import pymysql
u = urlsplit(os.environ["MYSQL_URL"])
db = pymysql.connect(host=u.hostname, port=u.port, user=unquote(u.username), password=unquote(u.password), database=u.path[1:])
with db.cursor() as c:
c.execute("SELECT sensor, t, total, total_kind, alarm FROM results ORDER BY sensor, t")
for row in c.fetchall():
print(*row)
File mysql/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "connector": "mysql", "settings": { "table": "readings" } }, "env": ["MYSQL_URL"] }
},
"outputs": {
"results": { "channels": ["total", "alarm"], "over": "sensor = 0..1, t = 0..2", "to": { "connector": "mysql", "settings": { "table": "results" }, "env": ["MYSQL_URL"] } }
}
}
# In the mysql folder, with MYSQL_URL set to your database:
python3 setup.py
./elucid8 run plan.json --config deploy.json --output results
python3 show.py
0 0 12.5 value 0
0 1 26.5 value 0
0 2 57.5 value 1
1 0 9.0 value 0
1 1 20.5 value 0
1 2 None error None
MySQL's BOOLEAN is a small integer, so alarm shows as 0 and 1 (and an input reads such a column as numbers). The same with SQL Server:
File sqlserver/setup.py:
# setup.py: a readings table, for the recipe (yours already has its own).
import os
from urllib.parse import unquote, urlsplit
import pymssql
u = urlsplit(os.environ["SQLSERVER_URL"])
db = pymssql.connect(server=u.hostname, port=str(u.port), user=unquote(u.username), password=unquote(u.password), database=u.path[1:])
c = db.cursor()
c.execute("DROP TABLE IF EXISTS readings; DROP TABLE IF EXISTS results")
c.execute("CREATE TABLE readings (sensor INT, t INT, value FLOAT, PRIMARY KEY (sensor, t))")
c.execute("INSERT INTO readings VALUES (0, 0, 12.5), (0, 1, 14), (0, 2, 31), (1, 0, 9), (1, 1, 11.5)")
db.commit()
File sqlserver/show.py:
# show.py: the results table the destination wrote.
import os
from urllib.parse import unquote, urlsplit
import pymssql
u = urlsplit(os.environ["SQLSERVER_URL"])
db = pymssql.connect(server=u.hostname, port=str(u.port), user=unquote(u.username), password=unquote(u.password), database=u.path[1:])
c = db.cursor()
c.execute("SELECT sensor, t, total, total_kind, alarm FROM results ORDER BY sensor, t")
for row in c.fetchall():
print(*row)
File sqlserver/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "connector": "sqlserver", "settings": { "table": "readings" } }, "env": ["SQLSERVER_URL"] }
},
"outputs": {
"results": { "channels": ["total", "alarm"], "over": "sensor = 0..1, t = 0..2", "to": { "connector": "sqlserver", "settings": { "table": "results" }, "env": ["SQLSERVER_URL"] } }
}
}
# In the sqlserver folder, with SQLSERVER_URL set to your database:
python3 setup.py
./elucid8 run plan.json --config deploy.json --output results
python3 show.py
0 0 12.5 value False
0 1 26.5 value False
0 2 57.5 value True
1 0 9.0 value False
1 1 20.5 value False
1 2 None error None
Settings, for both: url_env (default MYSQL_URL or SQLSERVER_URL), table (or database.table, schema.table) or query, value, create, connect_timeout (seconds, default 10), and read_timeout (MySQL) or timeout (SQL Server). Records are written with ON DUPLICATE KEY UPDATE (MySQL) or MERGE (SQL Server). What they cannot hold: their floating-point types have no NaN, no infinities and no −0, and SQL Server's none of the smallest numbers (below 2.2e-308, which it gives back as 0): a destination refuses a batch holding one, saying so; write such outputs to PostgreSQL or a file.
#Recipe: Amazon S3 and compatible stores, as a source and as a destination
The Python package's s3 connector reads an object (CSV, JSON lines or Parquet) as the elucid8 command reads the same file, and writes an output's records as a Parquet object. It uses pyarrow's file systems, which the package already needs (pip install elucid8), and works with Amazon S3 and stores that speak its protocol (MinIO, Cloudflare R2, SeaweedFS, …), and with Google Cloud Storage (gs://). The credentials are the standard variables, named in env; the store's address, for a store other than Amazon's, is given by S3_ENDPOINT here (endpoint_env).
File s3/readings.csv:
sensor,t,value
0,0,12.5
0,1,14
0,2,31
1,0,9
1,1,11.5
File s3/upload.py:
# upload.py: the readings into a bucket, for the recipe (yours already has its own objects).
import os
import pyarrow.fs as fs
store = fs.S3FileSystem(endpoint_override=os.environ.get("S3_ENDPOINT"), allow_bucket_creation=True)
store.create_dir("elucid8-recipe")
with open("readings.csv", "rb") as f, store.open_output_stream("elucid8-recipe/readings.csv") as out:
out.write(f.read())
File s3/show.py:
# show.py: the results object the destination wrote.
import os
import pyarrow.fs as fs
import pyarrow.parquet as pq
store = fs.S3FileSystem(endpoint_override=os.environ.get("S3_ENDPOINT"))
results = pq.read_table("elucid8-recipe/results.parquet", filesystem=store)
for r in results.select(["sensor", "t", "total_value", "total_kind", "alarm_value"]).to_pylist():
print(*r.values())
File s3/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "connector": "s3", "settings": { "url": "s3://elucid8-recipe/readings.csv", "endpoint_env": "S3_ENDPOINT" } }, "env": ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "S3_ENDPOINT"] }
},
"outputs": {
"results": { "channels": ["total", "alarm"], "over": "sensor = 0..1, t = 0..2", "to": { "connector": "s3", "settings": { "url": "s3://elucid8-recipe/results.parquet", "endpoint_env": "S3_ENDPOINT" }, "env": ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "S3_ENDPOINT"] } }
}
}
# In the s3 folder, with AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and (for a store other than Amazon's) S3_ENDPOINT set:
python3 upload.py
./elucid8 run plan.json --config deploy.json --query "total[sensor = 0, t = 0..2]"
./elucid8 run plan.json --config deploy.json --output results
python3 show.py
{"name":"total","context":{"sensor":0,"t":0},"outcome":{"kind":"value","value":12.5,"ts":0}}
{"name":"total","context":{"sensor":0,"t":1},"outcome":{"kind":"value","value":26.5,"ts":0}}
{"name":"total","context":{"sensor":0,"t":2},"outcome":{"kind":"value","value":57.5,"ts":0}}
0 0 12.5 value False
0 1 26.5 value False
0 2 57.5 value True
1 0 9.0 value False
1 1 20.5 value False
1 2 None error None
Settings:
url:s3://bucket/key, orgs://bucket/keyfor Google Cloud Storage (credentials fromGOOGLE_APPLICATION_CREDENTIALS). As an input, a key ending in/reads every object under it in the format, in the order of their names, as one table (one object a day, for example).format:parquet,csvorjsonl, when the key's ending (.parquet,.csv,.jsonl,.ndjson) does not say. A destination writes Parquet.endpoint(http://localhost:9000,https://<account>.r2.cloudflarestorage.com) orendpoint_env, for a store other than Amazon's;region(defaultus-east-1);anonymous: truefor a public bucket.valueandtime: the columns holding the values and the timestamps, when they are notvalueandts;labels: the dimensions whose coordinates are names, in a CSV object.spool: where a destination keeps its batches until the output ends (default: the system's temporary folder).
What it reads: an object gives exactly what the same file on disk gives: a CSV object cell by cell as CSV data files are read, a JSON-lines object as it is, a Parquet object column by column (a null value is missing data, as an empty CSV cell is; timestamps in any unit become milliseconds). The version is a hash of the rows read.
What it writes: one Parquet object when the output ends, with a column per dimension and, per channel v, v_value, v_kind, v_error, v_origin, v_message, v_ts and v_trail, as the command writes records. A batch sent again, or a connector started again after a fault, writes each record once.
#Recipe: Kafka as a source, a live stream and a destination
The Python package's kafka connector (pip install "elucid8[kafka]", which installs confluent-kafka) reads a topic from its beginning to its end as an input, writes an output's records as messages, and, as python3 -m elucid8.connectors.kafka stream, sends a topic's new messages to a running elucid8 serve as new rows. The cluster's address comes from KAFKA_BOOTSTRAP here (bootstrap_env). A message is a row as a JSON-lines data file holds one, or a JSON list of them.
File kafka/produce.py:
# produce.py: two topics, and five readings as messages, for the recipe (yours already has its own).
import json
import os
from confluent_kafka import Producer
from confluent_kafka.admin import AdminClient, NewTopic
servers = os.environ["KAFKA_BOOTSTRAP"]
admin = AdminClient({"bootstrap.servers": servers})
for f in admin.create_topics([NewTopic("readings", 1, 1), NewTopic("alarms", 1, 1)]).values():
f.result()
p = Producer({"bootstrap.servers": servers})
for sensor, t, value in [(0, 0, 12.5), (0, 1, 14), (0, 2, 31), (1, 0, 9), (1, 1, 11.5)]:
p.produce("readings", json.dumps({"sensor": sensor, "t": t, "value": value}))
p.flush()
File kafka/alarms.py:
# alarms.py: the alarm records the destination wrote, one message a record.
import json
import os
from confluent_kafka import Consumer
c = Consumer({"bootstrap.servers": os.environ["KAFKA_BOOTSTRAP"], "group.id": "recipe", "auto.offset.reset": "earliest"})
c.subscribe(["alarms"])
records = {}
while len(records) < 6:
m = c.poll(10)
if m is not None and m.error() is None:
r = json.loads(m.value())
records[m.key()] = r
c.close()
for r in sorted(records.values(), key=lambda r: (r["context"]["sensor"], r["context"]["t"])):
print(r["context"]["sensor"], r["context"]["t"], r["outcomes"]["alarm"])
File kafka/ask.py:
# ask.py: sensor 0's totals, from the service the stream fed; then stops it.
import json
import urllib.request
def post(path, body):
token = open("token").read().strip()
request = urllib.request.Request("http://127.0.0.1:8091" + path, json.dumps(body).encode(), {"Authorization": "Bearer " + token, "Content-Type": "application/json"})
return json.load(urllib.request.urlopen(request))
for p in post("/query", {"id": 1, "query": "total[sensor = 0, t = 0..2]"})["results"]:
print("total at t =", p["context"]["t"], "is", p["outcome"]["value"])
post("/shutdown", {"id": 2})
File kafka/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "connector": "kafka", "settings": { "bootstrap_env": "KAFKA_BOOTSTRAP", "topic": "readings" } }, "env": ["KAFKA_BOOTSTRAP"] }
},
"outputs": {
"alarms": { "channels": ["alarm"], "over": "sensor = 0..1, t = 0..2", "to": { "connector": "kafka", "settings": { "bootstrap_env": "KAFKA_BOOTSTRAP", "topic": "alarms" }, "env": ["KAFKA_BOOTSTRAP"] } }
}
}
File kafka/live.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": "start.jsonl" }
}
}
File kafka/start.jsonl:
# In the kafka folder, with KAFKA_BOOTSTRAP set to your cluster (host:port):
python3 produce.py
./elucid8 run plan.json --config deploy.json --output alarms && python3 alarms.py
printf 'a-token-of-your-own' > token
./elucid8 serve plan.json --config live.json --http 127.0.0.1:8091 --token-file token 2>/dev/null &
python3 -m elucid8.connectors.kafka stream '{"bootstrap_env": "KAFKA_BOOTSTRAP", "topic": "readings"}' --url http://127.0.0.1:8091 --source reading --token-file token --stop-after 5 2>/dev/null
python3 ask.py
wait
0 0 {'kind': 'value', 'value': False, 'ts': 0}
0 1 {'kind': 'value', 'value': False, 'ts': 0}
0 2 {'kind': 'value', 'value': True, 'ts': 0}
1 0 {'kind': 'value', 'value': False, 'ts': 0}
1 1 {'kind': 'value', 'value': False, 'ts': 0}
1 2 {'kind': 'error', 'error': 'missing', 'message': 'input reading has no data at this point', 'origin': {'name': 'reading', 'context': {'sensor': 1, 't': 2}}, 'via': {'length': 1, 'path': [{'name': 'reading', 'context': {'sensor': 1, 't': 2}}]}, 'ts': 0}
total at t = 0 is 12.5
total at t = 1 is 26.5
total at t = 2 is 57.5
The service starts with no readings (start.jsonl is empty); the stream sends the topic's five readings to it as new rows, and the query is answered from them. --stop-after 5 ends the stream here; without it, the stream keeps sending each new message's rows, --batch at a time (default 1,000) or --interval-ms after the first (default 1,000).
Settings:
bootstrap(host:port, several separated by commas) orbootstrap_env;topic.sasl_username_envandsasl_password_env(the variables holding a SASL user and password),security_protocol(SASL_SSLby default with SASL;SSL,SASL_PLAINTEXT) andsasl_mechanism(defaultPLAIN);config, other client settings by librdkafka's names, never credentials;timeout_s(default 10).- For
stream:group(defaultelucid8-<topic>) andfrom(beginning, the default, orend).
What it reads: as an input, every message of every partition, from the beginning to the end now; the version is a hash of the rows, so a topic with no new message gives the same version. As a stream, each message's rows are sent once: a point already sent (a message delivered twice) is left out. What it writes: one message a record, keyed by the record's coordinates, valued {"output", "context", "outcomes"}; a batch sent again is sent again, so a compacted topic, or a reader keeping each key's last message, holds each record once.
#Recipe: MQTT as a live stream, a source and a destination
The Python package's mqtt connector (pip install "elucid8[mqtt]", which installs paho-mqtt) sends a topic's messages to a running elucid8 serve as new rows (python3 -m elucid8.connectors.mqtt stream), reads the retained messages under a topic as a source (MQTT keeps no other history), and publishes an output's records. The broker's address comes from MQTT_HOST here (host or host:port), its user and password from MQTT_USERNAME and MQTT_PASSWORD.
File mqtt/publish.py:
# publish.py: five readings, each retained on a topic of its own, for the recipe (your devices publish their own).
import json
import os
import paho.mqtt.client as mqtt
c = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
c.username_pw_set(os.environ["MQTT_USERNAME"], os.environ["MQTT_PASSWORD"])
host, _, port = os.environ["MQTT_HOST"].partition(":")
c.connect(host, int(port or 1883))
c.loop_start()
for sensor, t, value in [(0, 0, 12.5), (0, 1, 14), (0, 2, 31), (1, 0, 9), (1, 1, 11.5)]:
row = {"sensor": sensor, "t": t, "value": value}
c.publish(f"plant/readings/{sensor}/{t}", json.dumps(row), qos=1, retain=True).wait_for_publish()
c.loop_stop()
c.disconnect()
File mqtt/alarms.py:
# alarms.py: the alarm records the destination retained, one topic a record.
import json
import os
import time
import paho.mqtt.client as mqtt
records = {}
c = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
c.username_pw_set(os.environ["MQTT_USERNAME"], os.environ["MQTT_PASSWORD"])
c.on_message = lambda client, userdata, m: records.__setitem__(m.topic, json.loads(m.payload))
host, _, port = os.environ["MQTT_HOST"].partition(":")
c.connect(host, int(port or 1883))
c.subscribe("plant/alarms/#", qos=1)
c.loop_start()
while len(records) < 6:
time.sleep(0.1)
c.loop_stop()
for r in sorted(records.values(), key=lambda r: (r["context"]["sensor"], r["context"]["t"])):
print(r["context"]["sensor"], r["context"]["t"], r["outcomes"]["alarm"])
File mqtt/ask.py:
# ask.py: sensor 0's totals, from the service the stream fed; then stops it.
import json
import urllib.request
def post(path, body):
token = open("token").read().strip()
request = urllib.request.Request("http://127.0.0.1:8092" + path, json.dumps(body).encode(), {"Authorization": "Bearer " + token, "Content-Type": "application/json"})
return json.load(urllib.request.urlopen(request))
for p in post("/query", {"id": 1, "query": "total[sensor = 0, t = 0..2]"})["results"]:
print("total at t =", p["context"]["t"], "is", p["outcome"]["value"])
post("/shutdown", {"id": 2})
File mqtt/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "connector": "mqtt", "settings": { "host_env": "MQTT_HOST", "topic": "plant/readings/#", "username_env": "MQTT_USERNAME", "password_env": "MQTT_PASSWORD" } }, "env": ["MQTT_HOST", "MQTT_USERNAME", "MQTT_PASSWORD"] }
},
"outputs": {
"alarms": { "channels": ["alarm"], "over": "sensor = 0..1, t = 0..2", "to": { "connector": "mqtt", "settings": { "host_env": "MQTT_HOST", "topic": "plant/alarms", "retain": true, "username_env": "MQTT_USERNAME", "password_env": "MQTT_PASSWORD" }, "env": ["MQTT_HOST", "MQTT_USERNAME", "MQTT_PASSWORD"] } }
}
}
File mqtt/live.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": "start.jsonl" }
}
}
File mqtt/start.jsonl:
# In the mqtt folder, with MQTT_HOST, MQTT_USERNAME and MQTT_PASSWORD set:
python3 publish.py
./elucid8 run plan.json --config deploy.json --output alarms && python3 alarms.py
printf 'a-token-of-your-own' > token
./elucid8 serve plan.json --config live.json --http 127.0.0.1:8092 --token-file token 2>/dev/null &
python3 -m elucid8.connectors.mqtt stream '{"host_env": "MQTT_HOST", "topic": "plant/readings/#", "username_env": "MQTT_USERNAME", "password_env": "MQTT_PASSWORD"}' --url http://127.0.0.1:8092 --source reading --token-file token --stop-after 5 2>/dev/null
python3 ask.py
wait
0 0 {'kind': 'value', 'value': False, 'ts': 0}
0 1 {'kind': 'value', 'value': False, 'ts': 0}
0 2 {'kind': 'value', 'value': True, 'ts': 0}
1 0 {'kind': 'value', 'value': False, 'ts': 0}
1 1 {'kind': 'value', 'value': False, 'ts': 0}
1 2 {'kind': 'error', 'error': 'missing', 'message': 'input reading has no data at this point', 'origin': {'name': 'reading', 'context': {'sensor': 1, 't': 2}}, 'via': {'length': 1, 'path': [{'name': 'reading', 'context': {'sensor': 1, 't': 2}}]}, 'ts': 0}
total at t = 0 is 12.5
total at t = 1 is 26.5
total at t = 2 is 57.5
With retain, each record is the retained message of a topic of its own, plant/alarms/<sensor>/<t>, so a reader that subscribes later gets the latest record of every key; without it, every record is published to plant/alarms. The stream received the five retained readings when it subscribed; it then sends each new message's rows as they arrive (--stop-after ends it here).
Settings: host or host_env (host, or host:port), port (default 1883; 8883 with tls), topic (wildcards + and # for subscriptions), tls (true, or {"ca": "ca.pem"}), username_env and password_env, qos (default 1), timeout_s (default 10); as a source, settle_ms (how long without a new retained message ends a read, default 500); as a destination, retain.
#Snowflake, BigQuery and Databricks as sources
The Python package's snowflake and bigquery connectors (pip install "elucid8[snowflake]", "elucid8[bigquery]", with their ADBC drivers) and databricks connector ("elucid8[databricks]", with the Databricks SQL Connector) run a query in the warehouse and read its answer as the elucid8 command reads a Parquet file. They are sources only for now. They have not been run against the warehouses themselves: their tests run the same queries on a stand-in database, and check the settings each passes to its driver.
File warehouses/snowflake.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "connector": "snowflake", "settings": { "account": "myorg-myaccount", "warehouse": "COMPUTE_WH", "database": "SHOP", "schema": "PUBLIC", "user_env": "SNOWFLAKE_USER", "password_env": "SNOWFLAKE_PASSWORD", "query": "SELECT sensor AS \"sensor\", t AS \"t\", value AS \"value\" FROM readings" } }, "env": ["SNOWFLAKE_USER", "SNOWFLAKE_PASSWORD"] }
}
}
File warehouses/bigquery.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "connector": "bigquery", "settings": { "project": "my-project", "query": "SELECT sensor, t, value FROM shop.readings" } }, "env": ["GOOGLE_APPLICATION_CREDENTIALS"] }
}
}
File warehouses/databricks.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "connector": "databricks", "settings": { "host": "adb-1234567890123456.7.azuredatabricks.net", "http_path": "/sql/1.0/warehouses/abcdef0123456789", "token_env": "DATABRICKS_TOKEN", "query": "SELECT sensor, t, value FROM shop.readings" } }, "env": ["DATABRICKS_TOKEN"] }
}
}
Settings: each takes query (or table) and value. Snowflake: account, warehouse, database, schema, role, with user_env and password_env or private_key_env (key-pair authentication), or uri_env (the whole connection URI); Snowflake folds unquoted names to upper case, so name the columns as the input's dimensions in quotes. BigQuery: project (or project_env), dataset, location, and the key file named by GOOGLE_APPLICATION_CREDENTIALS (or the key itself in credentials_env). Databricks: host (or host_env), http_path, token_env (default DATABRICKS_TOKEN), catalog, schema. The rows are filtered to the binding's over after the query has run, so put the conditions that matter for size in the query.
#Recipe: a REST API as a source
The Python package's http connector (standard library only) reads rows from a URL: a JSON list of rows (or a list at a path in a JSON answer), JSON lines, or CSV, as the elucid8 command reads the same data from a file. The address comes from READINGS_URL here (url_env); an API token would come from the environment the same way, as a header ("header_env": {"Authorization": "API_TOKEN"}, the variable holding Bearer …).
File rest/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": { "connector": "http", "settings": { "url_env": "READINGS_URL" } }, "env": ["READINGS_URL"] }
}
}
With an endpoint that answers [{"sensor": 0, "t": 0, "value": 12.5}, {"sensor": 0, "t": 1, "value": 14}, {"sensor": 0, "t": 2, "value": 31}]:
# In the rest folder, with READINGS_URL set to your endpoint:
./elucid8 run plan.json --config deploy.json --query "alarm[sensor = 0, t = 0..2]"
{"name":"alarm","context":{"sensor":0,"t":0},"outcome":{"kind":"value","value":false,"ts":0}}
{"name":"alarm","context":{"sensor":0,"t":1},"outcome":{"kind":"value","value":false,"ts":0}}
{"name":"alarm","context":{"sensor":0,"t":2},"outcome":{"kind":"value","value":true,"ts":0}}
Settings: url or url_env; header_env (headers from environment variables) and headers (others, never credentials); format (json, jsonl or csv; by default from the answer's Content-Type) and path ("data.items"); for CSV, value, time and labels; method and timeout_s (default 30). The version is a hash of the rows, so the same answer gives the same version. An answer of 401 or 403 is auth_failed, 404 not_found, another error read_failed, no answer in time timeout. For an API in another shape (items to turn into rows, pages to follow), the connector template is the place to start.
#Recipe: results to a webhook
The same connector as a destination sends each batch of records to a URL as one HTTP POST of JSON. If the endpoint fails, elucid8 sends the batch again (up to the binding's attempts).
File webhook/readings.csv:
sensor,t,value
0,0,12.5
0,1,14
1,0,9
File webhook/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": "readings.csv" }
},
"outputs": {
"alarms": { "channels": ["alarm"], "over": "sensor = 0..1, t = 0..1", "to": { "connector": "http", "settings": { "url_env": "WEBHOOK_URL" }, "env": ["WEBHOOK_URL"], "batch": 2} }
}
}
# In the webhook folder, with WEBHOOK_URL set to your endpoint:
./elucid8 run plan.json --config deploy.json --output alarms && echo sent
sent
The endpoint receives one POST per batch of two records:
{"output": "alarms", "records": [{"context": {"sensor": 0, "t": 0}, "outcomes": {"alarm": {"kind": "value", "value": false, "ts": 0}}}, {"context": {"sensor": 0, "t": 1}, "outcomes": {"alarm": {"kind": "value", "value": false, "ts": 0}}}]}
{"output": "alarms", "records": [{"context": {"sensor": 1, "t": 0}, "outcomes": {"alarm": {"kind": "value", "value": false, "ts": 0}}}, {"context": {"sensor": 1, "t": 1}, "outcomes": {"alarm": {"kind": "error", "error": "missing", "message": "input reading has no data at this point", "origin": {"name": "reading", "context": {"sensor": 1, "t": 1}}, "via": {"length": 1, "path": [{"name": "reading", "context": {"sensor": 1, "t": 1}}]}, "ts": 0}}}]}
#Recipe: a live stream, and live destinations
elucid8 serve keeps the program loaded. Rows are sent with advance as they arrive (from a queue, a socket, a sensor; to try a program on data you already have, a replay of a file gives the same rows a coordinate a tick with no program sending them, Inputs given rows over time); a standing query is answered again after each, and an output subscription sends only the records that changed, here into SQLite with the destination of the SQLite recipe.
Streams often name their sensors (north-07) rather than number them: a map under names lets the rows keep the names, and new names can be numbered as they arrive (Names instead of numbers).
File live/readings.csv:
sensor,t,value
0,0,12.5
1,0,9
2,0,20
File live/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": "readings.csv" }
},
"outputs": {
"alarms": { "channels": ["alarm"], "over": "sensor = 0..2, t = 0..9", "to": { "process": ["node", "--no-warnings", "sqlite_sink.ts", "alarms.db", "alarms"] } }
}
}
File live/live.py:
# live.py: readings arrive one tick at a time; elucid8 serve answers a standing query after each,
# and sends the alarm records that changed into alarms.db.
import json
import subprocess
serve = subprocess.Popen(["./elucid8", "serve", "plan.json", "--config", "deploy.json"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
def send(request):
serve.stdin.write(json.dumps(request) + "\n")
serve.stdin.flush()
def reply():
return json.loads(serve.stdout.readline())
def show(r):
if "results" in r: # the standing query's answer: sensor 0's newest total
for p in r["results"]:
print("total at t =", p["context"]["t"], "is", p["outcome"].get("value"))
elif r.get("output") == "alarms":
print("alarm records sent:", r["sent"], "unchanged:", r["unchanged"])
send({"id": "totals", "op": "subscribe", "query": "total[sensor = 0, t = last]"})
show(reply())
send({"id": "alarms", "op": "subscribe", "output": "alarms"})
show(reply())
for t, (a, b, c) in enumerate([(14, 11.5, 22), (31, 12, 21)], start=1):
send({"id": "tick%d" % t, "op": "advance", "input": "reading", "rows": "0,%d,%s\n1,%d,%s\n2,%d,%s\n" % (t, a, t, b, t, c)})
reply() # the advance itself
show(reply()) # the standing query, answered again
show(reply()) # the alarm records that changed
send({"id": "bye", "op": "shutdown"})
serve.wait()
# In the live folder:
cp ../sqlite/sqlite_sink.ts .
python3 live.py 2>/dev/null
total at t = 0 is 12.5
alarm records sent: 30 unchanged: 0
total at t = 1 is 26.5
alarm records sent: 3 unchanged: 27
total at t = 2 is 57.5
alarm records sent: 3 unchanged: 27
Each tick, the three new alarm records are sent; the other 27 are unchanged and not sent again. (The service writes its log to standard error, left out here.) For your own stream: replace the loop with your consumer (Kafka, MQTT, a socket), sending each batch of rows with advance; add "keepFrom" to keep only recent rows (The long-running service).
#Recipe: results into DuckDB and pandas
Arrow and the other output formats are read directly, with no connector. This writes the totals as an Apache Arrow file, then reads it with DuckDB and with pandas (pip install duckdb pandas pyarrow).
File analytics/readings.csv:
sensor,t,value
0,0,12.5
0,1,14
0,2,31
1,0,9
1,1,11.5
File analytics/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": "readings.csv" }
}
}
File analytics/to_duckdb.py:
# to_duckdb.py: the totals, in DuckDB and in pandas.
import duckdb
import pyarrow.ipc
totals = pyarrow.ipc.open_stream("totals.arrows").read_all()
print(duckdb.sql("SELECT sensor, max(total_value) AS latest FROM totals WHERE total_kind = 'value' GROUP BY sensor ORDER BY sensor").fetchall())
frame = totals.to_pandas()
print(frame[frame.total_kind == "value"].groupby("sensor")["total_value"].max().to_dict())
# In the analytics folder:
./elucid8 run plan.json --config deploy.json --query "total[sensor = 0..1, t = 0..2]" --format arrow --out totals.arrows
python3 to_duckdb.py
[(0, 57.5), (1, 20.5)]
{0: 57.5, 1: 20.5}
The columns are named after the value asked for: total_value, and total_kind, which says what each cell is (value, eod or error): sensor 1 has no reading at t = 2, where sensor 0 has one, so its total there is missing data (total_kind is error, total_error is missing) and is left out. More: Using eLucid8 from your code.
#Recipe: Parquet in and out, with pandas and Polars
Parquet and Arrow files are read as inputs as CSV files are, with no connector: the table is the one the CSV of the same rows gives, and a null value (pandas' None or NaN, a Polars null, a database's NULL) is missing data, as an empty CSV cell is. Here pandas writes the readings as a Parquet file, elucid8 reads it and writes the totals as a Parquet file, and Polars reads them (pip install pandas pyarrow polars).
File parquet/make_data.py:
# make_data.py: the readings as a Parquet file, written by pandas (yours may come from anywhere).
import pandas as pd
readings = pd.DataFrame({"sensor": [0, 0, 0, 1, 1], "t": [0, 1, 2, 0, 1], "value": [12.5, 14, 31, 9, 11.5]})
readings.to_parquet("readings.parquet")
File parquet/deploy.json:
{
"format": "elucid8-deploy/2",
"inputs": {
"reading": { "from": "readings.parquet" }
}
}
File parquet/show.py:
# show.py: the totals, in Polars.
import polars as pl
totals = pl.read_parquet("totals.parquet")
print(totals.filter(pl.col("total_kind") == "value").group_by("sensor").agg(pl.col("total_value").max().alias("latest")).sort("sensor").rows())
# In the parquet folder:
python3 make_data.py
./elucid8 run plan.json --config deploy.json --query "total[sensor = 0..1, t = 0..2]" --out totals.parquet
python3 show.py
[(0, 57.5), (1, 20.5)]
The input's columns are the program's names: a column for each of the input's dimensions and one named value or reading_value (or the input entry's "value"), with each row's timestamp in a column named ts or reading_ts when there is one; other columns are ignored. The totals' columns are named after the value asked for: total_value, total_kind, total_error, total_origin, total_message, total_ts and total_trail. A name ending in .parquet chooses the output's format, as --format parquet does (Data files, Apache Parquet).
#Where next
- Command reference: inputs, outputs and every option of
deploy.json; Programs as sources and sinks. - The long-running service:
advance, subscriptions and outputs inelucid8 serve. - Using eLucid8 from your code: results in Python, NumPy, pandas, Polars, DuckDB, JavaScript and the shell.