Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

name: expression-language
description: The per-row expression environment shared by the formula attribute and the expression filter — field binding by type, operators, built-in functions, set helpers, null handling, embedder functions and lookup tables. Not request templating.
type: guide
kind: design
applies_to: process, compose, predict
covers: [expression, expr-lang, formula, set-helpers, vector-functions, lookup, range_label, ExprFunctions, coef, response]

Expression language

Two operators evaluate an expr-lang/expr string per row: the formula attribute (a new column) and the expression filter (truthy keeps). One environment; nulls differ.

Field binding

Fields bind bare, by schema type:

Field typeBinds asWrite
numeric (u*, f*)number (u64 compares exactly)weight_kg / (height_m ** 2)
categorical_*dictionary STRING, never the indexregion in ["NA", "EU"]
set_*sorted []string of member labels (synth rule: map[string]bool, synth-set-fields)has_any(tags, "a", "b")
decimal128exact decimal — operators and numeric functions (decimal-formulas)price / cost > 1.2
date / datetimeepoch days / seconds; weekday month_index date_trunc to_day (calendar-formulas)month_index(order_day)

Categorical arithmetic errors; branch on labels.

Operators and functions

  • Operators: arithmetic (+ - * / % **), comparison, logical, membership / pattern (in; string-only contains, startsWith, endsWith, matches), range (..), nil-coalesce (??), ternary.
  • Functions: numeric (abs, ceil, floor, round, min, max, sum, mean, median), cast (int, float — a decimal’s f64 escape, string), collection (len, keys, values, concat, sort, uniq, filter, map, reduce, all, any), string (join, split, replace, trim, lower, upper, hasPrefix, hasSuffix, indexOf), JSON / time (toJSON, fromJSON, now, date, duration).
  • Set helpers: has_any, has_all, has_none, popcount, set_union, set_intersect, set_diff, set_xor.
  • Float % is math.Mod (dividend’s sign); % 0 → NaN, / 0 → ±Inf.

Vector and maths built-ins

A vector is a literal list, [q1, q2, q3]; a nil element is NaN. A request’s named vector binds by name, vmean(battery) (null member → NaN); cosine / dist on a poorly fitting kind warns (vector-metrics). Reductions skip NaN; none valid → NaN, vsum too.

FunctionResult
vsum vmean vmin vmax norm (L2)float
vcountint, valid elements
vsdsample SD (ddof 1); < 2 valid → NaN
dot dist cosine (vector pair)pairwise-complete; dist (euclidean) rescales by p/p_observed; cosine similarity, zero norm → NaN; unequal lengths → PROCESSING_VECTOR_LENGTH_MISMATCH (build + predict)
argmax argmin0-based int index; none valid → NaN
vcenter vzscore vnormalize (mode "l1" / "l2", case-sensitive)a vector, only inside a call: vmax(vzscore([q1, q2, q3])); top-level, a wrong arity or a literal bad mode → PROCESSING_CONFIG (build + predict)
sqrt log (natural) log1p exp pow(score, 2)scalar (sqrt(-1) NaN); all an overlay formula admits
sin cos tan (radians) atan2(y, x); constants pi() e() (calls)scalar; null → null
hill(score, 40, 2) (x, k, s)x^s / (x^s + k^s); null → null; x < 0, k/s <= 0 → NaN
jaccard dice overlap hamming (two sets: field or ["a", "b"], matched by label; a dictionary-less set pairs only with another)float, hamming int; null set → NaN; two empty → NaN, hamming 0
ref (table, key)a reference profile, aligned by label (vector-metrics)

Maths (** too) is machine-independent; non-finite is wire null.

Null handling

A null field binds nil; guard with x ?? 0 or x == nil ? a : b. An unguarded nil, by host:

  • Formula — arithmetic on nil raises PROCESSING_RUNTIME; a nil result is null.
  • Filter — == is false, != true; > / + / len on nil make it UNKNOWN: row dropped.

Compiled once, predict included: bad syntax, unknown name or type error → PULSE_FORMULA_COMPILE_ERROR; derived columns are numbers.

Embedder extensions

Options.Extensions.ExprFunctions adds functions (a reserved name → PULSE_EXTENSION_NAME_RESERVED); ReferenceVectors read as ref; lookup(table, keys...) and range_label(table, x[, unmatched]) read LookupTables / RangeTables — banded keys lookup("rate", range_label("bands", score)); misses, nulls, codes: lookup-formulas.

Bound models

coef(fit, term[, stat]) reads a fit’s figure: term a predictor, "(intercept)" or a model’s own term; stat point (default), lower / upper (at conf_level) or se. Codes: PULSE_MODEL_UNKNOWN, _TERM_UNKNOWN, _STAT_UNKNOWN (literal args: predict too; a registered model’s fits term: run only), _INTERVALS_UNAVAILABLE. Missing: NaN; a failed fit nulls a formula (PULSE_FIT_UNAVAILABLE), refuses a filter. An embedder coef shadows it. sweep_axis: compose-sweep-bind; response(fit, channel, spend[, geo]): mmm-workflow.

Patterns

Fourier term:

{"label": "sin1", "expression": "sin(2 * pi() * week / 52)"}

A formula’s result is a scalar (bool → 1.0 / 0.0); a filter’s must be bool: typed non-bool fails compile, untyped PROCESSING_RUNTIME.

Gotchas

  • A formula sees source fields, feature output and EARLIER attribute labels; a filter sees source fields and feature (and previous-state) labels, never another attribute or a window.
  • total(expr) — cohort-wide post-filter sum, ONLY in the formula attribute (PULSE_FORMULA_TOTAL_SITE in a filter or overlay formula); not overridable by ExprFunctions. Weights, the extra scan, recipes: formula-totals.
  • params.name reads a request constant (read-only; refusals, batch-root inheritance: request-params).
  • Optimize bounds take scalar expressions, result(slot, agg) only there: compose-optimize.

See