Expressions
PartialAn expression is a small piece of text an operator writes wherever the platform needs a computation
or a judgement: an event rule’s criteria (value > 80 && instance != "aux"), a calc rule’s reduce
(avg(temp)), an action rule’s when (severity_rank >= 40). Every one of them runs on one engine,
so there is exactly one language to learn: internal/expression, built on
Expr (pinned at v1.17.8) (#524). To write one in the console, see
rules and calc rules.
Each place an expression is written is a site, declared once in code as a Go struct: the names an
expression may use and their types and docs, the type it must yield (a criterion yields true or false),
the builtins it admits, and its run budget. The table below is generated from those declarations
(make gen):
action
: An action rule's when: true or false for one alarm transition, over the alarm facts a notification's subject and text read (in snake_case) and the severity's rank. Empty always holds. No key types it, so none is needed.
| Binding | Type | What it holds |
|---|---|---|
component | string | The component's name |
component_label | string | How the component reads: its label, else its name |
component_type | string | The label of the component type its product classifies it as |
location | string | How the location the component sits at reads; empty when it sits at none of its own |
severity | string | The severity level the alarm was raised at, by name |
severity_label | string | That level's label, else its name |
severity_rank | int | That level's rank: higher is worse (the shipped high is 40, so severity_rank >= 40 is high and above) |
message | string | The alarm's message |
transition | string | The edge: raised or cleared |
raised_at | string | When the alarm was raised, RFC 3339 in UTC |
cleared_at | string | When it was cleared, RFC 3339 in UTC; empty while raised |
rule | string | The event rule that raised it, by name; empty for an alarm an operator raised |
link | string | The component's page in the console; empty while notification.console_url is unset |
platform | bool | Whether the component is one of Omniglass's own parts (a server's or an outpost's), a member of the reserved platform system |
Builtins it admits: abs , all , any , ceil , count , filter , floor , len , lower , max , min , none , one , round , trim , trimPrefix , trimSuffix , upper
. A run may walk 10,000, allocate 10,000 and is stopped after 5ms of charged work.
calc
: A calc rule's reduce: one value of the output key's type, from the rule's aliased inputs on one owner. The output key types the result, so a key is required.
Bindings: Each of the rule's inputs by its alias, as the list of its current values, typed by its key (a metric is a number, a property text, a bool property a bool). For a component owner, one value per instance: the named instances, the aggregate instance only when it is the key's one, an instance not heard from in an hour left out. For a system owner, every slot-bound member's values, ordered by member name then id; and members: one record per member, holding id, name, value.<alias> (the member's own current value, the type's zero when it has none) and has.<alias> (whether it holds one), so one member's inputs stay together. A list function (avg, max, min, sum, majority, any, all) folds a list into one value. The result is number for a metric output , text for a string or json property output or bool for a bool property output .
| List function | Takes, and why it is bounded |
|---|---|
all | one list of bools: one pass over the charged list, output a bool (the predicate form is the builtin's) |
any | one list of bools: one pass over the charged list, output a bool (the predicate form is the builtin's) |
avg | one list of numbers: one pass over the charged list, output a number |
growth | one list of samples (records with a value and an at): one pass over the charged list, output a number |
majority | one list of text or bools: one pass over the charged list, its strings charged their bytes, counting into a map no larger than the list, output one of its values |
max | numbers, or one list of numbers: one pass over the charged list, output a number |
min | numbers, or one list of numbers: one pass over the charged list, output a number |
slope | one list of samples (records with a value and an at): one pass over the charged list, output a number |
span | one list of samples (records with a value and an at): one pass over the charged list, output a number |
sum | one list of numbers, or a list and a predicate yielding one: one pass over the charged list, output a number; a predicate may not nest another |
The 97 names an alias may not take (keywords, builtins, list functions and the site's own bindings)
abs , all , and , any , avg , bitand , bitnand , bitnot , bitor , bitshl , bitshr , bitushr , bitxor , ceil , component , concat , contains , count , date , duration , else , endsWith , false , filter , find , findIndex , findLast , findLastIndex , first , flatten , float , floor , fromBase64 , fromJSON , fromPairs , get , groupBy , growth , has , hasPrefix , hasSuffix , if , in , indexOf , int , join , keys , last , lastIndexOf , len , let , log2 , lower , majority , map , matches , max , mean , median , members , merge , min , nil , none , not , now , one , or , reduce , repeat , replace , reverse , round , slope , sort , sortBy , span , split , splitAfter , startsWith , string , sum , system , take , timezone , toBase64 , toJSON , toPairs , trim , trimPrefix , trimSuffix , true , type , uniq , upper , value , values
Builtins it admits: abs , all , any , avg , ceil , count , filter , floor , growth , len , lower , majority , max , min , none , one , round , slope , span , sum , trim , trimPrefix , trimSuffix , upper
. A run may walk 100,000, allocate 50,000 and is stopped after 25ms of charged work.
criteria
: An event rule's fire_criteria and clear_criteria: true or false for one arriving sample. The sample key's lane and data type type the value, so a key is required.
| List function | Takes, and why it is bounded |
|---|---|
all | one list of bools: one pass over the charged list, output a bool (the predicate form is the builtin's) |
any | one list of bools: one pass over the charged list, output a bool (the predicate form is the builtin's) |
avg | one list of numbers: one pass over the charged list, output a number |
growth | one list of samples (records with a value and an at): one pass over the charged list, output a number |
majority | one list of text or bools: one pass over the charged list, its strings charged their bytes, counting into a map no larger than the list, output one of its values |
max | numbers, or one list of numbers: one pass over the charged list, output a number |
min | numbers, or one list of numbers: one pass over the charged list, output a number |
slope | one list of samples (records with a value and an at): one pass over the charged list, output a number |
span | one list of samples (records with a value and an at): one pass over the charged list, output a number |
sum | one list of numbers, or a list and a predicate yielding one: one pass over the charged list, output a number; a predicate may not nest another |
| Binding | Type | What it holds |
|---|---|---|
value | float64 for a metric ; string for a string or json property ; bool for a bool property | The sample's value, typed by the key: a metric's number, a property's text, or a bool property's truth value |
key | string | The sample key the rule reads: a property or a metric, by name |
instance | string | The sample's instance (an endpoint), empty when it has none |
component.name | string | The component's name |
component.type | string | The component's type, by name; empty when its product names none |
window | []record | The series' samples over the rule's sample_window, oldest first, each a record of value and at (unix seconds), in at most 360 even buckets, each the mean of its newest 4 samples; empty for a rule with no sample_window. Read it with slope, growth and span |
window[].value | float64 | The bucket's mean value |
window[].at | float64 | The bucket's mean time, in unix seconds |
age | float64 | How long the series has run, in seconds: since the process last started for a process's own key (process-uptime), else since the series' oldest sample still kept; gate a trend on it so a fill from empty or a refill after a restart is not growth |
Builtins it admits: abs , all , any , avg , ceil , count , filter , floor , growth , len , lower , majority , max , min , none , one , round , slope , span , sum , trim , trimPrefix , trimSuffix , upper
. A run may walk 10,000, allocate 10,000 and is stopped after 5ms of charged work.
- criteria: an event rule’s fire and clear criteria,
over one sample (
value,key,instance,component) and, for a trend rule, itswindowandage. - calc: a calc rule’s reduce. Its bindings are authored with each rule: every input by its alias as the list of its values, from a struct type built when the rule is written, so the table describes them rather than listing them.
- action: an action rule’s
when, over one alarm transition: the alarm facts a notification renders, in snake_case, plus the severity’s rank. A test holds the two to one declaration, so a predicate and a message see the same alarm.
POST /expressions:validate (omniglass expression validate, gated rule:read) answers from the
same declarations: given a site, a source and its context (the sample key for criteria; the output key
and inputs for calc), it says whether the expression compiles, with each diagnostic, and returns the
site’s bindings, builtins and budget.
Compiling once
Section titled “Compiling once”An expression compiles against its site’s declaration. A name outside it, a result of the wrong type,
or a parse error is refused with a diagnostic: the line, the column and an operator-readable message
(a nested binding is named by its path, component, never by a Go type). A name nothing binds is said
by name, so an editor can offer to bind it; a let that would shadow a binding is refused where it is
declared. A fault inside a call’s argument (an unknown name in max(fan)) is checked by the engine
itself, since Expr trusts a call’s result type without looking inside again.
A compiled program is cached by its source and its site in a bounded cache, so a hot path (criteria judged per sample) never recompiles; an event rule also holds its compiled criteria per rule version, a failed compile included.
Safety
Section titled “Safety”Expressions are sandboxed: no I/O, no network, no unbounded loops, bounded execution (ADR-0146).
- An allowlist of builtins. Every Expr builtin is off, and each site declares the builtins it admits.
A builtin is admitted only once vetted: its cost linear in what the run is charged for, its output no
larger than its inputs. The criteria set is comparison, arithmetic,
in,contains,startsWith,endsWith,matcheswith a constant pattern (capped in compiled size and charged its subject’s length times that size),len,abs,ceil,floor,round,minandmaxon numbers,lower,upper,trim,trimPrefix,trimSuffix, andall,any,none,one,countandfilterover a bound list with no predicate nested in another. Equality andintake scalars and lists of scalars, never a record or a list of lists, whose deep comparison no charge covers. Builders and encoders (map,reduce,repeat,replace,join,uniq,flatten,toJSON, the range..) are never admitted: their cost is native work no input charge bounds. - List functions (#1018), vetted the same way and admitted where a site binds lists:
maxandminover a list of numbers,avg,sum(with or without a predicate),majority(the most common text or bool, a tie to the value that sorts first), and one-listanyandallover bools beside their predicate forms. Expr parsesany,allandsumas predicate builtins only, so a one-argument call is told apart lexically before parsing and renamed in place to the engine’s own function of the same length, keeping every position in the source where the author wrote it. - Trend functions (#1985) read a list of timestamped points, each with a number
valueand itsatin unix seconds:slopeis the least-squares rise per second,spanthe seconds from oldest to newest, andgrowththe fitted rise across that span as a share of the points’ mean (slope * span / |mean|), sogrowth(window) > 0.25reads “rose by more than a quarter of its level” whatever the unit. Fewer than two points, or no time between them, is no trend: 0. They are admitted where a site binds such a list: an event rule’s window and a calc rule’s windowed input. - Names stay owned. A builtin’s or list function’s name can never be bound, so admitting one later
never changes what a stored expression means. A
$name (Expr’s dynamic$env) is refused, so a site’s bindings are the whole namespace. - Determinism. The clock and zone builtins (
now,date,duration,timezone) can never be vetted; a time an expression needs is bound by its caller as data. An expression calls builtins only, never a method, and a site’s environment holds concrete data types, so no value chooses its behavior at run time. - Caps and budgets. A source is at most 4,096 bytes and 1,000 parse-tree elements, a list or map literal at most 64 entries. A run is bounded deterministically by its site’s budget of what it allocates and walks, under a fixed ceiling; a wall-clock deadline backs the budget for charged work only, which is why the allowlist exists.
- Values are data. A bound value (a sample’s text, however hostile) is evaluated literally, never executed. Integer arithmetic wraps on overflow, as Go’s does.
- Refused, never crashed. Expr’s optimizer is off: in v1.17.8 it rewrites
filter(list, p)[0]in a way that panics on a field read of the result, and it comes back on when upstream is fixed (#1006). A panic in any compile stage is refused as a type error naming the stage and the construct.
The expression field
Section titled “The expression field”The console’s expression field (an event rule’s Write as an expression, #960; a calc rule’s
reduce; an action rule’s when) is the validate route’s face: a CodeMirror 6 editor (#1000) driven
entirely by the route’s answer. It highlights Expr as it is typed, completes exactly the site’s bindings
and builtins (as a word begins, or on Ctrl-Space, the first word included), shows a binding’s doc on
hover, and underlines each diagnostic where it sits as well as listing it beneath with its line and
column. A site’s form may offer starters (a calc rule’s list functions) and an action on an unbound name
(a calc rule’s Bind it to a key). The editor is a chunk of its own, loaded only by a page with an
expression site; a page that cannot load it says so and refuses the source.
Diagnostics: clear messages and quick fixes
Section titled “Diagnostics: clear messages and quick fixes”Expr’s own refusals are accurate but speak the checker’s language: sum(members, .has.t) > 0 is
refused as an operator mismatch at the >, when the mistake is the sum. And an expression can compile
and still probably be wrong. So the engine keeps a registry of diagnostics (#1021,
internal/expression/diagnostics.go). Each common mistake is one declared rule with:
- a stable code (
sum-of-bools), a severity and the sites it applies at. An error refuses the expression; a warning (probably wrong) and a hint (could be simpler) ride along with one that compiles and never refuse it. - a trigger: a refine rule runs when the engine refuses an expression and recognises the shape behind the refusal, replacing the message with a clearer one at the mistake; a lint rule runs on an expression that compiles and flags a likely mistake.
- a matcher, a pure function over the typed tree, returning the positions it found.
- a message, and an optional fix: one text edit an editor offers as a quick fix.
- fixtures in Go: expressions it must and must not flag, with the source a fix must yield (which must compile clean). A rule without both kinds of fixture refuses to register, and a fixture that disagrees with its rule fails the build.
A site’s rules run once per compile, so a cached program carries its warnings and hints. A matcher that panics is a bug in the rule: the expression is judged as if the rule were absent, never refused by it.
The validate route answers each diagnostic’s severity, and a registered one’s code and fix, so the
expression field shows them where they arise (#1053): an error is a wavy red underline and refuses the
source, a warning a wavy amber one, a hint a dotted one, neither stopping a save. Beneath the field each
diagnostic names its severity, links its code to its entry below, and offers its fix as a button (F8
moves to the next diagnostic; Mod-Shift-M lists them). A fix is the author’s own edit, so Ctrl-Z takes it
back. A stored rule’s warnings show on its blade as a note.
Every registered diagnostic, generated from the registry (make gen), with the examples its fixtures
hold it to:
| Code | Severity | Sites | In short | Examples |
|---|---|---|---|---|
sum-of-bools | error explains a refusal | every site | sum adds numbers; to count matches use count(...) |
|
float-equality | warning flags an expression that compiles | every site | a measured number seldom equals a decimal exactly; compare a range instead, such as abs(value - 1.5) < 0.05 |
|
count-equals-len | hint flags an expression that compiles | every site | count(xs, p) == len(xs) is all(xs, p) |
|
unused-alias | warning flags an expression that compiles | calc | an input the expression never names is read for nothing; use it, or remove the input |
|
Not every input is an expression
Section titled “Not every input is an expression”No driver evaluates an expression today. A driver spec
locates and transforms values with declared selectors and a cast, scale or enum map, and its
configuration values are typed inputs supplied at attach, a secret input a reference resolved under
the caller’s own secret scope. So an operator’s value is always data the interpreter reads, never text
it runs.