Invariants
These are the properties the system preserves. They are enforced in code, not conventions — a change that breaks one of them is a bug, not a trade-off.
1. The LLM runs exactly once
Section titled “1. The LLM runs exactly once”Only on author, create, or edit — never on view, and never on a poller tick. Viewing and ticking replay the stored spec.
The one bounded exception is the structured-output
repair: when an author
action’s output fails the schema, it gets one more model call that shows the
model what was wrong, and that call’s own failure is final. The repair is part
of the same author action, never of a view, and it is rate limited, budgeted
and logged (attempts = 2) like any other call.
2. The LLM emits a validated spec, never data
Section titled “2. The LLM emits a validated spec, never data”streamObject is bound to the shared IR (DashboardGenerationSchema, which is
the Dashboard schema without specVersion: the version is stamped by the
app, never asserted by the model). Output is re-parsed with Zod before it is
trusted.
When a Prometheus source is in the call, the schema is the variant whose panel query may be PromQL, and each panel is held to the language of the source it names: a panel that writes SQL against a Prometheus source fails the schema and is repaired with a message saying which field to write. A call over SQL sources only is bound to the SQL schema, exactly as before.
3. Specs are immutable and versioned
Section titled “3. Specs are immutable and versioned”Each save inserts a new dashboard_versions row containing the whole spec as
jsonb. Specs are never mutated in place.
Every spec records the IR version it was written in as specVersion, and
Dashboard accepts only the current one (SPEC_VERSION in src/lib/ir.ts).
A breaking IR change bumps that number and appends an upgrader, a pure
function from version N to N+1, to src/lib/ir/upgrade.ts. Anything that
reads a spec it did not just build reads it through StoredDashboard: a
version row, a template, an export file, a browser draft, or a save from a tab
opened before a deploy. That applies the chain in memory and then validates.
A spec with no specVersion predates the field and is version 1. Reads never
write back, so a row keeps the version it was saved at and the next save writes
the current one. A spec from a newer build is refused rather than guessed at.
4. Panels carry only a stable sourceId
Section titled “4. Panels carry only a stable sourceId”No connection details, hosts, or credentials live in a panel. The registry owns
the safe connection config, the catalog (the table and column allowlist), and a
secret_ref.
For a Prometheus source (#385), the URL and the auth mode live in the
registry beside the metric allowlist, and never in a panel, a listing or the
editor’s catalog. sourceListing() and the kind’s catalog() name their fields
(the id, the name, the metric count; the metrics and their labels), and
neither names those two. A share’s sharedSpec() replaces the expression with
(not shared), as it does a SQL statement.
5. Credentials resolve from the environment
Section titled “5. Credentials resolve from the environment”Via secret_ref: TS_METRICS resolves TS_METRICS_USERNAME /
TS_METRICS_PASSWORD, as files in SOURCE_SECRETS_DIR or from the
environment. They are never stored in the database and never leave the server.
The resolved user is the read-only TimescaleDB role.
A ref resolves only for a workspace SOURCE_SECRET_REFS grants it to, and
unset grants nothing. The grant is checked in resolveCredentials
(src/lib/secrets/credentials.ts) on every connection, not only when a source
is saved, so one workspace cannot use another’s database role by naming its
ref. See Source secret references.
For a Prometheus source, auth: "bearer" resolves <REF>_TOKEN
(resolveBearerToken) and auth: "basic" resolves the user name and password,
both under the same grant and on every request. auth: "none" is for an
endpoint with no authentication, typically in the cluster. Such a source names
no secret_ref, and what it may reach is the operator’s
SOURCE_URL_ALLOWLIST. That allowlist is not per workspace. Every workspace’s
source admins may point a no-auth source at an address it lists, so an endpoint
that must stay one tenant’s needs authentication and a granted secret_ref.
Every request goes through the guarded fetch: https only unless allowlisted, no
private address unless allowlisted, checked at DNS time on every connection,
and no redirect followed.
6. Referenced sources are tombstoned, not hard-deleted
Section titled “6. Referenced sources are tombstoned, not hard-deleted”Deleting a source referenced by any panel sets tombstoned_at; panels then
surface a tombstone state instead of silently breaking.
7. All model SQL is untrusted
Section titled “7. All model SQL is untrusted”validateSql parses every statement with the real PostgreSQL grammar and
walks the tree: exactly one SELECT, built only from allowlisted node types, no
other statement anywhere in the tree, no SELECT INTO, no row locking, no
comments. Every relation the tree reads is checked against the catalog
allowlist, every function it calls against a denylist, and time and
non-deterministic functions, keywords and literals are banned. See
Executing a panel.
The function denylist spans dialects on purpose: one list, read by every SQL
kind. PostgreSQL is the first dialect it covers and DuckDB (#569) the second.
DuckDB parses with a fork of the same libpg_query grammar, so the guard reads
its SQL unchanged; what the list adds for it is the functions that reach
outside the database: the file readers (read_csv, read_parquet,
read_json, read_text, glob, …), which httpfs also points at s3:// and
https://, the scanners of other engines, the environment (getenv,
current_setting, duckdb_settings, duckdb_secrets), extensions (load,
install) and catalog introspection (duckdb_tables, …). DuckDB has no roles,
so the guard and the engine’s locked configuration are the only two belts.
Entries in ClickHouse vocabulary cost nothing against either and mean a future
driver inherits them. A future driver is a registered source kind, with its
own guard behind the same seam
(Source kinds). Three groups matter
most:
- Functions that take a query string and execute it —
query_to_xmland the rest of the*_to_xmlfamily, and DuckDB’squeryandquery_table. The catalog allowlist never sees the tables these reach, and the application’s read-only role holdsSELECTon the whole metrics schema rather than only the catalog tables, so this is an allowlist bypass rather than an information leak. - Table functions in
FROM—FROM read_parquet(…),FROM generate_series(…),LATERAL unnest(…), each function inROWS FROM (…). A table function is how DuckDB reads a file, and every extension adds more, so these are refused by an allowlist, not a denylist: every one is refused by name unless it is onALLOWED_TABLE_FUNCTIONS, which is empty. - Every synonym for the current time, not just
now()— see invariant 8.
Statements that are not a SELECT are refused whatever the dialect, DuckDB’s
ATTACH, DETACH, COPY, EXPORT, IMPORT, INSTALL, LOAD, SET,
PRAGMA and CALL among them; several are not PostgreSQL grammar at all and
fail to parse, which is a refusal too. test/sql-safety-duckdb.test.ts names
a refusal for each, and for every DuckDB function on the list.
Relation names are compared against the catalog exactly, character for
character, as the parser reports them: an unquoted identifier is already
folded to lowercase, a quoted one keeps its case. HTTP_REQUESTS is the
catalog table http_requests; "HTTP_REQUESTS" is a different relation and
is rejected.
Statement shape and table access are decided from the parse tree, so the
guard sees through dollar-quoting, unicode escapes, nested CTEs and
subqueries in any position, and it recognizes a CTE alias, FROM inside
extract(), and a keyword inside a string literal for what they are. The
function check is still a list of names, and a list can only block what it
has been told about. test/sql-safety-postgres.test.ts and
test/sql-safety-ast.test.ts pin both sides — what is blocked, and what the
regex guard used to block wrongly. test/sql-safety.fuzz.test.ts goes past the
cases anyone wrote down: it generates statements from a grammar of adversarial
shapes — every spelling of a forbidden function, every quoting of a time word,
tables in every position a relation can appear, writes inside CTEs, scoping
tricks, comments, casing, whitespace — and checks that everything poisoned is
rejected, everything benign is accepted, and everything accepted satisfies an
independent walk of the parse tree.
CI runs the SQL, PromQL and LogQL fuzz suites longer than npm test does, each
time with a fresh seed
(#611): 5,000 iterations on
a pull request that touches a guard path (the SQL, PromQL, LogQL and DuckDB
modules, the fuzz corpora and suites, or the lockfile), 20,000 on every push
to main, and 100,000 nightly. A pull request that touches no guard path skips
the fuzz, and its checks show it as skipped. A nightly failure opens an issue
titled “Fuzz counterexample”, or comments on the open one, with the seed and
the lines that replay it; the counterexample then goes into the corpus and a
named test.
A dashboard variable (Dashboard variables, #67) never
widens this. :name is found by PostgreSQL’s scanner, must be declared, and is
checked as the $n it runs as; a statement’s own $n is still refused. The
picked value is a bound parameter, never part of the text, and is checked
against what the variable allows the viewer before anything runs.
For a Prometheus source (#384), validatePromql (src/lib/promql/) is the
same guard for PromQL. It parses with the Prometheus project’s own grammar
(@prometheus-io/lezer-promql) and walks the tree. There is one expression,
built only from allowlisted node types, so the experimental functions, the
modifiers and a comment are refused until someone lists them. Every vector and
matrix selector must name exactly one metric on the catalog’s allowlist: as the
bare name, a quoted name, or a __name__="…" equality. A selector with no
metric name, or __name__ matched by a pattern or a negation, would read every
series the endpoint holds. It is PromQL’s query_to_xml, and it is refused.
info() is refused for the same reason, since it joins in target_info series
the expression never names. A string literal the grammar’s tokenizer would let
run unterminated is refused too. test/promql-safety.fuzz.test.ts generates
expressions from adversarial shapes beside the SQL suite, with an independent
oracle walking the raw parse tree.
A variable in PromQL may only be a label matcher’s whole value,
{host=":host"}, and must be declared; anywhere else its shape is refused. The
HTTP API has no bound parameters, so here the value is written into the text.
That happens only after the pick is checked, only as an escaped string literal
in that one position, and the rewrite is re-parsed and compared node by node
with the original. A value can change which series match, never what the
expression is.
8. The server owns the time range
Section titled “8. The server owns the time range”Blocking now() and current_timestamp is not sufficient on PostgreSQL:
clock_timestamp(), statement_timestamp(), transaction_timestamp() and
timeofday() all return a clock reading, and the first is not even stable
within a single statement. All of them are denied, alongside the
non-deterministic value functions (random(), gen_random_uuid()) that would
let the same spec produce a different query on each poller tick.
buildExecutablePlan wraps the validated query as a subquery and injects
from/to on the declared timeField via bound parameters, plus a
read-only transaction and execution-time, row, and result-byte limits. The
model controls neither the time window nor resource usage. Each execution also pins
search_path to the source’s configured schema — a validated bare identifier —
plus public, so unqualified table names resolve only against the allowlisted
schema.
POST /api/sources/[id]/test is where that claim is checked rather than
assumed (#126). Inside the same read-only transaction, it attempts a harmless
write — CREATE TEMP TABLE — and reports whether the server refused it with
SQLSTATE 25006. The refusal is the expected outcome; a write that succeeds
means the configured role is more privileged than everything above assumes, and
the test says so as a finding rather than showing a tick. The probe runs in a
savepoint inside a transaction that is always rolled back, and Postgres makes
DDL transactional, so it cannot leave anything behind even in the case where
the server allows it.
For a Prometheus source, the @ modifier is refused in every spelling
(@ start(), @ end(), a timestamp). It pins evaluation to a time, so it is
PromQL’s now(). offset is allowed because it is relative to the window the
server chose. A range, a subquery’s range and an offset are each bounded by
PROMQL_MAX_RANGE (default 7d), and a subquery’s step must be at least a
second. The expression carries no time at all: buildPromqlPlan sets start,
end and step from the window the server resolved, and a panel’s minStep
can only raise the step.
The Prometheus executor sends start, end and step from that plan, never
from the panel. The step is at least PROMETHEUS_MIN_STEP_MS (15 s by
default), coarse enough that a series has at most PROMQL_MAX_POINTS (1,000)
points, and raised by minStep. The window is aligned to the step, so two polls
a few seconds apart ask for the same points.
8a. A row-filtered source returns only the viewer’s rows
Section titled “8a. A row-filtered source returns only the viewer’s rows”The time window is not the only predicate the server owns. A source with a
rowFilter (#31) narrows every table a statement reads to the rows whose
filter column equals the viewer’s claim. The predicate is applied where each
table is read, not on the wrapper that carries the time bounds, because a
wrapper predicate filters only the output, and the output can claim any
tenant. applyRowFilter (src/lib/sql/row-filter.ts) replaces each real-table
reference, found with the guard’s own CTE scoping, with
(SELECT * FROM t AS _holo_rf WHERE _holo_rf.<column> = $n). It then
re-parses its own output and refuses any statement it cannot prove is fully
narrowed. The value is a bound parameter read from the verified identity
(bindRowFilter), never from the request or the model.
buildExecutablePlan takes rowFilter as a required input, null only
for a source without one, so a call site cannot leave it out. A viewer without
the claim is refused, never served unfiltered, and that includes a platform
admin. Pollers are keyed by the claim values they run with, so tenants never
share one. See Row-level filters.
For a Prometheus source, the row filter is a tenant label, { label, claim }. applyPromqlRowFilter (src/lib/promql/row-filter.ts) splices
label="<the viewer's claim value>" into every selector at the parser’s
offsets, including selectors inside subqueries and function arguments. A
selector that already matches on that label is refused rather than overridden.
The result is re-parsed and verified to have the same tree once the added
matchers are set aside, with exactly one equality matcher on the label in every
selector. A label-values variable with no match of its own draws its values
from the allowlisted metrics only, with the same tenant matcher.
9. The catalog prompt is metadata only, and that metadata is untrusted
Section titled “9. The catalog prompt is metadata only, and that metadata is untrusted”Table and column names and types for the selected, authorized sources of the
call: one, or for a dashboard up to three in one workspace, each in its own
fenced block (More than one source).
Every source is resolved and authorized on its own record, and a panel’s SQL
is validated against the catalog of the source it names, so a table from one
source under another’s id is refused. No sample rows are sent, and no column the catalog marks
"exposed": false: the guard refuses any read of one, so naming it to the
model would only produce SQL that fails.
The names come from information_schema.columns of a database the operator may
not control, and a column called -- ignore previous instructions is a prompt
injection aimed at every generation path. So the catalog enters a prompt only
through renderCatalog (src/lib/timescaledb/catalog.ts) and
fenceUntrustedBlock (src/lib/ai/untrusted.ts):
every field is flattened onto one line, stripped of control characters and
clamped to its registry-schema maximum, and the whole block sits between
markers carrying a random per-call token, preceded by a standing rule that the
contents are data. The body is scrubbed of the token, so no name or
description can close the block or open a fake one. The dashboard chat prompt
treats the stored panel specs (titles, descriptions, SQL written by an earlier
model run) the same way. This is a second line of defense: the model’s output
is untrusted regardless (invariant 7), which is what actually contains a
successful injection.
For a Prometheus source, the catalog is the metric allowlist: each metric’s
name, type, help line and labels, read by discovery from an endpoint the
operator may not control. The kind’s renderCatalog
(src/lib/sources/server/prometheus.ts) puts it in a prompt through the same
sanitizePromptField and fenceUntrustedBlock, with a help line clamped to 500
characters, and leaves out a metric the last refresh could not find. The URL and
the auth mode are never in it.
10. One poller per dashboard
Section titled “10. One poller per dashboard”Shared across independently authorized subscribers. Each browser opens one
EventSource. The poller executes each panel once per tick, keeps a delta
cursor per subscriber and panel, and sends each subscriber only the rows newer
than its cursor (append) or full snapshots (replace). A subscriber that
joins or resumes is caught up from the last results without another query.
11. Charts merge, never recreate
Section titled “11. Charts merge, never recreate”EChart initializes once and applies setOption(..., { notMerge: false }); the
browser keeps a bounded rolling window (MAX_WINDOW_POINTS). A query ordered
newest first (ORDER BY ts DESC), which the poller reads off each whole result,
gets its appends on top and keeps its first rows when the window is full. Each
append also says where the server’s whole result now starts, and the browser
drops what is older, so the held window is what a fresh load would show.
12. SSE is cookie-authenticated
Section titled “12. SSE is cookie-authenticated”The stream handler verifies the session cookie and re-authorizes the dashboard’s
workspace before subscribing. The stream then stays authorized only as long as
that session: it ends at the token’s expiry and on revocation, and every
SSE_REAUTH_INTERVAL_MS the token is verified again and the dashboard
re-authorized (#32, src/lib/auth/stream-guard.ts).
13. OKLCH tokens are resolved before reaching ECharts
Section titled “13. OKLCH tokens are resolved before reaching ECharts”src/lib/color/oklch.ts converts design tokens to RGB/hex, because ECharts
cannot parse oklch(). A spec never stores a raw color either: a gauge’s
threshold steps and a state timeline’s state colors name tokens
(src/lib/panels/colors.ts), which resolve through the same OKLCH values.
14. Every request is authorized from the validated identity
Section titled “14. Every request is authorized from the validated identity”The source is re-resolved and re-authorized on every execution, including
each poller tick. can() in src/lib/auth/authorize.ts is the only decision
point and the only place the platform-admin bypass applies.
15. Chat is read-only
Section titled “15. Chat is read-only”Both chats, Explore and the one beside a dashboard, can query and
draw, and change nothing. The engine (src/lib/ai/data-chat.ts) exposes the
model two tools, runQuery and showPanel, scoped to the sources the caller
resolved and may use (source:use, re-checked on every turn and every panel
run; a dashboard’s chat adds dashboard:view and the dashboard’s own
sources). Each takes sql or promql, whichever the source answers, and runs
the same check → plan → execute pipeline under the server’s window and the
caller’s row filter, with rows and steps capped. showPanel hands the browser
the rows and the model only a sample. Neither tool writes anything: a panel
reaches a dashboard only through Add to dashboard, which is the ordinary,
versioned dashboard save with its own authorization and re-validation. The
browser never sends a statement to run; a panel runs again from its stored
spec.
16. Statement errors are actionable; infrastructure errors are opaque
Section titled “16. Statement errors are actionable; infrastructure errors are opaque”executePlan raises QueryExecutionError for Postgres statement-level failures
— bad column, syntax, type mismatch, timeout, missing timeField, a result
over MAX_RESULT_BYTES. Routes
translate it to a 400 with the real message so an editor can fix and retry;
connection and socket failures stay a generic 500 and are never surfaced.
For a Prometheus source, the author’s errors are a 400 or 422 whose
errorType is bad_data or execution, which keep Prometheus’s message. So
are a result over MAX_RESULT_BYTES, more series than PROMETHEUS_MAX_SERIES,
and a native-histogram sample. A timeout, a 5xx, a refused address, a TLS
failure or a redirect is infrastructure. It is logged with the source id and
reaches the browser only as the opaque error.
The split is carried, not inferred. Every error body names a kind
(src/lib/errors.ts), and the SSE path honors it too: a panel-error or
panel-degraded frame carries the real message only for a statement failure, and
describePanelError reduces anything else to the generic sentence with the
cause going to the log. describeTickError makes the same split for a
dashboard-error: a TimeRangeError keeps its message because the range is
the one part of the spec a viewer picks, and everything else is opaque. The client decides presentation from kind alone —
presentError discards the message on the opaque path regardless of what
arrived, so a careless server change cannot turn into a disclosure.
17. Every model call is rate limited and budgeted, server-side
Section titled “17. Every model call is rate limited and budgeted, server-side”The three routes that call the model run enforceLlmLimits
(src/lib/limits/llm.ts) right after assertAuthorized: a per-user token
bucket, then a per-workspace daily token budget read back from llm_usage.
Over either, the request is a 429 naming the limit and its reset before the
model is invoked. Keys come from the validated identity and a trusted record,
never the request body, and platform admins are not exempt. See
LLM rate limits and budgets.
18. Every change and every refusal is audited, and the audit log is append-only
Section titled “18. Every change and every refusal is audited, and the audit log is append-only”Each event in AUDIT_ACTIONS (src/lib/audit.ts) writes one audit_log row
naming the verified actor, the workspace the action was authorized in, the
action and its outcome; assertAuthorized writes one for every refusal. Rows
are built by auditRow alone, which runs detail through the log’s redaction
pass and drops anything shaped like a result, so no credential and no metric
value is stored. The table’s triggers refuse UPDATE, DELETE and TRUNCATE
for every role. Writing never blocks or fails the request it describes. See
Audit log.
Last verified against the code at commit 00ea858 (2026-10-05).