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 type | Binds as | Write |
|---|---|---|
numeric (u*, f*) | number (u64 compares exactly) | weight_kg / (height_m ** 2) |
categorical_* | dictionary STRING, never the index | region in ["NA", "EU"] |
set_* | sorted []string of member labels (synth rule: map[string]bool, synth-set-fields) | has_any(tags, "a", "b") |
decimal128 | exact decimal — operators and numeric functions (decimal-formulas) | price / cost > 1.2 |
date / datetime | epoch 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-onlycontains,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
%ismath.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.
| Function | Result |
|---|---|
vsum vmean vmin vmax norm (L2) | float |
vcount | int, valid elements |
vsd | sample 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 argmin | 0-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
nilraisesPROCESSING_RUNTIME; anilresult is null. - Filter —
==is false,!=true;>/+/lenonnilmake 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_SITEin a filter or overlay formula); not overridable byExprFunctions. Weights, the extra scan, recipes:formula-totals.params.namereads a request constant (read-only; refusals, batch-root inheritance:request-params).- Optimize bounds take scalar expressions,
result(slot, agg)only there:compose-optimize.
See
attribute-composition,aggregation-design— attribute order; filter chaining.formula-totals—total(expr)in a formula.request-templating— the request-authoring parameters this language is not.docs/src/internals/extension-points.md—ExprFunctions+LookupTables.